diff --git a/README.md b/README.md index 7c5cf5541..63ed7df68 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,6 @@ ![taskt](https://i.imgur.com/gBpKDg0.png) +taskt uob is forked from taskt. taskt (formerly sharpRPA) is the first truly free, easy to use, and open-source process automation client built on the .NET Framework in C#. taskt allows you to build and design process automation without needing to write application code. [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0) @@ -21,13 +22,13 @@ taskt allows you to automate the boring stuff and create efficienies by giving y ![Recorder](https://i.imgur.com/EpiwkPj.gif) ![How does taskt work?](https://i.imgur.com/TxrH6YH.png) -taskt works by allowing a bot developer to design a bot configuration known as a script. The bot configuration is then intepreted by a script engine at run-time and executes against the bot developer's selected parameter inputs. Each command contains the definitions for the required inputs as well as the required logic at run-time. Please check out the [Wiki](https://github.com/saucepleez/taskt/wiki) for basic documenation surrounding the application and the available commands +taskt works by allowing a bot developer to design a bot configuration known as a script. The bot configuration is then intepreted by a script engine at run-time and executes against the bot developer's selected parameter inputs. Each command contains the definitions for the required inputs as well as the required logic at run-time. ![Configuring Tasks](https://i.imgur.com/ufvgfn2.gif) ![What can taskt do?](https://i.imgur.com/FTMRTi8.png) -taskt can perform automation on both web and desktop applications, simulating the actions a person would do. From swivel-chair data entry to report generation, taskt can handle your automation needs. Prefer to write and implement code? taskt can use your existing .NET DLLs and services additionally with the ability to compile code on the fly using the Custom Code command! taskt can start and stop processes, launch VB and PowerShell scripts, work directly with Excel workbooks, and perform OCR (OneNote installation required) among many other functions. You can review all the automation commands by clicking [here](https://github.com/saucepleez/taskt/wiki/Automation-Commands). +taskt can perform automation on both web and desktop applications, simulating the actions a person would do. From swivel-chair data entry to report generation, taskt can handle your automation needs. Prefer to write and implement code? taskt can use your existing .NET DLLs and services additionally with the ability to compile code on the fly using the Custom Code command! taskt can start and stop processes, launch VB and PowerShell scripts, work directly with Excel workbooks, and perform OCR (OneNote installation required) among many other functions. You can review all the automation commands by clicking [here](https://github.com/rcktrncn/taskt-wiki/blob/master/automation-commands.md). ![Manage Your Workforce](https://i.imgur.com/KQVqN9v.png) **CURRENTLY IN ALPHA** Manage and orchestrate your digital workforce with taskt's optional [server component](https://github.com/saucepleez/tasktServer) that allows you to publish and execute tasks remotely as well as monitor the overall health of your bots and discover metrics around your robot workers. @@ -37,7 +38,7 @@ taskt can perform automation on both web and desktop applications, simulating th ![How can I get started?](https://i.imgur.com/CkESBRT.png) -Find and download the latest signed release by clicking [HERE](https://github.com/saucepleez/taskt/releases/). Extract to any folder and double-click 'taskt.exe'. taskt will ask if you want to create a scripts folder to store your scripts as well as copy and deploy sample files. You can also build directly from source -- take the latest from the master branch! +Find and download the latest signed release by clicking [HERE](https://github.com/rcktrncn/taskt/releases/). Extract to any folder and double-click 'taskt.exe'. taskt will ask if you want to create a scripts folder to store your scripts as well as copy and deploy sample files. You can also build directly from source -- take the latest from the master branch! ![What does taskt Cost?](https://i.imgur.com/fzliKyN.png) @@ -48,18 +49,24 @@ Feel free to open up a feature request or report a bug/issue. # System specifications Please note whatever software that taskt is automating can affect the minimum software requirements. + ## Minimum - * Windows 7/8.1/10/Server 2012/Server 2016 + * Windows 7/8.1/10/Server 2012/Server 2016/Server 2019 * 1GB ram * 200MB disk space * 1 vCPU * .NET Framework 4.8 + * (We think it will probably work in Windows 11 :-) + +**Attension**: Windows 7, Windows 8.1, Windows Server 2012 are no longer supported. + ## Recommended - * Windows 10/Server 2012/Server 2016/Server 2019 + * Windows 10/Server 2016/Server 2019 * 4GB ram * 1GB disk space * 2 CPU * .NET Framework 4.8 + * (We think it will probably work in Windows 11 :-) [![Open New Issue](https://img.shields.io/badge/Open-New Issue-blue.svg)](https://github.com/saucepleez/taskt/issues/new) [![Chat on Gitter](https://img.shields.io/badge/Chat-On Gitter-green.svg)](https://gitter.im/taskt-rpa/Lobby) diff --git a/UIAutomationTester/App.config b/UIAutomationTester/App.config new file mode 100644 index 000000000..193aecc67 --- /dev/null +++ b/UIAutomationTester/App.config @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/UIAutomationTester/Program.cs b/UIAutomationTester/Program.cs new file mode 100644 index 000000000..38dc7644f --- /dev/null +++ b/UIAutomationTester/Program.cs @@ -0,0 +1,19 @@ +using System; +using System.Windows.Forms; + +namespace UIAutomationTester +{ + internal static class Program + { + /// + /// アプリケーションのメイン エントリ ポイントです。 + /// + [STAThread] + static void Main() + { + Application.EnableVisualStyles(); + Application.SetCompatibleTextRenderingDefault(false); + Application.Run(new frmMain()); + } + } +} diff --git a/UIAutomationTester/Properties/AssemblyInfo.cs b/UIAutomationTester/Properties/AssemblyInfo.cs new file mode 100644 index 000000000..e5179fdd5 --- /dev/null +++ b/UIAutomationTester/Properties/AssemblyInfo.cs @@ -0,0 +1,58 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// アセンブリに関する一般的な情報は、次の方法で制御されます +// 制御されます。アセンブリに関連付けられている情報を変更するには、 +// これらの属性値を変更します。 +[assembly: AssemblyTitle("UIAutomationTester")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("UIAutomationTester")] +[assembly: AssemblyCopyright("Copyright © 2023")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから +// 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、 +// その型の ComVisible 属性を true に設定してください。 +[assembly: ComVisible(false)] + +// このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります +[assembly: Guid("2db516fb-73c2-4c62-b465-403a9054d701")] + +// アセンブリのバージョン情報は、以下の 4 つの値で構成されています: +// +// メジャー バージョン +// マイナー バージョン +// ビルド番号 +// リビジョン +// +// すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます +// 既定値にすることができます: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.5")] +[assembly: AssemblyFileVersion("1.0.0.0")] + +/* + * my memo + * + * v1.0.0.5 + * a bit fix frmMain + * + * v1.0.0.4 + * add picturebox + * + * v1.0.0.3 + * set version + * show version in title bar + * + * v1.0.0.2 + * add new combobox (disable enter text, select only) + * + * v1.0.0.1 + * fix tab order, and fix inspect + * + * v1.0.0.0 + * first + */ diff --git a/UIAutomationTester/Properties/Resources.Designer.cs b/UIAutomationTester/Properties/Resources.Designer.cs new file mode 100644 index 000000000..0d6079535 --- /dev/null +++ b/UIAutomationTester/Properties/Resources.Designer.cs @@ -0,0 +1,73 @@ +//------------------------------------------------------------------------------ +// +// このコードはツールによって生成されました。 +// ランタイム バージョン:4.0.30319.42000 +// +// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、 +// コードが再生成されるときに損失したりします。 +// +//------------------------------------------------------------------------------ + +namespace UIAutomationTester.Properties { + using System; + + + /// + /// ローカライズされた文字列などを検索するための、厳密に型指定されたリソース クラスです。 + /// + // このクラスは StronglyTypedResourceBuilder クラスが ResGen + // または Visual Studio のようなツールを使用して自動生成されました。 + // メンバーを追加または削除するには、.ResX ファイルを編集して、/str オプションと共に + // ResGen を実行し直すか、または VS プロジェクトをビルドし直します。 + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] + [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + internal class Resources { + + private static global::System.Resources.ResourceManager resourceMan; + + private static global::System.Globalization.CultureInfo resourceCulture; + + [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] + internal Resources() { + } + + /// + /// このクラスで使用されているキャッシュされた ResourceManager インスタンスを返します。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Resources.ResourceManager ResourceManager { + get { + if (object.ReferenceEquals(resourceMan, null)) { + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("UIAutomationTester.Properties.Resources", typeof(Resources).Assembly); + resourceMan = temp; + } + return resourceMan; + } + } + + /// + /// すべてについて、現在のスレッドの CurrentUICulture プロパティをオーバーライドします + /// 現在のスレッドの CurrentUICulture プロパティをオーバーライドします。 + /// + [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] + internal static global::System.Globalization.CultureInfo Culture { + get { + return resourceCulture; + } + set { + resourceCulture = value; + } + } + + /// + /// 型 System.Drawing.Bitmap のローカライズされたリソースを検索します。 + /// + internal static System.Drawing.Bitmap taskt_logo_alt { + get { + object obj = ResourceManager.GetObject("taskt_logo_alt", resourceCulture); + return ((System.Drawing.Bitmap)(obj)); + } + } + } +} diff --git a/taskt/UI/Forms/Supplement Forms/frmThickAppBuilder.resx b/UIAutomationTester/Properties/Resources.resx similarity index 93% rename from taskt/UI/Forms/Supplement Forms/frmThickAppBuilder.resx rename to UIAutomationTester/Properties/Resources.resx index 1af7de150..e49f039e5 100644 --- a/taskt/UI/Forms/Supplement Forms/frmThickAppBuilder.resx +++ b/UIAutomationTester/Properties/Resources.resx @@ -117,4 +117,8 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + ..\Resources\taskt_logo_alt.png;System.Drawing.Bitmap, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a + \ No newline at end of file diff --git a/UIAutomationTester/Properties/Settings.Designer.cs b/UIAutomationTester/Properties/Settings.Designer.cs new file mode 100644 index 000000000..07a0b3044 --- /dev/null +++ b/UIAutomationTester/Properties/Settings.Designer.cs @@ -0,0 +1,30 @@ +//------------------------------------------------------------------------------ +// +// This code was generated by a tool. +// Runtime Version:4.0.30319.42000 +// +// Changes to this file may cause incorrect behavior and will be lost if +// the code is regenerated. +// +//------------------------------------------------------------------------------ + +namespace UIAutomationTester.Properties +{ + + + [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] + internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase + { + + private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); + + public static Settings Default + { + get + { + return defaultInstance; + } + } + } +} diff --git a/UIAutomationTester/Properties/Settings.settings b/UIAutomationTester/Properties/Settings.settings new file mode 100644 index 000000000..39645652a --- /dev/null +++ b/UIAutomationTester/Properties/Settings.settings @@ -0,0 +1,7 @@ + + + + + + + diff --git a/UIAutomationTester/Resources/taskt_logo_alt.png b/UIAutomationTester/Resources/taskt_logo_alt.png new file mode 100644 index 000000000..99d9e988c Binary files /dev/null and b/UIAutomationTester/Resources/taskt_logo_alt.png differ diff --git a/UIAutomationTester/UIAutomationTester.csproj b/UIAutomationTester/UIAutomationTester.csproj new file mode 100644 index 000000000..9c480c9da --- /dev/null +++ b/UIAutomationTester/UIAutomationTester.csproj @@ -0,0 +1,114 @@ + + + + + Debug + AnyCPU + {2DB516FB-73C2-4C62-B465-403A9054D701} + WinExe + UIAutomationTester + UIAutomationTester + v4.8 + 512 + true + true + publish\ + true + Disk + false + Foreground + 7 + Days + false + false + true + 0 + 1.0.0.%2a + false + false + true + + + AnyCPU + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + AnyCPU + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + Form + + + frmMain.cs + + + + + frmMain.cs + + + ResXFileCodeGenerator + Resources.Designer.cs + Designer + + + True + Resources.resx + True + + + SettingsSingleFileGenerator + Settings.Designer.cs + + + True + Settings.settings + True + + + + + + + + + + + False + Microsoft .NET Framework 4.8 %28x86 および x64%29 + true + + + False + .NET Framework 3.5 SP1 + false + + + + \ No newline at end of file diff --git a/UIAutomationTester/frmMain.Designer.cs b/UIAutomationTester/frmMain.Designer.cs new file mode 100644 index 000000000..4b76fa51e --- /dev/null +++ b/UIAutomationTester/frmMain.Designer.cs @@ -0,0 +1,787 @@ +namespace UIAutomationTester +{ + partial class frmMain + { + /// + /// 必要なデザイナー変数です。 + /// + private System.ComponentModel.IContainer components = null; + + /// + /// 使用中のリソースをすべてクリーンアップします。 + /// + /// マネージド リソースを破棄する場合は true を指定し、その他の場合は false を指定します。 + protected override void Dispose(bool disposing) + { + if (disposing && (components != null)) + { + components.Dispose(); + } + base.Dispose(disposing); + } + + #region Windows フォーム デザイナーで生成されたコード + + /// + /// デザイナー サポートに必要なメソッドです。このメソッドの内容を + /// コード エディターで変更しないでください。 + /// + private void InitializeComponent() + { + System.Windows.Forms.ListViewItem listViewItem1 = new System.Windows.Forms.ListViewItem(new string[] { + "A1", + "B1", + "C1"}, -1); + System.Windows.Forms.ListViewItem listViewItem2 = new System.Windows.Forms.ListViewItem(new string[] { + "A2", + "B2", + "C2"}, -1); + System.Windows.Forms.ListViewItem listViewItem3 = new System.Windows.Forms.ListViewItem(new string[] { + "A3", + "B3", + "C3"}, -1); + System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("node0_0"); + System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("node0_1"); + System.Windows.Forms.TreeNode treeNode3 = new System.Windows.Forms.TreeNode("node0", new System.Windows.Forms.TreeNode[] { + treeNode1, + treeNode2}); + System.Windows.Forms.TreeNode treeNode4 = new System.Windows.Forms.TreeNode("node1_0"); + System.Windows.Forms.TreeNode treeNode5 = new System.Windows.Forms.TreeNode("node1_1"); + System.Windows.Forms.TreeNode treeNode6 = new System.Windows.Forms.TreeNode("node1_2_0"); + System.Windows.Forms.TreeNode treeNode7 = new System.Windows.Forms.TreeNode("node1_2", new System.Windows.Forms.TreeNode[] { + treeNode6}); + System.Windows.Forms.TreeNode treeNode8 = new System.Windows.Forms.TreeNode("node1", new System.Windows.Forms.TreeNode[] { + treeNode4, + treeNode5, + treeNode7}); + System.Windows.Forms.TreeNode treeNode9 = new System.Windows.Forms.TreeNode("node2"); + this.button1 = new System.Windows.Forms.Button(); + this.checkBox1 = new System.Windows.Forms.CheckBox(); + this.label1 = new System.Windows.Forms.Label(); + this.groupBox1 = new System.Windows.Forms.GroupBox(); + this.checkBox3 = new System.Windows.Forms.CheckBox(); + this.checkBox2 = new System.Windows.Forms.CheckBox(); + this.groupBox2 = new System.Windows.Forms.GroupBox(); + this.radioButton3 = new System.Windows.Forms.RadioButton(); + this.radioButton2 = new System.Windows.Forms.RadioButton(); + this.radioButton1 = new System.Windows.Forms.RadioButton(); + this.comboBox1 = new System.Windows.Forms.ComboBox(); + this.label2 = new System.Windows.Forms.Label(); + this.listBox1 = new System.Windows.Forms.ListBox(); + this.label3 = new System.Windows.Forms.Label(); + this.textBox1 = new System.Windows.Forms.TextBox(); + this.label4 = new System.Windows.Forms.Label(); + this.tabControl1 = new System.Windows.Forms.TabControl(); + this.tabPage1 = new System.Windows.Forms.TabPage(); + this.button2 = new System.Windows.Forms.Button(); + this.label5 = new System.Windows.Forms.Label(); + this.tabPage2 = new System.Windows.Forms.TabPage(); + this.button3 = new System.Windows.Forms.Button(); + this.label6 = new System.Windows.Forms.Label(); + this.tabPage3 = new System.Windows.Forms.TabPage(); + this.button4 = new System.Windows.Forms.Button(); + this.label7 = new System.Windows.Forms.Label(); + this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); + this.label8 = new System.Windows.Forms.Label(); + this.listView1 = new System.Windows.Forms.ListView(); + this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); + this.label9 = new System.Windows.Forms.Label(); + this.cmbListViewView = new System.Windows.Forms.ComboBox(); + this.progressBar1 = new System.Windows.Forms.ProgressBar(); + this.label10 = new System.Windows.Forms.Label(); + this.trackBar1 = new System.Windows.Forms.TrackBar(); + this.label11 = new System.Windows.Forms.Label(); + this.dateTimePicker1 = new System.Windows.Forms.DateTimePicker(); + this.label12 = new System.Windows.Forms.Label(); + this.treeView1 = new System.Windows.Forms.TreeView(); + this.label13 = new System.Windows.Forms.Label(); + this.dataGridView1 = new System.Windows.Forms.DataGridView(); + this.colA = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.colB = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.colC = new System.Windows.Forms.DataGridViewTextBoxColumn(); + this.label14 = new System.Windows.Forms.Label(); + this.label15 = new System.Windows.Forms.Label(); + this.dateTimePicker2 = new System.Windows.Forms.DateTimePicker(); + this.label16 = new System.Windows.Forms.Label(); + this.comboBox2 = new System.Windows.Forms.ComboBox(); + this.pictureBox1 = new System.Windows.Forms.PictureBox(); + this.label17 = new System.Windows.Forms.Label(); + this.groupBox1.SuspendLayout(); + this.groupBox2.SuspendLayout(); + this.tabControl1.SuspendLayout(); + this.tabPage1.SuspendLayout(); + this.tabPage2.SuspendLayout(); + this.tabPage3.SuspendLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); + this.SuspendLayout(); + // + // button1 + // + this.button1.Location = new System.Drawing.Point(12, 12); + this.button1.Name = "button1"; + this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.TabIndex = 0; + this.button1.Text = "button1"; + this.button1.UseVisualStyleBackColor = true; + this.button1.Click += new System.EventHandler(this.button1_Click); + // + // checkBox1 + // + this.checkBox1.AutoSize = true; + this.checkBox1.Location = new System.Drawing.Point(6, 18); + this.checkBox1.Name = "checkBox1"; + this.checkBox1.Size = new System.Drawing.Size(80, 16); + this.checkBox1.TabIndex = 1; + this.checkBox1.Text = "checkBox1"; + this.checkBox1.UseVisualStyleBackColor = true; + // + // label1 + // + this.label1.AutoSize = true; + this.label1.Location = new System.Drawing.Point(105, 17); + this.label1.Name = "label1"; + this.label1.Size = new System.Drawing.Size(35, 12); + this.label1.TabIndex = 1; + this.label1.Text = "label1"; + // + // groupBox1 + // + this.groupBox1.Controls.Add(this.checkBox3); + this.groupBox1.Controls.Add(this.checkBox2); + this.groupBox1.Controls.Add(this.checkBox1); + this.groupBox1.Location = new System.Drawing.Point(12, 41); + this.groupBox1.Name = "groupBox1"; + this.groupBox1.Size = new System.Drawing.Size(94, 91); + this.groupBox1.TabIndex = 2; + this.groupBox1.TabStop = false; + this.groupBox1.Text = "groupBox1"; + // + // checkBox3 + // + this.checkBox3.AutoSize = true; + this.checkBox3.Location = new System.Drawing.Point(6, 62); + this.checkBox3.Name = "checkBox3"; + this.checkBox3.Size = new System.Drawing.Size(80, 16); + this.checkBox3.TabIndex = 3; + this.checkBox3.Text = "checkBox3"; + this.checkBox3.UseVisualStyleBackColor = true; + // + // checkBox2 + // + this.checkBox2.AutoSize = true; + this.checkBox2.Checked = true; + this.checkBox2.CheckState = System.Windows.Forms.CheckState.Checked; + this.checkBox2.Location = new System.Drawing.Point(6, 40); + this.checkBox2.Name = "checkBox2"; + this.checkBox2.Size = new System.Drawing.Size(80, 16); + this.checkBox2.TabIndex = 2; + this.checkBox2.Text = "checkBox2"; + this.checkBox2.UseVisualStyleBackColor = true; + // + // groupBox2 + // + this.groupBox2.Controls.Add(this.radioButton3); + this.groupBox2.Controls.Add(this.radioButton2); + this.groupBox2.Controls.Add(this.radioButton1); + this.groupBox2.Location = new System.Drawing.Point(112, 41); + this.groupBox2.Name = "groupBox2"; + this.groupBox2.Size = new System.Drawing.Size(106, 91); + this.groupBox2.TabIndex = 3; + this.groupBox2.TabStop = false; + this.groupBox2.Text = "groupBox2"; + // + // radioButton3 + // + this.radioButton3.AutoSize = true; + this.radioButton3.Location = new System.Drawing.Point(6, 65); + this.radioButton3.Name = "radioButton3"; + this.radioButton3.Size = new System.Drawing.Size(88, 16); + this.radioButton3.TabIndex = 2; + this.radioButton3.Text = "radioButton3"; + this.radioButton3.UseVisualStyleBackColor = true; + // + // radioButton2 + // + this.radioButton2.AutoSize = true; + this.radioButton2.Checked = true; + this.radioButton2.Location = new System.Drawing.Point(6, 44); + this.radioButton2.Name = "radioButton2"; + this.radioButton2.Size = new System.Drawing.Size(88, 16); + this.radioButton2.TabIndex = 1; + this.radioButton2.TabStop = true; + this.radioButton2.Text = "radioButton2"; + this.radioButton2.UseVisualStyleBackColor = true; + // + // radioButton1 + // + this.radioButton1.AutoSize = true; + this.radioButton1.Location = new System.Drawing.Point(6, 22); + this.radioButton1.Name = "radioButton1"; + this.radioButton1.Size = new System.Drawing.Size(88, 16); + this.radioButton1.TabIndex = 0; + this.radioButton1.Text = "radioButton1"; + this.radioButton1.UseVisualStyleBackColor = true; + // + // comboBox1 + // + this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.comboBox1.FormattingEnabled = true; + this.comboBox1.Items.AddRange(new object[] { + "ItemA", + "ItemB", + "ItemC"}); + this.comboBox1.Location = new System.Drawing.Point(296, 9); + this.comboBox1.Name = "comboBox1"; + this.comboBox1.Size = new System.Drawing.Size(144, 20); + this.comboBox1.TabIndex = 14; + // + // label2 + // + this.label2.AutoSize = true; + this.label2.Location = new System.Drawing.Point(226, 12); + this.label2.Name = "label2"; + this.label2.Size = new System.Drawing.Size(64, 12); + this.label2.TabIndex = 13; + this.label2.Text = "comboBox1"; + // + // listBox1 + // + this.listBox1.FormattingEnabled = true; + this.listBox1.ItemHeight = 12; + this.listBox1.Items.AddRange(new object[] { + "Item-a", + "Item-b", + "Item-c", + "Item-d", + "Item-e", + "Item-f", + "Item-g", + "Item-h", + "Item-i", + "Item-j"}); + this.listBox1.Location = new System.Drawing.Point(296, 56); + this.listBox1.Name = "listBox1"; + this.listBox1.Size = new System.Drawing.Size(144, 40); + this.listBox1.TabIndex = 18; + // + // label3 + // + this.label3.AutoSize = true; + this.label3.Location = new System.Drawing.Point(243, 56); + this.label3.Name = "label3"; + this.label3.Size = new System.Drawing.Size(47, 12); + this.label3.TabIndex = 17; + this.label3.Text = "listBox1"; + // + // textBox1 + // + this.textBox1.Location = new System.Drawing.Point(12, 157); + this.textBox1.Multiline = true; + this.textBox1.Name = "textBox1"; + this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; + this.textBox1.Size = new System.Drawing.Size(133, 66); + this.textBox1.TabIndex = 5; + this.textBox1.Text = "Hello1\r\nHello2\r\nHello3\r\nHello4\r\nHello5\r\nHello6\r\nHello7\r\nHello8\r\nHello9\r\nHello10\r\n" + + "Hello11"; + // + // label4 + // + this.label4.AutoSize = true; + this.label4.Location = new System.Drawing.Point(12, 142); + this.label4.Name = "label4"; + this.label4.Size = new System.Drawing.Size(51, 12); + this.label4.TabIndex = 4; + this.label4.Text = "textBox1"; + // + // tabControl1 + // + this.tabControl1.Controls.Add(this.tabPage1); + this.tabControl1.Controls.Add(this.tabPage2); + this.tabControl1.Controls.Add(this.tabPage3); + this.tabControl1.Location = new System.Drawing.Point(244, 102); + this.tabControl1.Name = "tabControl1"; + this.tabControl1.SelectedIndex = 0; + this.tabControl1.Size = new System.Drawing.Size(200, 100); + this.tabControl1.TabIndex = 19; + // + // tabPage1 + // + this.tabPage1.Controls.Add(this.button2); + this.tabPage1.Controls.Add(this.label5); + this.tabPage1.Location = new System.Drawing.Point(4, 22); + this.tabPage1.Name = "tabPage1"; + this.tabPage1.Padding = new System.Windows.Forms.Padding(3); + this.tabPage1.Size = new System.Drawing.Size(192, 74); + this.tabPage1.TabIndex = 0; + this.tabPage1.Text = "tabPage1"; + this.tabPage1.UseVisualStyleBackColor = true; + // + // button2 + // + this.button2.Location = new System.Drawing.Point(8, 34); + this.button2.Name = "button2"; + this.button2.Size = new System.Drawing.Size(75, 23); + this.button2.TabIndex = 1; + this.button2.Text = "button2"; + this.button2.UseVisualStyleBackColor = true; + this.button2.Click += new System.EventHandler(this.button2_Click); + // + // label5 + // + this.label5.AutoSize = true; + this.label5.Location = new System.Drawing.Point(6, 13); + this.label5.Name = "label5"; + this.label5.Size = new System.Drawing.Size(125, 12); + this.label5.TabIndex = 0; + this.label5.Text = "tabControl1 > tabPage1"; + // + // tabPage2 + // + this.tabPage2.Controls.Add(this.button3); + this.tabPage2.Controls.Add(this.label6); + this.tabPage2.Location = new System.Drawing.Point(4, 22); + this.tabPage2.Name = "tabPage2"; + this.tabPage2.Padding = new System.Windows.Forms.Padding(3); + this.tabPage2.Size = new System.Drawing.Size(192, 74); + this.tabPage2.TabIndex = 1; + this.tabPage2.Text = "tabPage2"; + this.tabPage2.UseVisualStyleBackColor = true; + // + // button3 + // + this.button3.Location = new System.Drawing.Point(8, 34); + this.button3.Name = "button3"; + this.button3.Size = new System.Drawing.Size(75, 23); + this.button3.TabIndex = 2; + this.button3.Text = "button3"; + this.button3.UseVisualStyleBackColor = true; + this.button3.Click += new System.EventHandler(this.button3_Click); + // + // label6 + // + this.label6.AutoSize = true; + this.label6.Location = new System.Drawing.Point(6, 13); + this.label6.Name = "label6"; + this.label6.Size = new System.Drawing.Size(125, 12); + this.label6.TabIndex = 1; + this.label6.Text = "tabControl1 > tabPage2"; + // + // tabPage3 + // + this.tabPage3.Controls.Add(this.button4); + this.tabPage3.Controls.Add(this.label7); + this.tabPage3.Location = new System.Drawing.Point(4, 22); + this.tabPage3.Name = "tabPage3"; + this.tabPage3.Padding = new System.Windows.Forms.Padding(3); + this.tabPage3.Size = new System.Drawing.Size(192, 74); + this.tabPage3.TabIndex = 2; + this.tabPage3.Text = "tabPage3"; + this.tabPage3.UseVisualStyleBackColor = true; + // + // button4 + // + this.button4.Location = new System.Drawing.Point(8, 34); + this.button4.Name = "button4"; + this.button4.Size = new System.Drawing.Size(75, 23); + this.button4.TabIndex = 2; + this.button4.Text = "button4"; + this.button4.UseVisualStyleBackColor = true; + this.button4.Click += new System.EventHandler(this.button4_Click); + // + // label7 + // + this.label7.AutoSize = true; + this.label7.Location = new System.Drawing.Point(6, 13); + this.label7.Name = "label7"; + this.label7.Size = new System.Drawing.Size(125, 12); + this.label7.TabIndex = 1; + this.label7.Text = "tabControl1 > tabPage3"; + // + // numericUpDown1 + // + this.numericUpDown1.Location = new System.Drawing.Point(151, 229); + this.numericUpDown1.Maximum = new decimal(new int[] { + 10, + 0, + 0, + 0}); + this.numericUpDown1.Name = "numericUpDown1"; + this.numericUpDown1.Size = new System.Drawing.Size(55, 19); + this.numericUpDown1.TabIndex = 8; + // + // label8 + // + this.label8.AutoSize = true; + this.label8.Location = new System.Drawing.Point(8, 231); + this.label8.Name = "label8"; + this.label8.Size = new System.Drawing.Size(137, 12); + this.label8.TabIndex = 7; + this.label8.Text = "numericUpDown1 (0 - 10)"; + // + // listView1 + // + this.listView1.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { + this.columnHeader1, + this.columnHeader2, + this.columnHeader3}); + this.listView1.HideSelection = false; + this.listView1.Items.AddRange(new System.Windows.Forms.ListViewItem[] { + listViewItem1, + listViewItem2, + listViewItem3}); + this.listView1.Location = new System.Drawing.Point(244, 234); + this.listView1.Name = "listView1"; + this.listView1.Size = new System.Drawing.Size(200, 85); + this.listView1.TabIndex = 22; + this.listView1.UseCompatibleStateImageBehavior = false; + this.listView1.View = System.Windows.Forms.View.Details; + // + // columnHeader1 + // + this.columnHeader1.Text = "col1"; + // + // columnHeader2 + // + this.columnHeader2.Text = "col2"; + // + // columnHeader3 + // + this.columnHeader3.Text = "col3"; + // + // label9 + // + this.label9.AutoSize = true; + this.label9.Location = new System.Drawing.Point(242, 211); + this.label9.Name = "label9"; + this.label9.Size = new System.Drawing.Size(52, 12); + this.label9.TabIndex = 20; + this.label9.Text = "listView1"; + // + // cmbListViewView + // + this.cmbListViewView.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; + this.cmbListViewView.FormattingEnabled = true; + this.cmbListViewView.Items.AddRange(new object[] { + "LargeIcon", + "Details", + "SmallIcon", + "List", + "Tile"}); + this.cmbListViewView.Location = new System.Drawing.Point(300, 208); + this.cmbListViewView.Name = "cmbListViewView"; + this.cmbListViewView.Size = new System.Drawing.Size(79, 20); + this.cmbListViewView.TabIndex = 21; + this.cmbListViewView.SelectedIndexChanged += new System.EventHandler(this.cmbListViewView_SelectedIndexChanged); + // + // progressBar1 + // + this.progressBar1.Location = new System.Drawing.Point(151, 254); + this.progressBar1.Maximum = 10; + this.progressBar1.Name = "progressBar1"; + this.progressBar1.Size = new System.Drawing.Size(67, 23); + this.progressBar1.TabIndex = 10; + this.progressBar1.Value = 5; + // + // label10 + // + this.label10.AutoSize = true; + this.label10.Location = new System.Drawing.Point(28, 260); + this.label10.Name = "label10"; + this.label10.Size = new System.Drawing.Size(117, 12); + this.label10.TabIndex = 9; + this.label10.Text = "progressBar1 (0 - 10)"; + // + // trackBar1 + // + this.trackBar1.Location = new System.Drawing.Point(118, 283); + this.trackBar1.Name = "trackBar1"; + this.trackBar1.Size = new System.Drawing.Size(104, 45); + this.trackBar1.TabIndex = 12; + this.trackBar1.Value = 3; + // + // label11 + // + this.label11.AutoSize = true; + this.label11.Location = new System.Drawing.Point(16, 286); + this.label11.Name = "label11"; + this.label11.Size = new System.Drawing.Size(99, 12); + this.label11.TabIndex = 11; + this.label11.Text = "trackBar1 (0 - 10)"; + // + // dateTimePicker1 + // + this.dateTimePicker1.CustomFormat = "yyyy-MM-dd"; + this.dateTimePicker1.Format = System.Windows.Forms.DateTimePickerFormat.Custom; + this.dateTimePicker1.Location = new System.Drawing.Point(530, 28); + this.dateTimePicker1.Name = "dateTimePicker1"; + this.dateTimePicker1.Size = new System.Drawing.Size(114, 19); + this.dateTimePicker1.TabIndex = 24; + // + // label12 + // + this.label12.AutoSize = true; + this.label12.Location = new System.Drawing.Point(458, 9); + this.label12.Name = "label12"; + this.label12.Size = new System.Drawing.Size(90, 12); + this.label12.TabIndex = 23; + this.label12.Text = "dateTimePicker1"; + // + // treeView1 + // + this.treeView1.Location = new System.Drawing.Point(460, 116); + this.treeView1.Name = "treeView1"; + treeNode1.Name = "node0_0"; + treeNode1.Text = "node0_0"; + treeNode2.Name = "node0_1"; + treeNode2.Text = "node0_1"; + treeNode3.Name = "node0"; + treeNode3.Text = "node0"; + treeNode4.Name = "node1_0"; + treeNode4.Text = "node1_0"; + treeNode5.Name = "node1_1"; + treeNode5.Text = "node1_1"; + treeNode6.Name = "node1_2_0"; + treeNode6.Text = "node1_2_0"; + treeNode7.Name = "node1_2"; + treeNode7.Text = "node1_2"; + treeNode8.Name = "node1"; + treeNode8.Text = "node1"; + treeNode9.Name = "node2"; + treeNode9.Text = "node2"; + this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] { + treeNode3, + treeNode8, + treeNode9}); + this.treeView1.Size = new System.Drawing.Size(184, 80); + this.treeView1.TabIndex = 28; + // + // label13 + // + this.label13.AutoSize = true; + this.label13.Location = new System.Drawing.Point(458, 101); + this.label13.Name = "label13"; + this.label13.Size = new System.Drawing.Size(56, 12); + this.label13.TabIndex = 27; + this.label13.Text = "treeView1"; + // + // dataGridView1 + // + this.dataGridView1.AllowUserToAddRows = false; + this.dataGridView1.AllowUserToDeleteRows = false; + this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; + this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { + this.colA, + this.colB, + this.colC}); + this.dataGridView1.Location = new System.Drawing.Point(460, 228); + this.dataGridView1.Name = "dataGridView1"; + this.dataGridView1.RowTemplate.Height = 21; + this.dataGridView1.Size = new System.Drawing.Size(184, 85); + this.dataGridView1.TabIndex = 30; + // + // colA + // + this.colA.HeaderText = "colA"; + this.colA.Name = "colA"; + this.colA.Width = 40; + // + // colB + // + this.colB.HeaderText = "colB"; + this.colB.Name = "colB"; + this.colB.Width = 40; + // + // colC + // + this.colC.HeaderText = "colC"; + this.colC.Name = "colC"; + this.colC.Width = 40; + // + // label14 + // + this.label14.AutoSize = true; + this.label14.Location = new System.Drawing.Point(458, 209); + this.label14.Name = "label14"; + this.label14.Size = new System.Drawing.Size(79, 12); + this.label14.TabIndex = 29; + this.label14.Text = "dataGridView1"; + // + // label15 + // + this.label15.AutoSize = true; + this.label15.Location = new System.Drawing.Point(458, 57); + this.label15.Name = "label15"; + this.label15.Size = new System.Drawing.Size(90, 12); + this.label15.TabIndex = 25; + this.label15.Text = "dateTimePicker2"; + // + // dateTimePicker2 + // + this.dateTimePicker2.Format = System.Windows.Forms.DateTimePickerFormat.Time; + this.dateTimePicker2.Location = new System.Drawing.Point(539, 76); + this.dateTimePicker2.Name = "dateTimePicker2"; + this.dateTimePicker2.Size = new System.Drawing.Size(105, 19); + this.dateTimePicker2.TabIndex = 26; + // + // label16 + // + this.label16.AutoSize = true; + this.label16.Location = new System.Drawing.Point(226, 35); + this.label16.Name = "label16"; + this.label16.Size = new System.Drawing.Size(64, 12); + this.label16.TabIndex = 15; + this.label16.Text = "comboBox2"; + // + // comboBox2 + // + this.comboBox2.FormattingEnabled = true; + this.comboBox2.Items.AddRange(new object[] { + "ItemA", + "ItemB", + "ItemC"}); + this.comboBox2.Location = new System.Drawing.Point(296, 32); + this.comboBox2.Name = "comboBox2"; + this.comboBox2.Size = new System.Drawing.Size(144, 20); + this.comboBox2.TabIndex = 16; + // + // pictureBox1 + // + this.pictureBox1.Location = new System.Drawing.Point(158, 163); + this.pictureBox1.Name = "pictureBox1"; + this.pictureBox1.Size = new System.Drawing.Size(60, 58); + this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; + this.pictureBox1.TabIndex = 30; + this.pictureBox1.TabStop = false; + // + // label17 + // + this.label17.AutoSize = true; + this.label17.Location = new System.Drawing.Point(156, 148); + this.label17.Name = "label17"; + this.label17.Size = new System.Drawing.Size(66, 12); + this.label17.TabIndex = 6; + this.label17.Text = "pictureBox1"; + // + // frmMain + // + this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; + this.ClientSize = new System.Drawing.Size(656, 325); + this.Controls.Add(this.label17); + this.Controls.Add(this.pictureBox1); + this.Controls.Add(this.label16); + this.Controls.Add(this.comboBox2); + this.Controls.Add(this.label15); + this.Controls.Add(this.dateTimePicker2); + this.Controls.Add(this.label14); + this.Controls.Add(this.dataGridView1); + this.Controls.Add(this.label13); + this.Controls.Add(this.treeView1); + this.Controls.Add(this.label12); + this.Controls.Add(this.dateTimePicker1); + this.Controls.Add(this.label11); + this.Controls.Add(this.trackBar1); + this.Controls.Add(this.label10); + this.Controls.Add(this.progressBar1); + this.Controls.Add(this.cmbListViewView); + this.Controls.Add(this.label9); + this.Controls.Add(this.listView1); + this.Controls.Add(this.label8); + this.Controls.Add(this.numericUpDown1); + this.Controls.Add(this.tabControl1); + this.Controls.Add(this.label4); + this.Controls.Add(this.textBox1); + this.Controls.Add(this.label3); + this.Controls.Add(this.listBox1); + this.Controls.Add(this.label2); + this.Controls.Add(this.comboBox1); + this.Controls.Add(this.groupBox2); + this.Controls.Add(this.groupBox1); + this.Controls.Add(this.label1); + this.Controls.Add(this.button1); + this.Name = "frmMain"; + this.Text = "UIAutomation Tester"; + this.Load += new System.EventHandler(this.frmMain_Load); + this.groupBox1.ResumeLayout(false); + this.groupBox1.PerformLayout(); + this.groupBox2.ResumeLayout(false); + this.groupBox2.PerformLayout(); + this.tabControl1.ResumeLayout(false); + this.tabPage1.ResumeLayout(false); + this.tabPage1.PerformLayout(); + this.tabPage2.ResumeLayout(false); + this.tabPage2.PerformLayout(); + this.tabPage3.ResumeLayout(false); + this.tabPage3.PerformLayout(); + ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.trackBar1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); + ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); + this.ResumeLayout(false); + this.PerformLayout(); + + } + + #endregion + + private System.Windows.Forms.Button button1; + private System.Windows.Forms.CheckBox checkBox1; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.GroupBox groupBox1; + private System.Windows.Forms.CheckBox checkBox3; + private System.Windows.Forms.CheckBox checkBox2; + private System.Windows.Forms.GroupBox groupBox2; + private System.Windows.Forms.RadioButton radioButton3; + private System.Windows.Forms.RadioButton radioButton2; + private System.Windows.Forms.RadioButton radioButton1; + private System.Windows.Forms.ComboBox comboBox1; + private System.Windows.Forms.Label label2; + private System.Windows.Forms.ListBox listBox1; + private System.Windows.Forms.Label label3; + private System.Windows.Forms.TextBox textBox1; + private System.Windows.Forms.Label label4; + private System.Windows.Forms.TabControl tabControl1; + private System.Windows.Forms.TabPage tabPage1; + private System.Windows.Forms.Label label5; + private System.Windows.Forms.TabPage tabPage2; + private System.Windows.Forms.Label label6; + private System.Windows.Forms.TabPage tabPage3; + private System.Windows.Forms.Label label7; + private System.Windows.Forms.Button button2; + private System.Windows.Forms.Button button3; + private System.Windows.Forms.Button button4; + private System.Windows.Forms.NumericUpDown numericUpDown1; + private System.Windows.Forms.Label label8; + private System.Windows.Forms.ListView listView1; + private System.Windows.Forms.ColumnHeader columnHeader1; + private System.Windows.Forms.ColumnHeader columnHeader2; + private System.Windows.Forms.ColumnHeader columnHeader3; + private System.Windows.Forms.Label label9; + private System.Windows.Forms.ComboBox cmbListViewView; + private System.Windows.Forms.ProgressBar progressBar1; + private System.Windows.Forms.Label label10; + private System.Windows.Forms.TrackBar trackBar1; + private System.Windows.Forms.Label label11; + private System.Windows.Forms.DateTimePicker dateTimePicker1; + private System.Windows.Forms.Label label12; + private System.Windows.Forms.TreeView treeView1; + private System.Windows.Forms.Label label13; + private System.Windows.Forms.DataGridView dataGridView1; + private System.Windows.Forms.DataGridViewTextBoxColumn colA; + private System.Windows.Forms.DataGridViewTextBoxColumn colB; + private System.Windows.Forms.DataGridViewTextBoxColumn colC; + private System.Windows.Forms.Label label14; + private System.Windows.Forms.Label label15; + private System.Windows.Forms.DateTimePicker dateTimePicker2; + private System.Windows.Forms.Label label16; + private System.Windows.Forms.ComboBox comboBox2; + private System.Windows.Forms.PictureBox pictureBox1; + private System.Windows.Forms.Label label17; + } +} + diff --git a/UIAutomationTester/frmMain.cs b/UIAutomationTester/frmMain.cs new file mode 100644 index 000000000..ad25bc1b5 --- /dev/null +++ b/UIAutomationTester/frmMain.cs @@ -0,0 +1,59 @@ +using System; +using System.Reflection; +using System.Windows.Forms; + +namespace UIAutomationTester +{ + public partial class frmMain : Form + { + public frmMain() + { + InitializeComponent(); + } + + #region Load + private void frmMain_Load(object sender, EventArgs e) + { + var asm = Assembly.GetExecutingAssembly(); + this.Text += " v" + asm.GetName().Version; + + cmbListViewView.SelectedIndex = 1; + + dataGridView1.Rows.Add(new string[] { "A1", "B1", "C1" }); + dataGridView1.Rows.Add(new string[] { "A2", "B2", "C2" }); + dataGridView1.Rows.Add(new string[] { "A3", "B3", "C3" }); + + pictureBox1.Image = Properties.Resources.taskt_logo_alt; + } + #endregion + + #region Buttons + private void button1_Click(object sender, EventArgs e) + { + label1.Text = "button1 Clicked"; + } + + private void button2_Click(object sender, EventArgs e) + { + label1.Text = "button2 Clicked"; + } + + private void button3_Click(object sender, EventArgs e) + { + label1.Text = "button3 Clicked"; + } + + private void button4_Click(object sender, EventArgs e) + { + label1.Text = "button4 Clicked"; + } + #endregion + + #region listView1 + private void cmbListViewView_SelectedIndexChanged(object sender, EventArgs e) + { + listView1.View = (View)cmbListViewView.SelectedIndex; + } + #endregion + } +} diff --git a/UIAutomationTester/frmMain.resx b/UIAutomationTester/frmMain.resx new file mode 100644 index 000000000..9364c4667 --- /dev/null +++ b/UIAutomationTester/frmMain.resx @@ -0,0 +1,129 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + text/microsoft-resx + + + 2.0 + + + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + + + True + + + True + + + True + + \ No newline at end of file diff --git a/taskt-updater/Properties/AssemblyInfo.cs b/taskt-updater/Properties/AssemblyInfo.cs index 1ddd205c1..b98713933 100644 --- a/taskt-updater/Properties/AssemblyInfo.cs +++ b/taskt-updater/Properties/AssemblyInfo.cs @@ -1,5 +1,4 @@ using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following @@ -10,7 +9,7 @@ [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("taskt-updater")] -[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyCopyright("Copyright © 2024")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] @@ -32,5 +31,5 @@ // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: AssemblyVersion("1.3.0.0")] +[assembly: AssemblyFileVersion("1.3.0.0")] diff --git a/taskt-updater/Properties/Resources.resx b/taskt-updater/Properties/Resources.resx index af7dbebba..1af7de150 100644 --- a/taskt-updater/Properties/Resources.resx +++ b/taskt-updater/Properties/Resources.resx @@ -46,7 +46,7 @@ mimetype: application/x-microsoft.net.object.binary.base64 value : The object must be serialized with - : System.Serialization.Formatters.Binary.BinaryFormatter + : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter : and then encoded with base64 encoding. mimetype: application/x-microsoft.net.object.soap.base64 @@ -60,6 +60,7 @@ : and then encoded with base64 encoding. --> + @@ -68,9 +69,10 @@ - + + @@ -85,9 +87,10 @@ - + + @@ -109,9 +112,9 @@ 2.0 - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 + System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 \ No newline at end of file diff --git a/taskt-updater/frmUpdating.Designer.cs b/taskt-updater/frmUpdating.Designer.cs index 76f047d66..2bc09c653 100644 --- a/taskt-updater/frmUpdating.Designer.cs +++ b/taskt-updater/frmUpdating.Designer.cs @@ -87,7 +87,7 @@ private void InitializeComponent() this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "frmUpdating"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "Updating"; + this.Text = "taskt Updater"; this.Load += new System.EventHandler(this.frmUpdating_Load); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); diff --git a/taskt-updater/frmUpdating.cs b/taskt-updater/frmUpdating.cs index cde33e03e..b3fa7aff6 100644 --- a/taskt-updater/frmUpdating.cs +++ b/taskt-updater/frmUpdating.cs @@ -1,20 +1,31 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; using System.IO.Compression; using System.IO; +using System.Reflection; namespace taskt_updater { public partial class frmUpdating : Form { - private const string TASKT_WORK_DIR_NAME = "temp"; + /// + /// update work folder name + /// + private const string TASKT_WORK_FOLDER_NAME = "temp"; + /// + /// taskt Resouces name + /// + private const string TASKT_RESOUCES_FOLDER_NAME = "Resources"; + /// + /// my name + /// + private const string TASKT_UPDATER_NAME = "taskt-updater.exe"; + /// + /// taskt name + /// + private const string TASKT_NAME = "taskt.exe"; string topLevelFolder = Application.StartupPath; string myPath = Application.ExecutablePath; @@ -52,7 +63,8 @@ public frmUpdating(string paramName, string paramValue) private void frmUpdating_Load(object sender, EventArgs e) { - + var asm = Assembly.GetExecutingAssembly(); + this.Text += " v" + asm.GetName().Version; } #endregion @@ -112,7 +124,7 @@ private void bgwUpdate_RunWorkerCompleted(object sender, RunWorkerCompletedEvent string tasktFolder = Directory.GetParent(topLevelFolder).FullName; var copyProcess = new System.Diagnostics.Process(); - copyProcess.StartInfo.FileName = Path.Combine(tasktFolder, TASKT_WORK_DIR_NAME, zipFileName, "Resources", "taskt-updater.exe"); + copyProcess.StartInfo.FileName = Path.Combine(tasktFolder, TASKT_WORK_FOLDER_NAME, zipFileName, TASKT_RESOUCES_FOLDER_NAME, TASKT_UPDATER_NAME); copyProcess.StartInfo.Arguments = "/c \"" + tasktFolder + "\""; copyProcess.Start(); this.Close(); @@ -120,12 +132,18 @@ private void bgwUpdate_RunWorkerCompleted(object sender, RunWorkerCompletedEvent case "/c": string newTasktFolder = Directory.GetParent(topLevelFolder).Parent.Parent.FullName; var removeProcess = new System.Diagnostics.Process(); - removeProcess.StartInfo.FileName = Path.Combine(newTasktFolder, "Resources", "taskt-updater.exe"); + removeProcess.StartInfo.FileName = Path.Combine(newTasktFolder, TASKT_RESOUCES_FOLDER_NAME ,TASKT_UPDATER_NAME); removeProcess.StartInfo.Arguments = "/r \"" + newTasktFolder + "\""; removeProcess.Start(); this.Close(); break; case "/r": + string startTasktFolder = Directory.GetParent(topLevelFolder).FullName; + //DBG + //MessageBox.Show(startTasktFolder); + var tasktProcess = new System.Diagnostics.Process(); + tasktProcess.StartInfo.FileName = Path.Combine(startTasktFolder, TASKT_NAME); + tasktProcess.Start(); this.Close(); break; default: @@ -144,7 +162,7 @@ private void bgwUpdate_RunWorkerCompleted(object sender, RunWorkerCompletedEvent private void DownloadExtractNewRelease(string packageURL) { //define update folder - var tempUpdateFolder = Path.Combine(Directory.GetParent(topLevelFolder).FullName, TASKT_WORK_DIR_NAME); + var tempUpdateFolder = Path.Combine(Directory.GetParent(topLevelFolder).FullName, TASKT_WORK_FOLDER_NAME); // DBG //MessageBox.Show("temp: " + tempUpdateFolder + "\r\nURL: " + packageURL); @@ -211,7 +229,7 @@ private void RemoveDownloadRelease() { bgwUpdate.ReportProgress(0, "Remove Downloaded Files..."); - string tempFolder = Path.Combine(Directory.GetParent(topLevelFolder).FullName, TASKT_WORK_DIR_NAME); + string tempFolder = Path.Combine(Directory.GetParent(topLevelFolder).FullName, TASKT_WORK_FOLDER_NAME); // DBG //MessageBox.Show("temp: " + tempFolder); diff --git a/taskt-updater/taskt-updater.csproj b/taskt-updater/taskt-updater.csproj index c1a873b55..0c67f8e8c 100644 --- a/taskt-updater/taskt-updater.csproj +++ b/taskt-updater/taskt-updater.csproj @@ -45,7 +45,7 @@ bin\Release\ TRACE prompt - 4 + 5 x64 diff --git a/taskt.sln b/taskt.sln index 2d7b739fd..bbb3adda1 100644 --- a/taskt.sln +++ b/taskt.sln @@ -7,6 +7,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "taskt", "taskt\taskt.csproj EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "taskt-updater", "taskt-updater\taskt-updater.csproj", "{3FC72D0C-D083-44C4-96E9-13FE599F8E0E}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "UIAutomationTester", "UIAutomationTester\UIAutomationTester.csproj", "{2DB516FB-73C2-4C62-B465-403A9054D701}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -31,6 +33,14 @@ Global {3FC72D0C-D083-44C4-96E9-13FE599F8E0E}.Release|Any CPU.Build.0 = Release|Any CPU {3FC72D0C-D083-44C4-96E9-13FE599F8E0E}.Release|x64.ActiveCfg = Release|x64 {3FC72D0C-D083-44C4-96E9-13FE599F8E0E}.Release|x64.Build.0 = Release|x64 + {2DB516FB-73C2-4C62-B465-403A9054D701}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2DB516FB-73C2-4C62-B465-403A9054D701}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2DB516FB-73C2-4C62-B465-403A9054D701}.Debug|x64.ActiveCfg = Debug|Any CPU + {2DB516FB-73C2-4C62-B465-403A9054D701}.Debug|x64.Build.0 = Debug|Any CPU + {2DB516FB-73C2-4C62-B465-403A9054D701}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2DB516FB-73C2-4C62-B465-403A9054D701}.Release|Any CPU.Build.0 = Release|Any CPU + {2DB516FB-73C2-4C62-B465-403A9054D701}.Release|x64.ActiveCfg = Release|Any CPU + {2DB516FB-73C2-4C62-B465-403A9054D701}.Release|x64.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/taskt/App.config b/taskt/App.config index b94759129..1e2bb3463 100644 --- a/taskt/App.config +++ b/taskt/App.config @@ -44,6 +44,26 @@ limitations under the License. + + + + + + + + + + + + + + + + + + + + diff --git a/taskt/Core/ApplicationSettings.cs b/taskt/Core/ApplicationSettings.cs deleted file mode 100644 index 8aeb0e91d..000000000 --- a/taskt/Core/ApplicationSettings.cs +++ /dev/null @@ -1,606 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Xml.Serialization; -using taskt.Core.IO; - -namespace taskt.Core -{ - /// - /// Defines settings for the entire application - /// - [Serializable] - public class ApplicationSettings - { - public ServerSettings ServerSettings { get; set; } = new ServerSettings(); - public EngineSettings EngineSettings { get; set; } = new EngineSettings(); - public ClientSettings ClientSettings { get; set; } = new ClientSettings(); - public LocalListenerSettings ListenerSettings { get; set; } = new LocalListenerSettings(); - public ApplicationSettings() - { - - } - - public void Save(ApplicationSettings appSettings) - { - //create settings directory - - var settingsDir = Core.IO.Folders.GetFolder(Folders.FolderType.SettingsFolder); - - //if directory does not exist then create directory - if (!System.IO.Directory.Exists(settingsDir)) - { - System.IO.Directory.CreateDirectory(settingsDir); - } - - //create file path - var filePath = System.IO.Path.Combine(settingsDir, "AppSettings.xml"); - - ////create filestream - //var fileStream = System.IO.File.Create(filePath); - - ////output to xml file - //XmlSerializer serializer = new XmlSerializer(typeof(ApplicationSettings)); - //serializer.Serialize(fileStream, appSettings); - //fileStream.Close(); - SaveAs(appSettings, filePath); - } - - public static void SaveAs(ApplicationSettings appSettings, string filePath) - { - using (FileStream fileStream = System.IO.File.Create(filePath)) - { - XmlSerializer serializer = new XmlSerializer(typeof(ApplicationSettings)); - serializer.Serialize(fileStream, appSettings); - fileStream.Close(); - } - } - - public ApplicationSettings GetOrCreateApplicationSettings() - { - //create settings directory - var settingsDir = Core.IO.Folders.GetFolder(Folders.FolderType.SettingsFolder); - - //create file path - var filePath = System.IO.Path.Combine(settingsDir, "AppSettings.xml"); - - ApplicationSettings appSettings; - if (System.IO.File.Exists(filePath)) - { - ////open file and return it or return new settings on error - //var fileStream = System.IO.File.Open(filePath, FileMode.Open); - - //try - //{ - // XmlSerializer serializer = new XmlSerializer(typeof(ApplicationSettings)); - // appSettings = (ApplicationSettings)serializer.Deserialize(fileStream); - //} - //catch (Exception) - //{ - // appSettings = new ApplicationSettings(); - //} - - //fileStream.Close(); - try - { - appSettings = Open(filePath); - } - catch - { - appSettings = new ApplicationSettings(); - } - } - else - { - appSettings = new ApplicationSettings(); - } - - return appSettings; - } - - public static ApplicationSettings Open(string filePath) - { - ApplicationSettings appSettings = null; - using (FileStream fileStream = System.IO.File.Open(filePath, FileMode.Open)) - { - try - { - XmlSerializer serializer = new XmlSerializer(typeof(ApplicationSettings)); - appSettings = (ApplicationSettings)serializer.Deserialize(fileStream); - } - catch (Exception ex) - { - //appSettings = new ApplicationSettings(); - throw ex; - } - finally - { - fileStream.Close(); - } - } - return appSettings; - } - - public string replaceApplicationKeyword(string targetString) - { - return this.ClientSettings.replaceClientKeyword(this.EngineSettings.replaceEngineKeyword(targetString)); - } - } - /// - /// Defines Server settings for tasktServer if using the server component to manage the client - /// - [Serializable] - public class ServerSettings - { - public bool ServerConnectionEnabled { get; set; } - public bool ConnectToServerOnStartup { get; set; } - public bool RetryServerConnectionOnFail { get; set; } - public bool BypassCertificateValidation { get; set; } - public string ServerURL { get; set; } - public string ServerPublicKey { get; set; } - public string HTTPServerURL { get; set; } - public Guid HTTPGuid { get; set; } - - public ServerSettings() - { - HTTPServerURL = "https://localhost:44377/"; - } - } - /// - /// Defines engine settings which can be managed by the user - /// - [Serializable] - public class EngineSettings - { - public bool ShowDebugWindow { get; set; } - public bool AutoCloseDebugWindow { get; set; } - public bool EnableDiagnosticLogging { get; set; } - public bool ShowAdvancedDebugOutput { get; set; } - public bool CreateMissingVariablesDuringExecution { get; set; } - public bool TrackExecutionMetrics { get; set; } - public string VariableStartMarker { get; set; } - public string VariableEndMarker { get; set; } - public System.Windows.Forms.Keys CancellationKey { get; set; } - private int _delayBetweenCommands; - public int DelayBetweenCommands - { - get - { - return this._delayBetweenCommands; - } - set - { - if (value > 0) - { - _delayBetweenCommands = value; - } - } - } - public bool OverrideExistingAppInstances { get; set; } - public bool AutoCloseMessagesOnServerExecution { get; set; } - public bool AutoCloseDebugWindowOnServerExecution { get; set; } - public bool AutoCalcVariables { get; set; } - public string CurrentWindowKeyword { get; set; } - public string DesktopKeyword { get; set; } - public string AllWindowsKeyword { get; set; } - public string CurrentWindowPositionKeyword { get; set; } - public string CurrentWindowXPositionKeyword { get; set; } - public string CurrentWindowYPositionKeyword { get; set; } - public string CurrentWorksheetKeyword { get; set; } - public string NextWorksheetKeyword { get; set; } - public string PreviousWorksheetKeyword { get; set; } - public bool ExportIntermediateXML { get; set; } - public bool UseNewParser { get; set; } - public bool IgnoreFirstVariableMarkerInOutputParameter { get; set; } - public int MaxFileCounter { get; set; } - - private static string InterStartVariableMaker = "{{{"; - private static string InterEndVariableMaker = "}}}"; - private static string InterCurrentWindowKeyword = "%kwd_current_window%"; - private static string InterDesktopKeyword = "%kwd_desktop%"; - private static string InterAllWindowsKeyword = "%kwd_all_windows%"; - private static string InterCurrentWindowPositionKeyword = "%kwd_current_position%"; - private static string InterCurrentWindowXPositionKeyword = "%kwd_current_xposition%"; - private static string InterCurrentWindowYPositionKeyword = "%kwd_current_yposition%"; - private static string InterCurrentWorksheetKeyword = "%kwd_current_worksheet%"; - private static string InterNextWorksheetKeyword = "%kwd_next_worksheet%"; - private static string InterPreviousWorksheetKeyword = "%kwd_previous_worksheet%"; - - private static string[] m_KeyNameList = new string[] - { - "BACKSPACE", "BS", "BKSP", - "BREAK", - "CAPSLOCK", - "DELETE", "DEL", - "UP", "DOWN", "LEFT", "RIGHT", - "END", - "ENTER", - "INSERT", "INS", - "NUMLOCK", - "PGDN", - "PGUP", - "SCROLLROCK", - "TAB", - "F1", "F2", "F3", "F4", "F5", "F6", - "F7", "F8", "F9", "F10", "F11", "F12", - "ADD", "SUBTRACT", "MULTIPLY", "DIVIDE", - "WIN_KEY" - }; - private static string[] m_DisallowVariableCharList = new string[] - { - "+", "-", "*", "%", - "[", "]", "{", "}", - ".", - " ", - "\u2983", "\u2984", - "\U0001D542", "\U0001D54E" - }; - - public EngineSettings() - { - ShowDebugWindow = true; - AutoCloseDebugWindow = true; - EnableDiagnosticLogging = true; - ShowAdvancedDebugOutput = false; - CreateMissingVariablesDuringExecution = true; - TrackExecutionMetrics = true; - VariableStartMarker = "{"; - VariableEndMarker = "}"; - CancellationKey = System.Windows.Forms.Keys.Pause; - DelayBetweenCommands = 250; - OverrideExistingAppInstances = false; - AutoCloseMessagesOnServerExecution = true; - AutoCloseDebugWindowOnServerExecution = true; - AutoCalcVariables = true; - CurrentWindowKeyword = "Current Window"; - DesktopKeyword = "Desktop"; - AllWindowsKeyword = "All Windows"; - CurrentWindowPositionKeyword = "Current Position"; - CurrentWindowXPositionKeyword = "Current XPosition"; - CurrentWindowYPositionKeyword = "Current YPosition"; - CurrentWorksheetKeyword = "Current Sheet"; - NextWorksheetKeyword = "Next Sheet"; - PreviousWorksheetKeyword = "Previous Sheet"; - ExportIntermediateXML = true; - UseNewParser = true; - IgnoreFirstVariableMarkerInOutputParameter = true; - MaxFileCounter = 999; - } - - public string[] KeyNameList() - { - return m_KeyNameList; - } - - public string[] DisallowVariableCharList() - { - return m_DisallowVariableCharList; - } - public string replaceEngineKeyword(string targetString) - { - return targetString.Replace(InterStartVariableMaker, this.VariableStartMarker) - .Replace(InterEndVariableMaker, this.VariableEndMarker) - .Replace(InterCurrentWindowKeyword, this.CurrentWindowKeyword) - .Replace(InterCurrentWindowPositionKeyword, this.CurrentWindowPositionKeyword) - .Replace(InterCurrentWindowXPositionKeyword, this.CurrentWindowXPositionKeyword) - .Replace(InterCurrentWindowYPositionKeyword, this.CurrentWindowYPositionKeyword) - .Replace(InterCurrentWorksheetKeyword, this.CurrentWorksheetKeyword) - .Replace(InterNextWorksheetKeyword, this.NextWorksheetKeyword) - .Replace(InterPreviousWorksheetKeyword, this.PreviousWorksheetKeyword); - } - - public string convertToIntermediate(string targetString) - { - return targetString.Replace(this.VariableStartMarker, "\u2983") - .Replace(this.VariableEndMarker, "\u2984"); - } - - public string convertToRaw(string targetString) - { - return targetString.Replace("\u2983", this.VariableStartMarker) - .Replace("\u2984", this.VariableEndMarker); - } - - public string convertToIntermediateExcelSheet(string targetString) - { - return convertToIntermediate( - targetString.Replace(this.CurrentWorksheetKeyword, wrapIntermediateKeyword(InterCurrentWorksheetKeyword)) - .Replace(this.NextWorksheetKeyword, wrapIntermediateKeyword(InterNextWorksheetKeyword)) - .Replace(this.PreviousWorksheetKeyword, wrapIntermediateKeyword(InterPreviousWorksheetKeyword)) - ); - } - - public string convertToRawExcelSheet(string targetString) - { - return convertToRaw( - targetString.Replace(wrapIntermediateKeyword(InterCurrentWorksheetKeyword), this.CurrentWorksheetKeyword) - .Replace(wrapIntermediateKeyword(InterNextWorksheetKeyword), this.NextWorksheetKeyword) - .Replace(wrapIntermediateKeyword(InterPreviousWorksheetKeyword), this.PreviousWorksheetKeyword) - ); - } - - public string convertToIntermediateWindowName(string targetString) - { - return convertToIntermediate( - targetString.Replace(this.CurrentWindowKeyword, wrapIntermediateKeyword(InterCurrentWindowKeyword)) - .Replace(this.DesktopKeyword, wrapIntermediateKeyword(InterDesktopKeyword)) - .Replace(this.AllWindowsKeyword, wrapIntermediateKeyword(InterAllWindowsKeyword)) - ); - } - - public string convertToRawWindowName(string targetString) - { - return convertToRaw( - targetString.Replace(wrapIntermediateKeyword(InterCurrentWindowKeyword), this.CurrentWindowKeyword) - .Replace(wrapIntermediateKeyword(InterDesktopKeyword), this.DesktopKeyword) - .Replace(wrapIntermediateKeyword(InterAllWindowsKeyword), this.AllWindowsKeyword) - ); - } - - public string convertToIntermediateWindowPosition(string targetString) - { - return convertToIntermediate( - targetString.Replace(this.CurrentWindowPositionKeyword, wrapIntermediateKeyword(InterCurrentWindowPositionKeyword)) - .Replace(this.CurrentWindowXPositionKeyword, wrapIntermediateKeyword(InterCurrentWindowXPositionKeyword)) - .Replace(this.CurrentWindowYPositionKeyword, wrapIntermediateKeyword(InterCurrentWindowYPositionKeyword)) - ); - } - - public string convertToRawWindowPosition(string targetString) - { - return convertToRaw( - targetString.Replace(wrapIntermediateKeyword(InterCurrentWindowPositionKeyword), this.CurrentWindowPositionKeyword) - .Replace(wrapIntermediateKeyword(InterCurrentWindowXPositionKeyword), this.CurrentWindowXPositionKeyword) - .Replace(wrapIntermediateKeyword(InterCurrentWindowYPositionKeyword), this.CurrentWindowYPositionKeyword) - ); - } - - public string convertToIntermediateVariableParser(string targetString, List variables) - { - Core.Automation.Engine.AutomationEngineInstance engine = new Automation.Engine.AutomationEngineInstance(false); - engine.engineSettings = this; - engine.VariableList = variables; - return Core.ExtensionMethods.ConvertToUserVariable_Intermediate(targetString, engine); - } - - public string wrapVariableMarker(string variableName) - { - return this.VariableStartMarker + variableName + this.VariableEndMarker; - } - - public string unwrapVariableMarker(string variableName) - { - if (this.isWrappedVariableMarker(variableName)) - { - string rmvSt = variableName.Substring(this.VariableStartMarker.Length); - return rmvSt.Substring(0, rmvSt.Length - this.VariableEndMarker.Length); - } - else - { - return variableName; - } - } - - public bool isWrappedVariableMarker(string variableName) - { - return (variableName.StartsWith(this.VariableStartMarker) && variableName.EndsWith(this.VariableEndMarker)); - } - - public string wrapIntermediateVariableMaker(string variableName) - { - return "\u2983" + variableName + "\u2984"; - } - - private static string wrapIntermediateKeyword(string kw) - { - return "\U0001D542" + kw + "\U0001D54E"; - } - - public bool isValidVariableName(string vName) - { - foreach(string s in m_KeyNameList) - { - if (vName == s) - { - return false; - } - } - foreach(string s in m_DisallowVariableCharList) - { - if (vName.Contains(s)) - { - return false; - } - } - if (vName.StartsWith("__INNER_")) - { - return false; - } - return true; - } - } - /// - /// Defines application/client-level settings which can be managed by the user - /// - [Serializable] - public class ClientSettings - { - public bool AntiIdleWhileOpen { get; set; } - public string RootFolder { get; set; } - public bool MinimizeToTray { get; set; } - public string AttendedTasksFolder { get; set; } - public string StartupMode { get; set; } - public bool PreloadBuilderCommands { get; set; } - public bool UseSlimActionBar { get; set; } - public bool InsertCommandsInline { get; set; } - public bool EnableSequenceDragDrop { get; set; } - public bool InsertVariableAtCursor { get; set; } - public bool InsertElseAutomatically { get; set; } - public bool InsertCommentIfLoopAbove { get; set; } - public bool GroupingBySubgroup { get; set; } - public bool DontShowValidationMessage { get; set; } - public bool ShowPoliteTextInDescription { get; set; } - public bool ShowSampleUsageInDescription { get; set; } - public bool ShowDefaultValueInDescription { get; set; } - public bool ShowIndentLine { get; set; } - public bool ShowScriptMiniMap { get; set; } - private int _IndentWidth = 16; - public int IndentWidth - { - get - { - return this._IndentWidth; - } - set - { - if (value >= 1 && value <= 32) - { - this._IndentWidth = value; - } - } - } - public string DefaultBrowserInstanceName { get; set; } - public string DefaultStopWatchInstanceName { get; set; } - public string DefaultExcelInstanceName { get; set; } - public string DefaultWordInstanceName { get; set; } - public string DefaultDBInstanceName { get; set; } - public string DefaultNLGInstanceName { get; set; } - private string _InstanceNameOrder = "Creation Frequently"; - public string InstanceNameOrder - { - get - { - return this._InstanceNameOrder; - } - set - { - switch (value.ToLower()) - { - case "creation frequently": - case "by name": - case "frequency of use": - case "no sorting": - this._InstanceNameOrder = value; - break; - default: - this._InstanceNameOrder = "Frequency of use"; - break; - } - } - } - - public bool DontShowDefaultInstanceWhenMultipleItemsExists { get; set; } - - public bool SearchTargetGroupName { get; set; } - public bool SearchTargetSubGroupName { get; set; } - public bool SearchGreedlyGroupName { get; set; } - public bool SearchGreedlySubGroupName { get; set; } - - public bool ShowCommandSearchBar { get; set; } - - public bool HideNotifyAutomatically { get; set; } - - public bool RememberCommandEditorSizeAndPosition { get; set; } - - public bool CheckForUpdateAtStartup { get; set; } - public bool SkipBetaVersionUpdate { get; set; } - - private static string InterDefaultBrowserInstanceNameKeyword = "%kwd_default_browser_instance%"; - private static string InterDefaultStopWatchInstanceNameKeyword = "%kwd_default_stopwatch_instance%"; - private static string InterDefaultExcelInstanceNameKeyword = "%kwd_default_excel_instance%"; - private static string InterDefaultWordInstanceNameKeyword = "%kwd_default_word_instance%"; - private static string InterDefaultDBInstanceNameKeyword = "%kwd_default_db_instance%"; - private static string InterDefaultNLGInstanceNameKeyword = "%kwd_default_nlg_instance%"; - - public ClientSettings() - { - MinimizeToTray = false; - AntiIdleWhileOpen = false; - RootFolder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "taskt"); - StartupMode = "Builder Mode"; - AttendedTasksFolder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "taskt", "My Scripts"); - PreloadBuilderCommands = false; - UseSlimActionBar = true; - InsertCommandsInline = true; - EnableSequenceDragDrop = true; - InsertVariableAtCursor = true; - InsertElseAutomatically = false; - InsertCommentIfLoopAbove = false; - GroupingBySubgroup = true; - DontShowValidationMessage = false; - ShowPoliteTextInDescription = true; - ShowSampleUsageInDescription = true; - ShowDefaultValueInDescription = true; - ShowIndentLine = true; - ShowScriptMiniMap = false; - DefaultBrowserInstanceName = "RPABrowser"; - DefaultStopWatchInstanceName = "RPAStopwatch"; - DefaultExcelInstanceName = "RPAExcel"; - DefaultWordInstanceName = "RPAWord"; - DefaultDBInstanceName = "RPADB"; - DefaultNLGInstanceName = "nlgDefaultInstance"; - DontShowDefaultInstanceWhenMultipleItemsExists = false; - - SearchTargetGroupName = true; - SearchTargetSubGroupName = false; - SearchGreedlyGroupName = true; - SearchGreedlySubGroupName = false; - - ShowCommandSearchBar = false; - HideNotifyAutomatically = true; - RememberCommandEditorSizeAndPosition = true; - - CheckForUpdateAtStartup = true; - SkipBetaVersionUpdate = true; - } - - public string replaceClientKeyword(string targetString) - { - return targetString.Replace(InterDefaultBrowserInstanceNameKeyword, this.DefaultBrowserInstanceName) - .Replace(InterDefaultStopWatchInstanceNameKeyword, this.DefaultStopWatchInstanceName) - .Replace(InterDefaultExcelInstanceNameKeyword, this.DefaultExcelInstanceName) - .Replace(InterDefaultWordInstanceNameKeyword, this.DefaultWordInstanceName) - .Replace(InterDefaultDBInstanceNameKeyword, this.DefaultDBInstanceName) - .Replace(InterDefaultNLGInstanceNameKeyword, this.DefaultNLGInstanceName); - } - } - /// - /// Defines Server settings for tasktServer if using the server component to manage the client - /// - [Serializable] - public class LocalListenerSettings - { - public bool StartListenerOnStartup { get; set; } - public bool LocalListeningEnabled { get; set; } - public bool RequireListenerAuthenticationKey { get; set; } - public int ListeningPort { get; set; } - public string AuthKey { get; set; } - public bool EnableWhitelist { get; set; } - public string IPWhiteList { get; set; } - public LocalListenerSettings() - { - StartListenerOnStartup = false; - LocalListeningEnabled = false; - RequireListenerAuthenticationKey = false; - EnableWhitelist = false; - ListeningPort = 19312; - AuthKey = Guid.NewGuid().ToString(); - IPWhiteList = ""; - } - } - - [Serializable] - public class WhiteListIP - { - string _value; - public WhiteListIP(string s) - { - _value = s; - } - public string Value { get { return _value; } set { _value = value; } } - } -} diff --git a/taskt/Core/ApplicationSettings/ApplicationSettings.cs b/taskt/Core/ApplicationSettings/ApplicationSettings.cs new file mode 100644 index 000000000..81281dca0 --- /dev/null +++ b/taskt/Core/ApplicationSettings/ApplicationSettings.cs @@ -0,0 +1,129 @@ +using System; +using System.IO; +using System.Xml.Serialization; +using taskt.Core.IO; + +namespace taskt.Core +{ + /// + /// Defines settings for the entire application + /// + [Serializable] + public class ApplicationSettings + { + public ServerSettings ServerSettings { get; set; } = new ServerSettings(); + public EngineSettings EngineSettings { get; set; } = new EngineSettings(); + public ClientSettings ClientSettings { get; set; } = new ClientSettings(); + public LocalListenerSettings ListenerSettings { get; set; } = new LocalListenerSettings(); + public ApplicationSettings() + { + } + + public void Save(ApplicationSettings appSettings) + { + //create settings directory + + //var settingsDir = Folders.GetFolder(Folders.FolderType.SettingsFolder); + var settingsDir = Folders.GetSettingsFolderPath(); + + //if directory does not exist then create directory + if (!Directory.Exists(settingsDir)) + { + Directory.CreateDirectory(settingsDir); + } + + //create file path + var filePath = Path.Combine(settingsDir, "AppSettings.xml"); + + ////create filestream + //var fileStream = System.IO.File.Create(filePath); + + ////output to xml file + //XmlSerializer serializer = new XmlSerializer(typeof(ApplicationSettings)); + //serializer.Serialize(fileStream, appSettings); + //fileStream.Close(); + SaveAs(appSettings, filePath); + } + + public static void SaveAs(ApplicationSettings appSettings, string filePath) + { + using (FileStream fileStream = File.Create(filePath)) + { + XmlSerializer serializer = new XmlSerializer(typeof(ApplicationSettings)); + serializer.Serialize(fileStream, appSettings); + fileStream.Close(); + } + } + + public ApplicationSettings GetOrCreateApplicationSettings() + { + //create settings directory + //var settingsDir = Folders.GetFolder(Folders.FolderType.SettingsFolder); + //var settingsDir = Folders.GetSettingsFolderPath(); + + //create file path + var filePath = Path.Combine(Folders.GetSettingsFolderPath(), "AppSettings.xml"); + + ApplicationSettings appSettings; + if (File.Exists(filePath)) + { + ////open file and return it or return new settings on error + //var fileStream = System.IO.File.Open(filePath, FileMode.Open); + + //try + //{ + // XmlSerializer serializer = new XmlSerializer(typeof(ApplicationSettings)); + // appSettings = (ApplicationSettings)serializer.Deserialize(fileStream); + //} + //catch (Exception) + //{ + // appSettings = new ApplicationSettings(); + //} + + //fileStream.Close(); + try + { + appSettings = Open(filePath); + } + catch + { + appSettings = new ApplicationSettings(); + } + } + else + { + appSettings = new ApplicationSettings(); + } + + return appSettings; + } + + public static ApplicationSettings Open(string filePath) + { + ApplicationSettings appSettings = null; + using (FileStream fileStream = File.Open(filePath, FileMode.Open)) + { + try + { + XmlSerializer serializer = new XmlSerializer(typeof(ApplicationSettings)); + appSettings = (ApplicationSettings)serializer.Deserialize(fileStream); + } + catch (Exception ex) + { + //appSettings = new ApplicationSettings(); + throw ex; + } + finally + { + fileStream.Close(); + } + } + return appSettings; + } + + //public string replaceApplicationKeyword(string targetString) + //{ + // return this.ClientSettings.replaceClientKeyword(this.EngineSettings.replaceEngineKeyword(targetString)); + //} + } +} diff --git a/taskt/Core/ApplicationSettings/ClientSettings.cs b/taskt/Core/ApplicationSettings/ClientSettings.cs new file mode 100644 index 000000000..5f67382a9 --- /dev/null +++ b/taskt/Core/ApplicationSettings/ClientSettings.cs @@ -0,0 +1,239 @@ +using System; +using System.IO; + +namespace taskt.Core +{ + /// + /// Defines application/client-level settings which can be managed by the user + /// + [Serializable] + public class ClientSettings + { + public bool AntiIdleWhileOpen { get; set; } + public string RootFolder { get; set; } + public bool MinimizeToTray { get; set; } + public string AttendedTasksFolder { get; set; } + public string StartupMode { get; set; } + public bool PreloadBuilderCommands { get; set; } + public bool UseSlimActionBar { get; set; } + public bool InsertCommandsInline { get; set; } + public bool EnableSequenceDragDrop { get; set; } + public bool InsertVariableAtCursor { get; set; } + public bool InsertElseAutomatically { get; set; } + public bool InsertCommentIfLoopAbove { get; set; } + public bool GroupingBySubgroup { get; set; } + public bool DontShowValidationMessage { get; set; } + public bool ShowPoliteTextInDescription { get; set; } + public bool ShowSampleUsageInDescription { get; set; } + public bool ShowDefaultValueInDescription { get; set; } + public bool ShowIndentLine { get; set; } + public bool ShowScriptMiniMap { get; set; } + private int _IndentWidth = 16; + public int IndentWidth + { + get + { + return this._IndentWidth; + } + set + { + if (value >= 1 && value <= 32) + { + this._IndentWidth = value; + } + } + } + public string DefaultBrowserInstanceName { get; set; } + public string DefaultStopWatchInstanceName { get; set; } + public string DefaultExcelInstanceName { get; set; } + public string DefaultWordInstanceName { get; set; } + public string DefaultDBInstanceName { get; set; } + public string DefaultNLGInstanceName { get; set; } + private string _InstanceNameOrder = "Creation Frequently"; + public string InstanceNameOrder + { + get + { + return this._InstanceNameOrder; + } + set + { + switch (value.ToLower()) + { + case "creation frequently": + case "by name": + case "frequency of use": + case "no sorting": + this._InstanceNameOrder = value; + break; + default: + this._InstanceNameOrder = "Frequency of use"; + break; + } + } + } + + public bool DontShowDefaultInstanceWhenMultipleItemsExists { get; set; } + + public bool SearchTargetGroupName { get; set; } + public bool SearchTargetSubGroupName { get; set; } + public bool SearchGreedlyGroupName { get; set; } + public bool SearchGreedlySubGroupName { get; set; } + + public bool ShowCommandSearchBar { get; set; } + + public bool HideNotifyAutomatically { get; set; } + + public bool RememberCommandEditorSizeAndPosition { get; set; } + + public bool RememberSupplementFormsForCommandEditorPosition { get; set; } + + public bool CheckForUpdateAtStartup { get; set; } + public bool SkipBetaVersionUpdate { get; set; } + + public bool EnabledAutoSave { get; set; } + + private int _AutoSaveInterval; + public int AutoSaveInterval + { + get + { + return _AutoSaveInterval; + } + set + { + if (value >= 1 && value <= 120) + { + _AutoSaveInterval = value; + } + } + } + + private int _RemoveAutoSaveFileDays; + public int RemoveAutoSaveFileDays + { + get + { + return _RemoveAutoSaveFileDays; + } + set + { + if (value > 1) + { + _RemoveAutoSaveFileDays = value; + } + } + } + + private int _RemoveRunWithoutSavingFileDays; + public int RemoveRunWithtoutSavingFileDays + { + get + { + return _RemoveRunWithoutSavingFileDays; + } + set + { + if (value > 1) + { + _RemoveRunWithoutSavingFileDays = value; + } + } + } + + private int _RemoveBeforeConvertedFileDays; + public int RemoveBeforeConvertedFileDays + { + get + { + return _RemoveBeforeConvertedFileDays; + } + set + { + if (value > 1) + { + _RemoveBeforeConvertedFileDays = value; + } + } + } + + public bool SupportIECommand { get; set; } + + public bool ChangeItemsWithWheelWhenNotForcused { get; set; } + + public bool DisplayNumberBeforeParameterDescription { get; set; } + + //private static readonly string InterDefaultBrowserInstanceNameKeyword = "%kwd_default_browser_instance%"; + //private static readonly string InterDefaultStopWatchInstanceNameKeyword = "%kwd_default_stopwatch_instance%"; + //private static readonly string InterDefaultExcelInstanceNameKeyword = "%kwd_default_excel_instance%"; + //private static readonly string InterDefaultWordInstanceNameKeyword = "%kwd_default_word_instance%"; + //private static readonly string InterDefaultDBInstanceNameKeyword = "%kwd_default_db_instance%"; + //private static readonly string InterDefaultNLGInstanceNameKeyword = "%kwd_default_nlg_instance%"; + + public ClientSettings() + { + MinimizeToTray = false; + AntiIdleWhileOpen = false; + RootFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "taskt"); + StartupMode = "Builder Mode"; + AttendedTasksFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "taskt", "My Scripts"); + PreloadBuilderCommands = false; + UseSlimActionBar = true; + InsertCommandsInline = true; + EnableSequenceDragDrop = true; + InsertVariableAtCursor = true; + InsertElseAutomatically = false; + InsertCommentIfLoopAbove = false; + GroupingBySubgroup = true; + DontShowValidationMessage = false; + ShowPoliteTextInDescription = true; + ShowSampleUsageInDescription = true; + ShowDefaultValueInDescription = true; + ShowIndentLine = true; + ShowScriptMiniMap = false; + DefaultBrowserInstanceName = "RPABrowser"; + DefaultStopWatchInstanceName = "RPAStopwatch"; + DefaultExcelInstanceName = "RPAExcel"; + DefaultWordInstanceName = "RPAWord"; + DefaultDBInstanceName = "RPADB"; + DefaultNLGInstanceName = "nlgDefaultInstance"; + DontShowDefaultInstanceWhenMultipleItemsExists = false; + + SearchTargetGroupName = true; + SearchTargetSubGroupName = false; + SearchGreedlyGroupName = true; + SearchGreedlySubGroupName = false; + + ShowCommandSearchBar = false; + HideNotifyAutomatically = true; + RememberCommandEditorSizeAndPosition = true; + RememberSupplementFormsForCommandEditorPosition = true; + + CheckForUpdateAtStartup = true; + SkipBetaVersionUpdate = true; + + EnabledAutoSave = true; + AutoSaveInterval = 5; + RemoveAutoSaveFileDays = 7; + + RemoveRunWithtoutSavingFileDays = 30; + + RemoveBeforeConvertedFileDays = 30; + + SupportIECommand = false; + + ChangeItemsWithWheelWhenNotForcused = false; + DisplayNumberBeforeParameterDescription = true; + } + + //public string replaceClientKeyword(string targetString) + //{ + // return targetString.Replace(InterDefaultBrowserInstanceNameKeyword, this.DefaultBrowserInstanceName) + // .Replace(InterDefaultStopWatchInstanceNameKeyword, this.DefaultStopWatchInstanceName) + // .Replace(InterDefaultExcelInstanceNameKeyword, this.DefaultExcelInstanceName) + // .Replace(InterDefaultWordInstanceNameKeyword, this.DefaultWordInstanceName) + // .Replace(InterDefaultDBInstanceNameKeyword, this.DefaultDBInstanceName) + // .Replace(InterDefaultNLGInstanceNameKeyword, this.DefaultNLGInstanceName); + //} + } +} diff --git a/taskt/Core/ApplicationSettings/EngineSettings.cs b/taskt/Core/ApplicationSettings/EngineSettings.cs new file mode 100644 index 000000000..333f31969 --- /dev/null +++ b/taskt/Core/ApplicationSettings/EngineSettings.cs @@ -0,0 +1,286 @@ +using System; +using System.Collections.Generic; + +namespace taskt.Core +{ + /// + /// Defines engine settings which can be managed by the user + /// + [Serializable] + public class EngineSettings + { + public bool ShowDebugWindow { get; set; } + public bool AutoCloseDebugWindow { get; set; } + public bool EnableDiagnosticLogging { get; set; } + public bool ShowAdvancedDebugOutput { get; set; } + public bool CreateMissingVariablesDuringExecution { get; set; } + public bool TrackExecutionMetrics { get; set; } + public string VariableStartMarker { get; set; } + public string VariableEndMarker { get; set; } + public System.Windows.Forms.Keys CancellationKey { get; set; } + private int _delayBetweenCommands; + public int DelayBetweenCommands + { + get + { + return this._delayBetweenCommands; + } + set + { + if (value > 0) + { + _delayBetweenCommands = value; + } + } + } + public bool OverrideExistingAppInstances { get; set; } + public bool AutoCloseMessagesOnServerExecution { get; set; } + public bool AutoCloseDebugWindowOnServerExecution { get; set; } + public bool AutoCalcVariables { get; set; } + public string CurrentWindowKeyword { get; set; } + public string DesktopKeyword { get; set; } + public string AllWindowsKeyword { get; set; } + public string CurrentWindowPositionKeyword { get; set; } + public string CurrentWindowXPositionKeyword { get; set; } + public string CurrentWindowYPositionKeyword { get; set; } + public string CurrentWorksheetKeyword { get; set; } + public string NextWorksheetKeyword { get; set; } + public string PreviousWorksheetKeyword { get; set; } + public bool ExportIntermediateXML { get; set; } + public bool UseNewParser { get; set; } + public bool IgnoreFirstVariableMarkerInOutputParameter { get; set; } + public int MaxFileCounter { get; set; } + public int MaxUIElementInpectDepth { get; set; } + public int MaxUIElementInspectSiblingNodes { get; set; } + + //private static readonly string InterStartVariableMaker = "{{{"; + //private static readonly string InterEndVariableMaker = "}}}"; + //private static readonly string InterCurrentWindowKeyword = "%kwd_current_window%"; + //private static readonly string InterDesktopKeyword = "%kwd_desktop%"; + //private static readonly string InterAllWindowsKeyword = "%kwd_all_windows%"; + //private static readonly string InterCurrentWindowPositionKeyword = "%kwd_current_position%"; + //private static readonly string InterCurrentWindowXPositionKeyword = "%kwd_current_xposition%"; + //private static readonly string InterCurrentWindowYPositionKeyword = "%kwd_current_yposition%"; + //private static readonly string InterCurrentWorksheetKeyword = "%kwd_current_worksheet%"; + //private static readonly string InterNextWorksheetKeyword = "%kwd_next_worksheet%"; + //private static readonly string InterPreviousWorksheetKeyword = "%kwd_previous_worksheet%"; + + //private static readonly string[] m_KeyNameList = new string[] + //{ + // "BACKSPACE", "BS", "BKSP", + // "BREAK", + // "CAPSLOCK", + // "DELETE", "DEL", + // "UP", "DOWN", "LEFT", "RIGHT", + // "END", + // "ENTER", + // "INSERT", "INS", + // "NUMLOCK", + // "PGDN", + // "PGUP", + // "SCROLLROCK", + // "TAB", + // "F1", "F2", "F3", "F4", "F5", "F6", + // "F7", "F8", "F9", "F10", "F11", "F12", + // "ADD", "SUBTRACT", "MULTIPLY", "DIVIDE", + // "WIN_KEY" + //}; + //private static readonly string[] m_DisallowVariableCharList = new string[] + //{ + // "+", "-", "*", "%", + // "[", "]", "{", "}", + // ".", + // " ", + // "\u2983", "\u2984", + // "\U0001D542", "\U0001D54E" + //}; + + public EngineSettings() + { + ShowDebugWindow = true; + AutoCloseDebugWindow = true; + EnableDiagnosticLogging = true; + ShowAdvancedDebugOutput = false; + CreateMissingVariablesDuringExecution = true; + TrackExecutionMetrics = true; + VariableStartMarker = "{"; + VariableEndMarker = "}"; + CancellationKey = System.Windows.Forms.Keys.Pause; + DelayBetweenCommands = 250; + OverrideExistingAppInstances = false; + AutoCloseMessagesOnServerExecution = true; + AutoCloseDebugWindowOnServerExecution = true; + AutoCalcVariables = false; + CurrentWindowKeyword = "Current Window"; + DesktopKeyword = "Desktop"; + AllWindowsKeyword = "All Windows"; + CurrentWindowPositionKeyword = "Current Position"; + CurrentWindowXPositionKeyword = "Current XPosition"; + CurrentWindowYPositionKeyword = "Current YPosition"; + CurrentWorksheetKeyword = "Current Sheet"; + NextWorksheetKeyword = "Next Sheet"; + PreviousWorksheetKeyword = "Previous Sheet"; + ExportIntermediateXML = true; + UseNewParser = true; + IgnoreFirstVariableMarkerInOutputParameter = true; + MaxFileCounter = 999; + MaxUIElementInpectDepth = 256; + MaxUIElementInspectSiblingNodes = int.MaxValue; + } + + //public string[] KeyNameList() + //{ + // return m_KeyNameList; + //} + + //public string[] DisallowVariableCharList() + //{ + // return m_DisallowVariableCharList; + //} + + //// TODO: fix it... + //public string replaceEngineKeyword(string targetString) + //{ + // return targetString.Replace(InterStartVariableMaker, this.VariableStartMarker) + // .Replace(InterEndVariableMaker, this.VariableEndMarker) + // //.Replace(InterCurrentWindowKeyword, taskt.Core.Automation.Commands.VariableNameControls.GetWrappedVariableName(taskt.Core.Automation.Engine.SystemVariables.Window_CurrentWindowName.VariableName, this)) + // .Replace(InterCurrentWindowKeyword, this.CurrentWindowKeyword) + // .Replace(InterCurrentWindowPositionKeyword, this.CurrentWindowPositionKeyword) + // .Replace(InterCurrentWindowXPositionKeyword, this.CurrentWindowXPositionKeyword) + // .Replace(InterCurrentWindowYPositionKeyword, this.CurrentWindowYPositionKeyword) + // .Replace(InterCurrentWorksheetKeyword, this.CurrentWorksheetKeyword) + // .Replace(InterNextWorksheetKeyword, this.NextWorksheetKeyword) + // .Replace(InterPreviousWorksheetKeyword, this.PreviousWorksheetKeyword); + //} + + public string convertToIntermediate(string targetString) + { + return targetString.Replace(this.VariableStartMarker, "\u2983") + .Replace(this.VariableEndMarker, "\u2984"); + } + + public string convertToRaw(string targetString) + { + return targetString.Replace("\u2983", this.VariableStartMarker) + .Replace("\u2984", this.VariableEndMarker); + } + + //public string convertToIntermediateExcelSheet(string targetString) + //{ + // return convertToIntermediate( + // targetString.Replace(this.CurrentWorksheetKeyword, wrapIntermediateKeyword(InterCurrentWorksheetKeyword)) + // .Replace(this.NextWorksheetKeyword, wrapIntermediateKeyword(InterNextWorksheetKeyword)) + // .Replace(this.PreviousWorksheetKeyword, wrapIntermediateKeyword(InterPreviousWorksheetKeyword)) + // ); + //} + + //public string convertToRawExcelSheet(string targetString) + //{ + // return convertToRaw( + // targetString.Replace(wrapIntermediateKeyword(InterCurrentWorksheetKeyword), this.CurrentWorksheetKeyword) + // .Replace(wrapIntermediateKeyword(InterNextWorksheetKeyword), this.NextWorksheetKeyword) + // .Replace(wrapIntermediateKeyword(InterPreviousWorksheetKeyword), this.PreviousWorksheetKeyword) + // ); + //} + + //public string convertToIntermediateWindowName(string targetString) + //{ + // return convertToIntermediate( + // targetString.Replace(this.CurrentWindowKeyword, wrapIntermediateKeyword(InterCurrentWindowKeyword)) + // .Replace(this.DesktopKeyword, wrapIntermediateKeyword(InterDesktopKeyword)) + // .Replace(this.AllWindowsKeyword, wrapIntermediateKeyword(InterAllWindowsKeyword)) + // ); + //} + + //public string convertToRawWindowName(string targetString) + //{ + // return convertToRaw( + // targetString.Replace(wrapIntermediateKeyword(InterCurrentWindowKeyword), this.CurrentWindowKeyword) + // .Replace(wrapIntermediateKeyword(InterDesktopKeyword), this.DesktopKeyword) + // .Replace(wrapIntermediateKeyword(InterAllWindowsKeyword), this.AllWindowsKeyword) + // ); + //} + + //public string convertToIntermediateWindowPosition(string targetString) + //{ + // return convertToIntermediate( + // targetString.Replace(this.CurrentWindowPositionKeyword, wrapIntermediateKeyword(InterCurrentWindowPositionKeyword)) + // .Replace(this.CurrentWindowXPositionKeyword, wrapIntermediateKeyword(InterCurrentWindowXPositionKeyword)) + // .Replace(this.CurrentWindowYPositionKeyword, wrapIntermediateKeyword(InterCurrentWindowYPositionKeyword)) + // ); + //} + + //public string convertToRawWindowPosition(string targetString) + //{ + // return convertToRaw( + // targetString.Replace(wrapIntermediateKeyword(InterCurrentWindowPositionKeyword), this.CurrentWindowPositionKeyword) + // .Replace(wrapIntermediateKeyword(InterCurrentWindowXPositionKeyword), this.CurrentWindowXPositionKeyword) + // .Replace(wrapIntermediateKeyword(InterCurrentWindowYPositionKeyword), this.CurrentWindowYPositionKeyword) + // ); + //} + + public string convertToIntermediateVariableParser(string targetString, List variables) + { + Core.Automation.Engine.AutomationEngineInstance engine = new Automation.Engine.AutomationEngineInstance(false); + engine.engineSettings = this; + engine.VariableList = variables; + return ExtensionMethods.ConvertUserVariableToIntermediateNotation(targetString, engine); + } + + //public string wrapVariableMarker(string variableName) + //{ + // return this.VariableStartMarker + variableName + this.VariableEndMarker; + //} + + //public string unwrapVariableMarker(string variableName) + //{ + // if (this.isWrappedVariableMarker(variableName)) + // { + // string rmvSt = variableName.Substring(this.VariableStartMarker.Length); + // return rmvSt.Substring(0, rmvSt.Length - this.VariableEndMarker.Length); + // } + // else + // { + // return variableName; + // } + //} + + //public bool isWrappedVariableMarker(string variableName) + //{ + // return (variableName.StartsWith(this.VariableStartMarker) && variableName.EndsWith(this.VariableEndMarker)); + //} + + //public string wrapIntermediateVariableMaker(string variableName) + //{ + // return "\u2983" + variableName + "\u2984"; + //} + + //private static string wrapIntermediateKeyword(string kw) + //{ + // return "\U0001D542" + kw + "\U0001D54E"; + //} + + //public bool isValidVariableName(string vName) + //{ + // foreach (string s in m_KeyNameList) + // { + // if (vName == s) + // { + // return false; + // } + // } + // foreach (string s in m_DisallowVariableCharList) + // { + // if (vName.Contains(s)) + // { + // return false; + // } + // } + // if (vName.StartsWith("__INNER_")) + // { + // return false; + // } + // return true; + //} + } +} diff --git a/taskt/Core/ApplicationSettings/LocalListenerSettings.cs b/taskt/Core/ApplicationSettings/LocalListenerSettings.cs new file mode 100644 index 000000000..05b528cb4 --- /dev/null +++ b/taskt/Core/ApplicationSettings/LocalListenerSettings.cs @@ -0,0 +1,29 @@ +using System; + +namespace taskt.Core +{ + /// + /// Defines Server settings for tasktServer if using the server component to manage the client + /// + [Serializable] + public class LocalListenerSettings + { + public bool StartListenerOnStartup { get; set; } + public bool LocalListeningEnabled { get; set; } + public bool RequireListenerAuthenticationKey { get; set; } + public int ListeningPort { get; set; } + public string AuthKey { get; set; } + public bool EnableWhitelist { get; set; } + public string IPWhiteList { get; set; } + public LocalListenerSettings() + { + StartListenerOnStartup = false; + LocalListeningEnabled = false; + RequireListenerAuthenticationKey = false; + EnableWhitelist = false; + ListeningPort = 19312; + AuthKey = Guid.NewGuid().ToString(); + IPWhiteList = ""; + } + } +} diff --git a/taskt/Core/ApplicationSettings/ServerSettings.cs b/taskt/Core/ApplicationSettings/ServerSettings.cs new file mode 100644 index 000000000..5b9e74236 --- /dev/null +++ b/taskt/Core/ApplicationSettings/ServerSettings.cs @@ -0,0 +1,25 @@ +using System; + +namespace taskt.Core +{ + /// + /// Defines Server settings for tasktServer if using the server component to manage the client + /// + [Serializable] + public class ServerSettings + { + public bool ServerConnectionEnabled { get; set; } + public bool ConnectToServerOnStartup { get; set; } + public bool RetryServerConnectionOnFail { get; set; } + public bool BypassCertificateValidation { get; set; } + public string ServerURL { get; set; } + public string ServerPublicKey { get; set; } + public string HTTPServerURL { get; set; } + public Guid HTTPGuid { get; set; } + + public ServerSettings() + { + HTTPServerURL = "https://localhost:44377/"; + } + } +} diff --git a/taskt/Core/ApplicationSettings/WhiteListIP.cs b/taskt/Core/ApplicationSettings/WhiteListIP.cs new file mode 100644 index 000000000..206b05508 --- /dev/null +++ b/taskt/Core/ApplicationSettings/WhiteListIP.cs @@ -0,0 +1,16 @@ +using System; + +namespace taskt.Core +{ + + [Serializable] + public class WhiteListIP + { + string _value; + public WhiteListIP(string s) + { + _value = s; + } + public string Value { get { return _value; } set { _value = value; } } + } +} diff --git a/taskt/Core/Automation/Attributes/ClassAttributes.cs b/taskt/Core/Automation/Attributes/ClassAttributes.cs index bf9f4991a..7870ff35f 100644 --- a/taskt/Core/Automation/Attributes/ClassAttributes.cs +++ b/taskt/Core/Automation/Attributes/ClassAttributes.cs @@ -15,7 +15,7 @@ namespace taskt.Core.Automation.Attributes.ClassAttributes { [System.AttributeUsage(System.AttributeTargets.Class)] - public class Group : System.Attribute + public sealed class Group : System.Attribute { public string groupName; public Group(string name) @@ -24,7 +24,7 @@ public Group(string name) } } [System.AttributeUsage(System.AttributeTargets.Class)] - public class Description : System.Attribute + public sealed class Description : System.Attribute { public string commandFunctionalDescription; public Description(string desc) @@ -33,7 +33,7 @@ public Description(string desc) } } [System.AttributeUsage(System.AttributeTargets.Class)] - public class ImplementationDescription : System.Attribute + public sealed class ImplementationDescription : System.Attribute { public string commandImplementationDescription; public ImplementationDescription(string desc) @@ -42,7 +42,7 @@ public ImplementationDescription(string desc) } } [System.AttributeUsage(System.AttributeTargets.Class)] - public class UsesDescription : System.Attribute + public sealed class UsesDescription : System.Attribute { public string usesDescription; public UsesDescription(string desc) @@ -51,7 +51,7 @@ public UsesDescription(string desc) } } [System.AttributeUsage(System.AttributeTargets.Class)] - public class SubGruop : System.Attribute + public sealed class SubGruop : System.Attribute { public string subGruopName = ""; public SubGruop(string group) @@ -60,7 +60,7 @@ public SubGruop(string group) } } [System.AttributeUsage(System.AttributeTargets.Class)] - public class EnableAutomateDisplayText : System.Attribute + public sealed class EnableAutomateDisplayText : System.Attribute { public bool enableAutomateDisplayText = false; public EnableAutomateDisplayText(bool enableAutomateDisplayText) @@ -69,7 +69,7 @@ public EnableAutomateDisplayText(bool enableAutomateDisplayText) } } [System.AttributeUsage(System.AttributeTargets.Class)] - public class EnableAutomateRender : System.Attribute + public sealed class EnableAutomateRender : System.Attribute { public bool enableAutomateRender = false; public bool forceRenderComment = false; @@ -80,7 +80,7 @@ public EnableAutomateRender(bool enableAutomateRender, bool forceRenderComment = } } [System.AttributeUsage(System.AttributeTargets.Class)] - public class CommandSettings : System.Attribute + public sealed class CommandSettings : System.Attribute { public string selectionName = ""; public bool commandEnable = true; @@ -97,4 +97,17 @@ public CommandSettings(string selectionName, bool commandEnable = true, bool cus this.customeRender = customeRender; } } + [System.AttributeUsage(System.AttributeTargets.Class)] + public sealed class CommandIcon : System.Attribute + { + public string iconName = nameof(Properties.Resources.command_files); + + public CommandIcon() + { + } + public CommandIcon(string iconName) + { + this.iconName = iconName; + } + } } diff --git a/taskt/Core/Automation/Attributes/PropertyAttributes.cs b/taskt/Core/Automation/Attributes/PropertyAttributes.cs index 0420249d4..41768c369 100644 --- a/taskt/Core/Automation/Attributes/PropertyAttributes.cs +++ b/taskt/Core/Automation/Attributes/PropertyAttributes.cs @@ -1,6 +1,5 @@ using System; using System.Linq; -using System.Web.UI.HtmlControls; namespace taskt.Core.Automation.Attributes.PropertyAttributes { @@ -12,9 +11,28 @@ public enum MultiAttributesBehavior } #endregion + #region Parameter Order + [AttributeUsage(AttributeTargets.Property)] + public sealed class PropertyParameterOrder : Attribute + { + public int order = 3000; + public PropertyParameterOrder() + { + } + public PropertyParameterOrder(int order) + { + this.order = order; + } + } + #endregion + + #region Replace pattern + // TODO: make sometime + #endregion + #region Virtual Property [AttributeUsage(AttributeTargets.Property)] - public class PropertyVirtualProperty : Attribute + public sealed class PropertyVirtualProperty : Attribute { public string className; public string propertyName; @@ -33,7 +51,7 @@ public bool Equals(PropertyVirtualProperty other) #region Intermediate/Raw [AttributeUsage(AttributeTargets.Property)] - public class PropertyIntermediateConvert : Attribute + public sealed class PropertyIntermediateConvert : Attribute { public string intermediateMethod = ""; public string rawMethod = ""; @@ -51,7 +69,7 @@ public PropertyIntermediateConvert(string intermediateMethod, string rawMethod) #region to Label, Document [AttributeUsage(AttributeTargets.Property)] - public class InputSpecification : Attribute + public sealed class InputSpecification : Attribute { public string inputSpecification; public bool autoGenerate = false; @@ -70,7 +88,7 @@ public InputSpecification(string desc, bool autoGenerate = false) } [AttributeUsage(AttributeTargets.Property)] - public class SampleUsage : Attribute + public sealed class SampleUsage : Attribute { public string sampleUsage; public SampleUsage(string desc) @@ -80,7 +98,7 @@ public SampleUsage(string desc) } [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] - public class PropertyDetailSampleUsage : Attribute + public sealed class PropertyDetailSampleUsage : Attribute { public string sampleUsage = ""; public string means = ""; @@ -112,7 +130,7 @@ public enum ValueType } [AttributeUsage(AttributeTargets.Property)] - public class PropertyDetailSampleUsageBehavior : Attribute + public sealed class PropertyDetailSampleUsageBehavior : Attribute { public MultiAttributesBehavior behavior = MultiAttributesBehavior.Merge; @@ -127,7 +145,7 @@ public PropertyDetailSampleUsageBehavior(MultiAttributesBehavior behavior) } [AttributeUsage(AttributeTargets.Property)] - public class Remarks : Attribute + public sealed class Remarks : Attribute { public string remarks; public Remarks(string desc) @@ -194,7 +212,7 @@ public PropertyAddtionalParameterInfo(string searchKey, string description, stri } [AttributeUsage(AttributeTargets.Property)] - public class PropertyAddtionalParameterInfoBehavior : Attribute + public sealed class PropertyAddtionalParameterInfoBehavior : Attribute { public MultiAttributesBehavior behavior = MultiAttributesBehavior.Merge; @@ -227,7 +245,7 @@ public enum UIAdditionalHelperType } [AttributeUsage(AttributeTargets.Property)] - public class PropertyUIHelperBehavior : Attribute + public sealed class PropertyUIHelperBehavior : Attribute { public MultiAttributesBehavior behavior = MultiAttributesBehavior.Merge; @@ -256,7 +274,7 @@ public PropertyCustomUIHelper(string labelText, string methodName, string nameKe } [AttributeUsage(AttributeTargets.Property)] - public class PropertyCustomUIHelperBehavior : Attribute + public sealed class PropertyCustomUIHelperBehavior : Attribute { public MultiAttributesBehavior behavior = MultiAttributesBehavior.Merge; @@ -269,6 +287,35 @@ public PropertyCustomUIHelperBehavior(MultiAttributesBehavior behavior) this.behavior = behavior; } } + + [AttributeUsage(AttributeTargets.Property)] + public sealed class PropertyAvailableSystemVariableBehavior : Attribute + { + public MultiAttributesBehavior behavior = MultiAttributesBehavior.Merge; + + public PropertyAvailableSystemVariableBehavior() + { + + } + public PropertyAvailableSystemVariableBehavior(MultiAttributesBehavior behavior) + { + this.behavior = behavior; + } + } + + [AttributeUsage(AttributeTargets.Property, AllowMultiple = true)] + public sealed class PropertyAvailableSystemVariable : Attribute + { + public Engine.SystemVariables.LimitedSystemVariableNames variable = Engine.SystemVariables.LimitedSystemVariableNames.None; + public PropertyAvailableSystemVariable() + { + + } + public PropertyAvailableSystemVariable(Engine.SystemVariables.LimitedSystemVariableNames variable) + { + this.variable = variable; + } + } #endregion #region for All Controls @@ -329,7 +376,9 @@ public enum InstanceType Color, MailKitEMail, MailKitEMailList, - WebElement + WebElement, + WindowHandle, + Numeric, } } @@ -610,7 +659,7 @@ public PropertyUISelectionOption(string description) } [AttributeUsage(AttributeTargets.Property)] - public class PropertyUISelectionOptionBehavior : Attribute + public sealed class PropertyUISelectionOptionBehavior : Attribute { public MultiAttributesBehavior behavior = MultiAttributesBehavior.Merge; diff --git a/taskt/Core/Automation/Commands/API/ExecuteDLLCommand.cs b/taskt/Core/Automation/Commands/API/ExecuteDLLCommand.cs index e8c4785a6..dc99e25e5 100644 --- a/taskt/Core/Automation/Commands/API/ExecuteDLLCommand.cs +++ b/taskt/Core/Automation/Commands/API/ExecuteDLLCommand.cs @@ -11,14 +11,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("API Commands")] + [Attributes.ClassAttributes.Group("API")] [Attributes.ClassAttributes.CommandSettings("Execute DLL")] [Attributes.ClassAttributes.Description("This command processes an HTML source object")] [Attributes.ClassAttributes.UsesDescription("Use this command to parse and extract data from a successful **HTTP Request Command**")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_run_code))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExecuteDLLCommand : ScriptCommand + public sealed class ExecuteDLLCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -92,12 +93,12 @@ public ExecuteDLLCommand() //ParametersGridViewHelper.DataBindings.Add("DataSource", this, "v_MethodParameters", false, DataSourceUpdateMode.OnPropertyChanged); } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //get file path - var filePath = v_FilePath.ConvertToUserVariable(sender); - var className = v_ClassName.ConvertToUserVariable(sender); - var methodName = v_MethodName.ConvertToUserVariable(sender); + var filePath = v_FilePath.ExpandValueOrUserVariable(engine); + var className = v_ClassName.ExpandValueOrUserVariable(engine); + var methodName = v_MethodName.ExpandValueOrUserVariable(engine); //if file path does not exist if (!System.IO.File.Exists(filePath)) @@ -141,7 +142,7 @@ public override void RunCommand(object sender) //get parameter value var requiredParameterValue = (from rws in v_MethodParameters.AsEnumerable() where rws.Field("Parameter Name") == paramName - select rws.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender); + select rws.Field("Parameter Value")).FirstOrDefault().ExpandValueOrUserVariable(engine); //get type of parameter @@ -236,7 +237,7 @@ where rws.Field("Parameter Name") == paramName } //store result in variable - result.ToString().StoreInUserVariable(sender, v_applyToVariableName); + result.ToString().StoreInUserVariable(engine, v_applyToVariableName); } public override void BeforeValidate() @@ -314,10 +315,10 @@ private void lnkGenerateDLLParameters_Clicked(object sender, EventArgs e) private void lnkShowDLLExplorer_Clicked(object sender, EventArgs e) { //create form - using (UI.Forms.Supplemental.frmDLLExplorer dllExplorer = new UI.Forms.Supplemental.frmDLLExplorer()) + using (var dllExplorer = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmDLLExplorer()) { //show dialog - if (dllExplorer.ShowDialog() == DialogResult.OK) + if (dllExplorer.ShowDialog(((Control)sender).FindForm()) == DialogResult.OK) { //user accepted the selections //declare command diff --git a/taskt/Core/Automation/Commands/API/HTTPExecuteRESTAPICommand.cs b/taskt/Core/Automation/Commands/API/HTTPExecuteRESTAPICommand.cs index 56c955891..209f333c0 100644 --- a/taskt/Core/Automation/Commands/API/HTTPExecuteRESTAPICommand.cs +++ b/taskt/Core/Automation/Commands/API/HTTPExecuteRESTAPICommand.cs @@ -9,14 +9,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("API Commands")] + [Attributes.ClassAttributes.Group("API")] [Attributes.ClassAttributes.CommandSettings("Execute REST API")] [Attributes.ClassAttributes.Description("This command allows you to show a message to the user.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to present or display a value on screen to the user.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'MessageBox' and invokes VariableCommand to find variable data.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_run_code))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class HTTPExecuteRESTAPICommand : ScriptCommand + public sealed class HTTPExecuteRESTAPICommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -112,10 +113,8 @@ public HTTPExecuteRESTAPICommand() //this.v_AdvancedParameters.TableName = DateTime.Now.ToString("AdvRESTParamTable" + DateTime.Now.ToString("MMddyy.hhmmss")); } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - try { //make REST Request and store into variable @@ -134,9 +133,9 @@ public string ExecuteRESTRequest(object sender) var engine = (Engine.AutomationEngineInstance)sender; //get parameters - var targetURL = v_BaseURL.ConvertToUserVariable(engine); - var targetEndpoint = v_APIEndPoint.ConvertToUserVariable(engine); - var targetMethod = v_APIMethodType.ConvertToUserVariable(engine); + var targetURL = v_BaseURL.ExpandValueOrUserVariable(engine); + var targetEndpoint = v_APIEndPoint.ExpandValueOrUserVariable(engine); + var targetMethod = v_APIMethodType.ExpandValueOrUserVariable(engine); //client var client = new RestClient(targetURL); @@ -171,8 +170,8 @@ where rw.Field("Parameter Type") == "HEADER" //for each api parameter foreach (var param in apiParameters) { - var paramName = ((string)param["Parameter Name"]).ConvertToUserVariable(sender); - var paramValue = ((string)param["Parameter Value"]).ConvertToUserVariable(sender); + var paramName = ((string)param["Parameter Name"]).ExpandValueOrUserVariable(engine); + var paramValue = ((string)param["Parameter Value"]).ExpandValueOrUserVariable(engine); request.AddParameter(paramName, paramValue); } @@ -180,8 +179,8 @@ where rw.Field("Parameter Type") == "HEADER" //for each header foreach (var header in apiHeaders) { - var paramName = ((string)header["Parameter Name"]).ConvertToUserVariable(sender); - var paramValue = ((string)header["Parameter Value"]).ConvertToUserVariable(sender); + var paramName = ((string)header["Parameter Name"]).ExpandValueOrUserVariable(engine); + var paramValue = ((string)header["Parameter Value"]).ExpandValueOrUserVariable(engine); request.AddHeader(paramName, paramValue); } @@ -193,7 +192,7 @@ where rw.Field("Parameter Type") == "JSON BODY" //add json body if (jsonBody != null) { - var json = jsonBody.ConvertToUserVariable(sender); + var json = jsonBody.ExpandValueOrUserVariable(engine); request.AddJsonBody(jsonBody); } @@ -205,9 +204,9 @@ where rw.Field("Parameter Type") == "FILE" //get file if (file != null) { - var paramName = ((string)file["Parameter Name"]).ConvertToUserVariable(sender); - var paramValue = ((string)file["Parameter Value"]).ConvertToUserVariable(sender); - var fileData = paramValue.ConvertToUserVariable(sender); + var paramName = ((string)file["Parameter Name"]).ExpandValueOrUserVariable(engine); + var paramValue = ((string)file["Parameter Value"]).ExpandValueOrUserVariable(engine); + var fileData = paramValue.ExpandValueOrUserVariable(engine); request.AddFile(paramName, fileData); } @@ -215,10 +214,10 @@ where rw.Field("Parameter Type") == "FILE" //add advanced parameters foreach (DataRow rw in this.v_AdvancedParameters.Rows) { - var paramName = rw.Field("Parameter Name").ConvertToUserVariable(sender); - var paramValue = rw.Field("Parameter Value").ConvertToUserVariable(sender); - var paramType = rw.Field("Parameter Type").ConvertToUserVariable(sender); - var contentType = rw.Field("Content Type").ConvertToUserVariable(sender); + var paramName = rw.Field("Parameter Name").ExpandValueOrUserVariable(engine); + var paramValue = rw.Field("Parameter Value").ExpandValueOrUserVariable(engine); + var paramType = rw.Field("Parameter Type").ExpandValueOrUserVariable(engine); + var contentType = rw.Field("Content Type").ExpandValueOrUserVariable(engine); //var param = new Parameter(paramName, paramValue, (ParameterType)Enum.Parse(typeof(ParameterType), paramType)); @@ -227,7 +226,7 @@ where rw.Field("Parameter Type") == "FILE" request.AddParameter(paramName, paramValue, (ParameterType)Enum.Parse(typeof(ParameterType), paramType)); } - var requestFormat = v_RequestFormat.ConvertToUserVariable(sender); + var requestFormat = v_RequestFormat.ExpandValueOrUserVariable(engine); if (string.IsNullOrEmpty(requestFormat)) { requestFormat = "Xml"; @@ -236,7 +235,7 @@ where rw.Field("Parameter Type") == "FILE" //execute client request - RestResponse response = client.Execute(request); + var response = client.Execute(request); var content = response.Content; //add service response for tracking diff --git a/taskt/Core/Automation/Commands/API/HTTPSendHTTPRequestCommand.cs b/taskt/Core/Automation/Commands/API/HTTPSendHTTPRequestCommand.cs index 7465cb418..67baae3a4 100644 --- a/taskt/Core/Automation/Commands/API/HTTPSendHTTPRequestCommand.cs +++ b/taskt/Core/Automation/Commands/API/HTTPSendHTTPRequestCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("API Commands")] + [Attributes.ClassAttributes.Group("API")] [Attributes.ClassAttributes.CommandSettings("Send HTTP Request")] [Attributes.ClassAttributes.Description("This command downloads the HTML source of a web page for parsing")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to retrieve HTML of a web page without using browser automation.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements System.Web to achieve automation")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class HTTPSendHTTPRequestCommand : ScriptCommand + public sealed class HTTPSendHTTPRequestCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -28,7 +29,7 @@ public class HTTPSendHTTPRequestCommand : ScriptCommand public string v_WebRequestURL { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Execute Request as the currently logged on user?")] public string v_WebRequestCredentials { get; set; } @@ -44,16 +45,14 @@ public HTTPSendHTTPRequestCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - HttpWebRequest request = (HttpWebRequest)WebRequest.Create(v_WebRequestURL.ConvertToUserVariable(sender)); + HttpWebRequest request = (HttpWebRequest)WebRequest.Create(v_WebRequestURL.ExpandValueOrUserVariable(engine)); request.Method = "GET"; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2"; //if (v_WebRequestCredentials == "Yes") - if (this.GetYesNoSelectionValue(nameof(v_WebRequestCredentials), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_WebRequestCredentials), engine)) { request.Credentials = CredentialCache.DefaultCredentials; } @@ -64,7 +63,7 @@ public override void RunCommand(object sender) StreamReader reader = new StreamReader(dataStream); string strResponse = reader.ReadToEnd(); - strResponse.StoreInUserVariable(sender, v_userVariableName); + strResponse.StoreInUserVariable(engine, v_userVariableName); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/ApplicationScriptFile/LoadScriptFileCommand.cs b/taskt/Core/Automation/Commands/ApplicationScriptFile/LoadScriptFileCommand.cs index b4995fade..bf9b024c2 100644 --- a/taskt/Core/Automation/Commands/ApplicationScriptFile/LoadScriptFileCommand.cs +++ b/taskt/Core/Automation/Commands/ApplicationScriptFile/LoadScriptFileCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Application/Script Commands")] + [Attributes.ClassAttributes.Group("Application/Script")] [Attributes.ClassAttributes.SubGruop("taskt Script File")] [Attributes.ClassAttributes.CommandSettings("Load Script File")] [Attributes.ClassAttributes.Description("This command pre-loads tasks for future execution.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to load a task but not immediately execute it.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_script))] [Attributes.ClassAttributes.ImplementationDescription("")] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class LoadScriptFileCommand : ScriptCommand + public sealed class LoadScriptFileCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_NoSample_FilePath))] @@ -35,11 +36,8 @@ public LoadScriptFileCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //deserialize task - var engine = (Engine.AutomationEngineInstance)sender; - //string startFile = FilePathControls.FormatFilePath_NoFileCounter(v_taskPath, engine, "xml", true); var startFile = FilePathControls.WaitForFile(this, nameof(v_taskPath), nameof(v_WaitForFile), engine); diff --git a/taskt/Core/Automation/Commands/ApplicationScriptFile/RunBatchScriptFileCommand.cs b/taskt/Core/Automation/Commands/ApplicationScriptFile/RunBatchScriptFileCommand.cs index 6fdd6bdb9..9276d348c 100644 --- a/taskt/Core/Automation/Commands/ApplicationScriptFile/RunBatchScriptFileCommand.cs +++ b/taskt/Core/Automation/Commands/ApplicationScriptFile/RunBatchScriptFileCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Application/Script Commands")] + [Attributes.ClassAttributes.Group("Application/Script")] [Attributes.ClassAttributes.SubGruop("Windows Script File")] [Attributes.ClassAttributes.CommandSettings("Run Batch Script File")] [Attributes.ClassAttributes.Description("This command allows you to run a script or program and wait for it to exit before proceeding.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to run a script (such as vbScript, javascript, or executable) but wait for it to close before taskt continues executing.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Process.Start' and waits for the script/program to exit before proceeding.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_script))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RunBatchScriptFileCommand : ScriptCommand + public sealed class RunBatchScriptFileCommand : ScriptCommand { [XmlAttribute] //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -40,9 +41,8 @@ public RunBatchScriptFileCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; //string scriptPath = FilePathControls.FormatFilePath_NoFileCounter(v_ScriptPath, engine, new List() { "bat", "vbs", "js", "wsf" }, true); string scriptPath = FilePathControls.WaitForFile(this, nameof(v_ScriptPath), nameof(v_WaitForFile), engine); diff --git a/taskt/Core/Automation/Commands/ApplicationScriptFile/RunCSharpCodeCommand.cs b/taskt/Core/Automation/Commands/ApplicationScriptFile/RunCSharpCodeCommand.cs index ac2fd7c56..9d09b3a6b 100644 --- a/taskt/Core/Automation/Commands/ApplicationScriptFile/RunCSharpCodeCommand.cs +++ b/taskt/Core/Automation/Commands/ApplicationScriptFile/RunCSharpCodeCommand.cs @@ -7,15 +7,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Application/Script Commands")] + [Attributes.ClassAttributes.Group("Application/Script")] [Attributes.ClassAttributes.SubGruop("Windows Script File")] [Attributes.ClassAttributes.CommandSettings("Run CSharp Code")] [Attributes.ClassAttributes.Description("This command allows you to run C# code from the input")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to run custom C# code commands. The code in this command is compiled and run at runtime when this command is invoked. This command only supports the standard framework classes.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Process.Start' and waits for the script/program to exit before proceeding.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_script))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RunCSharpCodeCommand : ScriptCommand + public sealed class RunCSharpCodeCommand : ScriptCommand { [XmlAttribute] [PropertyDescription("C# Code")] @@ -57,17 +58,15 @@ public RunCSharpCodeCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var customCode = v_Code.ConvertToUserVariable(engine); + var customCode = v_Code.ExpandValueOrUserVariable(engine); //create compiler service - var compilerSvc = new CompilerServices(); + //var compilerSvc = new CompilerServices(); //compile custom code - var result = compilerSvc.CompileInput(customCode); + var result = CSharpCodeCompilerControls.CompileInput(customCode); //check for errors if (result.Errors.HasErrors) @@ -82,10 +81,10 @@ public override void RunCommand(object sender) System.Diagnostics.Process scriptProc = new System.Diagnostics.Process(); scriptProc.StartInfo.FileName = result.PathToAssembly; - var arguments = v_Args.ConvertToUserVariable(sender); + var arguments = v_Args.ExpandValueOrUserVariable(engine); scriptProc.StartInfo.Arguments = arguments; - if (!String.IsNullOrEmpty(v_applyToVariableName)) + if (!string.IsNullOrEmpty(v_applyToVariableName)) { //redirect output scriptProc.StartInfo.RedirectStandardOutput = true; @@ -96,10 +95,10 @@ public override void RunCommand(object sender) scriptProc.WaitForExit(); - if (!String.IsNullOrEmpty(v_applyToVariableName)) + if (!string.IsNullOrEmpty(v_applyToVariableName)) { var output = scriptProc.StandardOutput.ReadToEnd(); - output.StoreInUserVariable(sender, v_applyToVariableName); + output.StoreInUserVariable(engine, v_applyToVariableName); } scriptProc.Close(); @@ -109,9 +108,9 @@ public override void RunCommand(object sender) private void lnkShowCodeBuilderLink_Clicked(object sender, EventArgs e) { var targetTextbox = (TextBox)((CommandItemControl)sender).Tag; - using (UI.Forms.Supplemental.frmCodeBuilder codeBuilder = new UI.Forms.Supplemental.frmCodeBuilder(targetTextbox.Text)) + using (var codeBuilder = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmCodeBuilder(targetTextbox.Text)) { - if (codeBuilder.ShowDialog() == DialogResult.OK) + if (codeBuilder.ShowDialog(targetTextbox.FindForm()) == DialogResult.OK) { targetTextbox.Text = codeBuilder.rtbCode.Text; } diff --git a/taskt/Core/Automation/Commands/ApplicationScriptFile/RunJavaScriptFileCommand.cs b/taskt/Core/Automation/Commands/ApplicationScriptFile/RunJavaScriptFileCommand.cs new file mode 100644 index 000000000..df022c47c --- /dev/null +++ b/taskt/Core/Automation/Commands/ApplicationScriptFile/RunJavaScriptFileCommand.cs @@ -0,0 +1,83 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + + [Serializable] + [Attributes.ClassAttributes.Group("Application/Script")] + [Attributes.ClassAttributes.SubGruop("Windows Script File")] + [Attributes.ClassAttributes.CommandSettings("Run JavaScript File")] + [Attributes.ClassAttributes.Description("This command allows you to execute JavaScript.")] + [Attributes.ClassAttributes.ImplementationDescription("This command executes JavaScript using Edge")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class RunJavaScriptFileCommand : ScriptCommand + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_NoSample_FilePath))] + [PropertyDescription("Path to the JavaScript File")] + [PropertyDetailSampleUsage("**C:\\temp\\myscript.js**", PropertyDetailSampleUsage.ValueType.Value, "Script File")] + [PropertyDetailSampleUsage("**{{{vScriptPath}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Script File")] + [Remarks("")] + [PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtensionAndExists, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "js")] + public string v_FilePath { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Argument")] + [InputSpecification("Argument", true)] + [PropertyDetailSampleUsage("**0**", PropertyDetailSampleUsage.ValueType.Value, "Argument")] + [PropertyDetailSampleUsage("**{{{vValue}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Argument")] + [Remarks("The value of the argument can be obtained with 'arguments[0]' in code.")] + [PropertyIsOptional(true)] + [PropertyDisplayText(false, "")] + public string v_Args { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Recieve Result Value")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Result", PropertyValidationRule.ValidationRuleFlags.None)] + public string v_Result { get; set; } + + public RunJavaScriptFileCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + using (var myInstance = new InnerScriptVariable(engine)) + { + myInstance.VariableValue = engine.GetNewAppInstanceName(); + var instanceVar = VariableNameControls.GetWrappedVariableName(myInstance.VariableName, engine); + var webInstance = new SeleniumBrowserCreateWebBrowserInstanceCommand() + { + v_InstanceName = instanceVar, + v_EngineType = "Edge", + v_HeadlessMode = "Yes", + }; + webInstance.RunCommand(engine); + + var executeJS = new SeleniumBrowserExecuteScriptCommand() + { + v_InstanceName = instanceVar, + v_CodeType = "File", + v_ScriptCode = this.v_FilePath, + v_Args = this.v_Args, + v_userVariableName = this.v_Result, + }; + executeJS.RunCommand(engine); + + var closeInsntace = new SeleniumBrowserCloseWebBrowserInstanceCommand() + { + v_InstanceName = instanceVar, + }; + closeInsntace.RunCommand(engine); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/ApplicationScriptFile/RunPowerShellScriptFileCommand.cs b/taskt/Core/Automation/Commands/ApplicationScriptFile/RunPowerShellScriptFileCommand.cs index 610031892..2faa6bc65 100644 --- a/taskt/Core/Automation/Commands/ApplicationScriptFile/RunPowerShellScriptFileCommand.cs +++ b/taskt/Core/Automation/Commands/ApplicationScriptFile/RunPowerShellScriptFileCommand.cs @@ -8,15 +8,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Application/Script Commands")] + [Attributes.ClassAttributes.Group("Application/Script")] [Attributes.ClassAttributes.SubGruop("Windows Script File")] [Attributes.ClassAttributes.CommandSettings("Run PowerShell Script File")] [Attributes.ClassAttributes.Description("This command allows you to run a powershell script and wait for it to exit before proceeding.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to run a powershell script and wait for it to close before taskt continues executing.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Process.Start' and waits for the script/program to exit before proceeding.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_script))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RunPowerShellScriptFileCommand : ScriptCommand + public sealed class RunPowerShellScriptFileCommand : ScriptCommand { [XmlAttribute] //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -73,10 +74,8 @@ public RunPowerShellScriptFileCommand() //this.v_ReplaceScriptVariables = "No"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //define script path //string scriptPath = FilePathControls.FormatFilePath_NoFileCounter(v_ScriptPath, engine, new List() { "ps1", "bat" }, true); var scriptPath = FilePathControls.WaitForFile(this, nameof(v_ScriptPath), nameof(v_WaitForFile), engine); @@ -85,10 +84,10 @@ public override void RunCommand(object sender) var psCommand = File.ReadAllText(scriptPath); //if (v_ReplaceScriptVariables.ToUpperInvariant() == "YES") - if (this.GetUISelectionValue(nameof(v_ReplaceScriptVariables), engine) == "yes") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ReplaceScriptVariables), engine) == "yes") { //convert variables - psCommand = psCommand.ConvertToUserVariable(sender); + psCommand = psCommand.ExpandValueOrUserVariable(engine); } //convert ps script @@ -114,7 +113,7 @@ public override void RunCommand(object sender) if (!String.IsNullOrEmpty(v_applyToVariableName)) { string output = reader.ReadToEnd(); - output.StoreRawDataInUserVariable(sender, v_applyToVariableName); + output.StoreRawDataInUserVariable(engine, v_applyToVariableName); } } } diff --git a/taskt/Core/Automation/Commands/ApplicationScriptFile/RunScriptFileCommand.cs b/taskt/Core/Automation/Commands/ApplicationScriptFile/RunScriptFileCommand.cs index cd2e5dbf3..083ff511f 100644 --- a/taskt/Core/Automation/Commands/ApplicationScriptFile/RunScriptFileCommand.cs +++ b/taskt/Core/Automation/Commands/ApplicationScriptFile/RunScriptFileCommand.cs @@ -10,15 +10,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Application/Script Commands")] + [Attributes.ClassAttributes.Group("Application/Script")] [Attributes.ClassAttributes.SubGruop("taskt Script File")] [Attributes.ClassAttributes.CommandSettings("Run Script File")] [Attributes.ClassAttributes.Description("This command runs tasks.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to run another task.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_start_process))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RunScriptFileCommand : ScriptCommand + public sealed class RunScriptFileCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_NoSample_FilePath))] @@ -79,10 +80,8 @@ public RunScriptFileCommand() //AssignmentsGridViewHelper.Hide(); } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //var startFile = v_taskPath.ConvertToUserVariable(sender); //string startFile = FilePathControls.FormatFilePath_NoFileCounter(v_taskPath, engine, "xml", true); var startFile = FilePathControls.WaitForFile(this, nameof(v_taskPath), nameof(v_WaitForFile), engine); @@ -101,7 +100,7 @@ public override void RunCommand(object sender) } catch { - variableValue = rw.Field("VariableValue").ConvertToUserVariable(engine); + variableValue = rw.Field("VariableValue").ExpandValueOrUserVariable(engine); } var variableReturn = "No"; @@ -124,7 +123,7 @@ public override void RunCommand(object sender) } } - frmScriptEngine newEngine = new frmScriptEngine(startFile, null, variableList, true, engine.PreloadedTasks); + var newEngine = new UI.Forms.ScriptEngine.frmScriptEngine(startFile, null, variableList, true, engine.PreloadedTasks); engine.tasktEngineUI.Invoke((Action)delegate () { engine.tasktEngineUI.TopMost = false; }); Application.Run(newEngine); @@ -164,7 +163,7 @@ private void cmbAssignVariables_SelectedItemChanged(object sender, EventArgs e) var engine = new Engine.AutomationEngineInstance(); var cmb = (ComboBox)sender; - var engineSettings = ((frmCommandEditor)cmb.FindForm()).appSettings.EngineSettings; + var engineSettings = ((UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor)cmb.FindForm()).appSettings.EngineSettings; bool isVisible = (cmb.SelectedItem?.ToString().Trim().ToLower() == "yes"); foreach(var item in ControlsList.Where(c => (c.Key.Contains(nameof(v_VariableAssignments))))) @@ -174,12 +173,12 @@ private void cmbAssignVariables_SelectedItemChanged(object sender, EventArgs e) //var startFile = v_taskPath.ConvertToUserVariable(engine); //var startFile = FilePathControls.FormatFilePath_NoFileCounter(v_taskPath, engine, "xml", true); - var startFile = this.ConvertToUserVariableAsFilePath(nameof(v_taskPath), engine); + var startFile = this.ExpandValueOrUserVariableAsFilePath(nameof(v_taskPath), engine); // check file exists if (!System.IO.File.Exists(startFile)) { - using(var fm = new taskt.UI.Forms.Supplemental.frmDialog("Script File Not Found. Name: " + startFile, "error", UI.Forms.Supplemental.frmDialog.DialogType.OkOnly, 0)) + using(var fm = new UI.Forms.General.frmDialog("Script File Not Found. Name: " + startFile, "error", UI.Forms.General.frmDialog.DialogType.OkOnly, 0)) { fm.ShowDialog(); } diff --git a/taskt/Core/Automation/Commands/ApplicationScriptFile/StartApplicationCommand.cs b/taskt/Core/Automation/Commands/ApplicationScriptFile/StartApplicationCommand.cs index 239f6c137..6b865b506 100644 --- a/taskt/Core/Automation/Commands/ApplicationScriptFile/StartApplicationCommand.cs +++ b/taskt/Core/Automation/Commands/ApplicationScriptFile/StartApplicationCommand.cs @@ -5,19 +5,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Application/Script Commands")] + [Attributes.ClassAttributes.Group("Application/Script")] [Attributes.ClassAttributes.SubGruop("Application")] [Attributes.ClassAttributes.CommandSettings("Start Application")] [Attributes.ClassAttributes.Description("This command allows you to start a program or a process.")] [Attributes.ClassAttributes.UsesDescription("Use this command to start applications by entering their name such as 'chrome.exe' or a fully qualified path to a file 'c:/some.exe'")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Process.Start'.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_script))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class StartApplicationCommand : ScriptCommand + public sealed class StartApplicationCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] - [PropertyDescription("Path to the Application")] + [PropertyDescription("Path to the Application or Application Name")] [InputSpecification("Path", true)] [PropertyDetailSampleUsage("**notepad**", "Run Notepad")] [PropertyDetailSampleUsage("**C:\\Apps\\myapp.exe**", PropertyDetailSampleUsage.ValueType.Value, "Path")] @@ -54,10 +55,39 @@ public class StartApplicationCommand : ScriptCommand [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] [PropertyDescription("Variable Name to Store Application Process Name")] [PropertyIsOptional(true)] - [PropertyValidationRule("Result", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyValidationRule("Process Name", PropertyValidationRule.ValidationRuleFlags.None)] [PropertyDisplayText(false, "")] public string v_StartedProcessName { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Window Name")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Window Name", PropertyValidationRule.ValidationRuleFlags.None)] + public string v_WindowName { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_WindowHandle { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + [PropertyDescription("Wait Time until Application Starts (ms)")] + [PropertyIsOptional(true, "2000")] + [PropertyValidationRule("Wait Time", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyFirstValue("2000")] + [PropertyDisplayText(false, "")] + public string v_WaitTimeForExecute { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + [PropertyDescription("Wait Time before Executing Next Command (ms)")] + [PropertyIsOptional(true, "2000")] + [PropertyValidationRule("Wait Time", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyFirstValue("2000")] + [PropertyDisplayText(false, "")] + public string v_WaitTimeBeforeNext { get; set; } + public StartApplicationCommand() { //this.CommandName = "StartProcessCommand"; @@ -66,15 +96,13 @@ public StartApplicationCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var vProgramName = v_ProgramName.ConvertToUserVariable(engine); - var vProgramArgs = v_ProgramArgs.ConvertToUserVariable(engine); + var vProgramName = v_ProgramName.ExpandValueOrUserVariable(engine); + var vProgramArgs = v_ProgramArgs.ExpandValueOrUserVariable(engine); System.Diagnostics.Process p; - if (String.IsNullOrEmpty(vProgramArgs)) + if (string.IsNullOrEmpty(vProgramArgs)) { p = System.Diagnostics.Process.Start(vProgramName); } @@ -83,19 +111,35 @@ public override void RunCommand(object sender) p = System.Diagnostics.Process.Start(vProgramName, vProgramArgs); } - if (!String.IsNullOrEmpty(v_StartedProcessName)) + var waitTimeUntil = this.ExpandValueOrUserVariableAsInteger(nameof(v_WaitTimeForExecute), engine); + System.Threading.Thread.Sleep(waitTimeUntil); + + // process name + if (!string.IsNullOrEmpty(v_StartedProcessName)) { p.ProcessName.StoreInUserVariable(engine, v_StartedProcessName); } + // window name + if (!string.IsNullOrEmpty(v_WindowName)) + { + p.MainWindowTitle.StoreInUserVariable(engine, v_WindowName); + } + // window handle + if (!string.IsNullOrEmpty(v_WindowHandle)) + { + p.MainWindowHandle.StoreInUserVariable(engine, v_WindowHandle); + } - var waitForExit = this.GetUISelectionValue(nameof(v_WaitForExit), engine); + var waitForExit = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WaitForExit), engine); if (waitForExit == "yes") { p.WaitForExit(); } - System.Threading.Thread.Sleep(2000); + //System.Threading.Thread.Sleep(2000); + var waitTimeBeforeNext = this.ExpandValueOrUserVariableAsInteger(nameof(v_WaitTimeBeforeNext), engine); + System.Threading.Thread.Sleep(waitTimeBeforeNext); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/ApplicationScriptFile/StopApplicationCommand.cs b/taskt/Core/Automation/Commands/ApplicationScriptFile/StopApplicationCommand.cs index cba44f69c..ca6afde6d 100644 --- a/taskt/Core/Automation/Commands/ApplicationScriptFile/StopApplicationCommand.cs +++ b/taskt/Core/Automation/Commands/ApplicationScriptFile/StopApplicationCommand.cs @@ -8,19 +8,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Application/Script Commands")] + [Attributes.ClassAttributes.Group("Application/Script")] [Attributes.ClassAttributes.SubGruop("Application")] [Attributes.ClassAttributes.CommandSettings("Stop Application")] - [Attributes.ClassAttributes.Description("This command allows you to stop a program or a process.")] + [Attributes.ClassAttributes.Description("This command allows you to Stop a Application.")] [Attributes.ClassAttributes.UsesDescription("Use this command to close an application by its name such as 'chrome'. Alternatively, you may use the Close Window or Thick App Command instead.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Process.CloseMainWindow'.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_stop_process))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class StopApplicationCommand : ScriptCommand + public sealed class StopApplicationCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] - [PropertyDescription("Application Name")] + [PropertyDescription("Application Process Name")] [InputSpecification("Application Name", true)] [PropertyDetailSampleUsage("**notepad**", "Stop Notepad")] [PropertyDetailSampleUsage("**myapp**", PropertyDetailSampleUsage.ValueType.Value, "Application Name")] @@ -39,11 +40,9 @@ public StopApplicationCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - string shortName = v_ProgramShortName.ConvertToUserVariable(engine); + string shortName = v_ProgramShortName.ExpandValueOrUserVariable(engine); var processes = System.Diagnostics.Process.GetProcessesByName(shortName); foreach (var prc in processes) @@ -58,7 +57,7 @@ private void lnkProcessSelector_Click(object sender, EventArgs e) var ps = System.Diagnostics.Process.GetProcesses() .OrderByDescending(p => p.Id).Select(p => p.ProcessName).ToList(); - using (var fm = new UI.Forms.Supplemental.frmItemSelector(ps)) + using (var fm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmItemSelector(ps)) { if (fm.ShowDialog() == DialogResult.OK) { diff --git a/taskt/Core/Automation/Commands/ApplicationScriptFile/StopCurrentScriptFileCommand.cs b/taskt/Core/Automation/Commands/ApplicationScriptFile/StopCurrentScriptFileCommand.cs index 48eb72d67..4e38b5947 100644 --- a/taskt/Core/Automation/Commands/ApplicationScriptFile/StopCurrentScriptFileCommand.cs +++ b/taskt/Core/Automation/Commands/ApplicationScriptFile/StopCurrentScriptFileCommand.cs @@ -4,16 +4,17 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Application/Script Commands")] + [Attributes.ClassAttributes.Group("Application/Script")] [Attributes.ClassAttributes.SubGruop("taskt Script File")] [Attributes.ClassAttributes.CommandSettings("Stop Current Script File")] [Attributes.ClassAttributes.Description("This command stops the current task.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to stop the current running task.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_stop_process))] [Attributes.ClassAttributes.EnableAutomateRender(true, true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class StopCurrentScriptFileCommand : ScriptCommand + public sealed class StopCurrentScriptFileCommand : ScriptCommand { public StopCurrentScriptFileCommand() { @@ -23,9 +24,8 @@ public StopCurrentScriptFileCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; engine.IsCancellationPending = true; } } diff --git a/taskt/Core/Automation/Commands/ApplicationScriptFile/UnloadScriptFileCommand.cs b/taskt/Core/Automation/Commands/ApplicationScriptFile/UnloadScriptFileCommand.cs index c4031e7fd..db7fad4aa 100644 --- a/taskt/Core/Automation/Commands/ApplicationScriptFile/UnloadScriptFileCommand.cs +++ b/taskt/Core/Automation/Commands/ApplicationScriptFile/UnloadScriptFileCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Application/Script Commands")] + [Attributes.ClassAttributes.Group("Application/Script")] [Attributes.ClassAttributes.SubGruop("taskt Script File")] [Attributes.ClassAttributes.CommandSettings("Unload Script File")] [Attributes.ClassAttributes.Description("This command runs tasks.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to run another task.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_stop_process))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UnloadScriptFileCommand : ScriptCommand + public sealed class UnloadScriptFileCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_NoSample_FilePath))] @@ -48,14 +49,12 @@ public UnloadScriptFileCommand() //this.v_ErrorPreference = "Continue if not found"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //string startFile = FilePathControls.FormatFilePath_NoFileCounter(v_taskPath, engine, "xml", true); var startFile = FilePathControls.WaitForFile(this, nameof(v_taskPath), nameof(v_WaitForFile), engine); - var errorPreference = this.GetUISelectionValue(nameof(v_ErrorPreference), engine); + var errorPreference = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ErrorPreference), engine); if (engine.PreloadedTasks.ContainsKey(startFile)) { diff --git a/taskt/Core/Automation/Commands/BooleanControls.cs b/taskt/Core/Automation/Commands/BooleanControls.cs index 35d04f924..62e4235f0 100644 --- a/taskt/Core/Automation/Commands/BooleanControls.cs +++ b/taskt/Core/Automation/Commands/BooleanControls.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; @@ -29,32 +25,33 @@ internal static class BooleanControls [PropertyValidationRule("Result", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Result")] [PropertyInstanceType(PropertyInstanceType.InstanceType.Boolean, true)] + [PropertyParameterOrder(5000)] public static string v_Result { get; } /// - /// Convert variable to Boolean Value + /// expand value or user variable as Boolean Value /// - /// + /// /// - /// + /// /// - /// - public static bool ConvertToUserVariableAsBool(this string str, string parameterName, object sender) + /// value is not Boolean + public static bool ExpandValueOrUserVariableAsBool(this string value, string parameterName, Core.Automation.Engine.AutomationEngineInstance engine) { - string convertedText = str.ConvertToUserVariable(sender); + string convertedText = value.ExpandValueOrUserVariable(engine); if (bool.TryParse(convertedText, out bool v)) { return v; } else { - throw new Exception(parameterName + " '" + str + "' is not a boolean."); + throw new Exception(parameterName + " '" + value + "' is not a boolean."); } } - public static void StoreInUserVariable(this bool value, Core.Automation.Engine.AutomationEngineInstance sender, string targetVariable) + public static void StoreInUserVariable(this bool value, Engine.AutomationEngineInstance engine, string targetVariable) { - ExtensionMethods.StoreInUserVariable(targetVariable, value ? "TRUE" : "FALSE", sender, false); + ExtensionMethods.StoreInUserVariable(targetVariable, value ? "TRUE" : "FALSE", engine, false); } } } diff --git a/taskt/Core/Automation/Commands/CSharpCodeCompilerControls.cs b/taskt/Core/Automation/Commands/CSharpCodeCompilerControls.cs new file mode 100644 index 000000000..5da5c51a1 --- /dev/null +++ b/taskt/Core/Automation/Commands/CSharpCodeCompilerControls.cs @@ -0,0 +1,30 @@ +using System.CodeDom.Compiler; + +namespace taskt.Core.Automation.Commands +{ + public static class CSharpCodeCompilerControls + { + private const string compilerName = "tasktOnTheFly.exe"; + + public static CompilerResults CompileInput(string codeInput) + { + //define file output + //string Output = "tasktOnTheFly.exe"; + + //create provider + CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp"); + + //create compile parameters + CompilerParameters parameters = new CompilerParameters + { + GenerateExecutable = true, + OutputAssembly = compilerName, + }; + + //compile + //CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, codeInput); + //return results; + return codeProvider.CompileAssemblyFromSource(parameters, codeInput); + } + } +} diff --git a/taskt/Core/Automation/Commands/Color/AColorCreateCommands.cs b/taskt/Core/Automation/Commands/Color/AColorCreateCommands.cs new file mode 100644 index 000000000..8f05af393 --- /dev/null +++ b/taskt/Core/Automation/Commands/Color/AColorCreateCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Color Create commands + /// + public abstract class AColorCreateCommands : ScriptCommand, IColorCreateProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ColorControls), nameof(ColorControls.v_InputColorVariableName))] + [PropertyParameterOrder(5000)] + public string v_Color { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Color/ConvertColorCommand.cs b/taskt/Core/Automation/Commands/Color/ConvertColorCommand.cs index a10ca1d99..48dd0c2bd 100644 --- a/taskt/Core/Automation/Commands/Color/ConvertColorCommand.cs +++ b/taskt/Core/Automation/Commands/Color/ConvertColorCommand.cs @@ -1,23 +1,23 @@ using System; using System.Xml.Serialization; using System.Data; -using System.Drawing; using System.Collections.Generic; -using taskt.Core.Automation.Attributes.PropertyAttributes; using System.Windows.Forms; +using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Color Commands")] + [Attributes.ClassAttributes.Group("Color")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Convert Color")] [Attributes.ClassAttributes.Description("This command allows you to get convert Color Value.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get convert Color Value.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertColorCommand : ScriptCommand + public sealed class ConvertColorCommand : ScriptCommand, ICanHandleColor, IDictionaryResultProperties, IDataTableResultProperties { [XmlAttribute] [PropertyDescription("Color Variable Name")] @@ -76,13 +76,12 @@ public ConvertColorCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - Color co = v_Color.GetColorVariable(engine); - string format = this.GetUISelectionValue(nameof(v_Format), engine); + //Color co = v_Color.ExpandUserVariableAsColor(engine); + var co = this.ExpandUserVariableAsColor(nameof(v_Color), engine); + + string format = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_Format), engine); string res = ""; switch (format) @@ -119,7 +118,9 @@ public override void RunCommand(object sender) { "S", co.GetSaturation().ToString() }, { "L", co.GetBrightness().ToString() } }; - hsl.StoreInUserVariable(engine, v_Result); + //hsl.StoreInUserVariable(engine, v_Result); + //this.StoreDictionaryInUserVariable(hsl, nameof(v_Result), engine); + this.StoreDictionaryInUserVariable(hsl, engine); return; case "cmyk": @@ -150,7 +151,9 @@ public override void RunCommand(object sender) { "Y", y.ToString() }, { "K", k.ToString() } }; - cmyk.StoreInUserVariable(engine, v_Result); + //cmyk.StoreInUserVariable(engine, v_Result); + //this.StoreDictionaryInUserVariable(cmyk, nameof(v_Result), engine); + this.StoreDictionaryInUserVariable(cmyk, engine); return; case "rgba dictionary": @@ -161,7 +164,9 @@ public override void RunCommand(object sender) { "B", co.B.ToString() }, { "A", co.A.ToString() } }; - rgbaDic.StoreInUserVariable(engine, v_Result); + //rgbaDic.StoreInUserVariable(engine, v_Result); + //this.StoreDictionaryInUserVariable(rgbaDic, nameof(v_Result), engine); + this.StoreDictionaryInUserVariable(rgbaDic, engine); return; case "rgba datatable": @@ -175,7 +180,8 @@ public override void RunCommand(object sender) rgbaDT.Rows[0][1] = co.G; rgbaDT.Rows[0][2] = co.B; rgbaDT.Rows[0][3] = co.A; - rgbaDT.StoreInUserVariable(engine, v_Result); + //rgbaDT.StoreInUserVariable(engine, v_Result); + this.StoreDataTableInUserVariable(rgbaDT, engine); return; } res.StoreInUserVariable(engine, v_Result); diff --git a/taskt/Core/Automation/Commands/Color/CreateColorCommand.cs b/taskt/Core/Automation/Commands/Color/CreateColorCommand.cs index db44e2baf..9b76a559e 100644 --- a/taskt/Core/Automation/Commands/Color/CreateColorCommand.cs +++ b/taskt/Core/Automation/Commands/Color/CreateColorCommand.cs @@ -6,19 +6,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Color Commands")] + [Attributes.ClassAttributes.Group("Color")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Create Color")] [Attributes.ClassAttributes.Description("This command allows you to create Color.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create Color.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateColorCommand : ScriptCommand + public sealed class CreateColorCommand : AColorCreateCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ColorControls), nameof(ColorControls.v_InputColorVariableName))] - public string v_Color { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ColorControls), nameof(ColorControls.v_InputColorVariableName))] + //public string v_Color { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ColorControls), nameof(ColorControls.v_ColorValue))] @@ -26,6 +27,7 @@ public class CreateColorCommand : ScriptCommand [PropertyDetailSampleUsage("**{{{vRed}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Red")] [PropertyValidationRule("Red", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.NotBetween)] [PropertyDisplayText(true, "Red")] + [PropertyParameterOrder(6000)] public string v_Red { get; set; } [XmlAttribute] @@ -34,6 +36,7 @@ public class CreateColorCommand : ScriptCommand [PropertyDetailSampleUsage("**{{{vGreen}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Green")] [PropertyValidationRule("Green", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.NotBetween)] [PropertyDisplayText(true, "Green")] + [PropertyParameterOrder(6001)] public string v_Green { get; set; } [XmlAttribute] @@ -42,6 +45,7 @@ public class CreateColorCommand : ScriptCommand [PropertyDetailSampleUsage("**{{{vBlue}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Blue")] [PropertyValidationRule("Blue", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.NotBetween)] [PropertyDisplayText(true, "Blue")] + [PropertyParameterOrder(6002)] public string v_Blue { get; set; } [XmlAttribute] @@ -51,6 +55,7 @@ public class CreateColorCommand : ScriptCommand [PropertyIsOptional(true, "255")] [PropertyValidationRule("Alpha", PropertyValidationRule.ValidationRuleFlags.NotBetween)] [PropertyDisplayText(true, "Alpha")] + [PropertyParameterOrder(6003)] public string v_Alpha { get; set; } public CreateColorCommand() @@ -61,19 +66,17 @@ public CreateColorCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - int r = this.ConvertToUserVariableAsInteger(nameof(v_Red), engine); - int g = this.ConvertToUserVariableAsInteger(nameof(v_Green), engine); - int b = this.ConvertToUserVariableAsInteger(nameof(v_Blue), engine); + int r = this.ExpandValueOrUserVariableAsInteger(nameof(v_Red), engine); + int g = this.ExpandValueOrUserVariableAsInteger(nameof(v_Green), engine); + int b = this.ExpandValueOrUserVariableAsInteger(nameof(v_Blue), engine); - int a = this.ConvertToUserVariableAsInteger(nameof(v_Alpha), engine); + int a = this.ExpandValueOrUserVariableAsInteger(nameof(v_Alpha), engine); - Color co = Color.FromArgb(a, r, g, b); - co.StoreInUserVariable(engine, v_Color); + var co = Color.FromArgb(a, r, g, b); + //co.StoreInUserVariable(engine, v_Color); + this.StoreColorInUserVariable(co, nameof(v_Color), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Color/CreateColorFormExcelColorCommand.cs b/taskt/Core/Automation/Commands/Color/CreateColorFormExcelColorCommand.cs index 17dc63bce..14eddf3a2 100644 --- a/taskt/Core/Automation/Commands/Color/CreateColorFormExcelColorCommand.cs +++ b/taskt/Core/Automation/Commands/Color/CreateColorFormExcelColorCommand.cs @@ -6,19 +6,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Color Commands")] + [Attributes.ClassAttributes.Group("Color")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Create Color From Excel Color")] [Attributes.ClassAttributes.Description("This command allows you to create Color from Excel Color.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create Color from Excel Color.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateColorFromExcelColorCommand : ScriptCommand + public sealed class CreateColorFromExcelColorCommand : AColorCreateCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ColorControls), nameof(ColorControls.v_InputColorVariableName))] - public string v_Color { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ColorControls), nameof(ColorControls.v_InputColorVariableName))] + //public string v_Color { get; set; } [XmlAttribute] [PropertyDescription("Excel Color Value")] @@ -31,6 +32,7 @@ public class CreateColorFromExcelColorCommand : ScriptCommand [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Excel Color", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Color Value")] + [PropertyParameterOrder(6000)] public string v_ExcelColor { get; set; } public CreateColorFromExcelColorCommand() @@ -41,12 +43,9 @@ public CreateColorFromExcelColorCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - int color = this.ConvertToUserVariableAsInteger(nameof(v_ExcelColor), engine); + int color = this.ExpandValueOrUserVariableAsInteger(nameof(v_ExcelColor), engine); color &= 0xFFFFFF; int r = color & 0xFF; @@ -55,8 +54,9 @@ public override void RunCommand(object sender) color >>= 8; int b = color; - Color co = Color.FromArgb(255, r, g, b); - co.StoreInUserVariable(engine, v_Color); + var co = Color.FromArgb(255, r, g, b); + //co.StoreInUserVariable(engine, v_Color); + this.StoreColorInUserVariable(co, nameof(v_Color), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Color/CreateColorFormHexCommand.cs b/taskt/Core/Automation/Commands/Color/CreateColorFormHexCommand.cs index 084b7aa63..c2dd4d9a1 100644 --- a/taskt/Core/Automation/Commands/Color/CreateColorFormHexCommand.cs +++ b/taskt/Core/Automation/Commands/Color/CreateColorFormHexCommand.cs @@ -6,19 +6,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Color Commands")] + [Attributes.ClassAttributes.Group("Color")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Create Color From HEX")] [Attributes.ClassAttributes.Description("This command allows you to create Color from HEX.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create Color from HEX.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateColorFromHexCommand : ScriptCommand + public sealed class CreateColorFromHexCommand : AColorCreateCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ColorControls), nameof(ColorControls.v_InputColorVariableName))] - public string v_Color { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ColorControls), nameof(ColorControls.v_InputColorVariableName))] + //public string v_Color { get; set; } [XmlAttribute] [PropertyDescription("Color HEX Value")] @@ -32,6 +33,7 @@ public class CreateColorFromHexCommand : ScriptCommand [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Hex", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Hex")] + [PropertyParameterOrder(6000)] public string v_Hex { get; set; } public CreateColorFromHexCommand() @@ -42,12 +44,9 @@ public CreateColorFromHexCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - string hex = v_Hex.ConvertToUserVariable(engine); + string hex = v_Hex.ExpandValueOrUserVariable(engine); if (hex.Length > 6) { hex = hex.Substring(hex.Length - 6); @@ -58,8 +57,9 @@ public override void RunCommand(object sender) hex = hex.Substring(0, hex.Length - 2); int r = Int32.Parse(hex.Substring(hex.Length - 2), System.Globalization.NumberStyles.HexNumber); - Color co = Color.FromArgb(255, r, g, b); - co.StoreInUserVariable(engine, v_Color); + var co = Color.FromArgb(255, r, g, b); + //co.StoreInUserVariable(engine, v_Color); + this.StoreColorInUserVariable(co, nameof(v_Color), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Color/EM_CanHandleColorExtensionMethods.cs b/taskt/Core/Automation/Commands/Color/EM_CanHandleColorExtensionMethods.cs new file mode 100644 index 000000000..d0d9e4e2d --- /dev/null +++ b/taskt/Core/Automation/Commands/Color/EM_CanHandleColorExtensionMethods.cs @@ -0,0 +1,93 @@ +using System; +using System.Drawing; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_CanHandleColorExtensionMethods + { + /// + /// Check object is Color + /// + /// + /// + /// + public static bool IsColor(object value, out Color c) + { + // TODO: it's ok? not extension methods + c = default; + if (value is Color x) + { + c = x; + return true; + } + else + { + return false; + } + } + + /// + /// Expand User Variable as Color + /// + /// + /// + /// + /// + public static Color ExpandUserVariableAsColor(ScriptVariable variable) + { + // TODO: it's ok? not extension methods + if (IsColor(variable.VariableValue, out Color color)) + { + return color; + } + else + { + throw new Exception($"Variable '{variable.VariableName}' is not Color"); + } + } + + /// + /// expand variable as Color + /// + /// + /// + /// + /// + /// + public static Color ExpandUserVariableAsColor(this ICanHandleColor command, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "Color Variable"); + //var v = variableName.GetRawVariable(engine); + //if (v.VariableValue is Color color) + //{ + // return color; + //} + //else + //{ + // throw new Exception($"Variable '{variableName}' is not Color"); + //} + try + { + return ExpandUserVariableAsColor(variableName.GetRawVariable(engine)); + } + catch + { + throw new Exception($"Variable '{variableName}' is not Color"); + } + } + + /// + /// store color in User Variable + /// + /// + /// + /// + /// + public static void StoreColorInUserVariable(this ICanHandleColor command, Color c, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "Color Variable"); + ExtensionMethods.StoreInUserVariable(variableName, c, engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/Color/ICanHandleColor.cs b/taskt/Core/Automation/Commands/Color/ICanHandleColor.cs new file mode 100644 index 000000000..e97b62c41 --- /dev/null +++ b/taskt/Core/Automation/Commands/Color/ICanHandleColor.cs @@ -0,0 +1,9 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for Color Variable type + /// + public interface ICanHandleColor : ILExpandableProperties + { + } +} diff --git a/taskt/Core/Automation/Commands/Color/IColorCreateProperties.cs b/taskt/Core/Automation/Commands/Color/IColorCreateProperties.cs new file mode 100644 index 000000000..35d33902e --- /dev/null +++ b/taskt/Core/Automation/Commands/Color/IColorCreateProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// color create properties + /// + public interface IColorCreateProperties : ICanHandleColor + { + /// + /// color variable name + /// + string v_Color { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Color/IColorProperties.cs b/taskt/Core/Automation/Commands/Color/IColorProperties.cs new file mode 100644 index 000000000..1ea602bbd --- /dev/null +++ b/taskt/Core/Automation/Commands/Color/IColorProperties.cs @@ -0,0 +1,14 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Color Properties + /// + public interface IColorProperties : ICanHandleColor + { + // TODO: atodeyaru + /// + /// Color Variable Name + /// + string v_Color { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/ColorControls.cs b/taskt/Core/Automation/Commands/ColorControls.cs index 622c6d134..0c76da1f4 100644 --- a/taskt/Core/Automation/Commands/ColorControls.cs +++ b/taskt/Core/Automation/Commands/ColorControls.cs @@ -1,5 +1,4 @@ -using System; -using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { @@ -20,6 +19,7 @@ internal static class ColorControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("Variable", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Variable")] + [PropertyParameterOrder(5000)] public static string v_InputColorVariableName { get; } /// @@ -35,31 +35,32 @@ internal static class ColorControls [PropertyValidationRule("Value", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.NotBetween)] [PropertyValueRange(0, 255)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(5000)] public static string v_ColorValue { get; } - /// - /// Get Color variable from Variable name. This type is System.Drawing.Color. - /// - /// - /// - /// - /// Variable not Color - public static System.Drawing.Color GetColorVariable(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) - { - Script.ScriptVariable v = variableName.GetRawVariable(engine); - if (v.VariableValue is System.Drawing.Color color) - { - return color; - } - else - { - throw new Exception("Variable " + variableName + " is not Color"); - } - } + ///// + ///// Expand user variable as Color. This type is System.Drawing.Color. + ///// + ///// + ///// + ///// + ///// Value is not Color + //public static System.Drawing.Color ExpandUserVariableAsColor(this string variableName, Engine.AutomationEngineInstance engine) + //{ + // var v = variableName.GetRawVariable(engine); + // if (v.VariableValue is System.Drawing.Color color) + // { + // return color; + // } + // else + // { + // throw new Exception("Variable " + variableName + " is not Color"); + // } + //} - public static void StoreInUserVariable(this System.Drawing.Color value, Core.Automation.Engine.AutomationEngineInstance sender, string targetVariable) - { - ExtensionMethods.StoreInUserVariable(targetVariable, value, sender); - } + //public static void StoreInUserVariable(this System.Drawing.Color value, Engine.AutomationEngineInstance engine, string targetVariable) + //{ + // ExtensionMethods.StoreInUserVariable(targetVariable, value, engine); + //} } } diff --git a/taskt/Core/Automation/Commands/ConditionControls.cs b/taskt/Core/Automation/Commands/ConditionControls.cs index 383f56233..8bf598acb 100644 --- a/taskt/Core/Automation/Commands/ConditionControls.cs +++ b/taskt/Core/Automation/Commands/ConditionControls.cs @@ -4,7 +4,7 @@ using System.Collections.Generic; using System.Linq; using taskt.Core.Automation.Attributes.PropertyAttributes; -using System.Runtime.CompilerServices; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { @@ -17,7 +17,7 @@ public static bool DetermineStatementTruth(string actionType, DataTable actionPa //string actionType = actionType.ConvertToUserVariable(engine); - switch (actionType.ConvertToUserVariable(engine).ToLower()) + switch (actionType.ExpandValueOrUserVariable(engine).ToLower()) { //case "value": case "numeric compare": @@ -104,7 +104,7 @@ private static bool DetermineStatementTruth_NumericCompare(DataTable actionParam { var param = DataTableControls.GetFieldValues(actionParameterTable, "Parameter Name", "Parameter Value", engine); - string operand = param["Operand"].ConvertToUserVariable(engine); + string operand = param["Operand"].ExpandValueOrUserVariable(engine); bool isBoolCompare = false; decimal value1 = 0; @@ -119,8 +119,8 @@ private static bool DetermineStatementTruth_NumericCompare(DataTable actionParam default: //value1 = param["Value1"].ConvertToUserVariableAsDecimal("Value1", engine); //value2 = param["Value2"].ConvertToUserVariableAsDecimal("Value2", engine); - value1 = new PropertyConvertTag(param["Value1"], "Value1").ConvertToUserVariableAsDecimal(engine); - value2 = new PropertyConvertTag(param["Value2"], "Value2").ConvertToUserVariableAsDecimal(engine); + value1 = new PropertyConvertTag(param["Value1"], "Value1").ExpandValueOrUserVariableAsDecimal(engine); + value2 = new PropertyConvertTag(param["Value2"], "Value2").ExpandValueOrUserVariableAsDecimal(engine); break; } @@ -174,10 +174,10 @@ private static bool DetermineStatementTruth_DateCompare(DataTable actionParamete { var param = DataTableControls.GetFieldValues(actionParameterTable, "Parameter Name", "Parameter Value", false); - string operand = param["Operand"].ConvertToUserVariable(engine); + string operand = param["Operand"].ExpandValueOrUserVariable(engine); - DateTime dt1 = param["Value1"].ConvertToUserVariableAsDateTime("Value1", engine); - DateTime dt2 = param["Value2"].ConvertToUserVariableAsDateTime("Value2", engine); + DateTime dt1 = param["Value1"].ConvertValueToDateTime("Value1", engine); + DateTime dt2 = param["Value2"].ConvertValueToDateTime("Value2", engine); bool ifResult; switch (operand.ToLower()) @@ -278,7 +278,7 @@ private static bool DetermineStatementTruth_VariableIsNumeric(DataTable actionPa private static bool DetermineStatementTruth_ErrorOccur(DataTable actionParameterTable, Engine.AutomationEngineInstance engine, bool inverseResult = false) { var param = DataTableControls.GetFieldValues(actionParameterTable, "Parameter Name", "Parameter Value", false); - int lineNumber = param["Line Number"].ConvertToUserVariableAsInteger("Line Number", engine); + int lineNumber = param["Line Number"].ExpandValueOrUserVariableAsInteger("Line Number", engine); bool result; @@ -305,7 +305,7 @@ private static bool DetermineStatementTruth_WindowNameExists(DataTable actionPar var param = DataTableControls.GetFieldValues(actionParameterTable, "Parameter Name", "Parameter Value", engine); try { - IntPtr wHnd = WindowNameControls.FindWindowHandle(param["Window Name"], param["Search Method"], engine); + IntPtr wHnd = WindowControls.FindWindowHandle(param["Window Name"], param["Search Method"], engine); return true; } catch @@ -316,8 +316,8 @@ private static bool DetermineStatementTruth_WindowNameExists(DataTable actionPar private static bool DetermineStatementTruth_ActiveWindow(DataTable actionParameterTable, Engine.AutomationEngineInstance engine) { var param = DataTableControls.GetFieldValues(actionParameterTable, "Parameter Name", "Parameter Value", engine); - var searchFunc = WindowNameControls.GetWindowNameCompareMethod(param["Search Method"]); - return (searchFunc(WindowNameControls.GetCurrentWindowName(), param["Window Name"])); + var searchFunc = WindowControls.GetWindowNameCompareMethod(param["Search Method"]); + return (searchFunc(WindowControls.GetCurrentWindowName(), param["Window Name"])); } private static bool DetermineStatementTruth_File(DataTable actionParameterTable, Engine.AutomationEngineInstance engine) { @@ -363,16 +363,21 @@ private static bool DetermineStatementTruth_WebElement(DataTable actionParameter //newElementActionCommand.v_InstanceName = param["WebBrowser Instance Name"]; //bool elementExists = newElementActionCommand.ElementExists(engine, param["Element Search Method"], param["Element Search Parameter"]); - var checkWebElement = new SeleniumBrowserCheckWebElementExistsCommand() + using (var res = new InnerScriptVariable(engine)) { - v_InstanceName = param["WebBrowser Instance Name"], - v_SeleniumSearchType = param["Element Search Method"], - v_SeleniumSearchParameter = param["Element Search Parameter"], - v_Result = VariableNameControls.GetInnerVariableName(0, engine), - }; - checkWebElement.RunCommand(engine); + var checkWebElement = new SeleniumBrowserCheckWebElementExistsCommand() + { + v_InstanceName = param["WebBrowser Instance Name"], + v_SeleniumSearchType = param["Element Search Method"], + v_SeleniumSearchParameter = param["Element Search Parameter"], + //v_Result = VariableNameControls.GetInnerVariableName(0, engine), + v_Result = res.VariableName, + }; + checkWebElement.RunCommand(engine); - return VariableNameControls.GetInnerVariable(0, engine).VariableValue.ToString().ConvertToUserVariableAsBool("Result", engine); + //return VariableNameControls.GetInnerVariable(0, engine).VariableValue.ToString().ExpandValueOrUserVariableAsBool("Result", engine); + return res.VariableValue.ToString().ExpandValueOrUserVariableAsBool("Result", engine); + } } private static bool DetermineStatementTruth_GUIElement(DataTable actionParameterTable, Engine.AutomationEngineInstance engine) @@ -380,10 +385,11 @@ private static bool DetermineStatementTruth_GUIElement(DataTable actionParameter var param = DataTableControls.GetFieldValues(actionParameterTable, "Parameter Name", "Parameter Value", engine); string windowName = param["Window Name"]; - if (windowName == engine.engineSettings.CurrentWindowKeyword) + //if (windowName == engine.engineSettings.CurrentWindowKeyword) + if (windowName == VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Window_CurrentWindowName.VariableName, engine)) { //windowName = User32.User32Functions.GetActiveWindowTitle(); - windowName = WindowNameControls.GetActiveWindowTitle(); + windowName = WindowControls.GetActiveWindowTitle(); } var searchTb = new DataTable(); @@ -392,21 +398,40 @@ private static bool DetermineStatementTruth_GUIElement(DataTable actionParameter searchTb.Columns.Add("ParameterValue"); searchTb.Rows.Add(true, param["Element Search Method"], param["Element Search Parameter"]); - var vName = VariableNameControls.GetInnerVariableName(2, engine); + //var vName = VariableNameControls.GetInnerVariableName(2, engine); + + //var actionTb = new DataTable(); + //actionTb.Columns.Add("Parameter Name"); + //actionTb.Columns.Add("Parameter Value"); + //actionTb.Rows.Add("Apply To Variable", vName); - var actionTb = new DataTable(); - actionTb.Columns.Add("Parameter Name"); - actionTb.Columns.Add("Parameter Value"); - actionTb.Rows.Add("Apply To Variable", vName); + //var checkUI = new UIAutomationUIElementActionCommand(); + //checkUI.v_WindowName = windowName; + //checkUI.v_UIASearchParameters = searchTb; + //checkUI.v_AutomationType = "Check UIElement Exists"; + //checkUI.v_UIAActionParameters = actionTb; + //checkUI.RunCommand(engine); - var checkUI = new UIAutomationUIElementActionCommand(); - checkUI.v_WindowName = windowName; - checkUI.v_UIASearchParameters = searchTb; - checkUI.v_AutomationType = "Check UIElement Exists"; - checkUI.v_UIAActionParameters = actionTb; - checkUI.RunCommand(engine); + //return vName.ExpandValueOrUserVariableAsBool("result", engine); - return vName.ConvertToUserVariableAsBool("result", engine); + using (var myName = new InnerScriptVariable(engine)) + { + var actionTb = new DataTable(); + actionTb.Columns.Add("Parameter Name"); + actionTb.Columns.Add("Parameter Value"); + actionTb.Rows.Add("Apply To Variable", myName.VariableName); + + var checkUI = new UIAutomationUIElementActionCommand + { + v_WindowName = windowName, + v_UIASearchParameters = searchTb, + v_AutomationType = "Check UIElement Exists", + v_UIAActionParameters = actionTb, + }; + checkUI.RunCommand(engine); + + return myName.VariableValue.ToString().ExpandValueOrUserVariableAsBool("result", engine); + } //UIAutomationUIElementActionCommand newUIACommand = new UIAutomationUIElementActionCommand(); //newUIACommand.v_WindowName = windowName; @@ -446,8 +471,8 @@ private static bool DetermineStatementTruth_Boolean(DataTable actionParamterTabl { var param = DataTableControls.GetFieldValues(actionParamterTable, "Parameter Name", "Parameter Value", false); - bool value = param["Variable Name"].ConvertToUserVariableAsBool("Variable Name", engine); - string compare = param["Value Is"].ConvertToUserVariable(engine); + bool value = param["Variable Name"].ExpandValueOrUserVariableAsBool("Variable Name", engine); + string compare = param["Value Is"].ExpandValueOrUserVariable(engine); switch (compare.ToLower()) { @@ -463,9 +488,9 @@ private static bool DetermineStatementTruth_BooleanCompare(DataTable actionParam { var param = DataTableControls.GetFieldValues(actionParamterTable, "Parameter Name", "Parameter Value", false); - bool value1 = param["Value1"].ConvertToUserVariableAsBool("Variable Name", engine); - bool value2 = param["Value2"].ConvertToUserVariableAsBool("Variable Name", engine); - string operand = param["Operand"].ConvertToUserVariable(engine); + bool value1 = param["Value1"].ExpandValueOrUserVariableAsBool("Variable Name", engine); + bool value2 = param["Value2"].ExpandValueOrUserVariableAsBool("Variable Name", engine); + string operand = param["Operand"].ExpandValueOrUserVariable(engine); switch (operand.ToLower()) { @@ -490,8 +515,11 @@ private static bool DetermineStatementTruth_ListCompare(DataTable actionParamter { var param = DataTableControls.GetFieldValues(actionParamterTable, "Parameter Name", "Parameter Value", false); - var list1 = param["List1"].GetListVariable(engine); - var list2 = param["List2"].GetListVariable(engine); + //var list1 = param["List1"].ExpandUserVariableAsList(engine); + //var list2 = param["List2"].ExpandUserVariableAsList(engine); + + var list1 = EM_CanHandleListExtensionMethods.ExpandUserVariableAsList(param["List1"].GetRawVariable(engine)); + var list2 = EM_CanHandleListExtensionMethods.ExpandUserVariableAsList(param["List2"].GetRawVariable(engine)); if (list1.Count == list2.Count) { @@ -514,8 +542,11 @@ private static bool DetermineStatementTruth_DictionaryCompare(DataTable actionPa { var param = DataTableControls.GetFieldValues(actionParamterTable, "Parameter Name", "Parameter Value", false); - var dic1 = param["Dictionary1"].GetDictionaryVariable(engine); - var dic2 = param["Dictionary2"].GetDictionaryVariable(engine); + //var dic1 = param["Dictionary1"].ExpandUserVariableAsDictinary(engine); + //var dic2 = param["Dictionary2"].ExpandUserVariableAsDictinary(engine); + + var dic1 = EM_CanHandleDictionary.ExpandUserVariableAsDictionary(param["Dictionary1"].GetRawVariable(engine)); + var dic2 = EM_CanHandleDictionary.ExpandUserVariableAsDictionary(param["Dictionary2"].GetRawVariable(engine)); if (dic1.Count == dic2.Count) { @@ -543,8 +574,11 @@ private static bool DetermineStatementTruth_DataTableCompare(DataTable actionPar { var param = DataTableControls.GetFieldValues(actionParamterTable, "Parameter Name", "Parameter Value", false); - var dt1 = param["DataTable1"].GetDataTableVariable(engine); - var dt2 = param["DataTable2"].GetDataTableVariable(engine); + var dt1 = EM_CanHandleDataTable.ExpandUserVariableAsDataTable(param["DataTable1"].GetRawVariable(engine)); + var dt2 = EM_CanHandleDataTable.ExpandUserVariableAsDataTable(param["DataTable2"].GetRawVariable(engine)); + + //var dt1 = param["DataTable1"].ExpandUserVariableAsDataTable(engine); + //var dt2 = param["DataTable2"].ExpandUserVariableAsDataTable(engine); if ((dt1.Rows.Count == dt2.Rows.Count) && (dt1.Columns.Count == dt2.Columns.Count)) { @@ -762,7 +796,8 @@ public static void RenderGUIElement(object sender, DataGridView actionParameterB actionParameterBox.Visible = true; if (sender != null) { - actionParameters.Rows.Add("Window Name", settings.EngineSettings.CurrentWindowKeyword); + //actionParameters.Rows.Add("Window Name", settings.EngineSettings.CurrentWindowKeyword); + actionParameters.Rows.Add("Window Name", VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Window_CurrentWindowName.VariableName, settings)); actionParameters.Rows.Add("Element Search Method", ""); actionParameters.Rows.Add("Element Search Parameter", ""); actionParameterBox.DataSource = actionParameters; @@ -788,7 +823,7 @@ public static void RenderGUIElement(object sender, DataGridView actionParameterB parameterName.Items.Add("LocalizedControlType"); parameterName.Items.Add("Name"); parameterName.Items.Add("NativeWindowHandle"); - parameterName.Items.Add("ProcessID"); + parameterName.Items.Add("ProcessId"); //assign cell as a combobox actionParameterBox.Rows[1].Cells[1] = parameterName; @@ -1363,7 +1398,7 @@ private static void RenderFilter_Text(DataTable actionParameters, DataGridView a case "is not numeric": break; default: - int x = actionParametersBox.Rows.Count; + //int x = actionParametersBox.Rows.Count; var cmb = new DataGridViewComboBoxCell(); cmb.Items.AddRange(new string[] { "Yes", "No" }); actionParametersBox.Rows[1].Cells[1] = cmb; @@ -1436,7 +1471,7 @@ private static void RenderFilter_Numeric(DataTable actionParameters, DataGridVie /// public static Func, bool> GetFilterDeterminStatementTruthFunc(string targetTypeName, string filterActionName, Dictionary parameters, taskt.Core.Automation.Engine.AutomationEngineInstance engine, ScriptCommand command) { - string tp = command.GetUISelectionValue(targetTypeName, "Target Type", engine); + string tp = command.ExpandValueOrUserVariableAsSelectionItem(targetTypeName, "Target Type", engine); switch (tp) { case "text": @@ -1449,7 +1484,7 @@ public static Func, bool> GetFilterDeterminSt private static Func, bool> GetFilterDeterminStatementTruthFunc_Text(string filterActionName, Dictionary parameters, taskt.Core.Automation.Engine.AutomationEngineInstance engine, ScriptCommand command) { - string filterAction = command.ConvertToUserVariable(filterActionName, "Filter Action", engine).ToLower(); + string filterAction = command.ExpandValueOrUserVariable(filterActionName, "Filter Action", engine).ToLower(); Func checkFunc = null; switch (filterAction) { @@ -1549,7 +1584,7 @@ private static Func, bool> GetFilterDeterminS } private static Func, bool> GetFilterDeterminStatementTruthFunc_Numeric(string filterActionName, Dictionary parameters, taskt.Core.Automation.Engine.AutomationEngineInstance engine, ScriptCommand command) { - string filterAction = command.ConvertToUserVariable(filterActionName, "Filter Action", engine).ToLower(); + string filterAction = command.ExpandValueOrUserVariable(filterActionName, "Filter Action", engine).ToLower(); Func, (decimal trgValue, decimal value1, decimal value2)> convFunc; switch (filterAction) @@ -1558,17 +1593,17 @@ private static Func, bool> GetFilterDeterminS case "not between": convFunc = (txt, p) => { - decimal tv = new PropertyConvertTag(txt, "Value").ConvertToUserVariableAsDecimal(engine); - decimal v1 = new PropertyConvertTag(p["Value1"], "Compared Value1").ConvertToUserVariableAsDecimal(engine); - decimal v2 = new PropertyConvertTag(p["Value2"], "Compared Value2").ConvertToUserVariableAsDecimal(engine); + decimal tv = new PropertyConvertTag(txt, "Value").ExpandValueOrUserVariableAsDecimal(engine); + decimal v1 = new PropertyConvertTag(p["Value1"], "Compared Value1").ExpandValueOrUserVariableAsDecimal(engine); + decimal v2 = new PropertyConvertTag(p["Value2"], "Compared Value2").ExpandValueOrUserVariableAsDecimal(engine); return (tv, v1, v2); }; break; default: convFunc = (txt, p) => { - decimal tv = new PropertyConvertTag(txt, "Value").ConvertToUserVariableAsDecimal(engine); - decimal v1 = new PropertyConvertTag(p["Value"], "Compared Value").ConvertToUserVariableAsDecimal(engine); + decimal tv = new PropertyConvertTag(txt, "Value").ExpandValueOrUserVariableAsDecimal(engine); + decimal v1 = new PropertyConvertTag(p["Value"], "Compared Value").ExpandValueOrUserVariableAsDecimal(engine); return (tv, v1, 0); }; break; diff --git a/taskt/Core/Automation/Commands/Data/DateCalculationCommand.cs b/taskt/Core/Automation/Commands/Data/DateCalculationCommand.cs index 10955ba60..cac7c72fa 100644 --- a/taskt/Core/Automation/Commands/Data/DateCalculationCommand.cs +++ b/taskt/Core/Automation/Commands/Data/DateCalculationCommand.cs @@ -8,13 +8,13 @@ namespace taskt.Core.Automation.Commands { - [Serializable] - [Attributes.ClassAttributes.Group("Data Commands")] + [Attributes.ClassAttributes.Group("Data")] [Attributes.ClassAttributes.Description("This command allows you to build a date and apply it to a variable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to perform a date calculation.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] - public class DateCalculationCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + public sealed class DateCalculationCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please supply the date value or variable")] @@ -84,10 +84,10 @@ public DateCalculationCommand() //this.v_ToStringFormat = "MM/dd/yyyy hh:mm:ss"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //get variablized string - var variableDateTime = v_InputValue.ConvertToUserVariable(sender); + var variableDateTime = v_InputValue.ExpandValueOrUserVariable(engine); //convert to date time DateTime requiredDateTime; @@ -98,7 +98,7 @@ public override void RunCommand(object sender) //get increment value double requiredInterval; - var variableIncrement = v_Increment.ConvertToUserVariable(sender); + var variableIncrement = v_Increment.ExpandValueOrUserVariable(engine); //convert to double if (!Double.TryParse(variableIncrement, out requiredInterval)) @@ -144,15 +144,15 @@ public override void RunCommand(object sender) } //handle if formatter is required - var formatting = v_ToStringFormat.ConvertToUserVariable(sender); + var formatting = v_ToStringFormat.ExpandValueOrUserVariable(engine); var stringDateFormatted = requiredDateTime.ToString(formatting); //store string in variable - stringDateFormatted.StoreInUserVariable(sender, v_applyToVariableName); + stringDateFormatted.StoreInUserVariable(engine, v_applyToVariableName); } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -212,7 +212,7 @@ public override string GetDisplayValue() } - public override bool IsValidate(frmCommandEditor editor) + public override bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { this.IsValid = true; this.validationResult = ""; diff --git a/taskt/Core/Automation/Commands/Data/FormatDataCommand.cs b/taskt/Core/Automation/Commands/Data/FormatDataCommand.cs index a93a66a16..919d94241 100644 --- a/taskt/Core/Automation/Commands/Data/FormatDataCommand.cs +++ b/taskt/Core/Automation/Commands/Data/FormatDataCommand.cs @@ -1,22 +1,21 @@ using System; using System.Xml.Serialization; -using System.IO; -using System.Collections.Generic; using System.Windows.Forms; -using taskt.UI.Forms; using taskt.UI.CustomControls; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Data Commands")] + [Attributes.ClassAttributes.Group("Data")] [Attributes.ClassAttributes.Description("This command allows you to apply formatting to a string")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to apply specific formatting to text or a variable")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class FormatDataCommand : ScriptCommand + public sealed class FormatDataCommand : ScriptCommand { [XmlAttribute] [PropertyDescription("Please supply the value or variable.")] @@ -44,7 +43,7 @@ public class FormatDataCommand : ScriptCommand [XmlAttribute] [PropertyDescription("Specify required output format")] [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyCustomUIHelper("Format Checker", "lnkFormatChecker_Click")] + [PropertyCustomUIHelper("Format Checker", nameof(lnkFormatChecker_Click))] [InputSpecification("Specify if a specific string format is required.")] [SampleUsage("**MM/dd/yy** or **hh:mm** or **#.0** or **file** etc.")] [Remarks("Path supports **file**, **folder**, **filewithoutextension**, **extension**, **drive**")] @@ -78,49 +77,47 @@ public FormatDataCommand() //this.v_ToStringFormat = "MM/dd/yyyy"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - - //get variablized string - //var variableString = v_InputValue.ConvertToUserVariable(sender); - - //get formatting - //var formatting = v_ToStringFormat.ConvertToUserVariable(sender); - - //var variableName = v_applyToVariableName.ConvertToUserVariable(sender); - - //string formattedString = ""; switch (v_FormatType) { case "Date": - //if (DateTime.TryParse(variableString, out var parsedDate)) - //{ - // formattedString = parsedDate.ToString(formatting); - //} + //var inner0 = VariableNameControls.GetInnerVariableName(0, engine); - var inner0 = VariableNameControls.GetInnerVariableName(0, engine); + //var dateTimeFromText = new CreateDateTimeFromTextCommand() + //{ + // v_Text = v_InputValue, + // v_DateTime = inner0 + //}; + //dateTimeFromText.RunCommand(engine); + //var formatDateTime = new FormatDateTimeCommand() + //{ + // v_DateTime = inner0, + // v_Format = v_ToStringFormat, + // v_Result = v_applyToVariableName + //}; + //formatDateTime.RunCommand(engine); - var dateTimeFromText = new CreateDateTimeFromTextCommand() - { - v_Text = v_InputValue, - v_DateTime = inner0 - }; - dateTimeFromText.RunCommand(engine); - var formatDateTime = new FormatDateTimeCommand() + using(var myVar = new InnerScriptVariable(engine)) { - v_DateTime = inner0, - v_Format = v_ToStringFormat, - v_Result = v_applyToVariableName - }; - formatDateTime.RunCommand(engine); + var dateTimeFromText = new CreateDateTimeFromTextCommand() + { + v_Text = v_InputValue, + v_DateTime = myVar.VariableName, + }; + dateTimeFromText.RunCommand(engine); + + var formatDateTime = new FormatDateTimeCommand() + { + v_DateTime = myVar.VariableName, + v_Format = v_ToStringFormat, + v_Result = v_applyToVariableName + }; + formatDateTime.RunCommand(engine); + } break; - case "Number": - //if (Decimal.TryParse(variableString, out var parsedDecimal)) - //{ - // formattedString = parsedDecimal.ToString(formatting); - //} + case "Number": var formatNumber = new FormatNumberCommand() { v_Number = v_InputValue, @@ -129,44 +126,10 @@ public override void RunCommand(object sender) }; formatNumber.RunCommand(engine); break; - case "Path": - //switch(formatting.ToLower()) - //{ - // case "file": - // case "filename": - // case "fn": - // formattedString = Path.GetFileName(variableString); - // break; - - // case "folder": - // case "directory": - // case "dir": - // formattedString = Path.GetDirectoryName(variableString); - // break; - // case "filewithoutextension": - // case "filenamewithoutextension": - // case "fnwoext": - // formattedString = Path.GetFileNameWithoutExtension(variableString); - // break; - - // case "extension": - // case "ext": - // formattedString = Path.GetExtension(variableString); - // break; - - // case "drive": - // case "drivename": - // case "root": - // formattedString = Path.GetPathRoot(variableString); - // break; - - // default: - // formattedString = ""; - // break; - //} - var variableString = v_InputValue.ConvertToUserVariable(engine); - var formatting = v_ToStringFormat.ConvertToUserVariable(engine); + case "Path": + var variableString = v_InputValue.ExpandValueOrUserVariable(engine); + var formatting = v_ToStringFormat.ExpandValueOrUserVariable(engine); var formattedString = FilePathControls.FormatFileFolderPath(variableString, formatting); formattedString.StoreInUserVariable(engine, v_applyToVariableName); break; @@ -174,92 +137,12 @@ public override void RunCommand(object sender) default: throw new Exception("Formatter Type Not Supported: " + v_FormatType); } - - //if (formattedString == "") - //{ - // throw new InvalidDataException("Unable to convert '" + variableString + "' to type '" + v_FormatType + "'"); - //} - //else - //{ - // formattedString.StoreInUserVariable(sender, v_applyToVariableName); - //} } private void lnkFormatChecker_Click(object sender, EventArgs e) { - //using (var fm = new UI.Forms.Supplement_Forms.frmFormatChecker()) - //{ - // if (fm.ShowDialog() == DialogResult.OK) - // { - // ((TextBox)((CommandItemControl)sender).Tag).Text = fm.Format; - // } - //} TextBox txt = (TextBox)((CommandItemControl)sender).Tag; - UI.Forms.Supplement_Forms.frmFormatChecker.ShowFormatCheckerFormLinkClicked(txt); + UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmFormatChecker.ShowFormatCheckerFormLinkClicked(txt); } - - //public override List Render(frmCommandEditor editor) - //{ - // base.Render(editor); - - // //create standard group controls - // //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InputValue", this, editor)); - - // ////RenderedControls.Add(CommandControls.CreateDefaultLabelFor("v_FormatType", this)); - // ////RenderedControls.Add(CommandControls.CreateDropdownFor("v_FormatType", this)); - // //var typeCtrls = CommandControls.CreateDefaultDropdownGroupFor("v_FormatType", this, editor); - // //RenderedControls.AddRange(typeCtrls); - - // //var formatCtls = CommandControls.CreateDefaultInputGroupFor("v_ToStringFormat", this, editor); - // //RenderedControls.AddRange(formatCtls); - - // //RenderedControls.Add(CommandControls.CreateDefaultLabelFor("v_applyToVariableName", this)); - // //var VariableNameControl = CommandControls.CreateStandardComboboxFor("v_applyToVariableName", this).AddVariableNames(editor); - // //RenderedControls.AddRange(CommandControls.CreateUIHelpersFor("v_applyToVariableName", this, new Control[] { VariableNameControl }, editor)); - // //RenderedControls.Add(VariableNameControl); - - // RenderedControls.AddRange(CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor)); - - // //if (editor.creationMode == frmCommandEditor.CreationMode.Add) - // //{ - // // this.v_InputValue = CommandControls.replaceApplicationKeyword("{{{DateTime.Now}}}"); - // //} - - // return RenderedControls; - - //} - //public override string GetDisplayValue() - //{ - // return base.GetDisplayValue() + " [Format '" + v_InputValue + "' and Apply Result to Variable '" + v_applyToVariableName + "']"; - //} - - //public override bool IsValidate(frmCommandEditor editor) - //{ - // this.IsValid = true; - // this.validationResult = ""; - - // if (String.IsNullOrEmpty(this.v_InputValue)) - // { - // this.validationResult += "Value is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(this.v_FormatType)) - // { - // this.validationResult += "Type of data is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(this.v_FormatType)) - // { - // this.validationResult += "Output format is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(this.v_applyToVariableName)) - // { - // this.validationResult += "Variable is empty.\n"; - // this.IsValid = false; - // } - - // return this.IsValid; - //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Data/HTMLGetHTMLTextByXPath.cs b/taskt/Core/Automation/Commands/Data/HTMLGetHTMLTextByXPath.cs index 442257f7d..358af3a5f 100644 --- a/taskt/Core/Automation/Commands/Data/HTMLGetHTMLTextByXPath.cs +++ b/taskt/Core/Automation/Commands/Data/HTMLGetHTMLTextByXPath.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Data Commands")] + [Attributes.ClassAttributes.Group("Data")] [Attributes.ClassAttributes.CommandSettings("Get HTML Text By XPath")] [Attributes.ClassAttributes.Description("This command processes an HTML source object")] [Attributes.ClassAttributes.UsesDescription("Use this command to parse and extract data from a successful **HTTP Request Command**")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class HTMLGetHTMLTextByXPath : ScriptCommand + public sealed class HTMLGetHTMLTextByXPath : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -48,15 +49,15 @@ public HTMLGetHTMLTextByXPath() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); - doc.LoadHtml(v_userVariableName.ConvertToUserVariable(sender)); + doc.LoadHtml(v_userVariableName.ExpandValueOrUserVariable(engine)); var div = doc.DocumentNode.SelectSingleNode(v_xPathQuery); string divString = div.InnerText; - divString.StoreInUserVariable(sender, v_applyToVariableName); + divString.StoreInUserVariable(engine, v_applyToVariableName); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Data/LogDataCommand.cs b/taskt/Core/Automation/Commands/Data/LogDataCommand.cs index 0b97cbc70..8181b0a79 100644 --- a/taskt/Core/Automation/Commands/Data/LogDataCommand.cs +++ b/taskt/Core/Automation/Commands/Data/LogDataCommand.cs @@ -8,11 +8,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Data Commands")] + [Attributes.ClassAttributes.Group("Data")] [Attributes.ClassAttributes.Description("This command logs data to files.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to log custom data to a file for debugging or analytical purposes.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Thread.Sleep' to achieve automation.")] - public class LogDataCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] + public sealed class LogDataCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Select existing log file or enter a custom name.(ex. MyLog, Engine Log)")] @@ -41,17 +42,16 @@ public LogDataCommand() this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //get text to log and log file name - var textToLog = v_LogText.ConvertToUserVariable(sender); - var logFile = v_LogFile.ConvertToUserVariable(sender); + var textToLog = v_LogText.ExpandValueOrUserVariable(engine); + var logFile = v_LogFile.ExpandValueOrUserVariable(engine); //determine log file if (v_LogFile == "Engine Logs") { //log to the standard engine logs - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; //engine.engineLogger.Information(textToLog); engine.WriteLog(textToLog); } @@ -63,10 +63,9 @@ public override void RunCommand(object sender) logger.Information(textToLog); } } - - } - public override List Render(frmCommandEditor editor) + + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -95,7 +94,7 @@ public override string GetDisplayValue() return base.GetDisplayValue() + " [Write Log to 'taskt\\Logs\\" + logFileName + "']"; } - public override bool IsValidate(frmCommandEditor editor) + public override bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.IsValidate(editor); diff --git a/taskt/Core/Automation/Commands/Data/PDFTextExtractionCommand.cs b/taskt/Core/Automation/Commands/Data/PDFTextExtractionCommand.cs index 244f3ce8f..20cfaad91 100644 --- a/taskt/Core/Automation/Commands/Data/PDFTextExtractionCommand.cs +++ b/taskt/Core/Automation/Commands/Data/PDFTextExtractionCommand.cs @@ -9,11 +9,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Data Commands")] + [Attributes.ClassAttributes.Group("Data")] [Attributes.ClassAttributes.Description("")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] - public class PDFTextExtractionCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + public sealed class PDFTextExtractionCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please indicate the PDF file path or PDF file URL")] @@ -53,13 +54,12 @@ public PDFTextExtractionCommand() this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get variable path or URL to source file - var vSourceFilePath = v_FilePath.ConvertToUserVariable(sender); + var vSourceFilePath = v_FilePath.ExpandValueOrUserVariable(engine); // get source type of file either from a physical file or from a URL - var vSourceFileType = v_FileSourceType.ConvertToUserVariable(sender); + var vSourceFileType = v_FileSourceType.ExpandValueOrUserVariable(engine); if (String.IsNullOrEmpty(vSourceFileType)) { vSourceFileType = "FilePath"; @@ -68,7 +68,8 @@ public override void RunCommand(object sender) if (vSourceFileType == "File URL") { //create temp directory - var tempDir = Core.IO.Folders.GetFolder(Folders.FolderType.TempFolder); + //var tempDir = Core.IO.Folders.GetFolder(Folders.FolderType.TempFolder); + var tempDir = Folders.GetTempFolderPath(); var tempFile = System.IO.Path.Combine(tempDir, $"{ Guid.NewGuid()}.pdf"); //check if directory does not exist then create directory @@ -110,9 +111,9 @@ public override void RunCommand(object sender) var result = javaInterface.ExtractPDFText(vSourceFilePath); //apply to variable - result.StoreInUserVariable(sender, v_applyToVariableName); + result.StoreInUserVariable(engine, v_applyToVariableName); } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -137,7 +138,7 @@ public override string GetDisplayValue() return base.GetDisplayValue() + " [Extract From '" + v_FilePath + "' and apply result to '" + v_applyToVariableName + "'" ; } - public override bool IsValidate(frmCommandEditor editor) + public override bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.IsValidate(editor); diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableBothColumnCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableBothColumnCommands.cs new file mode 100644 index 000000000..ad1bd0ccb --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableBothColumnCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for DataTable Both Column Commands + /// + public abstract class ADataTableBothColumnCommands : ADataTableColumnCommands + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + public override string v_DataTable { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableBothDataTableCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableBothDataTableCommands.cs new file mode 100644 index 000000000..7688a075d --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableBothDataTableCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Both(Input/Output) DataTable commands + /// + public abstract class ADataTableBothDataTableCommands : ADataTableInputDataTableCommands + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + public override string v_DataTable { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableBothRowCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableBothRowCommands.cs new file mode 100644 index 000000000..c63e1044b --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableBothRowCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for DataTable Both Row Commands + /// + public abstract class ADataTableBothRowCommands : ADataTableRowCommands + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + public override string v_DataTable { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableColumnCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableColumnCommands.cs new file mode 100644 index 000000000..7c94cc7ab --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableColumnCommands.cs @@ -0,0 +1,21 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for DataTable Column Commands + /// + public abstract class ADataTableColumnCommands : ADataTableInputDataTableCommands, IDataTableColumnProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + [PropertyParameterOrder(6000)] + public virtual string v_ColumnType { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + [PropertyParameterOrder(7000)] + public virtual string v_ColumnIndex { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableColumnRowCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableColumnRowCommands.cs new file mode 100644 index 000000000..fce4ead95 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableColumnRowCommands.cs @@ -0,0 +1,26 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for DataTable Column Row specified commands + /// + public abstract class ADataTableColumnRowCommands : ADataTableInputDataTableCommands, IDataTableColumnRowPositionProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + [PropertyParameterOrder(7000)] + public virtual string v_ColumnType { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + [PropertyParameterOrder(8000)] + public virtual string v_ColumnIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + [PropertyParameterOrder(9000)] + public virtual string v_RowIndex { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableCreateFromDataTableCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableCreateFromDataTableCommands.cs new file mode 100644 index 000000000..be0971088 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableCreateFromDataTableCommands.cs @@ -0,0 +1,21 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Create From DataTable commands + /// + public abstract class ADataTableCreateFromDataTableCommands : ScriptCommand, ILDataTableCreateFromDataTableProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + [PropertyParameterOrder(5000)] + public abstract string v_TargetDataTable { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_NewOutputDataTableName))] + [PropertyParameterOrder(10000)] + public virtual string v_NewDataTable { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableGetFromDataTableColumnCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableGetFromDataTableColumnCommands.cs new file mode 100644 index 000000000..a03c579fd --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableGetFromDataTableColumnCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Get Something From DataTable Column commands + /// + public abstract class ADataTableGetFromDataTableColumnCommands : ADataTableColumnCommands, ILResultProperties + { + [XmlAttribute] + [PropertyParameterOrder(10000)] + public abstract string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableGetFromDataTableCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableGetFromDataTableCommands.cs new file mode 100644 index 000000000..a99d39abc --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableGetFromDataTableCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Get something from DataTable commands + /// + public abstract class ADataTableGetFromDataTableCommands : ADataTableInputDataTableCommands, IDataTableGetFromDataTable + { + [XmlAttribute] + [PropertyParameterOrder(10000)] + public abstract string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableGetFromDataTableRowCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableGetFromDataTableRowCommands.cs new file mode 100644 index 000000000..3248e27c2 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableGetFromDataTableRowCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Get From DataTable Row commands + /// + public abstract class ADataTableGetFromDataTableRowCommands : ADataTableRowCommands, ILResultProperties + { + [XmlAttribute] + [PropertyParameterOrder(10000)] + public abstract string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableInputDataTableCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableInputDataTableCommands.cs new file mode 100644 index 000000000..8692b040b --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableInputDataTableCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Input DataTable commands + /// + public abstract class ADataTableInputDataTableCommands : ScriptCommand, ILDataTableProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + [PropertyParameterOrder(5000)] + public virtual string v_DataTable { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ADataTableRowCommands.cs b/taskt/Core/Automation/Commands/DataTable/ADataTableRowCommands.cs new file mode 100644 index 000000000..67d329300 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ADataTableRowCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for DataTable Row commands + /// + public abstract class ADataTableRowCommands : ADataTableInputDataTableCommands, IDataTableRowProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + [PropertyParameterOrder(6000)] + public virtual string v_RowIndex { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/AddDataRowCommand.cs b/taskt/Core/Automation/Commands/DataTable/AddDataRowCommand.cs deleted file mode 100644 index 6affe2a44..000000000 --- a/taskt/Core/Automation/Commands/DataTable/AddDataRowCommand.cs +++ /dev/null @@ -1,158 +0,0 @@ -using System; -using System.Linq; -using System.Xml.Serialization; -using System.Data; -using System.Windows.Forms; -using System.Collections.Generic; -using taskt.UI.Forms; -using taskt.UI.CustomControls; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] - [Attributes.ClassAttributes.SubGruop("Other")] - [Attributes.ClassAttributes.Description("This command allows you to add a datarow to a DataTable")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a datarow to a DataTable.")] - [Attributes.ClassAttributes.ImplementationDescription("")] - public class AddDataRowCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Please indicate the DataTable Variable Name")] - [InputSpecification("Enter a existing DataTable to add rows to.")] - [SampleUsage("**myDataTable** or **{{{vMyDataTable}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_DataTableName { get; set; } - - [XmlElement] - [PropertyDescription("Define Data")] - [InputSpecification("Enter the Column Names required for each column of data")] - [SampleUsage("")] - [Remarks("")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.DataGridView)] - [PropertyDataGridViewSetting(true, true, true)] - [PropertyDataGridViewColumnSettings("Column Name", "Column Name", false)] - [PropertyDataGridViewColumnSettings("Data", "Data", false)] - [PropertyDataGridViewCellEditEvent("AddDataGridViewHelper_CellClick", PropertyDataGridViewCellEditEvent.DataGridViewCellEvent.CellClick)] - [PropertyCustomUIHelper("Load Column Names From Existing Table", nameof(LoadSchemaControl_Click), "load_column")] - public DataTable v_AddDataDataTable { get; set; } - - [XmlIgnore] - [NonSerialized] - private List DataTableCreationCommands; - - [XmlIgnore] - [NonSerialized] - private DataGridView AddDataGridViewHelper; - - public AddDataRowCommand() - { - this.CommandName = "AddDataRowCommand"; - this.SelectionName = "Add DataRow"; - this.CommandEnabled = true; - this.CustomRendering = true; - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - //DataTable dataTable = (DataTable)v_DataTableName.GetRawVariable(engine).VariableValue; - DataTable dataTable = v_DataTableName.GetDataTableVariable(engine); - - var newRow = dataTable.NewRow(); - - foreach (DataRow rw in v_AddDataDataTable.Rows) - { - var columnName = rw.Field("Column Name").ConvertToUserVariable(sender); - var data = rw.Field("Data").ConvertToUserVariable(sender); - newRow.SetField(columnName, data); - } - - dataTable.Rows.Add(newRow); - } - - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - - - var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); - RenderedControls.AddRange(ctrls); - - //AddDataGridViewHelper = (DataGridView)ctrls.GetControlsByName("v_AddDataDataTable")[0]; - - DataTableCreationCommands = editor.configuredCommands.Where(f => f is CreateDataTableCommand).Select(f => (CreateDataTableCommand)f).ToList(); - - return RenderedControls; - } - - private void LoadSchemaControl_Click(object sender, EventArgs e) - { - var items = new List(); - foreach (var item in DataTableCreationCommands) - { - items.Add(item.v_DataTableName); - } - UI.Forms.Supplemental.frmItemSelector selectionForm = new UI.Forms.Supplemental.frmItemSelector(items, "Load Schema", "Select a table from the list"); - - var result = selectionForm.ShowDialog(); - - if (result == DialogResult.OK) - { - //var tableName = selectionForm.lstVariables.SelectedItem.ToString(); - var tableName = selectionForm.selectedItem.ToString(); - var schema = DataTableCreationCommands.Where(f => f.v_DataTableName == tableName).FirstOrDefault(); - - v_AddDataDataTable.Rows.Clear(); - - foreach (DataRow rw in schema.v_ColumnNameDataTable.Rows) - { - v_AddDataDataTable.Rows.Add(rw.Field("Column Name"), ""); - } - } - } - - public override string GetDisplayValue() - { - return base.GetDisplayValue() + $" [{v_AddDataDataTable.Rows.Count} Fields, apply to '{v_DataTableName}']"; - } - - private void AddDataGridViewHelper_CellClick(object sender, DataGridViewCellEventArgs e) - { - if (e.ColumnIndex >= 0) - { - AddDataGridViewHelper.BeginEdit(false); - } - else - { - AddDataGridViewHelper.EndEdit(); - } - } - - public override void BeforeValidate() - { - base.BeforeValidate(); - //if (AddDataGridViewHelper.IsCurrentCellDirty || AddDataGridViewHelper.IsCurrentRowDirty) - //{ - // AddDataGridViewHelper.CommitEdit(DataGridViewDataErrorContexts.Commit); - // var newRow = v_AddDataDataTable.NewRow(); - // v_AddDataDataTable.Rows.Add(newRow); - // for (var i = v_AddDataDataTable.Rows.Count - 1; i >= 0; i--) - // { - // if (v_AddDataDataTable.Rows[i][0].ToString() == "" && v_AddDataDataTable.Rows[i][1].ToString() == "") - // { - // v_AddDataDataTable.Rows[i].Delete(); - // } - // } - //} - DataTableControls.BeforeValidate((DataGridView)ControlsList[nameof(v_AddDataDataTable)], v_AddDataDataTable); - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/AddDataTableColumnCommand.cs b/taskt/Core/Automation/Commands/DataTable/AddDataTableColumnCommand.cs index 86ca50232..8a56ed141 100644 --- a/taskt/Core/Automation/Commands/DataTable/AddDataTableColumnCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/AddDataTableColumnCommand.cs @@ -1,24 +1,25 @@ using System; -using System.Xml.Serialization; using System.Data; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Column Action")] [Attributes.ClassAttributes.CommandSettings("Add DataTable Column")] [Attributes.ClassAttributes.Description("This command allows you to add a column to a DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a column to a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class AddDataTableColumnCommand : ScriptCommand + public sealed class AddDataTableColumnCommand : ADataTableBothDataTableCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //public string v_DataTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -27,6 +28,7 @@ public class AddDataTableColumnCommand : ScriptCommand [PropertyDetailSampleUsage("**{{{vColumn}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "New Column")] [PropertyValidationRule("Column", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Column")] + [PropertyParameterOrder(6000)] public string v_AddColumnName { get; set; } [XmlAttribute] @@ -41,6 +43,7 @@ public class AddDataTableColumnCommand : ScriptCommand [PropertyUISelectionOption("Ignore")] [PropertyUISelectionOption("Replace")] [PropertyIsOptional(true, "Error")] + [PropertyParameterOrder(7000)] public string v_IfColumnExists { get; set; } public AddDataTableColumnCommand() @@ -51,15 +54,14 @@ public AddDataTableColumnCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable myDT = v_DataTableName.GetDataTableVariable(engine); + //DataTable myDT = v_DataTable.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(engine); - string newColName = v_AddColumnName.ConvertToUserVariable(engine); + string newColName = v_AddColumnName.ExpandValueOrUserVariable(engine); - string ifColumnExists = this.GetUISelectionValue(nameof(v_IfColumnExists), "If Column Exists", engine); + string ifColumnExists = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfColumnExists), "If Column Exists", engine); for (int i = 0; i < myDT.Columns.Count; i++) { diff --git a/taskt/Core/Automation/Commands/DataTable/AddDataTableRowByDictionaryCommand.cs b/taskt/Core/Automation/Commands/DataTable/AddDataTableRowByDictionaryCommand.cs index 3d04d7d96..ff9836e2c 100644 --- a/taskt/Core/Automation/Commands/DataTable/AddDataTableRowByDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/AddDataTableRowByDictionaryCommand.cs @@ -1,37 +1,38 @@ using System; -using System.Linq; -using System.Xml.Serialization; using System.Data; -using System.Collections.Generic; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Row Action")] [Attributes.ClassAttributes.CommandSettings("Add DataTable Row By Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to add a DataTable Row to a DataTable by a Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a DataTable Row to a DataTable by a Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class AddDataTableRowByDictionaryCommand : ScriptCommand + public sealed class AddDataTableRowByDictionaryCommand : ADataTableBothDataTableCommands, ICanHandleDictionary { [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] [PropertyDescription("DataTable Variable Name to be Added a Row")] - public string v_DataTableName { get; set; } + public override string v_DataTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] [PropertyDescription("Dictionary Variable Name to add to the DataTable")] + [PropertyParameterOrder(6000)] public string v_RowName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_WhenColumnNotExists))] [PropertyDescription("When Dictionary Key does not Exists")] - public string v_NotExistsKey { get; set; } + [PropertyParameterOrder(7000)] + public string v_WhenColumnNotExists { get; set; } public AddDataTableRowByDictionaryCommand() { @@ -41,18 +42,19 @@ public AddDataTableRowByDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable myDT = v_DataTableName.GetDataTableVariable(engine); + //DataTable myDT = v_DataTable.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(engine); - Dictionary myDic = v_RowName.GetDictionaryVariable(engine); + //Dictionary myDic = v_RowName.ExpandUserVariableAsDictinary(engine); + var myDic = this.ExpandUserVariableAsDictionary(nameof(v_RowName), engine); - string notExistsKey = this.GetUISelectionValue(nameof(v_NotExistsKey), "Key Does Not Exists", engine); + string notExistsKey = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenColumnNotExists), "Key Does Not Exists", engine); // get columns list - List columns = myDT.Columns.Cast().Select(x => x.ColumnName).ToList(); + //var columns = myDT.Columns.Cast().Select(x => x.ColumnName).ToList(); + var columns = myDT.GetColumnNameList(); // check column exists if (notExistsKey == "error") @@ -66,7 +68,7 @@ public override void RunCommand(object sender) } } - DataRow row = myDT.NewRow(); + var row = myDT.NewRow(); foreach(var item in myDic) { if (columns.Contains(item.Key)) diff --git a/taskt/Core/Automation/Commands/DataTable/AddDataTableRowCommand.cs b/taskt/Core/Automation/Commands/DataTable/AddDataTableRowCommand.cs index f9f610226..22278f5d4 100644 --- a/taskt/Core/Automation/Commands/DataTable/AddDataTableRowCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/AddDataTableRowCommand.cs @@ -1,27 +1,26 @@ using System; -using System.Linq; -using System.Xml.Serialization; using System.Data; +using System.Xml.Serialization; using System.Windows.Forms; -using System.Collections.Generic; -using taskt.UI.CustomControls; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Row Action")] + [Attributes.ClassAttributes.CommandSettings("Add DataTable Row")] [Attributes.ClassAttributes.Description("This command allows you to add a row to a DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a row to a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class AddDataTableRowCommand : ScriptCommand + public sealed class AddDataTableRowCommand : ADataTableBothDataTableCommands, IHaveDataTableElements { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //public string v_DataTable { get; set; } [XmlElement] [PropertyDescription("Column Names and Values")] @@ -37,6 +36,7 @@ public class AddDataTableRowCommand : ScriptCommand // todo: enable //[PropertyCustomUIHelper("Load Column Names From Existing Table", nameof(LoadSchemaControl_Click), "load_column")] [PropertyDisplayText(true, "Rows", "items")] + [PropertyParameterOrder(6000)] public DataTable v_AddDataDataTable { get; set; } //[XmlIgnore] @@ -45,27 +45,27 @@ public class AddDataTableRowCommand : ScriptCommand public AddDataTableRowCommand() { - this.CommandName = "AddDataTableRowCommand"; - this.SelectionName = "Add DataTable Row"; - this.CommandEnabled = true; - this.CustomRendering = true; + //this.CommandName = "AddDataTableRowCommand"; + //this.SelectionName = "Add DataTable Row"; + //this.CommandEnabled = true; + //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - DataTable dataTable = v_DataTableName.GetDataTableVariable(engine); + //DataTable dataTable = v_DataTable.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(engine); - var newRow = dataTable.NewRow(); + var newRow = myDT.NewRow(); foreach (DataRow rw in v_AddDataDataTable.Rows) { - var columnName = (rw.Field("Column Name") ?? "").ConvertToUserVariable(sender); - var data = (rw.Field("Data") ?? "").ConvertToUserVariable(sender); + var columnName = (rw.Field("Column Name") ?? "").ExpandValueOrUserVariable(engine); + var data = (rw.Field("Data") ?? "").ExpandValueOrUserVariable(engine); newRow.SetField(columnName, data); } - dataTable.Rows.Add(newRow); + myDT.Rows.Add(newRow); } //public override List Render(UI.Forms.frmCommandEditor editor) diff --git a/taskt/Core/Automation/Commands/DataTable/AddDataTableRowsByDataTableCommand.cs b/taskt/Core/Automation/Commands/DataTable/AddDataTableRowsByDataTableCommand.cs index 495c4be35..0a2f1bcce 100644 --- a/taskt/Core/Automation/Commands/DataTable/AddDataTableRowsByDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/AddDataTableRowsByDataTableCommand.cs @@ -1,41 +1,42 @@ using System; -using System.Linq; -using System.Xml.Serialization; using System.Data; -using System.Collections.Generic; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Row Action")] [Attributes.ClassAttributes.CommandSettings("Add DataTable Rows By DataTable")] [Attributes.ClassAttributes.Description("This command allows you to add a DataTable Row to a DataTable by a DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a DataTable Row to a DataTable by a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class AddDataTableRowsByDataTableCommand : ScriptCommand + public sealed class AddDataTableRowsByDataTableCommand : ADataTableBothDataTableCommands { [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] [PropertyDescription("DataTable Variable Name to be added a row")] [PropertyValidationRule("DataTable to be added", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "DataTable to be added")] - public string v_DataTableName { get; set; } + public override string v_DataTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] [PropertyDescription("DataTable Variable Name to add to the DataTable")] [PropertyValidationRule("DataTable to add", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "DataTable to add")] + [PropertyParameterOrder(6000)] public string v_RowName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_WhenColumnNotExists))] [PropertyDescription("When DataTable (to add) Column does not Exists")] - public string v_NotExistsKey { get; set; } + [PropertyParameterOrder(7000)] + public string v_WhenColumnNotExists { get; set; } public AddDataTableRowsByDataTableCommand() { @@ -45,18 +46,19 @@ public AddDataTableRowsByDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable myDT = v_DataTableName.GetDataTableVariable(engine); + //DataTable myDT = v_DataTable.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(engine); - DataTable addDT = v_RowName.GetDataTableVariable(engine); + //DataTable addDT = v_RowName.ExpandUserVariableAsDataTable(engine); + var addDT = this.ExpandUserVariableAsDataTable(nameof(v_RowName), engine); - string notExistsKey = this.GetUISelectionValue(nameof(v_NotExistsKey), "Key Does Not Exists", engine); + string notExistsKey = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenColumnNotExists), "Key Does Not Exists", engine); // get columns list - List columns = myDT.Columns.Cast().Select(x => x.ColumnName).ToList(); + //List columns = myDT.Columns.Cast().Select(x => x.ColumnName).ToList(); + var columns = myDT.GetColumnNameList(); if (notExistsKey == "error") { for (int i = 0; i < addDT.Columns.Count; i++) @@ -69,7 +71,7 @@ public override void RunCommand(object sender) } for (int i = 0; i < addDT.Rows.Count; i++) { - DataRow row = myDT.NewRow(); + var row = myDT.NewRow(); for (int j = 0; j < addDT.Columns.Count; j++) { if (columns.Contains(addDT.Columns[j].ColumnName)) diff --git a/taskt/Core/Automation/Commands/DataTable/CheckDataTableColumnExistsCommand.cs b/taskt/Core/Automation/Commands/DataTable/CheckDataTableColumnExistsCommand.cs index a9196de60..f2f737684 100644 --- a/taskt/Core/Automation/Commands/DataTable/CheckDataTableColumnExistsCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/CheckDataTableColumnExistsCommand.cs @@ -1,42 +1,47 @@ using System; using System.Xml.Serialization; -using System.Data; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Column Action")] [Attributes.ClassAttributes.CommandSettings("Check DataTable Column Exists")] [Attributes.ClassAttributes.Description("This command allows you to check the column name existance")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check the column name existance.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CheckDataTableColumnExistsCommand : ScriptCommand + public sealed class CheckDataTableColumnExistsCommand : ADataTableGetFromDataTableColumnCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyDescription("Name of Column")] - [InputSpecification("")] - //[SampleUsage("**colName** or **{{{vColName}}}**")] - [PropertyDetailSampleUsage("**name**", PropertyDetailSampleUsage.ValueType.Value, "Column Name to be Checked")] - [PropertyDetailSampleUsage("**{{{vColName}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Column Name to be Checked")] - [Remarks("")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - [PropertyValidationRule("Column", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "Column")] - public string v_ColumnName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + //public string v_ColumnType { get; set; } + + //[XmlAttribute] + ////[PropertyDescription("Name of Column")] + ////[InputSpecification("")] + //////[SampleUsage("**colName** or **{{{vColName}}}**")] + ////[PropertyDetailSampleUsage("**name**", PropertyDetailSampleUsage.ValueType.Value, "Column Name to be Checked")] + ////[PropertyDetailSampleUsage("**{{{vColName}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Column Name to be Checked")] + ////[Remarks("")] + ////[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + ////[PropertyShowSampleUsageInDescription(true)] + ////[PropertyTextBoxSetting(1, false)] + ////[PropertyValidationRule("Column", PropertyValidationRule.ValidationRuleFlags.Empty)] + ////[PropertyDisplayText(true, "Column")] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + //public string v_ColumnIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public CheckDataTableColumnExistsCommand() { @@ -46,15 +51,24 @@ public CheckDataTableColumnExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //DataTable myDT = v_DataTable.ExpandUserVariableAsDataTable(engine); - DataTable myDT = v_DataTableName.GetDataTableVariable(engine); + //string targetColumnName = v_ColumnIndex.ExpandValueOrUserVariable(engine); - string targetColumnName = v_ColumnName.ConvertToUserVariable(engine); + //myDT.Columns.Contains(targetColumnName).StoreInUserVariable(engine, v_Result); - myDT.Columns.Contains(targetColumnName).StoreInUserVariable(engine, v_OutputVariableName); + var myDT = this.ExpandUserVariableAsDataTable(engine); + try + { + this.ExpandValueOrUserVariableAsDataTableColumn(myDT, engine); + true.StoreInUserVariable(engine, v_Result); + } + catch + { + false.StoreInUserVariable(engine, v_Result); + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToDataTableCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToDataTableCommand.cs index b7bdb0cd6..5902dd5c4 100644 --- a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToDataTableCommand.cs @@ -6,32 +6,33 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Convert Column")] [Attributes.ClassAttributes.CommandSettings("Convert DataTable Column To DataTable")] [Attributes.ClassAttributes.Description("This command allows you to convert DataTable Column to DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable Column to DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDataTableColumnToDataTableCommand : ScriptCommand + public sealed class ConvertDataTableColumnToDataTableCommand : ADataTableGetFromDataTableColumnCommands, IDataTableResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - [PropertyDescription("DataTable Variable Name to Converted")] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //[PropertyDescription("DataTable Variable Name to Converted")] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_DataColumnIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + //public string v_ColumnIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_NewOutputDataTableName))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public ConvertDataTableColumnToDataTableCommand() { @@ -41,20 +42,22 @@ public ConvertDataTableColumnToDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var srcDT, var colIndex) = this.GetDataTableVariableAndColumnIndex(nameof(v_DataTableName), nameof(v_ColumnType), nameof(v_DataColumnIndex), engine); + //(var srcDT, var colIndex) = this.ExpandUserVariablesAsDataTableAndColumnIndex(nameof(v_DataTable), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + (var srcDT, var colIndex, var colName) = this.ExpandValueOrUserVariableAsDataTableAndColumn(engine); + DataTable myDT = new DataTable(); - myDT.Columns.Add(srcDT.Columns[colIndex].ColumnName); + myDT.Columns.Add(colName); for (int i = 0; i < srcDT.Rows.Count; i++) { myDT.Rows.Add(); myDT.Rows[i][0] = srcDT.Rows[i][colIndex]?.ToString() ?? ""; } - myDT.StoreInUserVariable(engine, v_OutputVariableName); + //myDT.StoreInUserVariable(engine, v_Result); + //this.StoreDataTableInUserVariable(myDT, nameof(v_Result), engine); + this.StoreDataTableInUserVariable(myDT, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToDictionaryCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToDictionaryCommand.cs index 805b75ce0..148f9759c 100644 --- a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToDictionaryCommand.cs @@ -6,27 +6,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Convert Column")] [Attributes.ClassAttributes.CommandSettings("Convert DataTable Column To Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to convert DataTable Column to Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable Column to Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDataTableColumnToDictionaryCommand : ScriptCommand + public sealed class ConvertDataTableColumnToDictionaryCommand : ADataTableGetFromDataTableColumnCommands, IDictionaryResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_DataColumnIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + //public string v_ColumnIndex { get; set; } [XmlAttribute] [PropertyDescription("Dictionary Key prefix")] @@ -38,11 +39,12 @@ public class ConvertDataTableColumnToDictionaryCommand : ScriptCommand [PropertyIsOptional(true, "row")] [PropertyShowSampleUsageInDescription(true)] [PropertyTextBoxSetting(1, false)] + [PropertyParameterOrder(8000)] public string v_KeyPrefix { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_OutputDictionaryName))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public ConvertDataTableColumnToDictionaryCommand() { @@ -52,27 +54,32 @@ public ConvertDataTableColumnToDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + // TODO: key is other column value, List, etc string prefix; - if (String.IsNullOrEmpty(v_KeyPrefix)) + if (string.IsNullOrEmpty(v_KeyPrefix)) { prefix = "row"; } else { - prefix = v_KeyPrefix.ConvertToUserVariable(engine); + prefix = v_KeyPrefix.ExpandValueOrUserVariable(engine); } - (var srcDT, var colIndex) = this.GetDataTableVariableAndColumnIndex(nameof(v_DataTableName), nameof(v_ColumnType), nameof(v_DataColumnIndex), engine); - Dictionary myDic = new Dictionary(); + //(var srcDT, var colIndex) = this.ExpandUserVariablesAsDataTableAndColumnIndex(nameof(v_DataTable), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + (var srcDT, var colIndex, _) = this.ExpandValueOrUserVariableAsDataTableAndColumn(engine); + + var myDic = new Dictionary(); for (int i = 0; i < srcDT.Rows.Count; i++) { myDic.Add(prefix + i.ToString(), srcDT.Rows[i][colIndex]?.ToString() ?? ""); } - myDic.StoreInUserVariable(engine, v_OutputVariableName); + + //myDic.StoreInUserVariable(engine, v_Result); + //this.StoreDictionaryInUserVariable(myDic, nameof(v_Result), engine); + this.StoreDictionaryInUserVariable(myDic, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToJSONCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToJSONCommand.cs index a16334fa3..e5015a064 100644 --- a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToJSONCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToJSONCommand.cs @@ -1,36 +1,38 @@ using System; -using System.Xml.Serialization; using System.Collections.Generic; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Convert Column")] [Attributes.ClassAttributes.CommandSettings("Convert DataTable Column To JSON")] [Attributes.ClassAttributes.Description("This command allows you to convert DataTable Column to JSON")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable Column to JSON.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDataTableColumnToJSONCommand : ScriptCommand + public sealed class ConvertDataTableColumnToJSONCommand : ADataTableGetFromDataTableColumnCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_DataColumnIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + //public string v_ColumnIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_OutputJSONName))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public ConvertDataTableColumnToJSONCommand() { @@ -40,23 +42,41 @@ public ConvertDataTableColumnToJSONCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //var listCommand = new ConvertDataTableColumnToListCommand + //{ + // v_DataTable = this.v_DataTable, + // v_ColumnType = this.v_ColumnType, + // v_ColumnIndex = this.v_ColumnIndex, + // v_Result = VariableNameControls.GetInnerVariableName(0, engine) + //}; + //listCommand.RunCommand(engine); + + //var myList = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; - var listCommand = new ConvertDataTableColumnToListCommand + //var json = Newtonsoft.Json.JsonConvert.SerializeObject(myList); + //json.StoreInUserVariable(engine, v_Result); + + using (var myList = new InnerScriptVariable(engine)) { - v_DataTableName = this.v_DataTableName, - v_ColumnType = this.v_ColumnType, - v_DataColumnIndex = this.v_DataColumnIndex, - v_OutputVariableName = VariableNameControls.GetInnerVariableName(0, engine) - }; - listCommand.RunCommand(engine); + var listCommand = new ConvertDataTableColumnToListCommand + { + v_DataTable = this.v_DataTable, + v_ColumnType = this.v_ColumnType, + v_ColumnIndex = this.v_ColumnIndex, + v_Result = myList.VariableName, + }; + listCommand.RunCommand(engine); + + //var myList = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; - List myList = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; + //var json = Newtonsoft.Json.JsonConvert.SerializeObject((List)myList.VariableValue); + var json = Newtonsoft.Json.JsonConvert.SerializeObject(EM_CanHandleListExtensionMethods.ExpandUserVariableAsList(myList)); + json.StoreInUserVariable(engine, v_Result); + } - var json = Newtonsoft.Json.JsonConvert.SerializeObject(myList); - json.StoreInUserVariable(engine, v_OutputVariableName); + int v = 3; } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToListCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToListCommand.cs index 9526d4645..4aac767e8 100644 --- a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToListCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToListCommand.cs @@ -6,31 +6,32 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Convert Column")] [Attributes.ClassAttributes.CommandSettings("Convert DataTable Column To List")] [Attributes.ClassAttributes.Description("This command allows you to convert DataTable Column to List")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable Column to List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDataTableColumnToListCommand : ScriptCommand + public sealed class ConvertDataTableColumnToListCommand : ADataTableGetFromDataTableColumnCommands, IListResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + // [XmlAttribute] + // [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + // public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] - public string v_ColumnType { get; set; } + // [XmlAttribute] + // [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + // public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_DataColumnIndex { get; set; } + // [XmlAttribute] + // [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + // public string v_ColumnIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public ConvertDataTableColumnToListCommand() { @@ -40,18 +41,20 @@ public ConvertDataTableColumnToListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var srcDT, var colIndex) = this.GetDataTableVariableAndColumnIndex(nameof(v_DataTableName), nameof(v_ColumnType), nameof(v_DataColumnIndex), engine); - List myList = new List(); + //(var srcDT, var colIndex) = this.ExpandUserVariablesAsDataTableAndColumnIndex(nameof(v_DataTable), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + (var srcDT, var colIndex, _) = this.ExpandValueOrUserVariableAsDataTableAndColumn(engine); + + var myList = new List(); for (int i = 0; i < srcDT.Rows.Count; i++) { myList.Add(srcDT.Rows[i][colIndex]?.ToString() ?? ""); } - myList.StoreInUserVariable(engine, v_OutputVariableName); + //myList.StoreInUserVariable(engine, v_Result); + //this.StoreListInUserVariable(myList, nameof(v_Result), engine); + this.StoreListInUserVariable(myList, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToTextCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToTextCommand.cs new file mode 100644 index 000000000..c3badf1af --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableColumnToTextCommand.cs @@ -0,0 +1,81 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("DataTable")] + [Attributes.ClassAttributes.SubGruop("Convert Column")] + [Attributes.ClassAttributes.CommandSettings("Convert DataTable Column To Text")] + [Attributes.ClassAttributes.Description("This command allows you to convert DataTable Column to Text")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable Column to Text.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ConvertDataTableColumnToTextCommand : ADataTableGetFromDataTableColumnCommands + { + //public string v_DataTable { get; set; } + + //public string v_ColumnType { get; set; } + + //public string v_ColumnIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(8000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Header")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Header", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9000)] + public string v_ExportHeader { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Row Index")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9001)] + public string v_ExportIndex { get; set; } + + public ConvertDataTableColumnToTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //(var srcDT, var colIndex, _) = this.ExpandValueOrUserVariableAsDataTableAndColumn(engine); + + using(var myDT = new InnerScriptVariable(engine)) + { + var createTable = new ConvertDataTableColumnToDataTableCommand() + { + v_DataTable = this.v_DataTable, + v_ColumnType = this.v_ColumnType, + v_ColumnIndex = this.v_ColumnIndex, + v_Result = myDT.VariableName, + }; + createTable.RunCommand(engine); + + var convText = new ConvertDataTableToTextCommand() + { + v_DataTable = myDT.VariableName, + v_ExportHeader = this.v_ExportHeader, + v_ExportIndex = this.v_ExportIndex, + v_Result = this.v_Result, + }; + convText.RunCommand(engine); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToDataTableCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToDataTableCommand.cs index c4b3745a0..3535ab448 100644 --- a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToDataTableCommand.cs @@ -6,28 +6,29 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Convert Row")] [Attributes.ClassAttributes.CommandSettings("Convert DataTable Row To DataTable")] [Attributes.ClassAttributes.Description("This command allows you to convert DataTable Row to DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable Row to DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDataTableRowToDataTableCommand : ScriptCommand + public sealed class ConvertDataTableRowToDataTableCommand : ADataTableGetFromDataTableRowCommands, IDataTableResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - [PropertyDescription("DataTable Variable Name to Converted")] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //[PropertyDescription("DataTable Variable Name to Converted")] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - public string v_DataRowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //public string v_RowIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_NewOutputDataTableName))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public ConvertDataTableRowToDataTableCommand() { @@ -37,13 +38,12 @@ public ConvertDataTableRowToDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var srcDT, var index) = this.GetDataTableVariableAndRowIndex(nameof(v_DataTableName), nameof(v_DataRowIndex), engine); + //(var srcDT, var index) = this.ExpandUserVariablesAsDataTableAndRowIndex(nameof(v_DataTable), nameof(v_RowIndex), engine); + (var srcDT, var index) = this.ExpandValueOrUserVariableAsDataTableAndRow(engine); - DataTable myDT = new DataTable(); + var myDT = new DataTable(); int cols = srcDT.Columns.Count; myDT.Rows.Add(); @@ -53,7 +53,8 @@ public override void RunCommand(object sender) myDT.Rows[0][i] = srcDT.Rows[index][i]; } - myDT.StoreInUserVariable(engine, v_OutputVariableName); + //myDT.StoreInUserVariable(engine, v_Result); + this.StoreDataTableInUserVariable(myDT, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToDictionaryCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToDictionaryCommand.cs index fb25b5189..255ce5212 100644 --- a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToDictionaryCommand.cs @@ -6,27 +6,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Convert Row")] [Attributes.ClassAttributes.CommandSettings("Convert DataTable Row To Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to convert DataTable Row to Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable Row to Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDataTableRowToDictionaryCommand : ScriptCommand + public sealed class ConvertDataTableRowToDictionaryCommand : ADataTableGetFromDataTableRowCommands, IDictionaryResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - public string v_DataRowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //public string v_RowIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_OutputDictionaryName))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public ConvertDataTableRowToDictionaryCommand() { @@ -36,13 +37,12 @@ public ConvertDataTableRowToDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var srcDT, var index) = this.GetDataTableVariableAndRowIndex(nameof(v_DataTableName), nameof(v_DataRowIndex), engine); + //(var srcDT, var index) = this.ExpandUserVariablesAsDataTableAndRowIndex(nameof(v_DataTable), nameof(v_RowIndex), engine); + (var srcDT, var index) = this.ExpandValueOrUserVariableAsDataTableAndRow(engine); - Dictionary myDic = new Dictionary(); + var myDic = new Dictionary(); int cols = srcDT.Columns.Count; for (int i = 0; i < cols; i++) @@ -50,7 +50,8 @@ public override void RunCommand(object sender) myDic.Add(srcDT.Columns[i].ColumnName, srcDT.Rows[index][i]?.ToString() ?? ""); } - myDic.StoreInUserVariable(engine, v_OutputVariableName); + //myDic.StoreInUserVariable(engine, v_Result); + this.StoreDictionaryInUserVariable(myDic, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToJSONCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToJSONCommand.cs index 9059e185b..df0f0d652 100644 --- a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToJSONCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToJSONCommand.cs @@ -2,31 +2,33 @@ using System.Xml.Serialization; using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Convert Row")] [Attributes.ClassAttributes.CommandSettings("Convert DataTable Row To JSON")] [Attributes.ClassAttributes.Description("This command allows you to convert DataTable Row to JSON")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable Row to JSON.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDataTableRowToJSONCommand : ScriptCommand + public sealed class ConvertDataTableRowToJSONCommand : ADataTableGetFromDataTableRowCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - public string v_DataRowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //public string v_RowIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_OutputJSONName))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public ConvertDataTableRowToJSONCommand() { @@ -36,21 +38,34 @@ public ConvertDataTableRowToJSONCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //var dicCommand = new ConvertDataTableRowToDictionaryCommand + //{ + // v_DataTable = this.v_DataTable, + // v_RowIndex = this.v_RowIndex, + // v_Result = VariableNameControls.GetInnerVariableName(0, engine) + //}; + //dicCommand.RunCommand(engine); - var dicCommand = new ConvertDataTableRowToDictionaryCommand + //var tDic = (Dictionary)VariableNameControls.GetInnerVariable(0, engine).VariableValue; + //string json = Newtonsoft.Json.JsonConvert.SerializeObject(tDic); + //json.StoreInUserVariable(engine, v_Result); + + using (var myDic = new InnerScriptVariable(engine)) { - v_DataTableName = this.v_DataTableName, - v_DataRowIndex = this.v_DataRowIndex, - v_OutputVariableName = VariableNameControls.GetInnerVariableName(0, engine) - }; - dicCommand.RunCommand(engine); - - Dictionary tDic = (Dictionary)VariableNameControls.GetInnerVariable(0, engine).VariableValue; - string json = Newtonsoft.Json.JsonConvert.SerializeObject(tDic); - json.StoreInUserVariable(engine, v_OutputVariableName); + var dicCommand = new ConvertDataTableRowToDictionaryCommand + { + v_DataTable = this.v_DataTable, + v_RowIndex = this.v_RowIndex, + v_Result = myDic.VariableName, + }; + dicCommand.RunCommand(engine); + + //string json = Newtonsoft.Json.JsonConvert.SerializeObject((Dictionary)myDic.VariableValue); + var json = Newtonsoft.Json.JsonConvert.SerializeObject(EM_CanHandleDictionary.ExpandUserVariableAsDictionary(myDic)); + json.StoreInUserVariable(engine, v_Result); + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToListCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToListCommand.cs index 7760c94cf..507c0ee83 100644 --- a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToListCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToListCommand.cs @@ -6,27 +6,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Convert Row")] [Attributes.ClassAttributes.CommandSettings("Convert DataTable Row To List")] [Attributes.ClassAttributes.Description("This command allows you to convert DataTable Row to List")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable Row to List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDataTableRowToListCommand : ScriptCommand + public sealed class ConvertDataTableRowToListCommand : ADataTableGetFromDataTableRowCommands, IListResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - public string v_DataRowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //public string v_RowIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public ConvertDataTableRowToListCommand() { @@ -36,13 +37,12 @@ public ConvertDataTableRowToListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var srcDT, var index) = this.GetDataTableVariableAndRowIndex(nameof(v_DataTableName), nameof(v_DataRowIndex), engine); + //(var srcDT, var index) = this.ExpandUserVariablesAsDataTableAndRowIndex(nameof(v_DataTable), nameof(v_RowIndex), engine); + (var srcDT, var index) = this.ExpandValueOrUserVariableAsDataTableAndRow(engine); - List myList = new List(); + var myList = new List(); int cols = srcDT.Columns.Count; for (int i = 0; i < cols; i++) @@ -50,7 +50,8 @@ public override void RunCommand(object sender) myList.Add(srcDT.Rows[index][i]?.ToString() ?? ""); } - myList.StoreInUserVariable(engine, v_OutputVariableName); + //myList.StoreInUserVariable(engine, v_Result); + this.StoreListInUserVariable(myList, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToTextCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToTextCommand.cs new file mode 100644 index 000000000..b4404506e --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableRowToTextCommand.cs @@ -0,0 +1,114 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("DataTable")] + [Attributes.ClassAttributes.SubGruop("Convert Row")] + [Attributes.ClassAttributes.CommandSettings("Convert DataTable Row To Text")] + [Attributes.ClassAttributes.Description("This command allows you to convert DataTable Row to Text.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable Row to Text.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ConvertDataTableRowToTextCommand : ADataTableGetFromDataTableRowCommands + { + //public string v_DataTable { get; set; } + + //public string v_RowIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(7000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Header")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Header", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9000)] + public string v_ExportHeader { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Row Index")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9001)] + public string v_ExportIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("When Exporting Row Index, Export the Actual Row Index")] + [PropertyIsOptional(true, "Yes")] + [PropertyFirstValue("Yes")] + [PropertyValidationRule("Actual Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(10000)] + public string v_ActualRowIndex { get; set; } + + public ConvertDataTableRowToTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + using (var myDT = new InnerScriptVariable(engine)) + { + var rowDT = new ConvertDataTableRowToDataTableCommand() + { + v_DataTable = this.v_DataTable, + v_RowIndex = this.v_RowIndex, + v_Result = myDT.VariableName, + }; + rowDT.RunCommand(engine); + + using (var myRes = new InnerScriptVariable(engine)) + { + var convertText = new ConvertDataTableToTextCommand() + { + v_DataTable = myDT.VariableName, + v_ExportHeader = this.v_ExportHeader, + v_ExportIndex = this.v_ExportIndex, + v_Result = myRes.VariableName, + }; + convertText.RunCommand(engine); + + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportIndex), engine) && + this.ExpandValueOrUserVariableAsYesNo(nameof(v_ActualRowIndex), engine)) + { + (_ , var row) = this.ExpandValueOrUserVariableAsDataTableAndRow(engine); + + var t = myRes.VariableValue.ToString(); + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportHeader), engine)) + { + // line 2 + var spt = t.Split(new string[] { "\r\n" }, StringSplitOptions.None); + var values = spt[1].Substring(spt[1].IndexOf(',')); + $"{spt[0]}\r\n{row}{values}".StoreInUserVariable(engine, v_Result); + } + else + { + // line 1 + var values = t.Substring(t.IndexOf(',')); + $"{row}{values}".StoreInUserVariable(engine, v_Result); + } + } + else + { + myRes.VariableValue.ToString().StoreInUserVariable(engine, v_Result); + } + } + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableToJSONCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableToJSONCommand.cs index cc4b1676a..6b78d4d08 100644 --- a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableToJSONCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableToJSONCommand.cs @@ -1,29 +1,29 @@ using System; using System.Xml.Serialization; -using System.Data; using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Convert")] [Attributes.ClassAttributes.CommandSettings("Convert DataTable To JSON")] [Attributes.ClassAttributes.Description("This command allows you to convert DataTable to JSON")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert DataTable to JSON.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDataTableToJSONCommand : ScriptCommand + public sealed class ConvertDataTableToJSONCommand : ADataTableGetFromDataTableCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_OutputJSONName))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public ConvertDataTableToJSONCommand() { @@ -33,13 +33,12 @@ public ConvertDataTableToJSONCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable srcDT = v_DataTableName.GetDataTableVariable(engine); + //DataTable srcDT = v_DataTable.ExpandUserVariableAsDataTable(engine); + var srcDT = this.ExpandUserVariableAsDataTable(engine); - List> jsonList = new List>(); + var jsonList = new List>(); for (int j = 0; j < srcDT.Rows.Count; j++) { Dictionary tDic = new Dictionary(); @@ -52,7 +51,7 @@ public override void RunCommand(object sender) } string json = Newtonsoft.Json.JsonConvert.SerializeObject(jsonList); - json.StoreInUserVariable(engine, v_OutputVariableName); + json.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableToTextCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableToTextCommand.cs new file mode 100644 index 000000000..77a9dea0c --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableToTextCommand.cs @@ -0,0 +1,110 @@ +using System; +using System.Data; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("DataTable")] + [Attributes.ClassAttributes.SubGruop("Convert")] + [Attributes.ClassAttributes.CommandSettings("Convert DataTable To Text")] + [Attributes.ClassAttributes.Description("This command allows you to Convert DataTable to Text.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Convert DataTable to Text.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ConvertDataTableToTextCommand : ADataTableGetFromDataTableCommands + { + //[XmlAttribute] + //public string v_DataTable { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(6000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Header")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Header", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7000)] + public string v_ExportHeader { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Row Index")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7001)] + public string v_ExportIndex { get; set; } + + public ConvertDataTableToTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var dt = this.ExpandUserVariableAsDataTable(engine); + var columnNum = dt.Columns.Count; + + var exportHeader = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportHeader), engine); + var exportIndex = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportIndex), engine); + + string txt = ""; + if (exportHeader) + { + if (exportIndex) + { + txt = "index,"; + } + string t = ""; + foreach (DataColumn c in dt.Columns) + { + t += $"{c.ColumnName},"; + } + txt += t.Substring(0, t.Length - 1) + "\r\n"; + } + + string rowTextAction(DataRow row, int column) + { + string v = ""; + + for (int i = 0; i < column; i++) + { + v += $"{row[i]?.ToString() ?? ""},"; + } + return v.Substring(0, v.Length - 1) + "\r\n"; + } + + Func textAction; + if (exportIndex) + { + textAction = new Func((r, index) => + { + return $"{index},{rowTextAction(r, columnNum)}"; + }); + } + else + { + textAction = new Func((r, index) => + { + return rowTextAction(r, columnNum); + }); + } + + for (int i = 0; i < dt.Rows.Count; i++) + { + txt += textAction(dt.Rows[i], i); + } + + txt.Trim().StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ConvertDataTableToVisualizedTextCommand.cs b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableToVisualizedTextCommand.cs new file mode 100644 index 000000000..d868f6d8a --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ConvertDataTableToVisualizedTextCommand.cs @@ -0,0 +1,131 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("DataTable")] + [Attributes.ClassAttributes.SubGruop("Convert")] + [Attributes.ClassAttributes.CommandSettings("Convert DataTable To Visualized Text")] + [Attributes.ClassAttributes.Description("This command allows you to Convert DataTable to Visualized Text.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Convert DataTable to Visualized Text.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ConvertDataTableToVisualizedTextCommand : ADataTableGetFromDataTableCommands + { + //[XmlAttribute] + //public string v_DataTable { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + public override string v_Result { get; set; } + + public ConvertDataTableToVisualizedTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var dt = this.ExpandUserVariableAsDataTable(engine); + var columnSize = dt.Columns.Count; + var rows = dt.Rows.Count; + + var columnMaxLength = new List(); + for (int i = 0; i < columnSize; i++) + { + columnMaxLength.Add(0); + } + + foreach (DataRow row in dt.Rows) + { + for (int i = 0; i < columnSize; i++) + { + var s = (row[i]?.ToString() ?? "").Length; + if (columnMaxLength[i] < s) + { + columnMaxLength[i] = s; + } + } + } + for (int i = 0; i < columnSize; i++) + { + var s = dt.Columns[i].ColumnName.Length; + if (columnMaxLength[i] < s) + { + columnMaxLength[i] = s; + } + } + + var columnFormats = new List(); + foreach(var s in columnMaxLength) + { + columnFormats.Add($"{{0, -{s}}}"); + } + + int rowLength = (int)Math.Log10(rows) + 1; + if (rowLength < 3) + { + rowLength = 3; // Row + } + var rowFormat = $"{{0, {rowLength}}}"; + + // first header + string txt = $"{string.Format(rowFormat, "")} "; + int cnt = 0; + foreach(var s in columnFormats) + { + txt += $"| {string.Format(s, cnt)} "; + cnt++; + } + txt = txt.TrimEnd() + "\r\n"; + + // second header + txt += $"{string.Format(rowFormat, "Row")} "; + cnt = 0; + foreach(var s in columnFormats) + { + txt += $"| {string.Format(s, dt.Columns[cnt].ColumnName)} "; + cnt++; + } + txt = txt.TrimEnd() + "\r\n"; + + // split lines + for (int i = 0; i < rowLength; i++) + { + txt += "-"; + } + txt += "-|-"; + + for (int i = 0; i < columnSize - 1; i++) + { + for (int j = 0; j < columnMaxLength[i]; j++) + { + txt += "-"; + } + txt += "-|-"; + } + for (int i = 0; i < columnMaxLength[columnSize - 1]; i++) + { + txt += "-"; + } + txt += "\r\n"; + + for (int i = 0; i < rows; i++) + { + txt += $"{string.Format(rowFormat, i)} "; + for (int j = 0; j < columnSize; j++) + { + txt += $"| {string.Format(columnFormats[j], dt.Rows[i][j]?.ToString() ?? "")} "; + } + txt = txt.TrimEnd() + "\r\n"; + } + + txt.StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/CopyDataTableCommand.cs b/taskt/Core/Automation/Commands/DataTable/CopyDataTableCommand.cs index 69cd817ec..aacc82e21 100644 --- a/taskt/Core/Automation/Commands/DataTable/CopyDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/CopyDataTableCommand.cs @@ -6,26 +6,27 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("DataTable Action")] [Attributes.ClassAttributes.CommandSettings("Copy DataTable")] [Attributes.ClassAttributes.Description("This command allows you to copy a DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to copy a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CopyDataTableCommand : ScriptCommand + public sealed class CopyDataTableCommand : ADataTableCreateFromDataTableCommands { [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] [PropertyDescription("DataTable Variable Name to Copy")] [PropertyValidationRule("DataTable to Copy", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "DataTable to Copy")] - public string v_DataTableName { get; set; } + public override string v_TargetDataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_NewOutputDataTableName))] - public string v_OutputVariableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_NewOutputDataTableName))] + //public string v_NewDataTable { get; set; } public CopyDataTableCommand() { @@ -35,13 +36,12 @@ public CopyDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable myDT = v_DataTableName.GetDataTableVariable(engine); + //DataTable myDT = v_TargetDataTable.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(engine); - DataTable newDT = new DataTable(); + var newDT = new DataTable(); foreach(DataColumn col in myDT.Columns) { newDT.Columns.Add(col.ColumnName); @@ -49,7 +49,7 @@ public override void RunCommand(object sender) foreach(DataRow row in myDT.Rows) { - DataRow newRow = newDT.NewRow(); + var newRow = newDT.NewRow(); for (int i = 0; i < myDT.Columns.Count; i++) { newRow[i] = row[i]; @@ -57,7 +57,8 @@ public override void RunCommand(object sender) newDT.Rows.Add(newRow); } - newDT.StoreInUserVariable(engine, v_OutputVariableName); + //newDT.StoreInUserVariable(engine, v_NewDataTable); + this.StoreDataTableInUserVariable(newDT, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/CreateDataTableCommand.cs b/taskt/Core/Automation/Commands/DataTable/CreateDataTableCommand.cs index ca61b4bb3..e4ee5c87e 100644 --- a/taskt/Core/Automation/Commands/DataTable/CreateDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/CreateDataTableCommand.cs @@ -1,25 +1,27 @@ using System; -using System.Xml.Serialization; +using System.Collections.Generic; using System.Data; using System.Windows.Forms; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("DataTable Action")] [Attributes.ClassAttributes.CommandSettings("Create DataTable")] [Attributes.ClassAttributes.Description("This command created a DataTable with the column names provided")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create a new DataTable")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateDataTableCommand : ScriptCommand + public sealed class CreateDataTableCommand : ADataTableInputDataTableCommands { [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] - public string v_DataTableName { get; set; } + public override string v_DataTable { get; set; } [XmlElement] [PropertyDescription("Column Names")] @@ -32,6 +34,7 @@ public class CreateDataTableCommand : ScriptCommand [PropertyDataGridViewColumnSettings("Column Name", "Column Name", false)] [PropertyDataGridViewCellEditEvent(nameof(DataTableControls)+"+"+nameof(DataTableControls.AllEditableDataGridView_CellClick), PropertyDataGridViewCellEditEvent.DataGridViewCellEvent.CellClick)] [PropertyDisplayText(true, "Columns")] + [PropertyParameterOrder(6000)] public DataTable v_ColumnNameDataTable { get; set; } public CreateDataTableCommand() @@ -50,27 +53,53 @@ public CreateDataTableCommand() //this.v_ColumnNameDataTable.Columns.Add("Column Name"); } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var newDT = new DataTable(); - DataTable newDT = new DataTable(); + var nameList = new List(); // check column name is empty - for (int i = v_ColumnNameDataTable.Rows.Count - 1; i >= 0 ; i--) + //for (int i = v_ColumnNameDataTable.Rows.Count - 1; i >= 0 ; i--) + for (int i = 0; i < v_ColumnNameDataTable.Rows.Count; i++) { - if ((v_ColumnNameDataTable.Rows[i].Field("Column Name") ?? "") == "") + var name = v_ColumnNameDataTable.Rows[i].Field("Column Name") ?? ""; + if (!string.IsNullOrEmpty(name)) + { + nameList.Add(name); + } + else { - throw new Exception("Column Name is Empty. Row: " + i); + + throw new Exception($"Column Name is Empty. Row: {i}"); } } - foreach(DataRow row in v_ColumnNameDataTable.Rows) + // dup check + int num = nameList.Count; + for (int i = 0; i < num - 1; i++) + { + for (int j = i + 1; j < num; j++) + { + if (nameList[i] == nameList[j]) + { + throw new Exception($"Duplicate Column Name '{nameList[i]}'. Row1: {i}, Row2: {j}"); + } + } + } + + //foreach(DataRow row in v_ColumnNameDataTable.Rows) + //{ + // newDT.Columns.Add(row.Field("Column Name")); + //} + + foreach(var col in nameList) { - newDT.Columns.Add(row.Field("Column Name")); + newDT.Columns.Add(col); } - newDT.StoreInUserVariable(engine, v_DataTableName); + //newDT.StoreInUserVariable(engine, v_DataTable); + this.StoreDataTableInUserVariable(newDT, nameof(v_DataTable), engine); } public override void BeforeValidate() diff --git a/taskt/Core/Automation/Commands/DataTable/DeleteDataTableColumnCommand.cs b/taskt/Core/Automation/Commands/DataTable/DeleteDataTableColumnCommand.cs index ab501148e..1738dc1c0 100644 --- a/taskt/Core/Automation/Commands/DataTable/DeleteDataTableColumnCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/DeleteDataTableColumnCommand.cs @@ -5,27 +5,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Column Action")] [Attributes.ClassAttributes.CommandSettings("Delete DataTable Column")] [Attributes.ClassAttributes.Description("This command allows you to delete a column to a DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to delete a column to a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class DeleteDataTableColumnCommand : ScriptCommand + public sealed class DeleteDataTableColumnCommand : ADataTableColumnCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_DeleteColumnName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + //public string v_ColumnIndex { get; set; } public DeleteDataTableColumnCommand() { @@ -35,11 +36,10 @@ public DeleteDataTableColumnCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var myDT, var colIndex) = this.GetDataTableVariableAndColumnIndex(nameof(v_DataTableName), nameof(v_ColumnType), nameof(v_DeleteColumnName), engine); + //(var myDT, var colIndex) = this.ExpandUserVariablesAsDataTableAndColumnIndex(nameof(v_DataTable), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + (var myDT, var colIndex, _) = this.ExpandValueOrUserVariableAsDataTableAndColumn(engine); myDT.Columns.RemoveAt(colIndex); } diff --git a/taskt/Core/Automation/Commands/DataTable/DeleteDataTableRowCommand.cs b/taskt/Core/Automation/Commands/DataTable/DeleteDataTableRowCommand.cs index d96b8afcd..808e951e3 100644 --- a/taskt/Core/Automation/Commands/DataTable/DeleteDataTableRowCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/DeleteDataTableRowCommand.cs @@ -5,23 +5,24 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Row Action")] [Attributes.ClassAttributes.CommandSettings("Delete DataTable Row")] [Attributes.ClassAttributes.Description("This command allows you to delete a DataTable Row")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to delete a DataTable Row.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class DeleteDataTableRowCommand : ScriptCommand + public sealed class DeleteDataTableRowCommand : ADataTableRowCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - public string v_RowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //public string v_RowIndex { get; set; } public DeleteDataTableRowCommand() { @@ -31,11 +32,10 @@ public DeleteDataTableRowCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var myDT, var rowIndex) = this.GetDataTableVariableAndRowIndex(nameof(v_DataTableName), nameof(v_RowIndex), engine); + //(var myDT, var rowIndex) = this.ExpandUserVariablesAsDataTableAndRowIndex(nameof(v_DataTable), nameof(v_RowIndex), engine); + (var myDT, var rowIndex) = this.ExpandValueOrUserVariableAsDataTableAndRow(engine); myDT.Rows[rowIndex].Delete(); } diff --git a/taskt/Core/Automation/Commands/DataTable/EM_CanHandleDataTable.cs b/taskt/Core/Automation/Commands/DataTable/EM_CanHandleDataTable.cs new file mode 100644 index 000000000..60720455f --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/EM_CanHandleDataTable.cs @@ -0,0 +1,105 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_CanHandleDataTable + { + /// + /// Check object is DataTable + /// + /// + /// + /// + public static bool IsDataTable(object value, out DataTable table) + { + // TODO: it's ok? + table = default; + if (value is DataTable t) + { + table = t; + return true; + } + else + { + return false; + } + } + + /// + /// Create new Empty DataTable + /// + /// + public static DataTable CreateEmptyDataTable(this ICanHandleDataTable command) + { + // TODO: is it ok? + return new DataTable(); + } + + /// + /// Expand User Variable As DataTable + /// + /// + /// + /// + /// + public static DataTable ExpandUserVariableAsDataTable(ScriptVariable variable) + { + // TODO: it's ok? + if (IsDataTable(variable.VariableValue, out DataTable table)) + { + return table; + } + else + { + throw new Exception($"Variable '{variable.VariableName}' is not DataTable"); + } + } + + /// + /// expand user variable as DataTable + /// + /// + /// + /// + /// + /// + public static DataTable ExpandUserVariableAsDataTable(this ICanHandleDataTable command, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "DataTable Variable"); + //var v = variableName.GetRawVariable(engine); + //if (v.VariableValue is DataTable table) + //{ + // return table; + //} + //else + //{ + // throw new Exception($"Variable '{variableName}' is not DataTable"); + //} + try + { + return ExpandUserVariableAsDataTable(variableName.GetRawVariable(engine)); + } + catch + { + throw new Exception($"Variable '{variableName}' is not DataTable"); + } + } + + /// + /// store DataTable in User Variable + /// + /// + /// + /// + /// + public static void StoreDataTableInUserVariable(this ICanHandleDataTable command, DataTable table, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "DataTable Variable"); + ExtensionMethods.StoreInUserVariable(variableName, table, engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/EM_DataTableColumnPositionPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/DataTable/EM_DataTableColumnPositionPropertiesExtensionMethods.cs new file mode 100644 index 000000000..ede079418 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/EM_DataTableColumnPositionPropertiesExtensionMethods.cs @@ -0,0 +1,52 @@ +using System; +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DataTableColumnPositionPropertiesExtensionMethods + { + /// + /// Expand Value Or User Variable as DataTable Column Index and Name + /// + /// + /// + /// + /// + /// + public static (int, string) ExpandValueOrUserVariableAsDataTableColumn(this ILDataTableColumnPositionProperties command, DataTable table, Engine.AutomationEngineInstance engine) + { + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ColumnType), "Column Type", engine)) + { + case "column name": + var name = ((ScriptCommand)command).ExpandValueOrUserVariable(nameof(command.v_ColumnIndex), "Column Name", engine); + for (int i = table.Columns.Count - 1; i >= 0; i--) + { + if (table.Columns[i].ColumnName == name) + { + return (i, name); + } + } + throw new Exception($"Strange DataTable Column Name. Value: '{command.v_ColumnIndex}', Expand Value: '{name}'"); + + case "index": + var index = ((ScriptCommand)command).ExpandValueOrUserVariableAsInteger(nameof(command.v_ColumnIndex), "Column Index", engine); + if (index < 0) + { + index += table.Columns.Count; + } + if (index >= 0 && index < table.Columns.Count) + { + return (index, table.Columns[index].ColumnName); + } + else + { + throw new Exception($"Strange DataTable Column Index. Index: '{command.v_ColumnIndex}', Expand Value: '{index}'"); + } + + default: + // but not come here + throw new Exception("error"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/EM_DataTableColumnPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/DataTable/EM_DataTableColumnPropertiesExtensionMethods.cs new file mode 100644 index 000000000..f68a13e35 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/EM_DataTableColumnPropertiesExtensionMethods.cs @@ -0,0 +1,22 @@ +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DataTableColumnPropertiesExtensionMethods + { + /// + /// Expand Value Or User Variable As DataTable and DataTable Column + /// + /// + /// + /// + public static (DataTable, int columnIndex, string columnName) ExpandValueOrUserVariableAsDataTableAndColumn(this IDataTableColumnProperties command, Engine.AutomationEngineInstance engine) + { + var table = command.ExpandUserVariableAsDataTable(engine); + + (var index, var name) = command.ExpandValueOrUserVariableAsDataTableColumn(table, engine); + + return (table, index, name); + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/EM_DataTableColumnRowPositionPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/DataTable/EM_DataTableColumnRowPositionPropertiesExtensionMethods.cs new file mode 100644 index 000000000..74533aed3 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/EM_DataTableColumnRowPositionPropertiesExtensionMethods.cs @@ -0,0 +1,21 @@ +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DataTableColumnRowPositionPropertiesExtensionMethods + { + /// + /// Expand value or User Variable as DataTable, Column, and Row + /// + /// + /// + /// (DataTable, Column Index, Column Name, Row Index) + public static (DataTable, int, string, int) ExpandValueOrUserVariableAsDataTableAndColumnRow(this IDataTableColumnRowPositionProperties command, Engine.AutomationEngineInstance engine) + { + var myDT = command.ExpandUserVariableAsDataTable(engine); + (var colIndex, var colName) = command.ExpandValueOrUserVariableAsDataTableColumn(myDT, engine); + var rowIndex = command.ExpandValueOrUserVariableAsDataTableRow(myDT, engine); + return (myDT, colIndex, colName, rowIndex); + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/EM_DataTableCreateFromDataTableExtensionMethods.cs b/taskt/Core/Automation/Commands/DataTable/EM_DataTableCreateFromDataTableExtensionMethods.cs new file mode 100644 index 000000000..5e82a4774 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/EM_DataTableCreateFromDataTableExtensionMethods.cs @@ -0,0 +1,29 @@ +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DataTableCreateFromDataTableExtensionMethods + { + /// + /// Expand User Variable as DataTable + /// + /// + /// + /// + public static DataTable ExpandUserVariableAsDataTable(this ILDataTableCreateFromDataTableProperties command, Engine.AutomationEngineInstance engine) + { + return command.ExpandUserVariableAsDataTable(nameof(command.v_TargetDataTable), engine); + } + + /// + /// Store DataTable in User Variable + /// + /// + /// + /// + public static void StoreDataTableInUserVariable(this ILDataTableCreateFromDataTableProperties command, DataTable table, Engine.AutomationEngineInstance engine) + { + command.StoreDataTableInUserVariable(table, nameof(command.v_NewDataTable), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/EM_DataTableExtensionMethods.cs b/taskt/Core/Automation/Commands/DataTable/EM_DataTableExtensionMethods.cs new file mode 100644 index 000000000..ef3953ec5 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/EM_DataTableExtensionMethods.cs @@ -0,0 +1,42 @@ +using System.Data; +using System.Collections.Generic; +using System.Linq; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DataTableExtensionMethods + { + /// + /// Get DataTable Column Name List + /// + /// + /// + public static List GetColumnNameList(this DataTable table) + { + return table.Columns.Cast().Select(x => x.ColumnName).ToList(); + } + + /// + /// Check Column Name Exists + /// + /// + /// + /// + public static bool IsColumnNameExists(this DataTable table, string name) + { + return table.GetColumnNameList().Contains(name); + } + + /// + /// Clone DataTable Only Columns + /// + /// + /// + public static DataTable CloneDataTableOnlyColumns(this DataTable table) + { + var newDT = new DataTable(); + newDT.Columns.AddRange(table.Columns.Cast().ToArray()); + return newDT; + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/EM_DataTablePropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/DataTable/EM_DataTablePropertiesExtensionMethods.cs new file mode 100644 index 000000000..640e0f01c --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/EM_DataTablePropertiesExtensionMethods.cs @@ -0,0 +1,18 @@ +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DataTablePropertiesExtensionMethods + { + /// + /// Expand User Variable As DataTable + /// + /// + /// + /// + public static DataTable ExpandUserVariableAsDataTable(this ILDataTableProperties command, Engine.AutomationEngineInstance engine) + { + return command.ExpandUserVariableAsDataTable(nameof(command.v_DataTable), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/EM_DataTableResultPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/DataTable/EM_DataTableResultPropertiesExtensionMethods.cs new file mode 100644 index 000000000..c6bb32281 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/EM_DataTableResultPropertiesExtensionMethods.cs @@ -0,0 +1,18 @@ +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DataTableResultPropertiesExtensionMethods + { + /// + /// Store DataTable in User Variable + /// + /// + /// + /// + public static void StoreDataTableInUserVariable(this IDataTableResultProperties command, DataTable table, Engine.AutomationEngineInstance engine) + { + command.StoreDataTableInUserVariable(table, nameof(command.v_Result), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/EM_DataTableRowPositionPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/DataTable/EM_DataTableRowPositionPropertiesExtensionMethods.cs new file mode 100644 index 000000000..f341e9bae --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/EM_DataTableRowPositionPropertiesExtensionMethods.cs @@ -0,0 +1,33 @@ +using System; +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DataTableRowPositionPropertiesExtensionMethods + { + /// + /// Expand Value or User Variable as DataTable Row + /// + /// + /// + /// + /// + /// + public static int ExpandValueOrUserVariableAsDataTableRow(this ILDataTableRowPositionProperties command, DataTable table, Engine.AutomationEngineInstance engine) + { + var index = ((ScriptCommand)command).ExpandValueOrUserVariableAsInteger(nameof(command.v_RowIndex), "Row Index", engine); + if (index < 0) + { + index += table.Rows.Count; + } + if (index >= 0 && index < table.Rows.Count) + { + return index; + } + else + { + throw new Exception($"Strange DataTable Row Index. Value: '{command.v_RowIndex}', Expand Value: '{index}'"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/EM_DataTableRowPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/DataTable/EM_DataTableRowPropertiesExtensionMethods.cs new file mode 100644 index 000000000..63002a3f7 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/EM_DataTableRowPropertiesExtensionMethods.cs @@ -0,0 +1,20 @@ +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DataTableRowPropertiesExtensionMethods + { + /// + /// Expand Value Or User Variable As DataTable and Row + /// + /// + /// + /// + public static (DataTable, int) ExpandValueOrUserVariableAsDataTableAndRow(this IDataTableRowProperties command, Engine.AutomationEngineInstance engine) + { + var table = command.ExpandUserVariableAsDataTable(engine); + var index = command.ExpandValueOrUserVariableAsDataTableRow(table, engine); + return (table, index); + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ExportDataTableAsTextFileCommand.cs b/taskt/Core/Automation/Commands/DataTable/ExportDataTableAsTextFileCommand.cs new file mode 100644 index 000000000..3fa5b4470 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ExportDataTableAsTextFileCommand.cs @@ -0,0 +1,116 @@ +using System; +using System.Data; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("DataTable")] + [Attributes.ClassAttributes.SubGruop("File")] + [Attributes.ClassAttributes.CommandSettings("Export DataTable As Text File")] + [Attributes.ClassAttributes.Description("This command allows you to Export DataTable as Text File.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Export DataTable as Text File.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ExportDataTableAsTextFileCommand : ADataTableInputDataTableCommands + { + //[XmlAttribute] + //public string v_DataTable { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_FilePath))] + [PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtension, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "txt")] + [PropertyParameterOrder(6000)] + public string v_FilePath { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Header")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Header", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7000)] + public string v_ExportHeader { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Row Index")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7001)] + public string v_ExportIndex { get; set; } + + public ExportDataTableAsTextFileCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var dt = this.ExpandUserVariableAsDataTable(engine); + var columnNum = dt.Columns.Count; + + var exportHeader = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportHeader), engine); + var exportIndex = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportIndex), engine); + + string txt = ""; + if (exportHeader) + { + if (exportIndex) + { + txt = "index,"; + } + string t = ""; + foreach (DataColumn c in dt.Columns) + { + t += $"{c.ColumnName},"; + } + txt += t.Substring(0, t.Length - 1) + "\r\n"; + } + + string rowTextAction(DataRow row, int column) + { + string v = ""; + + for (int i = 0; i < column; i++) + { + v += $"{row[i]?.ToString() ?? ""},"; + } + return v.Substring(0, v.Length - 1) + "\r\n"; + } + + Func textAction; + if (exportIndex) + { + textAction = new Func((r, index) => + { + return $"{index},{rowTextAction(r, columnNum)}"; + }); + } + else + { + textAction = new Func((r, index) => + { + return rowTextAction(r, columnNum); + }); + } + + for (int i = 0; i < dt.Rows.Count; i++) + { + txt += textAction(dt.Rows[i], i); + } + + var writeText = new WriteTextFileCommand() + { + v_FilePath = this.v_FilePath, + v_TextToWrite = txt.Trim(), + }; + writeText.RunCommand(engine); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ExportDataTableColumnAsTextFileCommand.cs b/taskt/Core/Automation/Commands/DataTable/ExportDataTableColumnAsTextFileCommand.cs new file mode 100644 index 000000000..b060718d6 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ExportDataTableColumnAsTextFileCommand.cs @@ -0,0 +1,80 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("DataTable")] + [Attributes.ClassAttributes.SubGruop("File")] + [Attributes.ClassAttributes.CommandSettings("Export DataTable Column As Text File")] + [Attributes.ClassAttributes.Description("This command allows you to Export DataTable Column as Text File")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Export DataTable Column as Text File.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ExportDataTableColumnAsTextFileCommand : ADataTableColumnCommands + { + //public string v_DataTable { get; set; } + + //public string v_ColumnType { get; set; } + + //public string v_ColumnIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_FilePath))] + [PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtension, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "txt")] + [PropertyParameterOrder(8000)] + public string v_FilePath { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Header")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Header", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9000)] + public string v_ExportHeader { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Row Index")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9001)] + public string v_ExportIndex { get; set; } + + public ExportDataTableColumnAsTextFileCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + using(var myDT = new InnerScriptVariable(engine)) + { + var createTable = new ConvertDataTableColumnToDataTableCommand() + { + v_DataTable = this.v_DataTable, + v_ColumnType = this.v_ColumnType, + v_ColumnIndex = this.v_ColumnIndex, + v_Result = myDT.VariableName, + }; + createTable.RunCommand(engine); + + var exportText = new ExportDataTableAsTextFileCommand() + { + v_DataTable = myDT.VariableName, + v_ExportHeader = this.v_ExportHeader, + v_ExportIndex = this.v_ExportIndex, + v_FilePath = this.v_FilePath, + }; + exportText.RunCommand(engine); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ExportDataTableRowAsTextFileCommand.cs b/taskt/Core/Automation/Commands/DataTable/ExportDataTableRowAsTextFileCommand.cs new file mode 100644 index 000000000..94cc9a60d --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ExportDataTableRowAsTextFileCommand.cs @@ -0,0 +1,88 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("DataTable")] + [Attributes.ClassAttributes.SubGruop("File")] + [Attributes.ClassAttributes.CommandSettings("Export DataTable Row As Text File")] + [Attributes.ClassAttributes.Description("This command allows you to Export DataTable Row as Text File.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Export DataTable Row as Text File.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ExportDataTableRowAsTextFileCommand : ADataTableRowCommands + { + //public string v_DataTable { get; set; } + + //public string v_RowIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_FilePath))] + [PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtension, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "txt")] + [PropertyParameterOrder(7000)] + public string v_FilePath { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Header")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Header", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9000)] + public string v_ExportHeader { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Row Index")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9001)] + public string v_ExportIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("When Exporting Row Index, Export the Actual Row Index")] + [PropertyIsOptional(true, "Yes")] + [PropertyFirstValue("Yes")] + [PropertyValidationRule("Actual Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(10000)] + public string v_ActualRowIndex { get; set; } + + public ExportDataTableRowAsTextFileCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + using (var myTxt = new InnerScriptVariable(engine)) + { + var rowText = new ConvertDataTableRowToTextCommand() + { + v_DataTable = this.v_DataTable, + v_RowIndex = this.v_RowIndex, + v_ExportHeader = this.v_ExportHeader, + v_ExportIndex = this.v_ExportIndex, + v_ActualRowIndex = this.v_ActualRowIndex, + v_Result = myTxt.VariableName, + }; + rowText.RunCommand(engine); + + var writeText = new WriteTextFileCommand() + { + v_TextToWrite = VariableNameControls.GetWrappedVariableName(myTxt.VariableName, engine), + v_FilePath = this.v_FilePath, + }; + writeText.RunCommand(engine); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/FilterDataTableColumnByRowValueCommand.cs b/taskt/Core/Automation/Commands/DataTable/FilterDataTableColumnByRowValueCommand.cs index b465e18a9..f504e2ed6 100644 --- a/taskt/Core/Automation/Commands/DataTable/FilterDataTableColumnByRowValueCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/FilterDataTableColumnByRowValueCommand.cs @@ -1,50 +1,55 @@ using System; -using System.Xml.Serialization; using System.Data; using System.Windows.Forms; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("DataTable Action")] [Attributes.ClassAttributes.CommandSettings("Filter DataTable Column By Row Value")] [Attributes.ClassAttributes.Description("This command allows you to Filter Columns by reference to Row values.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Filter Columns by reference to Row values.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class FilterDataTableColumnByRowValueCommand : ScriptCommand + public sealed class FilterDataTableColumnByRowValueCommand : ADataTableCreateFromDataTableCommands, ILDataTableRowPositionProperties, ILFilterValueProperties, IHaveDataTableElements { [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] [PropertyDescription("DataTable Variable Name to Filter")] [PropertyValidationRule("DataTable to Filter", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "DataTable to Filter")] - public string v_InputDataTable { get; set; } + public override string v_TargetDataTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - public string v_TargetRowIndex { get; set; } + [PropertyParameterOrder(6000)] + public string v_RowIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_FilterValueType))] [PropertySelectionChangeEvent(nameof(cmbTargetType_SelectionChangeCommited))] - public string v_TargetType { get; set; } + [PropertyParameterOrder(7000)] + public string v_ValueType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_FilterAction))] [PropertySelectionChangeEvent(nameof(cmbFilterAction_SelectionChangeCommited))] + [PropertyParameterOrder(8000)] public string v_FilterAction { get; set; } [XmlElement] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ActionParameterTable))] + [PropertyParameterOrder(9000)] public DataTable v_FilterActionParameterTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_NewOutputDataTableName))] - public string v_OutputDataTable { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_NewOutputDataTableName))] + //public string v_NewDataTable { get; set; } public FilterDataTableColumnByRowValueCommand() { @@ -56,16 +61,16 @@ public FilterDataTableColumnByRowValueCommand() //this.v_TargetType = "Text"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var targetDT, var rowIndex) = this.GetDataTableVariableAndRowIndex(nameof(v_InputDataTable), nameof(v_TargetRowIndex), engine); + //(var targetDT, var rowIndex) = this.ExpandUserVariablesAsDataTableAndRowIndex(nameof(v_TargetDataTable), nameof(v_RowIndex), engine); + var targetDT = this.ExpandUserVariableAsDataTable(engine); + var rowIndex = this.ExpandValueOrUserVariableAsDataTableRow(targetDT, engine); var parameters = DataTableControls.GetFieldValues(v_FilterActionParameterTable, "ParameterName", "ParameterValue", engine); - var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_TargetType), nameof(v_FilterAction), parameters, engine, this); + var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_ValueType), nameof(v_FilterAction), parameters, engine, this); - var res = new DataTable(); + var newDT = new DataTable(); int cols = targetDT.Columns.Count; int rows = targetDT.Rows.Count; @@ -75,33 +80,34 @@ public override void RunCommand(object sender) string value = targetDT.Rows[rowIndex][i]?.ToString() ?? ""; if (checkFunc(value, parameters)) { - if (res.Rows.Count == 0) + if (newDT.Rows.Count == 0) { // first add column - res.Columns.Add(targetDT.Columns[i].ColumnName); + newDT.Columns.Add(targetDT.Columns[i].ColumnName); for (int j = 0; j < rows; j++) { - res.Rows.Add(targetDT.Rows[j][i]); + newDT.Rows.Add(targetDT.Rows[j][i]); } } else { - int c = res.Columns.Count; - res.Columns.Add(targetDT.Columns[i].ColumnName); + int c = newDT.Columns.Count; + newDT.Columns.Add(targetDT.Columns[i].ColumnName); for (int j = 0; j < rows; j++) { - res.Rows[j][c] = targetDT.Rows[j][i]; + newDT.Rows[j][c] = targetDT.Rows[j][i]; } } } } - res.StoreInUserVariable(engine, v_OutputDataTable); + //res.StoreInUserVariable(engine, v_NewDataTable); + this.StoreDataTableInUserVariable(newDT, engine); } private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) { - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var FilterActionComboboxHelper = (ComboBox)ControlsList[nameof(v_FilterAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, FilterActionComboboxHelper); } @@ -109,17 +115,25 @@ private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) private void cmbFilterAction_SelectionChangeCommited(object sender, EventArgs e) { var FilterParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_FilterActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var FilterActionComboboxHelper = (ComboBox)ControlsList[nameof(v_FilterAction)]; ConditionControls.RenderFilter(v_FilterActionParameterTable, FilterParametersGridViewHelper, FilterActionComboboxHelper, TargetTypeComboboxHelper); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var FilterParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_FilterActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var FilterActionComboboxHelper = (ComboBox)ControlsList[nameof(v_FilterAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, FilterActionComboboxHelper); ConditionControls.RenderFilter(v_FilterActionParameterTable, FilterParametersGridViewHelper, FilterActionComboboxHelper, TargetTypeComboboxHelper); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_FilterActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_FilterActionParameterTable); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/FilterDataTableCommand.cs b/taskt/Core/Automation/Commands/DataTable/FilterDataTableCommand.cs index e8786deec..ef8e082a6 100644 --- a/taskt/Core/Automation/Commands/DataTable/FilterDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/FilterDataTableCommand.cs @@ -1,45 +1,46 @@ using System; -using System.Linq; -using System.Xml.Serialization; +using System.Collections.Generic; using System.Data; +using System.Linq; using System.Windows.Forms; -using System.Collections.Generic; -using taskt.UI.Forms; -using taskt.UI.CustomControls; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.UI.CustomControls; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Other")] [Attributes.ClassAttributes.Description("This command allows you filter a DataTable into a new Datatable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get specific rows of a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("This command attempts to filter a Datatable into a new Datatable")] - public class FilterDataTableCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + public sealed class FilterDataTableCommand : ADataTableCreateFromDataTableCommands { [XmlAttribute] [PropertyDescription("Please indicate the DataTable Variable Name")] [InputSpecification("Enter the DataTable name you would like to filter through.")] - [SampleUsage("**myDataTable** or **{{{vMyDataTable}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_DataTableName { get; set; } - [XmlAttribute] - [PropertyDescription("Please indicate the output DataTable Variable Name")] - [InputSpecification("Enter a unique DataTable name for future reference.")] - [SampleUsage("**newData** or **{{{vNewData}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - [PropertyIsVariablesList(true)] - [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] - public string v_OutputDTName { get; set; } + //[SampleUsage("**myDataTable** or **{{{vMyDataTable}}}**")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + public override string v_TargetDataTable { get; set; } + + //[XmlAttribute] + //[PropertyDescription("Please indicate the output DataTable Variable Name")] + //[InputSpecification("Enter a unique DataTable name for future reference.")] + //[SampleUsage("**newData** or **{{{vNewData}}}**")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //[PropertyIsVariablesList(true)] + //[PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] + //public string v_NewDataTable { get; set; } [XmlAttribute] [PropertyDescription("Please indicate tuples to filter by.")] @@ -48,6 +49,7 @@ public class FilterDataTableCommand : ScriptCommand [SampleUsage("{ColumnName1,Item1},{ColumnName2,Item2}")] [Remarks("")] [PropertyShowSampleUsageInDescription(true)] + [PropertyParameterOrder(11000)] public string v_SearchItem { get; set; } public FilterDataTableCommand() @@ -58,62 +60,67 @@ public FilterDataTableCommand() this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //var targetDT = (DataTable)v_TargetDataTable.GetRawVariable(engine).VariableValue; + var targetDT = this.ExpandUserVariableAsDataTable(engine); + + var vSearchItem = v_SearchItem.ExpandValueOrUserVariable(engine); - DataTable Dt = (DataTable)v_DataTableName.GetRawVariable(engine).VariableValue; + //var searchConditions = new List>(); + var searchConditions = new List<(string, string)>(); - var vSearchItem = v_SearchItem.ConvertToUserVariable(engine); - var t = new List>(); var listPairs = vSearchItem.Split('}'); - int i = 0; + //int i = 0; - listPairs = listPairs.Take(listPairs.Count() - 1).ToArray(); + //listPairs = listPairs.Take(listPairs.Count() - 1).ToArray(); foreach (string item in listPairs) { string temp; temp = item.Trim('{'); var tempList = temp.Split(','); - t.Insert(i, Tuple.Create(tempList[0], tempList[1])); - i++; + //searchConditions.Insert(i, Tuple.Create(tempList[0], tempList[1])); + searchConditions.Add((tempList[0], tempList[1])); + //i++; } - List listrows = Dt.AsEnumerable().ToList(); - List templist = new List(); + var listrows = targetDT.AsEnumerable().ToList(); + var templist = new List(); - foreach (Tuple tuple in t) + foreach ((string col, string value) in searchConditions) { - - foreach (DataRow item in listrows) { - if (item[tuple.Item1] != null) + if (item[col] != null) { - if (item[tuple.Item1].ToString() == tuple.Item2.ToString()) + if (item[col].ToString() == value.ToString()) { templist.Add(item); } } } } - DataTable outputDT = new DataTable(); + + var newDT = new DataTable(); int x = 0; - foreach(DataColumn column in Dt.Columns) + foreach(DataColumn column in targetDT.Columns) { - outputDT.Columns.Add(Dt.Columns[x].ToString()); + newDT.Columns.Add(targetDT.Columns[x].ToString()); x++; } + foreach (DataRow item in templist) { - outputDT.Rows.Add(item.ItemArray); + newDT.Rows.Add(item.ItemArray); } - Dt.AcceptChanges(); - outputDT.StoreInUserVariable(engine, v_OutputDTName); + targetDT.AcceptChanges(); + + //newDT.StoreInUserVariable(engine, v_NewDataTable); + this.StoreDataTableInUserVariable(newDT, engine); } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -125,7 +132,7 @@ public override List Render(frmCommandEditor editor) public override string GetDisplayValue() { - return base.GetDisplayValue()+ "[Filter all datarows with the filter: " + v_SearchItem + " from DataTable: " + v_DataTableName + " and put them in DataTable: "+ v_OutputDTName+"]"; + return base.GetDisplayValue()+ "[Filter all datarows with the filter: " + v_SearchItem + " from DataTable: " + v_TargetDataTable + " and put them in DataTable: "+ v_NewDataTable+"]"; } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/FilterDataTableRowByColumnValueCommand.cs b/taskt/Core/Automation/Commands/DataTable/FilterDataTableRowByColumnValueCommand.cs index 0a3feb8a2..329141975 100644 --- a/taskt/Core/Automation/Commands/DataTable/FilterDataTableRowByColumnValueCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/FilterDataTableRowByColumnValueCommand.cs @@ -7,48 +7,54 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("DataTable Action")] [Attributes.ClassAttributes.CommandSettings("Filter DataTable Row By Column Value")] [Attributes.ClassAttributes.Description("This command allows you to Filter Rows by reference to Column values.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Filter Rows by reference to Column values.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class FilterDataTableRowByColumnValueCommand : ScriptCommand + public sealed class FilterDataTableRowByColumnValueCommand : ADataTableCreateFromDataTableCommands, ILDataTableColumnPositionProperties, ILFilterValueProperties, IHaveDataTableElements { [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] [PropertyDescription("DataTable Variable Name to Filter")] [PropertyValidationRule("DataTable to Filter", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "DataTable to Filter")] - public string v_InputDataTable { get; set; } + public override string v_TargetDataTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + [PropertyParameterOrder(6000)] public string v_ColumnType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_TargetColumnIndex { get; set; } + [PropertyParameterOrder(6001)] + public string v_ColumnIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_FilterValueType))] [PropertySelectionChangeEvent(nameof(cmbTargetType_SelectionChangeCommited))] - public string v_TargetType { get; set; } + [PropertyParameterOrder(6002)] + public string v_ValueType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_FilterAction))] [PropertySelectionChangeEvent(nameof(cmbFilterAction_SelectionChangeCommited))] + [PropertyParameterOrder(6003)] public string v_FilterAction { get; set; } [XmlElement] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ActionParameterTable))] + [PropertyParameterOrder(6004)] public DataTable v_FilterActionParameterTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_NewOutputDataTableName))] - public string v_OutputDataTable { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_NewOutputDataTableName))] + //public string v_NewDataTable { get; set; } public FilterDataTableRowByColumnValueCommand() { @@ -60,16 +66,17 @@ public FilterDataTableRowByColumnValueCommand() //this.v_TargetType = "Text"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var targetDT, var colIndex) = this.GetDataTableVariableAndColumnIndex(nameof(v_InputDataTable), nameof(v_ColumnType), nameof(v_TargetColumnIndex), engine); + //(var targetDT, var colIndex) = this.ExpandUserVariablesAsDataTableAndColumnIndex(nameof(v_TargetDataTable), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + var targetDT = this.ExpandUserVariableAsDataTable(engine); + (var colIndex, _) = this.ExpandValueOrUserVariableAsDataTableColumn(targetDT, engine); var parameters = DataTableControls.GetFieldValues(v_FilterActionParameterTable, "ParameterName", "ParameterValue", engine); var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_ColumnType), nameof(v_FilterAction), parameters, engine, this); - var res = DataTableControls.CloneDataTableOnlyColumnName(targetDT); + //var newDT = DataTableControls.CloneDataTableOnlyColumnName(targetDT); + var newDT = targetDT.CloneDataTableOnlyColumns(); int cols = targetDT.Columns.Count; @@ -79,21 +86,22 @@ public override void RunCommand(object sender) string value = targetDT.Rows[i][colIndex]?.ToString() ?? ""; if (checkFunc(value, parameters)) { - int r = res.Rows.Count; - res.Rows.Add(); + int r = newDT.Rows.Count; + newDT.Rows.Add(); for (int j = 0; j < cols; j++) { - res.Rows[r][j] = targetDT.Rows[i][j]; + newDT.Rows[r][j] = targetDT.Rows[i][j]; } } } - res.StoreInUserVariable(engine, v_OutputDataTable); + //res.StoreInUserVariable(engine, v_NewDataTable); + this.StoreDataTableInUserVariable(newDT, engine); } private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) { - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var FilterActionComboboxHelper = (ComboBox)ControlsList[nameof(v_FilterAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, FilterActionComboboxHelper); } @@ -101,17 +109,25 @@ private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) private void cmbFilterAction_SelectionChangeCommited(object sender, EventArgs e) { var FilterParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_FilterActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var FilterActionComboboxHelper = (ComboBox)ControlsList[nameof(v_FilterAction)]; ConditionControls.RenderFilter(v_FilterActionParameterTable, FilterParametersGridViewHelper, FilterActionComboboxHelper, TargetTypeComboboxHelper); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var FilterParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_FilterActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var FilterActionComboboxHelper = (ComboBox)ControlsList[nameof(v_FilterAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, FilterActionComboboxHelper); ConditionControls.RenderFilter(v_FilterActionParameterTable, FilterParametersGridViewHelper, FilterActionComboboxHelper, TargetTypeComboboxHelper); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_FilterActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_FilterActionParameterTable); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/GetDataRowCommand.cs b/taskt/Core/Automation/Commands/DataTable/GetDataRowCommand.cs deleted file mode 100644 index 334db243d..000000000 --- a/taskt/Core/Automation/Commands/DataTable/GetDataRowCommand.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Linq; -using System.Xml.Serialization; -using System.Data; -using System.Windows.Forms; -using System.Collections.Generic; -using taskt.UI.Forms; -using taskt.UI.CustomControls; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] - [Attributes.ClassAttributes.SubGruop("Other")] - [Attributes.ClassAttributes.Description("This command allows you to get a DataRow from a DataTable")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a datarow to a DataTable.")] - [Attributes.ClassAttributes.ImplementationDescription("")] - public class GetDataRowCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Please indicate the DataTable Variable Name")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter a existing DataTable to fet rows from.")] - [SampleUsage("**myDataTable** or **{{{vMyDataTable}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - [PropertyIsVariablesList(true)] - public string v_DataTableName { get; set; } - - [XmlAttribute] - [PropertyDescription("Please enter the index of the DataRow")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter a valid DataRow index value")] - [SampleUsage("**0** or **{{{vRowIndex}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - public string v_DataRowIndex { get; set; } - - [XmlAttribute] - [PropertyDescription("Please Specify the Variable Name To Assign The DataRow")] - [InputSpecification("Select or provide a variable from the variable list")] - [SampleUsage("**vSomeVariable**")] - [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - [PropertyIsVariablesList(true)] - public string v_UserVariableName { get; set; } - - public GetDataRowCommand() - { - this.CommandName = "GetDataRowCommand"; - this.SelectionName = "Get DataRow"; - this.CommandEnabled = true; - this.CustomRendering = true; - - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable dataTable = (DataTable)v_DataTableName.GetRawVariable(engine).VariableValue; - - int index = int.Parse(v_DataRowIndex.ConvertToUserVariable(engine)); - - DataRow row = dataTable.Rows[index]; - - row.StoreInUserVariable(engine, v_UserVariableName); - } - - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - - var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); - RenderedControls.AddRange(ctrls); - - return RenderedControls; - } - - public override string GetDisplayValue() - { - return base.GetDisplayValue() + $" [Get DataRow '{v_DataRowIndex}' from '{v_DataTableName}', Store In: '{v_UserVariableName}']"; - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/GetDataRowCountCommand.cs b/taskt/Core/Automation/Commands/DataTable/GetDataRowCountCommand.cs deleted file mode 100644 index 8a1d09eb9..000000000 --- a/taskt/Core/Automation/Commands/DataTable/GetDataRowCountCommand.cs +++ /dev/null @@ -1,75 +0,0 @@ -using System; -using System.Linq; -using System.Xml.Serialization; -using System.Data; -using System.Windows.Forms; -using System.Collections.Generic; -using taskt.UI.Forms; -using taskt.UI.CustomControls; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] - [Attributes.ClassAttributes.SubGruop("Other")] - [Attributes.ClassAttributes.Description("This command allows you to get the datarow count of a DataTable")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get the datarow count of a DataTable.")] - [Attributes.ClassAttributes.ImplementationDescription("")] - public class GetDataRowCountCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Please indicate the DataTable Variable Name")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter a existing DataTable.")] - [SampleUsage("**myDataTable** or **{{{vMyDataTable}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_DataTableName { get; set; } - - [XmlAttribute] - [PropertyDescription("Please Specify the Variable Name To Assign the Result")] - [InputSpecification("Select or provide a variable from the variable list")] - [SampleUsage("**vSomeVariable**")] - [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - [PropertyIsVariablesList(true)] - public string v_UserVariableName { get; set; } - - public GetDataRowCountCommand() - { - this.CommandName = "GetDataRowCountCommand"; - this.SelectionName = "Get DataRow Count"; - this.CommandEnabled = true; - this.CustomRendering = true; - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable dataTable = (DataTable)v_DataTableName.GetRawVariable(engine).VariableValue; - - var count = dataTable.Rows.Count.ToString(); - - count.StoreInUserVariable(sender, v_UserVariableName); - } - - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); - RenderedControls.AddRange(ctrls); - - return RenderedControls; - } - - public override string GetDisplayValue() - { - return base.GetDisplayValue() + $" [From '{v_DataTableName}', Store In: '{v_UserVariableName}']"; - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/GetDataRowValueCommand.cs b/taskt/Core/Automation/Commands/DataTable/GetDataRowValueCommand.cs deleted file mode 100644 index 31d95b007..000000000 --- a/taskt/Core/Automation/Commands/DataTable/GetDataRowValueCommand.cs +++ /dev/null @@ -1,115 +0,0 @@ -using System; -using System.Linq; -using System.Xml.Serialization; -using System.Data; -using System.Windows.Forms; -using System.Collections.Generic; -using taskt.UI.Forms; -using taskt.UI.CustomControls; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] - [Attributes.ClassAttributes.SubGruop("Other")] - [Attributes.ClassAttributes.Description("This command allows you to get a DataRow Value from a DataTable")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a datarow to a DataTable.")] - [Attributes.ClassAttributes.ImplementationDescription("")] - public class GetDataRowValueCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Please indicate the DataRow Variable Name")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter a existing DataRow to get Values from.")] - [SampleUsage("**myDataRow** or **{{{vMyDataRow}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_DataRowName { get; set; } - - [XmlAttribute] - [PropertyDescription("Select value by Index or Column Name (Default is Index)")] - [PropertyUISelectionOption("Index")] - [PropertyUISelectionOption("Column Name")] - [InputSpecification("Select whether the DataRow value should be found by index or column name")] - [SampleUsage("Select from **Index** or **Column Name**")] - [Remarks("")] - [PropertyIsOptional(true)] - public string v_Option { get; set; } - - [XmlAttribute] - [PropertyDescription("Please enter the index of the DataRow Value")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter a valid DataRow index value")] - [SampleUsage("**0** or **ColName** or **{{{vIndex}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - public string v_DataValueIndex { get; set; } - - [XmlAttribute] - [PropertyDescription("Please Specify the Variable to Assign the Value")] - [InputSpecification("Select or provide a variable from the variable list")] - [SampleUsage("**vSomeVariable**")] - [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - [PropertyIsVariablesList(true)] - public string v_UserVariableName { get; set; } - - public GetDataRowValueCommand() - { - this.CommandName = "GetDataRowValueCommand"; - this.SelectionName = "Get DataRow Value"; - this.CommandEnabled = true; - this.CustomRendering = true; - - this.v_Option = "Index"; - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - DataRow dataRow = (DataRow)v_DataRowName.GetRawVariable(engine).VariableValue; - - - var valueIndex = v_DataValueIndex.ConvertToUserVariable(sender); - - if (String.IsNullOrEmpty(v_Option)) - { - v_Option = "Index"; - } - - string value = ""; - if (v_Option == "Index") - { - int index = int.Parse(valueIndex); - value = dataRow[index].ToString(); - } - else if (v_Option == "Column Name") - { - string index = valueIndex; - value = dataRow.Field(index); - } - - value.StoreInUserVariable(sender, v_UserVariableName); - - } - - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - - var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); - RenderedControls.AddRange(ctrls); - - return RenderedControls; - } - - public override string GetDisplayValue() - { - return base.GetDisplayValue() + $" [Get Value '{v_DataValueIndex}' from '{v_DataRowName}', Store In: '{v_UserVariableName}']"; - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/GetDataTableColumnCountCommand.cs b/taskt/Core/Automation/Commands/DataTable/GetDataTableColumnCountCommand.cs index 3362a10a7..3214f4590 100644 --- a/taskt/Core/Automation/Commands/DataTable/GetDataTableColumnCountCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/GetDataTableColumnCountCommand.cs @@ -1,28 +1,28 @@ using System; using System.Xml.Serialization; -using System.Data; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Column Action")] [Attributes.ClassAttributes.CommandSettings("Get DataTable Column Count")] [Attributes.ClassAttributes.Description("This command allows you to get the column count of a DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get the column count of a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetDataTableColumnCountCommand : ScriptCommand + public sealed class GetDataTableColumnCountCommand : ADataTableGetFromDataTableCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_OutputVariableName { get; set; } + public override string v_Result { get; set; } public GetDataTableColumnCountCommand() { @@ -32,13 +32,12 @@ public GetDataTableColumnCountCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable myDT = v_DataTableName.GetDataTableVariable(engine); + //DataTable myDT = v_DataTable.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(engine); - myDT.Columns.Count.ToString().StoreInUserVariable(engine, v_OutputVariableName); + myDT.Columns.Count.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/GetDataTableColumnListCommand.cs b/taskt/Core/Automation/Commands/DataTable/GetDataTableColumnListCommand.cs index 53b925750..bd4226772 100644 --- a/taskt/Core/Automation/Commands/DataTable/GetDataTableColumnListCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/GetDataTableColumnListCommand.cs @@ -7,23 +7,24 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Column Action")] [Attributes.ClassAttributes.CommandSettings("Get DataTable Column List")] [Attributes.ClassAttributes.Description("This command allows you to get the column name List of a DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get the column name List of a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetDataTableColumnListCommand : ScriptCommand + public sealed class GetDataTableColumnListCommand : ADataTableGetFromDataTableCommands, IListResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] - public string v_OutputList { get; set; } + public override string v_Result { get; set; } public GetDataTableColumnListCommand() { @@ -33,13 +34,17 @@ public GetDataTableColumnListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable myDT = v_DataTableName.GetDataTableVariable(engine); + //DataTable myDT = v_DataTable.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(engine); - myDT.Columns.Cast().Select(col => col.ColumnName).ToList().StoreInUserVariable(engine, v_OutputList); + //myDT.Columns.Cast().Select(col => col.ColumnName).ToList().StoreInUserVariable(engine, v_Result); + this.StoreListInUserVariable( + //myDT.Columns.Cast().Select(col => col.ColumnName).ToList(), + myDT.GetColumnNameList(), + engine + ); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/GetDataTableRowCountCommand.cs b/taskt/Core/Automation/Commands/DataTable/GetDataTableRowCountCommand.cs index aa15b0970..552f923e3 100644 --- a/taskt/Core/Automation/Commands/DataTable/GetDataTableRowCountCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/GetDataTableRowCountCommand.cs @@ -6,23 +6,24 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Row Action")] [Attributes.ClassAttributes.CommandSettings("Get DataTable Row Count")] [Attributes.ClassAttributes.Description("This command allows you to get the Row count of a DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get the Row count of a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetDataTableRowCountCommand : ScriptCommand + public sealed class GetDataTableRowCountCommand : ADataTableGetFromDataTableCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_UserVariableName { get; set; } + public override string v_Result { get; set; } public GetDataTableRowCountCommand() { @@ -32,13 +33,12 @@ public GetDataTableRowCountCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable myDT = v_DataTableName.GetDataTableVariable(engine); + //DataTable myDT = v_DataTable.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(engine); - myDT.Rows.Count.ToString().StoreInUserVariable(engine, v_UserVariableName); + myDT.Rows.Count.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/GetDataTableValueCommand.cs b/taskt/Core/Automation/Commands/DataTable/GetDataTableValueCommand.cs index 0a4f1b65d..5dc3a2cfd 100644 --- a/taskt/Core/Automation/Commands/DataTable/GetDataTableValueCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/GetDataTableValueCommand.cs @@ -5,35 +5,37 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("DataTable Action")] [Attributes.ClassAttributes.CommandSettings("Get DataTable Value")] [Attributes.ClassAttributes.Description("This command allows you to get the DataTable value")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get the DataTable value.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetDataTableValueCommand : ScriptCommand + public sealed class GetDataTableValueCommand : ADataTableColumnRowCommands, ILResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_ColumnIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + //public string v_ColumnIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - public string v_RowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //public string v_RowIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_UserVariableName { get; set; } + [PropertyParameterOrder(9000)] + public string v_Result { get; set; } public GetDataTableValueCommand() { @@ -43,15 +45,14 @@ public GetDataTableValueCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var myDT, var rowIndex, var columnIndex) = this.GetDataTableVariableAndRowColumnIndeies(nameof(v_DataTableName), nameof(v_RowIndex), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + //(var myDT, var rowIndex, var columnIndex) = this.ExpandUserVariablesAsDataTableAndRowColumnIndices(nameof(v_DataTable), nameof(v_RowIndex), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + (var myDT, var columnIndex, _, var rowIndex) = this.ExpandValueOrUserVariableAsDataTableAndColumnRow(engine); string v = myDT.Rows[rowIndex][columnIndex]?.ToString() ?? ""; - v.StoreInUserVariable(engine, v_UserVariableName); + v.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ICanHandleDataTable.cs b/taskt/Core/Automation/Commands/DataTable/ICanHandleDataTable.cs new file mode 100644 index 000000000..11108a4fa --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ICanHandleDataTable.cs @@ -0,0 +1,7 @@ +namespace taskt.Core.Automation.Commands +{ + public interface ICanHandleDataTable : ILExpandableProperties + { + // nothing + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/IDataTableColumnProperties.cs b/taskt/Core/Automation/Commands/DataTable/IDataTableColumnProperties.cs new file mode 100644 index 000000000..3114c86bb --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/IDataTableColumnProperties.cs @@ -0,0 +1,7 @@ +namespace taskt.Core.Automation.Commands +{ + public interface IDataTableColumnProperties : ILDataTableProperties, ILDataTableColumnPositionProperties + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/IDataTableColumnRowPositionProperties.cs b/taskt/Core/Automation/Commands/DataTable/IDataTableColumnRowPositionProperties.cs new file mode 100644 index 000000000..119960492 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/IDataTableColumnRowPositionProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// DataTable Column Row specified properties + /// + public interface IDataTableColumnRowPositionProperties : ILDataTableProperties, ILDataTableColumnPositionProperties, ILDataTableRowPositionProperties + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/IDataTableGetFromDataTable.cs b/taskt/Core/Automation/Commands/DataTable/IDataTableGetFromDataTable.cs new file mode 100644 index 000000000..709ffd6ac --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/IDataTableGetFromDataTable.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Get something from DataTable properties + /// + public interface IDataTableGetFromDataTable : ILResultProperties + { + // string v_Result { get;set;} + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/IDataTableResultProperties.cs b/taskt/Core/Automation/Commands/DataTable/IDataTableResultProperties.cs new file mode 100644 index 000000000..0594d71a7 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/IDataTableResultProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Result is DataTable properties + /// + public interface IDataTableResultProperties : ILResultProperties, ICanHandleDataTable + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/IDataTableRowProperties.cs b/taskt/Core/Automation/Commands/DataTable/IDataTableRowProperties.cs new file mode 100644 index 000000000..53e3a9f05 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/IDataTableRowProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// DataTable Row Properties + /// + public interface IDataTableRowProperties : ILDataTableProperties, ILDataTableRowPositionProperties + { + // no imple + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ILDataTableColumnPositionProperties.cs b/taskt/Core/Automation/Commands/DataTable/ILDataTableColumnPositionProperties.cs new file mode 100644 index 000000000..5c943e50d --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ILDataTableColumnPositionProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// DataTable Column Position Properties + /// + public interface ILDataTableColumnPositionProperties : ILExpandableProperties + { + /// + /// Column Type (Index or ColumnName) + /// + string v_ColumnType { get; set; } + + /// + /// Column Index or Name + /// + string v_ColumnIndex { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ILDataTableCreateFromDataTableProperties.cs b/taskt/Core/Automation/Commands/DataTable/ILDataTableCreateFromDataTableProperties.cs new file mode 100644 index 000000000..488be4ffd --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ILDataTableCreateFromDataTableProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Create From DataTable properties + /// + public interface ILDataTableCreateFromDataTableProperties : ILExpandableProperties, ICanHandleDataTable + { + /// + /// DataTable Variable Name to Create DataTable + /// + string v_TargetDataTable { get; set; } + + /// + /// DataTable Variable Name to Store New DataTable + /// + string v_NewDataTable { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ILDataTableProperties.cs b/taskt/Core/Automation/Commands/DataTable/ILDataTableProperties.cs new file mode 100644 index 000000000..aa7bab118 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ILDataTableProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// DataTable properties + /// + public interface ILDataTableProperties : ICanHandleDataTable, ILExpandableProperties + { + /// + /// DataTable variabe name + /// + string v_DataTable { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/ILDataTableRowPositionProperties.cs b/taskt/Core/Automation/Commands/DataTable/ILDataTableRowPositionProperties.cs new file mode 100644 index 000000000..65ab210e7 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/ILDataTableRowPositionProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// DataTable Row Position Properties + /// + public interface ILDataTableRowPositionProperties : ILExpandableProperties + { + /// + /// DataTable Row Index + /// + string v_RowIndex { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DataTable/JoinDataTableColumnAsTextCommand.cs b/taskt/Core/Automation/Commands/DataTable/JoinDataTableColumnAsTextCommand.cs new file mode 100644 index 000000000..4f75e8dc6 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/JoinDataTableColumnAsTextCommand.cs @@ -0,0 +1,95 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("DataTable")] + [Attributes.ClassAttributes.SubGruop("Column Action")] + [Attributes.ClassAttributes.CommandSettings("Join DataTable Column As Text")] + [Attributes.ClassAttributes.Description("This command allows you to Join DataTable Column Values as Text")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Join DataTable Column Values as Text.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class JoinDataTableColumnAsTextCommand : ADataTableGetFromDataTableColumnCommands + { + //public string v_DataTable { get; set; } + + //public string v_ColumnType { get; set; } + + //public string v_ColumnIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Separator of List Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage(",", PropertyDetailSampleUsage.ValueType.Value, "Separator")] + [PropertyDetailSampleUsage("{{{vSep}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Separator")] + [PropertyValidationRule("Separator", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyDisplayText(true, "Separator")] + [PropertyParameterOrder(8000)] + public string v_Separator { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(9000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Text before Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyIsOptional(true)] + [PropertyDetailSampleUsage("\"", PropertyDetailSampleUsage.ValueType.Value, "Text before Values")] + [PropertyDetailSampleUsage("{{{vText}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Text before Values")] + [PropertyValidationRule("Text before Values", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9000)] + public string v_BeforeText { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Text after Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyIsOptional(true)] + [PropertyDetailSampleUsage("\"", PropertyDetailSampleUsage.ValueType.Value, "Text after Values")] + [PropertyDetailSampleUsage("{{{vText}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Text after Values")] + [PropertyValidationRule("Text after Values", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9001)] + public string v_AfterText { get; set; } + + public JoinDataTableColumnAsTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + using (var myList = new InnerScriptVariable(engine)) + { + var convList = new ConvertDataTableColumnToListCommand() + { + v_DataTable = this.v_DataTable, + v_ColumnType = this.v_ColumnType, + v_ColumnIndex = this.v_ColumnIndex, + v_Result = myList.VariableName, + }; + convList.RunCommand(engine); + + var joinText = new JoinListValuesAsTextCommand() + { + v_List = myList.VariableName, + v_Separator = this.v_Separator, + v_Result = this.v_Result, + v_BeforeText = this.v_BeforeText, + v_AfterText = this.v_AfterText, + }; + joinText.RunCommand(engine); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/JoinDataTableRowAsTextCommand.cs b/taskt/Core/Automation/Commands/DataTable/JoinDataTableRowAsTextCommand.cs new file mode 100644 index 000000000..8ae8679c3 --- /dev/null +++ b/taskt/Core/Automation/Commands/DataTable/JoinDataTableRowAsTextCommand.cs @@ -0,0 +1,96 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("DataTable")] + [Attributes.ClassAttributes.SubGruop("Row Action")] + [Attributes.ClassAttributes.CommandSettings("Join DataTable Row As Text")] + [Attributes.ClassAttributes.Description("This command allows you to join DataTable Row Values as Text")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to join DataTable Row Values as Text.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class JoinDataTableRowAsTextCommand : ADataTableGetFromDataTableRowCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + //public string v_DataTable { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //public string v_RowIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Separator of List Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage(",", PropertyDetailSampleUsage.ValueType.Value, "Separator")] + [PropertyDetailSampleUsage("{{{vSep}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Separator")] + [PropertyValidationRule("Separator", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyDisplayText(true, "Separator")] + [PropertyParameterOrder(7000)] + public string v_Separator { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(8000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Text before Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyIsOptional(true)] + [PropertyDetailSampleUsage("\"", PropertyDetailSampleUsage.ValueType.Value, "Text before Values")] + [PropertyDetailSampleUsage("{{{vText}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Text before Values")] + [PropertyValidationRule("Text before Values", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9000)] + public string v_BeforeText { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Text after Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyIsOptional(true)] + [PropertyDetailSampleUsage("\"", PropertyDetailSampleUsage.ValueType.Value, "Text after Values")] + [PropertyDetailSampleUsage("{{{vText}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Text after Values")] + [PropertyValidationRule("Text after Values", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(9001)] + public string v_AfterText { get; set; } + + public JoinDataTableRowAsTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + using (var myList = new InnerScriptVariable(engine)) + { + var convList = new ConvertDataTableRowToListCommand() + { + v_DataTable = this.v_DataTable, + v_RowIndex = this.v_RowIndex, + v_Result = myList.VariableName, + }; + convList.RunCommand(engine); + + var joinList = new JoinListValuesAsTextCommand() + { + v_List = myList.VariableName, + v_Separator = this.v_Separator, + v_Result = this.v_Result, + v_BeforeText = this.v_BeforeText, + v_AfterText = this.v_AfterText, + }; + joinList.RunCommand(engine); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/LoadDataTableCommand.cs b/taskt/Core/Automation/Commands/DataTable/LoadDataTableCommand.cs deleted file mode 100644 index 0c5dc6252..000000000 --- a/taskt/Core/Automation/Commands/DataTable/LoadDataTableCommand.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Xml.Serialization; -using System.Data; -using System.Collections.Generic; -using System.Windows.Forms; -using taskt.UI.Forms; -using taskt.UI.CustomControls; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] - [Attributes.ClassAttributes.SubGruop("DataTable Action")] - [Attributes.ClassAttributes.Description("This command gets a range of cells and applies them against a dataset")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to quickly iterate over Excel as a dataset.")] - [Attributes.ClassAttributes.ImplementationDescription("This command implements 'OLEDB' to achieve automation.")] - [Attributes.ClassAttributes.EnableAutomateRender(true)] - [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class LoadDataTableCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Please create a DataTable Variable Name")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Indicate a unique reference name for later use")] - [SampleUsage("**vMyDataset** or **{{{vMyDataset}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - [PropertyIsVariablesList(true)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] - [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] - [PropertyValidationRule("DataTable", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "DataTable")] - public string v_DataSetName { get; set; } - - [XmlAttribute] - [PropertyDescription("Please indicate the workbook file path")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowFileSelectionHelper)] - [InputSpecification("Enter or Select the path to the workbook file")] - [SampleUsage("**C:\\temp\\myfile.xlsx** or **{{{vFilePath}}}**")] - [Remarks("This command does not require Excel to be opened. A snapshot will be taken of the workbook as it exists at the time this command runs.")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - [PropertyValidationRule("File", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "File")] - public string v_FilePath { get; set; } - - [XmlAttribute] - [PropertyDescription("Please indicate the sheet name")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Indicate the specific sheet that should be retrieved.")] - [SampleUsage("**Sheet1** or **mySheet** or **{{{vSheet}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - [PropertyValidationRule("Sheet", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "Sheet")] - public string v_SheetName { get; set; } - - [XmlAttribute] - [PropertyDescription("Indicate if Header Row Exists")] - [PropertyUISelectionOption("Yes")] - [PropertyUISelectionOption("No")] - [InputSpecification("Select the necessary indicator")] - [SampleUsage("Select **Yes**, **No**. Data will be loaded as column headers if **YES** is selected.")] - [Remarks("")] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_ContainsHeaderRow { get; set; } - - public LoadDataTableCommand() - { - this.CommandName = "LoadDataTableCommand"; - this.SelectionName = "Load DataTable"; - this.CommandEnabled = true; - this.CustomRendering = true; - - this.v_ContainsHeaderRow = "Yes"; - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - //DataTableControls dataSetCommand = new DataTableControls(); - - //string filePath = FilePathControls.FormatFilePath_NoFileCounter(v_FilePath, engine, new List() { "xlsx", "xlsm", "xls" }, true); - var filePath = v_FilePath.ConvertToUserVariable(engine); - - DataTable requiredData = DataTableControls.CreateDataTable(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + $@";Extended Properties=""Excel 12.0;HDR={v_ContainsHeaderRow.ConvertToUserVariable(sender)};IMEX=1""", "Select * From [" + v_SheetName.ConvertToUserVariable(sender) + "$]"); - - requiredData.StoreInUserVariable(engine, v_DataSetName); - } - //public override List Render(frmCommandEditor editor) - //{ - // base.Render(editor); - - // var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); - // RenderedControls.AddRange(ctrls); - - // return RenderedControls; - //} - - //public override string GetDisplayValue() - //{ - // return base.GetDisplayValue() + " [Get '" + v_SheetName + "' from '" + v_FilePath + "' and apply to '" + v_DataSetName + "']"; - //} - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ParseDatasetRowCommand.cs b/taskt/Core/Automation/Commands/DataTable/ParseDatasetRowCommand.cs deleted file mode 100644 index 45f6a2d78..000000000 --- a/taskt/Core/Automation/Commands/DataTable/ParseDatasetRowCommand.cs +++ /dev/null @@ -1,149 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Xml.Serialization; -using System.Data; -using System.Windows.Forms; -using taskt.UI.Forms; -using taskt.UI.CustomControls; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] - [Attributes.ClassAttributes.SubGruop("Other")] - [Attributes.ClassAttributes.Description("This command allows you to parse a dataset row column into a variable.")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to extract data from a dataset variable")] - [Attributes.ClassAttributes.ImplementationDescription("")] - public class ParseDatasetRowCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Supply the name of the variable containing the datasource")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Select or provide a variable")] - [SampleUsage("**vSomeVariable**")] - [Remarks("")] - public string v_DatasetName { get; set; } - - [XmlAttribute] - [PropertyDescription("Please Select Column Parse Type")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyUISelectionOption("By Column Name")] - [PropertyUISelectionOption("By Column Index")] - [InputSpecification("")] - [SampleUsage("")] - [Remarks("")] - public string v_ColumnParseType { get; set; } - - [XmlAttribute] - [PropertyDescription("Specify Column Name or Index")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("")] - [SampleUsage("")] - [Remarks("")] - public string v_ColumnParameter { get; set; } - - [XmlAttribute] - [PropertyDescription("Please select the variable to receive the extracted column data")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Select or provide a variable from the variable list")] - [SampleUsage("**vSomeVariable**")] - [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] - public string v_applyToVariableName { get; set; } - - [XmlAttribute] - [PropertyDescription("Optional - Specify Alternate Row Number")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("If not executing within a loop, select the applicable index of the row required")] - [SampleUsage("**0** or **vRowNumber**")] - [Remarks("")] - public string v_SpecifiedRow { get; set; } - public ParseDatasetRowCommand() - { - this.CommandName = "ParseRowCommand"; - this.SelectionName = "Parse Dataset Row"; - this.CommandEnabled = true; - this.CustomRendering = true; - this.v_SpecifiedRow = "N/A"; - this.v_ColumnParseType = "By Column Name"; - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - //try to find dataset based on variable name - var dataSourceVariable = engine.VariableList.FirstOrDefault(f => engine.engineSettings.VariableStartMarker + f.VariableName + engine.engineSettings.VariableEndMarker == v_DatasetName); - - if (dataSourceVariable == null) - { - //see if match is found without encasing - dataSourceVariable = engine.VariableList.FirstOrDefault(f => f.VariableName == v_DatasetName); - - //no match was found - if (dataSourceVariable == null) - { - throw new Exception($"Data Source {v_DatasetName} Not Found! Did you input the correct name?"); - } - - } - - var columnName = v_ColumnParameter.ConvertToUserVariable(sender); - var parseStrat = v_ColumnParseType.ConvertToUserVariable(sender); - //get datatable - var dataTable = (DataTable)dataSourceVariable.VariableValue; - - int requiredRowNumber; - - if (!int.TryParse(this.v_SpecifiedRow.ConvertToUserVariable(sender), out requiredRowNumber)) - { - requiredRowNumber = dataSourceVariable.CurrentPosition; - } - - //get required row - var requiredRow = dataTable.Rows[requiredRowNumber]; - - //parse column name based on requirement - object requiredColumn; - if (parseStrat == "By Column Index") - { - requiredColumn = requiredRow[int.Parse(columnName)]; - } - else - { - requiredColumn = requiredRow[columnName]; - } - - - //store value in variable - requiredColumn.ToString().StoreInUserVariable(sender, v_applyToVariableName); - - } - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - - //create standard group controls - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_DatasetName", this, editor)); - - RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_ColumnParseType", this, editor)); - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_ColumnParameter", this, editor)); - - RenderedControls.Add(CommandControls.CreateDefaultLabelFor("v_applyToVariableName", this)); - var VariableNameControl = CommandControls.CreateStandardComboboxFor("v_applyToVariableName", this).AddVariableNames(editor); - RenderedControls.AddRange(CommandControls.CreateDefaultUIHelpersFor("v_applyToVariableName", this, VariableNameControl, editor)); - RenderedControls.Add(VariableNameControl); - - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_SpecifiedRow", this, editor)); - - return RenderedControls; - - } - - public override string GetDisplayValue() - { - return $"{base.GetDisplayValue()} - [Select '{v_ColumnParameter}' {v_ColumnParseType} from '{v_DatasetName}', Apply Result(s) To Variable: {v_applyToVariableName}]"; - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableColumnValueCommand.cs b/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableColumnValueCommand.cs index 4fea6ab73..2b74f7c40 100644 --- a/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableColumnValueCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableColumnValueCommand.cs @@ -7,43 +7,48 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("DataTable Action")] [Attributes.ClassAttributes.CommandSettings("Replace DataTable Column Value")] [Attributes.ClassAttributes.Description("This command allows you to Replace Column values.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Replace Column values.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ReplaceDataTableColumnValueCommand : ScriptCommand + public sealed class ReplaceDataTableColumnValueCommand : ADataTableColumnCommands, ILReplaceValueProperties, IHaveDataTableElements { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] - public string v_InputDataTable { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_TargetColumnIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + //public string v_ColumnIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValueType))] [PropertySelectionChangeEvent(nameof(cmbTargetType_SelectionChangeCommited))] - public string v_TargetType { get; set; } + [PropertyParameterOrder(8000)] + public string v_ValueType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceAction))] + [PropertyParameterOrder(8001)] public string v_ReplaceAction { get; set; } [XmlElement] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ActionParameterTable))] + [PropertyParameterOrder(8002)] public DataTable v_ReplaceActionParameterTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValue))] + [PropertyParameterOrder(8003)] public string v_NewValue { get; set; } public ReplaceDataTableColumnValueCommand() @@ -54,16 +59,15 @@ public ReplaceDataTableColumnValueCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var targetDT, var colIndex) = this.GetDataTableVariableAndColumnIndex(nameof(v_InputDataTable), nameof(v_ColumnType), nameof(v_TargetColumnIndex), engine); + //(var targetDT, var colIndex) = this.ExpandUserVariablesAsDataTableAndColumnIndex(nameof(v_DataTable), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + (var targetDT, var colIndex, _) = this.ExpandValueOrUserVariableAsDataTableAndColumn(engine); var parameters = DataTableControls.GetFieldValues(v_ReplaceActionParameterTable, "ParameterName", "ParameterValue", engine); - var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_TargetType), nameof(v_ReplaceAction), parameters, engine, this); + var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_ValueType), nameof(v_ReplaceAction), parameters, engine, this); - string newValue = v_NewValue.ConvertToUserVariable(engine); + string newValue = v_NewValue.ExpandValueOrUserVariable(engine); int rows = targetDT.Rows.Count; for (int i = 0; i < rows; i++) @@ -78,7 +82,7 @@ public override void RunCommand(object sender) private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) { - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, ReplaceActionComboboxHelper); } @@ -86,18 +90,26 @@ private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) private void cmbReplaceAction_SelectionChangeCommited(object sender, EventArgs e) { var ReplaceParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.RenderFilter(v_ReplaceActionParameterTable, ReplaceParametersGridViewHelper, ReplaceActionComboboxHelper, TargetTypeComboboxHelper); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var ReplaceParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, ReplaceActionComboboxHelper); ConditionControls.RenderFilter(v_ReplaceActionParameterTable, ReplaceParametersGridViewHelper, ReplaceActionComboboxHelper, TargetTypeComboboxHelper); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_ReplaceActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_ReplaceActionParameterTable); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableRowValueCommand.cs b/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableRowValueCommand.cs index e10a62010..d20ecaac5 100644 --- a/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableRowValueCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableRowValueCommand.cs @@ -7,40 +7,45 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("DataTable Action")] [Attributes.ClassAttributes.CommandSettings("Replace DataTable Row Value")] [Attributes.ClassAttributes.Description("This command allows you to Replace Row values.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Replace Row values.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ReplaceDataTableRowValueCommand : ScriptCommand + public sealed class ReplaceDataTableRowValueCommand : ADataTableRowCommands, ILReplaceValueProperties, IHaveDataTableElements { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] - public string v_InputDataTable { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - public string v_TargetRowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //public string v_RowIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValueType))] [PropertySelectionChangeEvent(nameof(cmbTargetType_SelectionChangeCommited))] - public string v_TargetType { get; set; } + [PropertyParameterOrder(8000)] + public string v_ValueType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceAction))] [PropertySelectionChangeEvent(nameof(cmbReplaceAction_SelectionChangeCommited))] + [PropertyParameterOrder(8001)] public string v_ReplaceAction { get; set; } [XmlElement] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ActionParameterTable))] + [PropertyParameterOrder(8002)] public DataTable v_ReplaceActionParameterTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValue))] + [PropertyParameterOrder(8003)] public string v_NewValue { get; set; } public ReplaceDataTableRowValueCommand() @@ -51,16 +56,15 @@ public ReplaceDataTableRowValueCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var targetDT, var rowIndex) = this.GetDataTableVariableAndRowIndex(nameof(v_InputDataTable), nameof(v_TargetRowIndex), engine); + //(var targetDT, var rowIndex) = this.ExpandUserVariablesAsDataTableAndRowIndex(nameof(v_DataTable), nameof(v_RowIndex), engine); + (var targetDT, var rowIndex) = this.ExpandValueOrUserVariableAsDataTableAndRow(engine); var parameters = DataTableControls.GetFieldValues(v_ReplaceActionParameterTable, "ParameterName", "ParameterValue", engine); - var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_TargetType), nameof(v_ReplaceAction), parameters, engine, this); + var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_ValueType), nameof(v_ReplaceAction), parameters, engine, this); - string newValue = v_NewValue.ConvertToUserVariable(engine); + string newValue = v_NewValue.ExpandValueOrUserVariable(engine); int cols = targetDT.Columns.Count; @@ -76,7 +80,7 @@ public override void RunCommand(object sender) private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) { - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, ReplaceActionComboboxHelper); } @@ -84,18 +88,26 @@ private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) private void cmbReplaceAction_SelectionChangeCommited(object sender, EventArgs e) { var ReplaceParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.RenderFilter(v_ReplaceActionParameterTable, ReplaceParametersGridViewHelper, ReplaceActionComboboxHelper, TargetTypeComboboxHelper); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var ReplaceParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, ReplaceActionComboboxHelper); ConditionControls.RenderFilter(v_ReplaceActionParameterTable, ReplaceParametersGridViewHelper, ReplaceActionComboboxHelper, TargetTypeComboboxHelper); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_ReplaceActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_ReplaceActionParameterTable); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableValueCommand.cs b/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableValueCommand.cs index 65ee4e59b..8a9a9ab67 100644 --- a/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableValueCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/ReplaceDataTableValueCommand.cs @@ -7,36 +7,41 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("DataTable Action")] [Attributes.ClassAttributes.CommandSettings("Replace DataTable Value")] [Attributes.ClassAttributes.Description("This command allows you to Replace values.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Replace values.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ReplaceDataTableValueCommand : ScriptCommand + public sealed class ReplaceDataTableValueCommand : ADataTableBothDataTableCommands, ILReplaceValueProperties, IHaveDataTableElements { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] - public string v_InputDataTable { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //public string v_DataTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValueType))] [PropertySelectionChangeEvent(nameof(cmbTargetType_SelectionChangeCommited))] - public string v_TargetType { get; set; } + [PropertyParameterOrder(6000)] + public string v_ValueType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceAction))] [PropertySelectionChangeEvent(nameof(cmbReplaceAction_SelectionChangeCommited))] + [PropertyParameterOrder(7000)] public string v_ReplaceAction { get; set; } [XmlElement] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ActionParameterTable))] + [PropertyParameterOrder(8000)] public DataTable v_ReplaceActionParameterTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValue))] + [PropertyParameterOrder(9000)] public string v_NewValue { get; set; } public ReplaceDataTableValueCommand() @@ -47,16 +52,15 @@ public ReplaceDataTableValueCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetDT = v_InputDataTable.GetDataTableVariable(engine); + //var targetDT = v_DataTable.ExpandUserVariableAsDataTable(engine); + var targetDT = this.ExpandUserVariableAsDataTable(engine); var parameters = DataTableControls.GetFieldValues(v_ReplaceActionParameterTable, "ParameterName", "ParameterValue", engine); - var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_TargetType), nameof(v_ReplaceAction), parameters, engine, this); + var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_ValueType), nameof(v_ReplaceAction), parameters, engine, this); - string newValue = v_NewValue.ConvertToUserVariable(engine); + string newValue = v_NewValue.ExpandValueOrUserVariable(engine); int cols = targetDT.Columns.Count; int rows = targetDT.Rows.Count; @@ -76,7 +80,7 @@ public override void RunCommand(object sender) private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) { - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, ReplaceActionComboboxHelper); } @@ -84,18 +88,26 @@ private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) private void cmbReplaceAction_SelectionChangeCommited(object sender, EventArgs e) { var ReplaceParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.RenderFilter(v_ReplaceActionParameterTable, ReplaceParametersGridViewHelper, ReplaceActionComboboxHelper, TargetTypeComboboxHelper); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var ReplaceParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, ReplaceActionComboboxHelper); ConditionControls.RenderFilter(v_ReplaceActionParameterTable, ReplaceParametersGridViewHelper, ReplaceActionComboboxHelper, TargetTypeComboboxHelper); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_ReplaceActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_ReplaceActionParameterTable); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/RemoveDataRowCommand.cs b/taskt/Core/Automation/Commands/DataTable/SearchAndDeleteDataTableRowsCommand.cs similarity index 54% rename from taskt/Core/Automation/Commands/DataTable/RemoveDataRowCommand.cs rename to taskt/Core/Automation/Commands/DataTable/SearchAndDeleteDataTableRowsCommand.cs index 716050ba9..3820840a0 100644 --- a/taskt/Core/Automation/Commands/DataTable/RemoveDataRowCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/SearchAndDeleteDataTableRowsCommand.cs @@ -4,30 +4,31 @@ using System.Data; using System.Windows.Forms; using System.Collections.Generic; -using taskt.UI.Forms; using taskt.UI.CustomControls; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] - [Attributes.ClassAttributes.SubGruop("Other")] - [Attributes.ClassAttributes.Description("This command allows you remove specified data rows.")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to delete a specific row.")] + [Attributes.ClassAttributes.Group("DataTable")] + [Attributes.ClassAttributes.SubGruop("Row Action")] + [Attributes.ClassAttributes.CommandSettings("Search And Delete DataTable Rows")] + [Attributes.ClassAttributes.Description("This command allows you Delete specified DataTable Rows.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Delete a specific Row.")] [Attributes.ClassAttributes.ImplementationDescription("This command attempts to delete a DataTable Row")] - public class RemoveDataRowCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + public sealed class SearchAndDeleteDataTableRowsCommand : ADataTableBothDataTableCommands { - [XmlAttribute] - [PropertyDescription("Please indicate the DataTable Variable Name")] - [InputSpecification("Enter the name of your DataTable")] - [SampleUsage("**myDataTable** or **{{{vMyDataTable}}}**")] - [Remarks("")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyShowSampleUsageInDescription(true)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyDescription("Please indicate the DataTable Variable Name")] + //[InputSpecification("Enter the name of your DataTable")] + //[SampleUsage("**myDataTable** or **{{{vMyDataTable}}}**")] + //[Remarks("")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //public string v_DataTable { get; set; } [XmlAttribute] [PropertyDescription("Please indicate tuples to delete column rows")] @@ -36,6 +37,7 @@ public class RemoveDataRowCommand : ScriptCommand [SampleUsage("{ColumnName1,Item1},{ColumnName2,Item2}")] [Remarks("")] [PropertyShowSampleUsageInDescription(true)] + [PropertyParameterOrder(6000)] public string v_SearchItem { get; set; } [XmlAttribute] @@ -45,29 +47,30 @@ public class RemoveDataRowCommand : ScriptCommand [InputSpecification("Indicate whether this command should remove rows with all the constraints or remove them with 1 or more constraints")] [SampleUsage("Select from **And** or **Or**")] [Remarks("")] + [PropertyParameterOrder(7000)] public string v_AndOr { get; set; } - public RemoveDataRowCommand() + public SearchAndDeleteDataTableRowsCommand() { - this.CommandName = "RemoveDataRowCommand"; - this.SelectionName = "Remove DataRow"; - this.CommandEnabled = true; - this.CustomRendering = true; + //this.CommandName = "RemoveDataRowCommand"; + //this.SelectionName = "Remove DataRow"; + //this.CommandEnabled = true; + //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - DataTable Dt = (DataTable)v_DataTableName.GetRawVariable(engine).VariableValue; + //DataTable Dt = (DataTable)v_DataTable.GetRawVariable(engine).VariableValue; + var myDT = this.ExpandUserVariableAsDataTable(engine); - var vSearchItem = v_SearchItem.ConvertToUserVariable(engine); + var vSearchItem = v_SearchItem.ExpandValueOrUserVariable(engine); - var t = new List>(); + //var searchConditions = new List>(); + var searchConditions = new List<(string, string)>(); var listPairs = vSearchItem.Split('}'); - int i = 0; + //int i = 0; - listPairs = listPairs.Take(listPairs.Count() - 1).ToArray(); + //listPairs = listPairs.Take(listPairs.Count() - 1).ToArray(); foreach (string item in listPairs) { string temp; @@ -78,76 +81,77 @@ public override void RunCommand(object sender) { tempList[z] = tempList[z].Trim('{'); } - t.Insert(i, Tuple.Create(tempList[0], tempList[1])); - i++; + //searchConditions.Insert(i, Tuple.Create(tempList[0], tempList[1])); + searchConditions.Add((tempList[0], tempList[1])); + //i++; } List listrows = new List(); - listrows = Dt.AsEnumerable().ToList(); + listrows = myDT.AsEnumerable().ToList(); if (v_AndOr == "Or") { - List templist = new List(); + var templist = new List(); //for each filter - foreach (Tuple tuple in t) + //foreach (Tuple tuple in searchConditions) + foreach((string colName, string value) in searchConditions) { //for each datarow foreach (DataRow item in listrows) { - if (item[tuple.Item1] != null) + if (item[colName] != null) { - if (item[tuple.Item1].ToString() == tuple.Item2.ToString()) + if (item[colName].ToString() == value.ToString()) { //add to list if filter matches if (!templist.Contains(item)) + { templist.Add(item); + } } } } - } foreach (DataRow item in templist) { - Dt.Rows.Remove(item); + myDT.Rows.Remove(item); } - Dt.AcceptChanges(); + myDT.AcceptChanges(); //dataSetVariable.VariableValue = Dt; } - //If And operation is checked else if (v_AndOr == "And") { - List templist = new List(listrows); + var templist = new List(listrows); //for each tuple - foreach (Tuple tuple in t) + //foreach (Tuple tuple in searchConditions) + foreach((string colName, string value) in searchConditions) { //for each datarow - foreach (DataRow drow in Dt.AsEnumerable()) + foreach (DataRow drow in myDT.AsEnumerable()) { - if (drow[tuple.Item1].ToString() != tuple.Item2) + if (drow[colName].ToString() != value) { //remove from list if filter matches templist.Remove(drow); } } } - foreach (DataRow item in templist) { - - Dt.Rows.Remove(item); + myDT.Rows.Remove(item); } - Dt.AcceptChanges(); + myDT.AcceptChanges(); //Assigns Datatable to newly updated Datatable //dataSetVariable.VariableValue = Dt; } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -159,7 +163,7 @@ public override List Render(frmCommandEditor editor) public override string GetDisplayValue() { - return base.GetDisplayValue() + "[Remove all datarows with the filter: " + v_SearchItem + " from DataTable: " + v_DataTableName + "]"; + return base.GetDisplayValue() + "[Remove all datarows with the filter: " + v_SearchItem + " from DataTable: " + v_DataTable + "]"; } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTable/SetDataTableColumnValuesByDataTableCommand.cs b/taskt/Core/Automation/Commands/DataTable/SetDataTableColumnValuesByDataTableCommand.cs index a59c3d0ea..be3b6c5ff 100644 --- a/taskt/Core/Automation/Commands/DataTable/SetDataTableColumnValuesByDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/SetDataTableColumnValuesByDataTableCommand.cs @@ -6,45 +6,49 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Column Action")] [Attributes.ClassAttributes.CommandSettings("Set DataTable Column Values By DataTable")] [Attributes.ClassAttributes.Description("This command allows you to set a column to a DataTable by a DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a column to a DataTable by a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetDataTableColumnValuesByDataTableCommand : ScriptCommand + public sealed class SetDataTableColumnValuesByDataTableCommand : ADataTableBothColumnCommands { [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] [PropertyDescription("DataTable Variable Name to be Setted")] [PropertyValidationRule("DataTable to be Setted", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "DataTable to be Setted")] - public string v_DataTableName { get; set; } + public override string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_SetColumnName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + //public string v_ColumnIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] [PropertyDescription("DataTable Variable Name to Set")] [PropertyValidationRule("DataTable to Set", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "DataTable to Set")] + [PropertyParameterOrder(8000)] public string v_SetDataTableName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_WhenLessRows))] [PropertyDescription("When there are Less Rows than DataTable to set")] + [PropertyParameterOrder(8001)] public string v_IfRowNotEnough { set; get; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_WhenGreaterRows))] + [PropertyParameterOrder(8002)] public string v_IfSetDataTableNotEnough { set; get; } public SetDataTableColumnValuesByDataTableCommand() @@ -55,18 +59,18 @@ public SetDataTableColumnValuesByDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var myDT, var colIndex) = this.GetDataTableVariableAndColumnIndex(nameof(v_DataTableName), nameof(v_ColumnType), nameof(v_SetColumnName), engine); + //(var myDT, var colIndex) = this.ExpandUserVariablesAsDataTableAndColumnIndex(nameof(v_DataTable), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + (var myDT, var colIndex, _) = this.ExpandValueOrUserVariableAsDataTableAndColumn(engine); string trgColName = myDT.Columns[colIndex].ColumnName; - DataTable setDT = v_SetDataTableName.GetDataTableVariable(engine); + //DataTable setDT = v_SetDataTableName.ExpandUserVariableAsDataTable(engine); + var setDT = this.ExpandUserVariableAsDataTable(nameof(v_SetDataTableName), engine); - string ifRowNotEnough = this.GetUISelectionValue(nameof(v_IfRowNotEnough), "Row Not Enough", engine); + string ifRowNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfRowNotEnough), "Row Not Enough", engine); // rows check if (myDT.Rows.Count < setDT.Rows.Count) { @@ -81,7 +85,7 @@ public override void RunCommand(object sender) } } - string ifDataTableNotEnough = this.GetUISelectionValue(nameof(v_IfSetDataTableNotEnough), "DataTable Not Enough", engine); + string ifDataTableNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfSetDataTableNotEnough), "DataTable Not Enough", engine); if ((myDT.Rows.Count > setDT.Rows.Count) && (ifDataTableNotEnough == "error")) { throw new Exception("The number of DataTable items is less than the rows to settedd"); diff --git a/taskt/Core/Automation/Commands/DataTable/SetDataTableColumnValuesByListCommand.cs b/taskt/Core/Automation/Commands/DataTable/SetDataTableColumnValuesByListCommand.cs index e56802e3b..4edd58d2b 100644 --- a/taskt/Core/Automation/Commands/DataTable/SetDataTableColumnValuesByListCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/SetDataTableColumnValuesByListCommand.cs @@ -1,45 +1,48 @@ using System; using System.Xml.Serialization; -using System.Data; using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Column Action")] [Attributes.ClassAttributes.CommandSettings("Set DataTable Column Values By List")] [Attributes.ClassAttributes.Description("This command allows you to set a column to a DataTable by a List")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a column to a DataTable by a List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetDataTableColumnValuesByListCommand : ScriptCommand + public sealed class SetDataTableColumnValuesByListCommand : ADataTableBothColumnCommands, ICanHandleList { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //public override string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_SetColumnName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + //public string v_ColumnIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + [PropertyParameterOrder(8000)] public string v_SetListName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_WhenLessRows))] [PropertyDescription("When there are Less Rows than List to set")] + [PropertyParameterOrder(8001)] public string v_IfRowNotEnough { set; get; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_WhenGreaterRows))] + [PropertyParameterOrder(8002)] public string v_IfListNotEnough { set; get; } public SetDataTableColumnValuesByListCommand() @@ -50,16 +53,16 @@ public SetDataTableColumnValuesByListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var myDT, var colIndex) = this.GetDataTableVariableAndColumnIndex(nameof(v_DataTableName), nameof(v_ColumnType), nameof(v_SetColumnName), engine); - string trgColumnName = myDT.Columns[colIndex].ColumnName; + //(var myDT, var colIndex) = this.ExpandUserVariablesAsDataTableAndColumnIndex(nameof(v_DataTable), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + //string trgColumnName = myDT.Columns[colIndex].ColumnName; + (var myDT, _, var trgColumnName) = this.ExpandValueOrUserVariableAsDataTableAndColumn(engine); - List myList = v_SetListName.GetListVariable(engine); + //List myList = v_SetListName.ExpandUserVariableAsList(engine); + var myList = this.ExpandUserVariableAsList(nameof(v_SetListName), engine); - string ifRowNotEnough = this.GetUISelectionValue(nameof(v_IfRowNotEnough), "Row Not Enough", engine); + string ifRowNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfRowNotEnough), "Row Not Enough", engine); // rows check if (myDT.Rows.Count < myList.Count) { @@ -73,7 +76,7 @@ public override void RunCommand(object sender) } } - string ifListNotEnough = this.GetUISelectionValue(nameof(v_IfListNotEnough), "List Not Enough", engine); + string ifListNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfListNotEnough), "List Not Enough", engine); if ((myDT.Rows.Count > myList.Count) && (ifListNotEnough == "error")) { throw new Exception("The number of List items is less than the rows"); diff --git a/taskt/Core/Automation/Commands/DataTable/SetDataTableRowValuesByDataTableCommand.cs b/taskt/Core/Automation/Commands/DataTable/SetDataTableRowValuesByDataTableCommand.cs index c6712205e..383153868 100644 --- a/taskt/Core/Automation/Commands/DataTable/SetDataTableRowValuesByDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/SetDataTableRowValuesByDataTableCommand.cs @@ -2,29 +2,31 @@ using System.Xml.Serialization; using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Row Action")] [Attributes.ClassAttributes.CommandSettings("Set DataTable Row Values By DataTable")] [Attributes.ClassAttributes.Description("This command allows you to set a DataTable Row values to a DataTable by a DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a DataTable Row values to a DataTable by a DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetDataTableRowValuesByDataTableCommand : ScriptCommand + public sealed class SetDataTableRowValuesByDataTableCommand : ADataTableBothRowCommands { [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] [PropertyDescription("DataTable Variable Name to be Setted")] - public string v_DataTableName { get; set; } + public override string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - [PropertyDescription(" Row Index to be Setted")] - public string v_RowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //[PropertyDescription(" Row Index to be Setted")] + //public string v_RowIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] @@ -33,12 +35,12 @@ public class SetDataTableRowValuesByDataTableCommand : ScriptCommand [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - [PropertyDescription(" Row Index to Set")] + [PropertyDescription("Row Index to Set")] public string v_SrcRowIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_WhenColumnNotExists))] - public string v_NotExistsKey { get; set; } + public string v_WhenColumnNotExists { get; set; } public SetDataTableRowValuesByDataTableCommand() { @@ -48,40 +50,81 @@ public SetDataTableRowValuesByDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var myDT, var rowIndex) = this.ExpandUserVariablesAsDataTableAndRowIndex(nameof(v_DataTable), nameof(v_RowIndex), engine); + (var myDT, var rowIndex) = this.ExpandValueOrUserVariableAsDataTableAndRow(engine); + + var addDT = this.ExpandUserVariableAsDataTable(nameof(v_RowName), engine); + var srcRowIndex = this.ExpandValueOrUserVariableAsInteger(nameof(v_SrcRowIndex), engine); + if (srcRowIndex < 0) + { + srcRowIndex += addDT.Rows.Count; + } + if (srcRowIndex < 0 || srcRowIndex >= addDT.Rows.Count) + { + throw new Exception($"Strange DataTable Row Index. Index: '{v_SrcRowIndex}', Expand: '{srcRowIndex}'"); + } - (var myDT, var rowIndex) = this.GetDataTableVariableAndRowIndex(nameof(v_DataTableName), nameof(v_RowIndex), engine); + //(var addDT, var srcRowIndex) = this.ExpandUserVariablesAsDataTableAndRowIndex(nameof(v_RowName), nameof(v_SrcRowIndex), engine); + string ifNotColumnExists = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenColumnNotExists), "Column not exists", engine); - (var addDT, var srcRowIndex) = this.GetDataTableVariableAndRowIndex(nameof(v_RowName), nameof(v_SrcRowIndex), engine); - string ifNotColumnExists = this.GetUISelectionValue(nameof(v_NotExistsKey), "Column not exists", engine); + //// get columns list + //new GetDataTableColumnListCommand + //{ + // v_DataTable = this.v_DataTable, + // v_Result = VariableNameControls.GetInnerVariableName(0, engine) + //}.RunCommand(engine); + //var columns = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; - // get columns list - new GetDataTableColumnListCommand - { - v_DataTableName = this.v_DataTableName, - v_OutputList = VariableNameControls.GetInnerVariableName(0, engine) - }.RunCommand(engine); - var columns = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; + //if (ifNotColumnExists == "error") + //{ + // for (int i = 0; i < addDT.Columns.Count; i++) + // { + // if (!columns.Contains(addDT.Columns[i].ColumnName)) + // { + // throw new Exception("Column name " + addDT.Columns[i].ColumnName + " does not exists"); + // } + // } + //} + //for (int i = 0; i < addDT.Columns.Count; i++) + //{ + // if (columns.Contains(addDT.Columns[i].ColumnName)) + // { + // myDT.Rows[rowIndex][addDT.Columns[i].ColumnName] = addDT.Rows[srcRowIndex][addDT.Columns[i].ColumnName]; + // } + //} - if (ifNotColumnExists == "error") + using (var myColumn = new InnerScriptVariable(engine)) { - for (int i = 0; i < addDT.Columns.Count; i++) + // get columns list + new GetDataTableColumnListCommand + { + v_DataTable = this.v_DataTable, + v_Result = myColumn.VariableName, + }.RunCommand(engine); + //var columns = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; + //var columns = (List)myColumn.VariableValue; + var columns = EM_CanHandleListExtensionMethods.ExpandUserVariableAsList(myColumn); + + if (ifNotColumnExists == "error") { - if (!columns.Contains(addDT.Columns[i].ColumnName)) + for (int i = 0; i < addDT.Columns.Count; i++) { - throw new Exception("Column name " + addDT.Columns[i].ColumnName + " does not exists"); + if (!columns.Contains(addDT.Columns[i].ColumnName)) + { + throw new Exception($"Column name {addDT.Columns[i].ColumnName} does not exists"); + } } } - } - for (int i = 0; i < addDT.Columns.Count; i++) - { - if (columns.Contains(addDT.Columns[i].ColumnName)) + for (int i = 0; i < addDT.Columns.Count; i++) { - myDT.Rows[rowIndex][addDT.Columns[i].ColumnName] = addDT.Rows[srcRowIndex][addDT.Columns[i].ColumnName]; + if (columns.Contains(addDT.Columns[i].ColumnName)) + { + myDT.Rows[rowIndex][addDT.Columns[i].ColumnName] = addDT.Rows[srcRowIndex][addDT.Columns[i].ColumnName]; + } } } } } -} \ No newline at end of file +} diff --git a/taskt/Core/Automation/Commands/DataTable/SetDataTableRowValuesByDictionaryCommand.cs b/taskt/Core/Automation/Commands/DataTable/SetDataTableRowValuesByDictionaryCommand.cs index 4d5627a8a..c6b7e1e56 100644 --- a/taskt/Core/Automation/Commands/DataTable/SetDataTableRowValuesByDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/SetDataTableRowValuesByDictionaryCommand.cs @@ -2,27 +2,29 @@ using System.Xml.Serialization; using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("Row Action")] [Attributes.ClassAttributes.CommandSettings("Set DataTable Row Values By Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to set a DataTable Row values to a DataTable by a Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a DataTable Row values to a DataTable by a Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetDataTableRowValuesByDictionaryCommand : ScriptCommand + public sealed class SetDataTableRowValuesByDictionaryCommand : ADataTableBothRowCommands, ICanHandleDictionary { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //public override string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - public string v_RowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //public string v_RowIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] @@ -38,7 +40,7 @@ public class SetDataTableRowValuesByDictionaryCommand : ScriptCommand [PropertyUISelectionOption("Ignore")] [PropertyUISelectionOption("Error")] [PropertyIsOptional(true, "Ignore")] - public string v_NotExistsKey { get; set; } + public string v_WhenColumnNotExists { get; set; } public SetDataTableRowValuesByDictionaryCommand() { @@ -48,41 +50,74 @@ public SetDataTableRowValuesByDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var myDT, var rowIndex) = this.ExpandUserVariablesAsDataTableAndRowIndex(nameof(v_DataTable), nameof(v_RowIndex), engine); + (var myDT, var rowIndex) = this.ExpandValueOrUserVariableAsDataTableAndRow(engine); - (var myDT, var rowIndex) = this.GetDataTableVariableAndRowIndex(nameof(v_DataTableName), nameof(v_RowIndex), engine); + //var myDic = v_RowValues.ExpandUserVariableAsDictinary(engine); + var myDic = this.ExpandUserVariableAsDictionary(nameof(v_RowValues), engine); - var myDic = v_RowValues.GetDictionaryVariable(engine); + string ifKeyNotExists = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenColumnNotExists), "Key Not Exists", engine); - string ifKeyNotExists = this.GetUISelectionValue(nameof(v_NotExistsKey), "Key Not Exists", engine); + //// get columns list + //new GetDataTableColumnListCommand + //{ + // v_DataTable = this.v_DataTable, + // v_Result = VariableNameControls.GetInnerVariableName(0, engine) + //}.RunCommand(engine); + //var columns = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; - // get columns list - new GetDataTableColumnListCommand - { - v_DataTableName = this.v_DataTableName, - v_OutputList = VariableNameControls.GetInnerVariableName(0, engine) - }.RunCommand(engine); - var columns = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; + //if (ifKeyNotExists == "error") + //{ + // // check key and throw exception + // foreach(var item in myDic) + // { + // if (!columns.Contains(item.Key)) + // { + // throw new Exception("Column name " + item.Key + " does not exists"); + // } + // } + //} - if (ifKeyNotExists == "error") + //foreach(var item in myDic) + //{ + // if (columns.Contains(item.Key)) + // { + // myDT.Rows[rowIndex][item.Key] = item.Value; + // } + //} + + using (var myColumn = new InnerScriptVariable(engine)) { - // check key and throw exception - foreach(var item in myDic) + // get columns list + new GetDataTableColumnListCommand + { + v_DataTable = this.v_DataTable, + v_Result = myColumn.VariableName, + }.RunCommand(engine); + //var columns = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; + //var columns = (List)myColumn.VariableValue; + var columns = EM_CanHandleListExtensionMethods.ExpandUserVariableAsList(myColumn); + + if (ifKeyNotExists == "error") { - if (!columns.Contains(item.Key)) + // check key and throw exception + foreach (var item in myDic) { - throw new Exception("Column name " + item.Key + " does not exists"); + if (!columns.Contains(item.Key)) + { + throw new Exception($"Column name {item.Key} does not exists"); + } } } - } - foreach(var item in myDic) - { - if (columns.Contains(item.Key)) + foreach (var item in myDic) { - myDT.Rows[rowIndex][item.Key] = item.Value; + if (columns.Contains(item.Key)) + { + myDT.Rows[rowIndex][item.Key] = item.Value; + } } } } diff --git a/taskt/Core/Automation/Commands/DataTable/SetDataTableValueCommand.cs b/taskt/Core/Automation/Commands/DataTable/SetDataTableValueCommand.cs index 76048dfe3..5ce2c7db5 100644 --- a/taskt/Core/Automation/Commands/DataTable/SetDataTableValueCommand.cs +++ b/taskt/Core/Automation/Commands/DataTable/SetDataTableValueCommand.cs @@ -5,31 +5,32 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] + [Attributes.ClassAttributes.Group("DataTable")] [Attributes.ClassAttributes.SubGruop("DataTable Action")] [Attributes.ClassAttributes.CommandSettings("Set DataTable Value")] [Attributes.ClassAttributes.Description("This command allows you to set the DataTable value")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set the DataTable value.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetDataTableValueCommand : ScriptCommand + public sealed class SetDataTableValueCommand : ADataTableColumnRowCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] - public string v_DataTableName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_BothDataTableName))] + //public string v_DataTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnType))] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] - public string v_ColumnIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_ColumnNameIndex))] + //public string v_ColumnIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] - public string v_RowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_RowIndex))] + //public string v_RowIndex { get; set; } [XmlAttribute] [PropertyDescription("Value to Set")] @@ -40,6 +41,7 @@ public class SetDataTableValueCommand : ScriptCommand [Remarks("")] [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] [PropertyDisplayText(true, "Value to Set")] + [PropertyParameterOrder(9000)] public string v_NewValue { get; set; } public SetDataTableValueCommand() @@ -50,13 +52,12 @@ public SetDataTableValueCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var myDT, var rowIndex, var columnIndex) = this.GetDataTableVariableAndRowColumnIndeies(nameof(v_DataTableName), nameof(v_RowIndex), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + //(var myDT, var rowIndex, var columnIndex) = this.ExpandUserVariablesAsDataTableAndRowColumnIndices(nameof(v_DataTable), nameof(v_RowIndex), nameof(v_ColumnType), nameof(v_ColumnIndex), engine); + (var myDT, var columnIndex, _, var rowIndex) = this.ExpandValueOrUserVariableAsDataTableAndColumnRow(engine); - string newValue = v_NewValue.ConvertToUserVariable(engine); + string newValue = v_NewValue.ExpandValueOrUserVariable(engine); myDT.Rows[rowIndex][columnIndex] = newValue; } diff --git a/taskt/Core/Automation/Commands/DataTable/WriteDataRowValueCommand.cs b/taskt/Core/Automation/Commands/DataTable/WriteDataRowValueCommand.cs deleted file mode 100644 index 5e57b5625..000000000 --- a/taskt/Core/Automation/Commands/DataTable/WriteDataRowValueCommand.cs +++ /dev/null @@ -1,110 +0,0 @@ -using System; -using System.Linq; -using System.Xml.Serialization; -using System.Data; -using System.Windows.Forms; -using System.Collections.Generic; -using taskt.UI.Forms; -using taskt.UI.CustomControls; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("DataTable Commands")] - [Attributes.ClassAttributes.SubGruop("Other")] - [Attributes.ClassAttributes.Description("This command allows you to write a Value to a DataRow")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to write a Value to a DataRow.")] - [Attributes.ClassAttributes.ImplementationDescription("")] - public class WriteDataRowValueCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Please indicate the DataRow Variable Name")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter a existing DataTable to add rows to.")] - [SampleUsage("**myDataRow** or **{{{vMyDataRow}}}**")] - [Remarks("")] - public string v_DataRowName { get; set; } - - [XmlAttribute] - [PropertyDescription("Select value by Index or Column Name (Default is Index)")] - [PropertyUISelectionOption("Index")] - [PropertyUISelectionOption("Column Name")] - [InputSpecification("Select whether the DataRow value should be found by index or column name")] - [SampleUsage("Select from **Index** or **Column Name**")] - [Remarks("")] - [PropertyIsOptional(true)] - public string v_Option { get; set; } - - [XmlAttribute] - [PropertyDescription("Please enter the index of the DataRow Value")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter a valid DataRow index value")] - [SampleUsage("**0** or **{{{vIndex}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - public string v_DataValueIndex { get; set; } - - [XmlAttribute] - [PropertyDescription("Please enter the Value")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter the value to write to the DataRow cell")] - [SampleUsage("**vSomeVariable**")] - [Remarks("")] - public string v_DataRowValue { get; set; } - - public WriteDataRowValueCommand() - { - this.CommandName = "WriteDataRowValueCommand"; - this.SelectionName = "Write DataRow Value"; - this.CommandEnabled = true; - this.CustomRendering = true; - v_Option = "Index"; - - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - var dataRowValue = v_DataRowValue.ConvertToUserVariable(sender); - - DataRow dataRow = (DataRow)v_DataRowName.GetRawVariable(engine).VariableValue; - - var valueIndex = v_DataValueIndex.ConvertToUserVariable(sender); - - if (String.IsNullOrEmpty(v_Option)) - { - v_Option = "Index"; - } - - if (v_Option == "Index") - { - int index = int.Parse(valueIndex); - dataRow[index] = dataRowValue; - - } - else if (v_Option == "Column Name") - { - string index = valueIndex; - dataRow.SetField(index, dataRowValue); - } - } - - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - - var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); - RenderedControls.AddRange(ctrls); - - return RenderedControls; - } - - public override string GetDisplayValue() - { - return base.GetDisplayValue() + $" [Write Value '{v_DataRowValue}' to '{v_DataValueIndex}' in '{v_DataRowName}']"; - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DataTableControls.cs b/taskt/Core/Automation/Commands/DataTableControls.cs index 888e34ec6..5b4613606 100644 --- a/taskt/Core/Automation/Commands/DataTableControls.cs +++ b/taskt/Core/Automation/Commands/DataTableControls.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Data; using System.Linq; -using System.Reflection; using System.Windows.Forms; using taskt.Core.Automation.Attributes.PropertyAttributes; @@ -26,6 +25,7 @@ internal static class DataTableControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyValidationRule("DataTable", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "DataTable")] + [PropertyParameterOrder(5000)] public static string v_InputDataTableName { get; } /// @@ -43,6 +43,7 @@ internal static class DataTableControls [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] [PropertyValidationRule("DataTable", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "DataTable")] + [PropertyParameterOrder(5000)] public static string v_OutputDataTableName { get; } /// @@ -60,6 +61,7 @@ internal static class DataTableControls [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] [PropertyValidationRule("New DataTable", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "New DataTable")] + [PropertyParameterOrder(5000)] public static string v_NewOutputDataTableName { get; } /// @@ -77,6 +79,7 @@ internal static class DataTableControls [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] [PropertyValidationRule("DataTable", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "DataTable")] + [PropertyParameterOrder(5000)] public static string v_BothDataTableName { get; } /// @@ -91,6 +94,7 @@ internal static class DataTableControls [PropertyUISelectionOption("Ignore")] [PropertyUISelectionOption("Error")] [PropertyIsOptional(true, "Ignore")] + [PropertyParameterOrder(5000)] public static string v_WhenColumnNotExists { get; } /// @@ -106,6 +110,7 @@ internal static class DataTableControls [PropertyIsOptional(true, "Column Name")] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyDisplayText(true, "Column Type")] + [PropertyParameterOrder(5000)] public static string v_ColumnType { get; } /// @@ -122,6 +127,7 @@ internal static class DataTableControls [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Column", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Column")] + [PropertyParameterOrder(5000)] public static string v_ColumnNameIndex { get; } /// @@ -138,6 +144,7 @@ internal static class DataTableControls [PropertyTextBoxSetting(1, false)] [PropertyIsOptional(true, "Current Row")] [PropertyDisplayText(true, "Row")] + [PropertyParameterOrder(5000)] public static string v_RowIndex { get; } /// @@ -154,6 +161,7 @@ internal static class DataTableControls [PropertyUISelectionOption("Add Rows")] [PropertyUISelectionOption("Error")] [PropertyIsOptional(true, "Ignore")] + [PropertyParameterOrder(5000)] public static string v_WhenLessRows { get; } /// @@ -168,36 +176,43 @@ internal static class DataTableControls [PropertyUISelectionOption("Ignore")] [PropertyUISelectionOption("Error")] [PropertyIsOptional(true, "Ignore")] + [PropertyParameterOrder(5000)] public static string v_WhenGreaterRows { set; get; } - /// - /// get DataTable variable from variable name - /// - /// - /// - /// - /// - public static DataTable GetDataTableVariable(this string variableName, Engine.AutomationEngineInstance engine) - { - Script.ScriptVariable v = variableName.GetRawVariable(engine); - if (v.VariableValue is DataTable table) - { - return table; - } - else - { - throw new Exception("Variable " + variableName + " is not DataTable"); - } - } + ///// + ///// Expand user variable as DataTable + ///// + ///// + ///// + ///// + ///// Value is not DataTable + //public static DataTable ExpandUserVariableAsDataTable(this string variableName, Engine.AutomationEngineInstance engine) + //{ + // Script.ScriptVariable v = variableName.GetRawVariable(engine); + // if (v.VariableValue is DataTable table) + // { + // return table; + // } + // else + // { + // throw new Exception("Variable " + variableName + " is not DataTable"); + // } + //} + + //public static void StoreInUserVariable(this DataTable value, Engine.AutomationEngineInstance engine, string targetVariable) + //{ + // ExtensionMethods.StoreInUserVariable(targetVariable, value, engine, false); + //} /// - /// get DataTable variable from parameter name + /// Convert parameter value to DataTable /// /// /// /// /// - public static DataTable ConvertToUserVariableAsDataTable(this ScriptCommand command, string parameterName, Engine.AutomationEngineInstance engine) + /// value is not DataTable + public static DataTable ConvertParameterToDataTable(this ScriptCommand command, string parameterName, Engine.AutomationEngineInstance engine) { var prop = command.GetProperty(parameterName); var value = prop?.GetValue(command) ?? null; @@ -207,112 +222,113 @@ public static DataTable ConvertToUserVariableAsDataTable(this ScriptCommand comm } else { - throw new Exception("Property '" + parameterName + "' is not DataTable"); + throw new Exception($"Parameter '{parameterName}' is not DataTable"); } } - /// - /// get DataTable variable and Column Index from variable name property and column properies - /// - /// - /// - /// - /// - /// - /// - public static (DataTable table, int columnIndex) GetDataTableVariableAndColumnIndex(this ScriptCommand command, string tableName, string columnTypeName, string columnName, Engine.AutomationEngineInstance engine) - { - var targetTable = command.ConvertToUserVariable(tableName, "DataTable", engine); - var table = targetTable.GetDataTableVariable(engine); - var index = command.GetColumnIndex(table, columnTypeName, columnName, engine); - return (table, index); - } - - /// - /// get DataTable variable and Row Index from variable name property and row name property. If row index is empty, return value is current position. - /// - /// - /// - /// - /// - /// - /// - public static (DataTable table, int rowIndex) GetDataTableVariableAndRowIndex(this ScriptCommand command, string tableName, string rowName, Engine.AutomationEngineInstance engine) - { - var targetTable = command.ConvertToUserVariable(tableName, "DataTable", engine); - var table = targetTable.GetDataTableVariable(engine); - - var rowValue = command.ConvertToUserVariable(rowName, "Row Index", engine); - int index; - if (String.IsNullOrEmpty(rowValue)) - { - index = targetTable.GetRawVariable(engine).CurrentPosition; - } - else - { - index = command.ConvertToUserVariableAsInteger(rowName, "Row Index", engine); - } - if (index < 0) - { - index += table.Rows.Count; - } - - if ((index < 0) || (index >= table.Rows.Count)) - { - throw new Exception("Strange Row Index '" + rowName + "', parsed '" + index + "'"); - } - - return (table, index); - } - - /// - /// get DataTable variable Row Index, and Column Index from variable name property and row, column name properties. If row index is empty, return value is current position. - /// - /// - /// - /// - /// - /// - public static (DataTable table, int rowIndex, int columnIndex) GetDataTableVariableAndRowColumnIndeies(this ScriptCommand command, string tableName, string rowName, string columnTypeName, string columnName, Engine.AutomationEngineInstance engine) - { - (var table, var rowIndex) = command.GetDataTableVariableAndRowIndex(tableName, rowName, engine); - (_, var columnIndex) = command.GetDataTableVariableAndColumnIndex(tableName, columnTypeName, columnName, engine); - - return (table, rowIndex, columnIndex); - } - - - public static void StoreInUserVariable(this DataTable value, Engine.AutomationEngineInstance sender, string targetVariable) - { - ExtensionMethods.StoreInUserVariable(targetVariable, value, sender, false); - } - - - public static DataTable CreateDataTable(string connection, string query) - { - //create vars - var dataTable = new DataTable(); - var oleConnection = new System.Data.OleDb.OleDbConnection(connection); - var oleCommand = new System.Data.OleDb.OleDbCommand(query, oleConnection); - - //get data - System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(oleCommand); - oleConnection.Open(); - adapter.Fill(dataTable); - oleConnection.Close(); - - //clean up - oleConnection.Dispose(); - adapter.Dispose(); - oleCommand.Dispose(); - - //foreach (var rw in dataTable.Rows) - //{ - - //} - - return dataTable; - } + ///// + ///// expand user variables as DataTable and Column Index from variable name parameter and column parameters + ///// + ///// + ///// + ///// + ///// + ///// + ///// + //public static (DataTable table, int columnIndex) ExpandUserVariablesAsDataTableAndColumnIndex(this ScriptCommand command, string tableName, string columnTypeName, string columnName, Engine.AutomationEngineInstance engine) + //{ + // var targetTable = command.ExpandValueOrUserVariable(tableName, "DataTable", engine); + // var table = targetTable.ExpandUserVariableAsDataTable(engine); + // var index = command.GetColumnIndex(table, columnTypeName, columnName, engine); + // return (table, index); + //} + + ///// + ///// expand user variables as DataTable and Row Index from variable name property and row name property. If row index is empty, return value is current position. + ///// + ///// + ///// + ///// + ///// + ///// + ///// + //public static (DataTable table, int rowIndex) ExpandUserVariablesAsDataTableAndRowIndex(this ScriptCommand command, string tableName, string rowName, Engine.AutomationEngineInstance engine) + //{ + // var targetTable = command.ExpandValueOrUserVariable(tableName, "DataTable", engine); + // var table = targetTable.ExpandUserVariableAsDataTable(engine); + + // var rowValue = command.ExpandValueOrUserVariable(rowName, "Row Index", engine); + // //int index; + // //if (String.IsNullOrEmpty(rowValue)) + // //{ + // // index = targetTable.GetRawVariable(engine).CurrentPosition; + // //} + // //else + // //{ + // // index = command.ConvertToUserVariableAsInteger(rowName, "Row Index", engine); + // //} + + // //if (index < 0) + // //{ + // // index += table.Rows.Count; + // //} + + // //if ((index < 0) || (index >= table.Rows.Count)) + // //{ + // // throw new Exception("Strange Row Index '" + rowName + "', parsed '" + index + "'"); + // //} + + // if (string.IsNullOrEmpty(rowValue)) + // { + // rowValue = targetTable.GetRawVariable(engine).CurrentPosition.ToString(); + // } + + // var index = GetRowIndex(table, rowValue, engine); + + // return (table, index); + //} + + ///// + ///// expand user variables as DataTable Row Index, and Column Index from variable name property and row, column name properties. If row index is empty, return value is current position. + ///// + ///// + ///// + ///// + ///// + ///// + //public static (DataTable table, int rowIndex, int columnIndex) ExpandUserVariablesAsDataTableAndRowColumnIndices(this ScriptCommand command, string tableName, string rowName, string columnTypeName, string columnName, Engine.AutomationEngineInstance engine) + //{ + // (var table, var rowIndex) = command.ExpandUserVariablesAsDataTableAndRowIndex(tableName, rowName, engine); + // (_, var columnIndex) = command.ExpandUserVariablesAsDataTableAndColumnIndex(tableName, columnTypeName, columnName, engine); + + // return (table, rowIndex, columnIndex); + //} + + //public static DataTable CreateDataTable(string connection, string query) + //{ + // //create vars + // var dataTable = new DataTable(); + // var oleConnection = new System.Data.OleDb.OleDbConnection(connection); + // var oleCommand = new System.Data.OleDb.OleDbCommand(query, oleConnection); + + // //get data + // System.Data.OleDb.OleDbDataAdapter adapter = new System.Data.OleDb.OleDbDataAdapter(oleCommand); + // oleConnection.Open(); + // adapter.Fill(dataTable); + // oleConnection.Close(); + + // //clean up + // oleConnection.Dispose(); + // adapter.Dispose(); + // oleCommand.Dispose(); + + // //foreach (var rw in dataTable.Rows) + // //{ + + // //} + + // return dataTable; + //} /// /// check column name exists @@ -325,137 +341,164 @@ private static bool IsColumnExists(DataTable table, string columnName) return table.Columns.Contains(columnName); } - /// - /// check column index exists - /// - /// - /// - /// - private static bool IsColumnExists(DataTable table, int columnIndex) - { - if (columnIndex >= 0) - { - return (columnIndex < table.Columns.Count); - } - else - { - int idx = table.Columns.Count + columnIndex; - return ((idx >= 0) && (idx < table.Columns.Count)); - } - } - - /// - /// get DataTable column name from value specified by argument - /// - /// - /// - /// - /// - /// - private static string GetColumnName(DataTable table, string columnName, Engine.AutomationEngineInstance engine) - { - string col = columnName.ConvertToUserVariable(engine); - if (IsColumnExists(table, col)) - { - return col; - } - else - { - throw new Exception("Strange Column Name " + columnName); - } - } - - /// - /// get column index from value specified by argument - /// - /// - /// - /// - /// - /// - private static int GetColumnIndex(DataTable table, string columnIndex, Engine.AutomationEngineInstance engine) - { - int index = new PropertyConvertTag(columnIndex, "Column Index").ConvertToUserVariableAsInteger(engine); - if (index < 0) - { - index = table.Columns.Count + index; - } - if (IsColumnExists(table, index)) - { - return index; - } - else - { - throw new Exception("Strange Column Index " + columnIndex + ", parse " + index); - } - } - - /// - /// get column name or Index from value specified by arguments - /// - /// - /// - /// - /// - /// - /// - private static int GetColumnIndex(this ScriptCommand command, DataTable table, string columnTypeName, string columnName, Engine.AutomationEngineInstance engine) - { - string columnType = command.GetUISelectionValue(columnTypeName, "Column Type", engine); - - int columnIndex = 0; - switch (columnType) - { - case "column name": - string targetColumnName = command.ConvertToUserVariable(columnName, "Column Name", engine); - columnIndex = GetColumnIndexFromName(table, targetColumnName, engine); - break; - - case "index": - string targetColumnIndex = command.ConvertToUserVariable(columnName, "Column Index", engine); - columnIndex = GetColumnIndex(table, targetColumnIndex, engine); - break; - } - return columnIndex; - } - - /// - /// get column index from name - /// - /// - /// - /// - /// - /// - private static int GetColumnIndexFromName(DataTable table, string columnName, Engine.AutomationEngineInstance engine) - { - string col = GetColumnName(table, columnName, engine); - for (int i = table.Columns.Count - 1; i >= 0; i--) - { - if (table.Columns[i].ColumnName == col) - { - return i; - } - } - throw new Exception("Strange Column Name " + columnName); - } - - /// - /// return DataTable with the column names of argument table copied - /// - /// - /// - public static DataTable CloneDataTableOnlyColumnName(DataTable table) - { - DataTable ret = new DataTable(); - int cols = table.Columns.Count; - for (int i = 0; i < cols; i++) - { - ret.Columns.Add(table.Columns[i].ColumnName); - } - - return ret; - } + ///// + ///// check column index exists + ///// + ///// + ///// + ///// + //private static bool IsColumnExists(DataTable table, int columnIndex) + //{ + // if (columnIndex >= 0) + // { + // return (columnIndex < table.Columns.Count); + // } + // else + // { + // int idx = table.Columns.Count + columnIndex; + // return ((idx >= 0) && (idx < table.Columns.Count)); + // } + //} + + ///// + ///// get DataTable column name from value specified by argument + ///// + ///// + ///// + ///// + ///// + ///// + //private static string GetColumnName(DataTable table, string columnName, Engine.AutomationEngineInstance engine) + //{ + // string col = columnName.ExpandValueOrUserVariable(engine); + // if (IsColumnExists(table, col)) + // { + // return col; + // } + // else + // { + // throw new Exception("Strange Column Name " + columnName); + // } + //} + + ///// + ///// get column index from value specified by argument + ///// + ///// + ///// + ///// + ///// + ///// + //private static int GetColumnIndex(DataTable table, string columnIndex, Engine.AutomationEngineInstance engine) + //{ + // int index = new PropertyConvertTag(columnIndex, "Column Index").ExpandValueOrUserVariableAsInteger(engine); + // if (index < 0) + // { + // index = table.Columns.Count + index; + // } + // if (IsColumnExists(table, index)) + // { + // return index; + // } + // else + // { + // throw new Exception("Strange Column Index " + columnIndex + ", parse " + index); + // } + //} + + ///// + ///// get column name or Index from value specified by arguments + ///// + ///// + ///// + ///// + ///// + ///// + ///// + //private static int GetColumnIndex(this ScriptCommand command, DataTable table, string columnTypeName, string columnName, Engine.AutomationEngineInstance engine) + //{ + // string columnType = command.ExpandValueOrUserVariableAsSelectionItem(columnTypeName, "Column Type", engine); + + // int columnIndex = 0; + // switch (columnType) + // { + // case "column name": + // string targetColumnName = command.ExpandValueOrUserVariable(columnName, "Column Name", engine); + // columnIndex = GetColumnIndexFromName(table, targetColumnName, engine); + // break; + + // case "index": + // string targetColumnIndex = command.ExpandValueOrUserVariable(columnName, "Column Index", engine); + // columnIndex = GetColumnIndex(table, targetColumnIndex, engine); + // break; + // } + // return columnIndex; + //} + + ///// + ///// get column index from name + ///// + ///// + ///// + ///// + ///// + ///// + //private static int GetColumnIndexFromName(DataTable table, string columnName, Engine.AutomationEngineInstance engine) + //{ + // string col = GetColumnName(table, columnName, engine); + // for (int i = table.Columns.Count - 1; i >= 0; i--) + // { + // if (table.Columns[i].ColumnName == col) + // { + // return i; + // } + // } + // throw new Exception("Strange Column Name " + columnName); + //} + + ///// + ///// get datatable row index + ///// + ///// + ///// + ///// + ///// + ///// + //private static int GetRowIndex(DataTable table, string rowIndex, Engine.AutomationEngineInstance engine) + //{ + // var index = rowIndex.ExpandValueOrUserVariableAsInteger("Row Index", engine); + + // if (index < 0) + // { + // index += table.Rows.Count; + // } + + // if ((index< 0) || (index >= table.Rows.Count)) + // { + // throw new Exception("Strange Row Index '" + index + "'"); + // } + + // return index; + //} + + ///// + ///// return DataTable with the column names of argument table copied + ///// + ///// + ///// + //public static DataTable CloneDataTableOnlyColumnName(DataTable table) + //{ + // DataTable ret = new DataTable(); + // int cols = table.Columns.Count; + // for (int i = 0; i < cols; i++) + // { + // ret.Columns.Add(table.Columns[i].ColumnName); + // } + + // return ret; + //} + + // todo: fix use case in GetFieldValue methods /// /// get DataTable Value, specify ParameterName, ParameterValue column name @@ -526,7 +569,7 @@ public static Dictionary GetFieldValues(DataTable dt, string par throw new Exception("Parameter Column or Value Column does not exists"); } - Dictionary dic = new Dictionary(); + var dic = new Dictionary(); foreach (DataRow row in dt.Rows) { var key = row.Field(parameterColumnName) ?? ""; @@ -541,7 +584,7 @@ public static Dictionary GetFieldValues(DataTable dt, string par var keys = dic.Keys.ToArray(); foreach (string key in keys) { - dic[key] = dic[key].ConvertToUserVariable(engine); + dic[key] = dic[key].ExpandValueOrUserVariable(engine); } } @@ -565,7 +608,7 @@ public static Dictionary GetFieldValues(DataTable dt, string par throw new Exception("Parameter Column or Value Column does not exists"); } - Dictionary dic = new Dictionary(); + var dic = new Dictionary(); foreach (DataRow row in dt.Rows) { var key = row.Field(parameterColumnName) ?? ""; @@ -584,7 +627,7 @@ public static Dictionary GetFieldValues(DataTable dt, string par var keys = dic.Keys.ToArray(); foreach (string key in keys) { - dic[key] = dic[key].ConvertToUserVariable(engine); + dic[key] = dic[key].ExpandValueOrUserVariable(engine); } } @@ -641,7 +684,7 @@ public static bool IsParameterNamesExists(DataTable dt, List parameterNa foreach (DataRow row in dt.Rows) { var key = row.Field(parameterNameColumn) ?? ""; - if (!parameterNameColumn.Contains(key)) + if (!parameterNames.Contains(key)) { return false; } @@ -744,6 +787,15 @@ public static void BeforeValidate(DataGridView dgv, DataTable table) table.AcceptChanges(); } } + + public static void BeforeValidate_NoRowAdding(DataGridView dgv, DataTable table) + { + if (dgv.IsCurrentCellDirty || dgv.IsCurrentRowDirty) + { + dgv.CommitEdit(DataGridViewDataErrorContexts.Commit);; + table.AcceptChanges(); + } + } #endregion } } diff --git a/taskt/Core/Automation/Commands/Database/DatabaseDefineConnectionCommand.cs b/taskt/Core/Automation/Commands/Database/DatabaseDefineConnectionCommand.cs index f25ffd576..a63101899 100644 --- a/taskt/Core/Automation/Commands/Database/DatabaseDefineConnectionCommand.cs +++ b/taskt/Core/Automation/Commands/Database/DatabaseDefineConnectionCommand.cs @@ -15,11 +15,12 @@ namespace taskt.Core.Automation.Commands [Serializable] - [Attributes.ClassAttributes.Group("Database Commands")] + [Attributes.ClassAttributes.Group("Database")] [Attributes.ClassAttributes.Description("This command allows you to define a connection to an OLEDB data source")] [Attributes.ClassAttributes.UsesDescription("Use this command to create a new connection to a database.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'OLEDB' to achieve automation.")] - public class DatabaseDefineConnectionCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_database))] + public sealed class DatabaseDefineConnectionCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Enter the instance name")] @@ -75,15 +76,14 @@ public DatabaseDefineConnectionCommand() this.v_TestConnection = "Yes"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //get engine and preference - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - var instance = v_InstanceName.ConvertToUserVariable(sender); - var testPreference = v_TestConnection.ConvertToUserVariable(sender); + var instance = v_InstanceName.ExpandValueOrUserVariable(engine); + var testPreference = v_TestConnection.ExpandValueOrUserVariable(engine); //create connection - var oleDBConnection = CreateConnection(sender); + var oleDBConnection = CreateConnection(engine); //attempt to open and close connection if (testPreference == "Yes") @@ -95,10 +95,10 @@ public override void RunCommand(object sender) engine.AddAppInstance(instance, oleDBConnection); } - private OleDbConnection CreateConnection(object sender) + private OleDbConnection CreateConnection(Engine.AutomationEngineInstance engine) { - var connection = v_ConnectionString.ConvertToUserVariable(sender); - var connectionPass = v_ConnectionStringPassword.ConvertToUserVariable(sender); + var connection = v_ConnectionString.ExpandValueOrUserVariable(engine); + var connectionPass = v_ConnectionStringPassword.ExpandValueOrUserVariable(engine); if (connectionPass.StartsWith("!")) { @@ -110,7 +110,7 @@ private OleDbConnection CreateConnection(object sender) return new OleDbConnection(connection); } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -194,7 +194,7 @@ public override List Render(frmCommandEditor editor) RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_TestConnection", this, editor)); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultDBInstanceName; } diff --git a/taskt/Core/Automation/Commands/Database/DatabaseExecuteQueryCommand.cs b/taskt/Core/Automation/Commands/Database/DatabaseExecuteQueryCommand.cs index 7f9326966..418f200d6 100644 --- a/taskt/Core/Automation/Commands/Database/DatabaseExecuteQueryCommand.cs +++ b/taskt/Core/Automation/Commands/Database/DatabaseExecuteQueryCommand.cs @@ -12,11 +12,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Database Commands")] + [Attributes.ClassAttributes.Group("Database")] [Attributes.ClassAttributes.Description("This command allows you to perform a database query and apply the result to a dataset")] [Attributes.ClassAttributes.UsesDescription("Use this command to select data from a database.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'OLEDB' to achieve automation.")] - public class DatabaseExecuteQueryCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_database))] + public sealed class DatabaseExecuteQueryCommand : ScriptCommand, ICanHandleDataTable, IHaveDataTableElements { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Enter the instance name")] @@ -90,16 +91,15 @@ public DatabaseExecuteQueryCommand() } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //create engine, instance, query - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - var vInstance = v_InstanceName.ConvertToUserVariable(engine); - var query = v_Query.ConvertToUserVariable(sender); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); + var query = v_Query.ExpandValueOrUserVariable(engine); //define connection var databaseConnection = (OleDbConnection)engine.GetAppInstance(vInstance); - var queryExecutionType = v_QueryType.ConvertToUserVariable(sender); + var queryExecutionType = v_QueryType.ExpandValueOrUserVariable(engine); //define commad var oleCommand = new System.Data.OleDb.OleDbCommand(query, databaseConnection); @@ -107,9 +107,9 @@ public override void RunCommand(object sender) //add parameters foreach (DataRow rw in this.v_QueryParameters.Rows) { - var parameterName = rw.Field("Parameter Name").ConvertToUserVariable(sender); - var parameterValue = rw.Field("Parameter Value").ConvertToUserVariable(sender); - var parameterType = rw.Field("Parameter Type").ConvertToUserVariable(sender); + var parameterName = rw.Field("Parameter Name").ExpandValueOrUserVariable(engine); + var parameterValue = rw.Field("Parameter Value").ExpandValueOrUserVariable(engine); + var parameterType = rw.Field("Parameter Type").ExpandValueOrUserVariable(engine); object convertedValue = null; //"STRING", "BOOLEAN", "DECIMAL", "INT16", "INT32", "INT64", "DATETIME", "DOUBLE", "SINGLE", "GUID", "BYTE", "BYTE[]" @@ -156,13 +156,10 @@ public override void RunCommand(object sender) } oleCommand.Parameters.AddWithValue(parameterName, convertedValue); - - } if (queryExecutionType == "Return Dataset") { - DataTable dataTable = new DataTable(); OleDbDataAdapter adapter = new OleDbDataAdapter(oleCommand); adapter.SelectCommand = oleCommand; @@ -170,12 +167,12 @@ public override void RunCommand(object sender) adapter.Fill(dataTable); databaseConnection.Close(); - dataTable.TableName = v_DatasetName; engine.DataTables.Add(dataTable); - engine.AddVariable(v_DatasetName, dataTable); - + //engine.AddVariable(v_DatasetName, dataTable); + //dataTable.StoreInUserVariable(engine, v_DatasetName); + this.StoreDataTableInUserVariable(dataTable, nameof(v_DatasetName), engine); } else if (queryExecutionType == "Execute NonQuery") { @@ -183,7 +180,8 @@ public override void RunCommand(object sender) var result = oleCommand.ExecuteNonQuery(); databaseConnection.Close(); - engine.AddVariable(v_DatasetName, result.ToString()); + //engine.AddVariable(v_DatasetName, result.ToString()); + result.StoreInUserVariable(engine, v_DatasetName); } else if(queryExecutionType == "Execute Stored Procedure") { @@ -191,15 +189,16 @@ public override void RunCommand(object sender) databaseConnection.Open(); var result = oleCommand.ExecuteNonQuery(); databaseConnection.Close(); - engine.AddVariable(v_DatasetName, result.ToString()); + //engine.AddVariable(v_DatasetName, result.ToString()); + result.StoreInUserVariable(engine, v_DatasetName); } else { throw new NotImplementedException($"Query Execution Type '{queryExecutionType}' not implemented."); } - } - public override List Render(frmCommandEditor editor) + + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -267,7 +266,7 @@ public override List Render(frmCommandEditor editor) RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_QueryType", this, editor)); RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_DatasetName", this, editor)); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultDBInstanceName; } diff --git a/taskt/Core/Automation/Commands/DateTime/ADateTimeConvertCommands.cs b/taskt/Core/Automation/Commands/DateTime/ADateTimeConvertCommands.cs new file mode 100644 index 000000000..5df916b3e --- /dev/null +++ b/taskt/Core/Automation/Commands/DateTime/ADateTimeConvertCommands.cs @@ -0,0 +1,21 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for DateTime value convert commands + /// + public abstract class ADateTimeConvertCommands : ScriptCommand, IDateTimeConvertProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_InputDateTime))] + [PropertyParameterOrder(5000)] + public virtual string v_DateTime { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(7000)] + public virtual string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DateTime/ADateTimeCreateCommands.cs b/taskt/Core/Automation/Commands/DateTime/ADateTimeCreateCommands.cs new file mode 100644 index 000000000..4c459101b --- /dev/null +++ b/taskt/Core/Automation/Commands/DateTime/ADateTimeCreateCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Create DateTime variable commands + /// + public abstract class ADateTimeCreateCommands : ScriptCommand, IDateTimeCreateProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_OutputDateTime))] + [PropertyParameterOrder(5000)] + public virtual string v_DateTime { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DateTime/CalculateDateTimeCommand.cs b/taskt/Core/Automation/Commands/DateTime/CalculateDateTimeCommand.cs index 9d747ae30..9ba7c6dca 100644 --- a/taskt/Core/Automation/Commands/DateTime/CalculateDateTimeCommand.cs +++ b/taskt/Core/Automation/Commands/DateTime/CalculateDateTimeCommand.cs @@ -5,19 +5,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DateTime Commands")] + [Attributes.ClassAttributes.Group("DateTime")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Calculate DateTime")] [Attributes.ClassAttributes.Description("This command allows you to Calculate DateTime. Add Day, Minute, etc.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Calculate DateTime. Add Day, Minute, etc.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CalculateDateTimeCommand : ScriptCommand + public sealed class CalculateDateTimeCommand : ADateTimeConvertCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_InputDateTime))] - public string v_DateTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_InputDateTime))] + //public string v_DateTime { get; set; } [XmlAttribute] [PropertyDescription("Calculation Method")] @@ -39,6 +40,7 @@ public class CalculateDateTimeCommand : ScriptCommand [PropertyUISelectionOption("Substract Seconds")] [PropertyValidationRule("Calculation Method", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Method")] + [PropertyParameterOrder(6000)] public string v_CalculationMethod { get; set; } [XmlAttribute] @@ -52,12 +54,13 @@ public class CalculateDateTimeCommand : ScriptCommand [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Value", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(6001)] public string v_Value { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] [PropertyInstanceType(PropertyInstanceType.InstanceType.DateTime, true)] - public string v_Result { get; set; } + public override string v_Result { get; set; } public CalculateDateTimeCommand() { @@ -67,16 +70,15 @@ public CalculateDateTimeCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - var myDT = v_DateTime.GetDateTimeVariable(engine); + //var myDT = v_DateTime.ExpandUserVariableAsDateTime(engine); + //var myDT = this.ExpandValueOrVariableAsDateTime(nameof(v_DateTime), engine); + var myDT = this.ExpandValueOrVariableAsDateTime(engine); - string meth = this.GetUISelectionValue(nameof(v_CalculationMethod), engine); + string meth = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_CalculationMethod), engine); - int value = this.ConvertToUserVariableAsInteger(nameof(v_Value), engine); + int value = this.ExpandValueOrUserVariableAsInteger(nameof(v_Value), engine); string[] method = meth.Split(' '); if (method[0] == "substract") @@ -106,7 +108,9 @@ public override void RunCommand(object sender) calcDT = myDT.AddSeconds(value); break; } - calcDT.StoreInUserVariable(engine, v_Result); + + //calcDT.StoreInUserVariable(engine, v_Result); + this.StoreDateTimeInUserVariable(calcDT, nameof(v_Result), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DateTime/ConvertDateTimeToExcelSerialCommand.cs b/taskt/Core/Automation/Commands/DateTime/ConvertDateTimeToExcelSerialCommand.cs index ed65777ef..3f93d2d7f 100644 --- a/taskt/Core/Automation/Commands/DateTime/ConvertDateTimeToExcelSerialCommand.cs +++ b/taskt/Core/Automation/Commands/DateTime/ConvertDateTimeToExcelSerialCommand.cs @@ -5,27 +5,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DateTime Commands")] + [Attributes.ClassAttributes.Group("DateTime")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Convert DateTime To Excel Serial")] [Attributes.ClassAttributes.Description("This command allows you to Convert DateTime To Excel Serial Value.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want Convert DateTime To Excel Serial Value.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDateTimeToExcelSerialCommand : ScriptCommand + public sealed class ConvertDateTimeToExcelSerialCommand : ADateTimeConvertCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_InputDateTime))] - public string v_DateTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_InputDateTime))] + //public string v_DateTime { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] [PropertyDescription("Variable Name to Store Excel Serial Value")] - [PropertyDetailSampleUsageBehavior(MultiAttributesBehavior.Overwrite)] - [PropertyDetailSampleUsage("**vSerial**", PropertyDetailSampleUsage.ValueType.VariableName)] - [PropertyDetailSampleUsage("**{{{vSerial}}}**", PropertyDetailSampleUsage.ValueType.VariableName)] - public string v_Serial { get; set; } + //[PropertyDetailSampleUsageBehavior(MultiAttributesBehavior.Overwrite)] + //[PropertyDetailSampleUsage("**vSerial**", PropertyDetailSampleUsage.ValueType.VariableName)] + //[PropertyDetailSampleUsage("**{{{vSerial}}}**", PropertyDetailSampleUsage.ValueType.VariableName)] + public override string v_Result { get; set; } public ConvertDateTimeToExcelSerialCommand() { @@ -35,15 +36,16 @@ public ConvertDateTimeToExcelSerialCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; + //DateTime myDT = v_DateTime.ExpandUserVariableAsDateTime(engine); + //var myDT = this.ExpandValueOrVariableAsDateTime(nameof(v_DateTime), engine); + var myDT = this.ExpandValueOrVariableAsDateTime(engine); - DateTime myDT = v_DateTime.GetDateTimeVariable(engine); + //double serial = myDT.ToOADate(); + //serial.ToString().StoreInUserVariable(engine, v_Serial); - double serial = myDT.ToOADate(); - serial.ToString().StoreInUserVariable(engine, v_Serial); + myDT.ToOADate().StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DateTime/CreateDateTimeCommand.cs b/taskt/Core/Automation/Commands/DateTime/CreateDateTimeCommand.cs index a33e7ef8c..4345e85bd 100644 --- a/taskt/Core/Automation/Commands/DateTime/CreateDateTimeCommand.cs +++ b/taskt/Core/Automation/Commands/DateTime/CreateDateTimeCommand.cs @@ -5,19 +5,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DateTime Commands")] + [Attributes.ClassAttributes.Group("DateTime")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Create DateTime")] [Attributes.ClassAttributes.Description("This command allows you to create DateTime.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create DateTime.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateDateTimeCommand : ScriptCommand + public sealed class CreateDateTimeCommand : ADateTimeCreateCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_OutputDateTime))] - public string v_DateTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_OutputDateTime))] + //public string v_DateTime { get; set; } [XmlAttribute] [PropertyDescription("Year to set")] @@ -26,11 +27,12 @@ public class CreateDateTimeCommand : ScriptCommand [PropertyDetailSampleUsage("**2000**", PropertyDetailSampleUsage.ValueType.Value, "Year")] [PropertyDetailSampleUsage("**{{{vYear}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Year")] [Remarks("")] - [PropertyIsOptional(true, "1")] + [PropertyIsOptional(true, "2000")] [PropertyShowSampleUsageInDescription(true)] [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Year", PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] [PropertyDisplayText(true, "Year")] + [PropertyParameterOrder(6000)] public string v_Year { get; set; } [XmlAttribute] @@ -46,6 +48,7 @@ public class CreateDateTimeCommand : ScriptCommand [PropertyValidationRule("Month", PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero | PropertyValidationRule.ValidationRuleFlags.NotBetween)] [PropertyValueRange(1, 12)] [PropertyDisplayText(true, "Month")] + [PropertyParameterOrder(6001)] public string v_Month { get; set; } [XmlAttribute] @@ -61,6 +64,7 @@ public class CreateDateTimeCommand : ScriptCommand [PropertyValidationRule("Day", PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero | PropertyValidationRule.ValidationRuleFlags.NotBetween)] [PropertyValueRange(1, 31)] [PropertyDisplayText(true, "Day")] + [PropertyParameterOrder(6002)] public string v_Day { get; set; } [XmlAttribute] @@ -76,6 +80,7 @@ public class CreateDateTimeCommand : ScriptCommand [PropertyValidationRule("Hour", PropertyValidationRule.ValidationRuleFlags.LessThanZero | PropertyValidationRule.ValidationRuleFlags.NotBetween)] [PropertyValueRange(0, 23)] [PropertyDisplayText(true, "Hour")] + [PropertyParameterOrder(6003)] public string v_Hour { get; set; } [XmlAttribute] @@ -91,6 +96,7 @@ public class CreateDateTimeCommand : ScriptCommand [PropertyValidationRule("Minute", PropertyValidationRule.ValidationRuleFlags.LessThanZero | PropertyValidationRule.ValidationRuleFlags.NotBetween)] [PropertyValueRange(0, 59)] [PropertyDisplayText(true, "Minute")] + [PropertyParameterOrder(6004)] public string v_Minute { get; set; } [XmlAttribute] @@ -106,6 +112,7 @@ public class CreateDateTimeCommand : ScriptCommand [PropertyValidationRule("Second", PropertyValidationRule.ValidationRuleFlags.LessThanZero | PropertyValidationRule.ValidationRuleFlags.NotBetween)] [PropertyValueRange(0, 59)] [PropertyDisplayText(true, "Second")] + [PropertyParameterOrder(6005)] public string v_Second { get; set; } public CreateDateTimeCommand() @@ -116,25 +123,30 @@ public CreateDateTimeCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - int year = this.ConvertToUserVariableAsInteger(nameof(v_Year), engine); + int year = this.ExpandValueOrUserVariableAsInteger(nameof(v_Year), engine); - int month = this.ConvertToUserVariableAsInteger(nameof(v_Month), engine); + int month = this.ExpandValueOrUserVariableAsInteger(nameof(v_Month), engine); - int day = this.ConvertToUserVariableAsInteger(nameof(v_Day), engine); + int day = this.ExpandValueOrUserVariableAsInteger(nameof(v_Day), engine); - int hour = this.ConvertToUserVariableAsInteger(nameof(v_Hour), engine); + int hour = this.ExpandValueOrUserVariableAsInteger(nameof(v_Hour), engine); - int minute = this.ConvertToUserVariableAsInteger(nameof(v_Minute), engine); + int minute = this.ExpandValueOrUserVariableAsInteger(nameof(v_Minute), engine); - int second = this.ConvertToUserVariableAsInteger(nameof(v_Second), engine); + int second = this.ExpandValueOrUserVariableAsInteger(nameof(v_Second), engine); - DateTime myDT = new DateTime(year, month, day, hour, minute, second); - myDT.StoreInUserVariable(engine, v_DateTime); + try + { + DateTime myDT = new DateTime(year, month, day, hour, minute, second); + //myDT.StoreInUserVariable(engine, v_DateTime); + this.StoreDateTimeInUserVariable(myDT, nameof(v_DateTime), engine); + } + catch + { + throw new Exception($"Specified DateTime is not DateTime. Year: '{year}', Month: '{month}', Day: '{day}', Hour: '{hour}', Minute: '{minute}', Second: '{second}'"); + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DateTime/CreateDateTimeFromExcelSerialCommand.cs b/taskt/Core/Automation/Commands/DateTime/CreateDateTimeFromExcelSerialCommand.cs index 0ccff1b15..d57f64343 100644 --- a/taskt/Core/Automation/Commands/DateTime/CreateDateTimeFromExcelSerialCommand.cs +++ b/taskt/Core/Automation/Commands/DateTime/CreateDateTimeFromExcelSerialCommand.cs @@ -5,19 +5,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DateTime Commands")] + [Attributes.ClassAttributes.Group("DateTime")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Create DateTime From Excel Serial")] [Attributes.ClassAttributes.Description("This command allows you to create DateTime from Excel Serial Value.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create DateTime from Excel Serial Value.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateDateTimeFromExcelSerialCommand : ScriptCommand + public sealed class CreateDateTimeFromExcelSerialCommand : ADateTimeCreateCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_OutputDateTime))] - public string v_DateTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_OutputDateTime))] + //public string v_DateTime { get; set; } [XmlAttribute] [PropertyDescription("Excel Serial Value")] @@ -30,6 +31,7 @@ public class CreateDateTimeFromExcelSerialCommand : ScriptCommand [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Serial", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Serial")] + [PropertyParameterOrder(6000)] public string v_Serial { get; set; } public CreateDateTimeFromExcelSerialCommand() @@ -40,21 +42,19 @@ public CreateDateTimeFromExcelSerialCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - decimal value = this.ConvertToUserVariableAsDecimal(nameof(v_Serial), engine); + var value = this.ExpandValueOrUserVariableAsDecimal(nameof(v_Serial), engine); try { DateTime myDT = DateTime.FromOADate((double)value); - myDT.StoreInUserVariable(engine, v_DateTime); + //myDT.StoreInUserVariable(engine, v_DateTime); + this.StoreDateTimeInUserVariable(myDT, nameof(v_DateTime), engine); } catch (Exception) { - throw new Exception("Serial '" + v_Serial + "' is not Excel Serial"); + throw new Exception($"Specified Serial Value is not Excel Serial. Value: '{v_Serial}', Expand Value: '{value}'"); } } } diff --git a/taskt/Core/Automation/Commands/DateTime/CreateDateTimeFromTextCommand.cs b/taskt/Core/Automation/Commands/DateTime/CreateDateTimeFromTextCommand.cs index d4cc1261c..c91b83b10 100644 --- a/taskt/Core/Automation/Commands/DateTime/CreateDateTimeFromTextCommand.cs +++ b/taskt/Core/Automation/Commands/DateTime/CreateDateTimeFromTextCommand.cs @@ -5,19 +5,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DateTime Commands")] + [Attributes.ClassAttributes.Group("DateTime")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Create DateTime From Text")] [Attributes.ClassAttributes.Description("This command allows you to create DateTime from Text.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create DateTime from Text.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateDateTimeFromTextCommand : ScriptCommand + public sealed class CreateDateTimeFromTextCommand : ADateTimeCreateCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_OutputDateTime))] - public string v_DateTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_OutputDateTime))] + //public string v_DateTime { get; set; } [XmlAttribute] [PropertyDescription("Text Value")] @@ -30,6 +31,7 @@ public class CreateDateTimeFromTextCommand : ScriptCommand [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Text", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Text")] + [PropertyParameterOrder(6000)] public string v_Text { get; set; } public CreateDateTimeFromTextCommand() @@ -40,20 +42,18 @@ public CreateDateTimeFromTextCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - string value = v_Text.ConvertToUserVariable(engine); + var value = v_Text.ExpandValueOrUserVariable(engine); - if (DateTime.TryParse(value, out DateTime tryDT)) + if (DateTime.TryParse(value, out DateTime myDT)) { - tryDT.StoreInUserVariable(engine, v_DateTime); + //tryDT.StoreInUserVariable(engine, v_DateTime); + this.StoreDateTimeInUserVariable(myDT, nameof(v_DateTime), engine); } else { - throw new Exception("Text '" + v_Text + "' is not DateTime"); + throw new Exception($"Specified Text is not DateTime. Value: '{v_Text}', Expand Value: '{value}'"); } } } diff --git a/taskt/Core/Automation/Commands/DateTime/EM_CanHandleDateTimExtensionMethods.cs b/taskt/Core/Automation/Commands/DateTime/EM_CanHandleDateTimExtensionMethods.cs new file mode 100644 index 000000000..745e2c3a6 --- /dev/null +++ b/taskt/Core/Automation/Commands/DateTime/EM_CanHandleDateTimExtensionMethods.cs @@ -0,0 +1,93 @@ +using System; +using taskt.Core.Automation.Engine; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_CanHandleDateTimExtensionMethods + { + /// + /// Check object is DateTime + /// + /// + /// + /// + public static bool IsDateTime(object value, out DateTime date) + { + // TODO: it's ok? + date = default; + if (value is DateTime dt) + { + date = dt; + return true; + } + else + { + return false; + } + } + + /// + /// Expand User Variable As DateTime + /// + /// + /// + /// + /// + public static DateTime ExpandValueOrVariableAsDateTime(ScriptVariable variable) + { + // TODO: it's ok? + if (IsDateTime(variable.VariableValue, out DateTime time)) + { + return time; + } + else + { + throw new Exception($"Variable '{variable.VariableName}' is not DateTime"); + } + } + + /// + /// expand value or variable as DateTime + /// + /// + /// + /// + /// + /// + public static DateTime ExpandValueOrVariableAsDateTime(this ICanHandleDateTime command, string paramterName, AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(paramterName, "DateTime"); + //var v = variableName.GetRawVariable(engine); + //if (v.VariableValue is DateTime time) + //{ + // return time; + //} + //else + //{ + // throw new Exception($"Variable '{variableName}' is not DateTime"); + //} + try + { + return ExpandValueOrVariableAsDateTime(variableName.GetRawVariable(engine)); + } + catch + { + throw new Exception($"Variable '{variableName}' is not DateTime"); + } + } + + /// + /// store DateTime in User Variable + /// + /// + /// + /// + /// + public static void StoreDateTimeInUserVariable(this ICanHandleDateTime command, DateTime c, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "DateTime Variable"); + ExtensionMethods.StoreInUserVariable(variableName, c, engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/DateTime/EM_DateTimeConvertPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/DateTime/EM_DateTimeConvertPropertiesExtensionMethods.cs new file mode 100644 index 000000000..674197522 --- /dev/null +++ b/taskt/Core/Automation/Commands/DateTime/EM_DateTimeConvertPropertiesExtensionMethods.cs @@ -0,0 +1,20 @@ +using System; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DateTimeConvertPropertiesExtensionMethods + { + /// + /// expand value or variable as DateTime + /// + /// + /// + /// + /// + public static DateTime ExpandValueOrVariableAsDateTime(this IDateTimeConvertProperties command, AutomationEngineInstance engine) + { + return command.ExpandValueOrVariableAsDateTime(nameof(command.v_DateTime), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/DateTime/FormatDateTimeCommand.cs b/taskt/Core/Automation/Commands/DateTime/FormatDateTimeCommand.cs index 48323c241..61ba39f9b 100644 --- a/taskt/Core/Automation/Commands/DateTime/FormatDateTimeCommand.cs +++ b/taskt/Core/Automation/Commands/DateTime/FormatDateTimeCommand.cs @@ -7,19 +7,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DateTime Commands")] + [Attributes.ClassAttributes.Group("DateTime")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Format DateTime")] [Attributes.ClassAttributes.Description("This command allows you to Format DateTime Text.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Format DateTime Text.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class FormatDateTimeCommand : ScriptCommand + public sealed class FormatDateTimeCommand : ADateTimeConvertCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_InputDateTime))] - public string v_DateTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_InputDateTime))] + //public string v_DateTime { get; set; } [XmlAttribute] [PropertyDescription("DateTime Format")] @@ -34,11 +35,12 @@ public class FormatDateTimeCommand : ScriptCommand [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Format", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Format")] + [PropertyParameterOrder(6000)] public string v_Format { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_Result { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + //public string v_Result { get; set; } public FormatDateTimeCommand() { @@ -48,13 +50,12 @@ public FormatDateTimeCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - var myDT = v_DateTime.GetDateTimeVariable(engine); - string format = v_Format.ConvertToUserVariable(engine); + //var myDT = v_DateTime.ExpandUserVariableAsDateTime(engine); + var myDT = this.ExpandValueOrVariableAsDateTime(engine); + + string format = v_Format.ExpandValueOrUserVariable(engine); myDT.ToString(format).StoreInUserVariable(engine, v_Result); } @@ -62,7 +63,7 @@ public override void RunCommand(object sender) private void lnkFormatChecker_Click(object sender, EventArgs e) { TextBox txt = (TextBox)((CommandItemControl)sender).Tag; - UI.Forms.Supplement_Forms.frmFormatChecker.ShowFormatCheckerFormLinkClicked(txt, "DateTime"); + UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmFormatChecker.ShowFormatCheckerFormLinkClicked(txt, "DateTime"); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/DateTime/GetDateTimeDifferencesCommand.cs b/taskt/Core/Automation/Commands/DateTime/GetDateTimeDifferencesCommand.cs index d3013e9fe..0f63602af 100644 --- a/taskt/Core/Automation/Commands/DateTime/GetDateTimeDifferencesCommand.cs +++ b/taskt/Core/Automation/Commands/DateTime/GetDateTimeDifferencesCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("DateTime Commands")] + [Attributes.ClassAttributes.Group("DateTime")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Get DateTime Differences")] [Attributes.ClassAttributes.Description("This command allows you to Get 2 DateTime Differences.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get 2 DateTime Differences.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetDateTimeDifferencesCommand : ScriptCommand + public sealed class GetDateTimeDifferencesCommand : ScriptCommand, ICanHandleDateTime { [XmlAttribute] [PropertyVirtualProperty(nameof(DateTimeControls), nameof(DateTimeControls.v_InputDateTime))] @@ -62,15 +63,14 @@ public GetDateTimeDifferencesCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; + //var myDT1 = v_DateTime1.ExpandUserVariableAsDateTime(engine); + //var myDT2 = v_DateTime2.ExpandUserVariableAsDateTime(engine); + var myDT1 = this.ExpandValueOrVariableAsDateTime(nameof(v_DateTime1), engine); + var myDT2 = this.ExpandValueOrVariableAsDateTime(nameof(v_DateTime2), engine); - var myDT1 = v_DateTime1.GetDateTimeVariable(engine); - var myDT2 = v_DateTime2.GetDateTimeVariable(engine); - - string format = this.GetUISelectionValue(nameof(v_Format), engine); + string format = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_Format), engine); TimeSpan diff = myDT2 - myDT1; @@ -106,16 +106,21 @@ public override void RunCommand(object sender) break; case "datetime": // return here + DateTime res; if (diff.Ticks >= 0) { - new DateTime(0).Add(diff).StoreInUserVariable(engine, v_Result); + //new DateTime(0).Add(diff).StoreInUserVariable(engine, v_Result); + res = new DateTime(0).Add(diff); } else { - new DateTime(0).Subtract(diff).StoreInUserVariable(engine, v_Result); + //new DateTime(0).Subtract(diff).StoreInUserVariable(engine, v_Result); + res = new DateTime(0).Subtract(diff); } + this.StoreDateTimeInUserVariable(res, nameof(v_Result), engine); return; } + result.StoreInUserVariable(engine, v_Result); } diff --git a/taskt/Core/Automation/Commands/DateTime/ICanHandleDateTime.cs b/taskt/Core/Automation/Commands/DateTime/ICanHandleDateTime.cs new file mode 100644 index 000000000..6ada700f5 --- /dev/null +++ b/taskt/Core/Automation/Commands/DateTime/ICanHandleDateTime.cs @@ -0,0 +1,9 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for DateTime commands + /// + public interface ICanHandleDateTime : ILExpandableProperties + { + } +} diff --git a/taskt/Core/Automation/Commands/DateTime/IDateTimeConvertProperties.cs b/taskt/Core/Automation/Commands/DateTime/IDateTimeConvertProperties.cs new file mode 100644 index 000000000..30200e6e8 --- /dev/null +++ b/taskt/Core/Automation/Commands/DateTime/IDateTimeConvertProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// DateTime convert properties + /// + public interface IDateTimeConvertProperties : ICanHandleDateTime + { + /// + /// DateTime variable name + /// + string v_DateTime { get; set; } + + /// + /// Variable Name to Store Result + /// + string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DateTime/IDateTimeCreateProperties.cs b/taskt/Core/Automation/Commands/DateTime/IDateTimeCreateProperties.cs new file mode 100644 index 000000000..b4601a918 --- /dev/null +++ b/taskt/Core/Automation/Commands/DateTime/IDateTimeCreateProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// DateTime create properties + /// + public interface IDateTimeCreateProperties : ICanHandleDateTime + { + /// + /// DateTime variable name + /// + string v_DateTime { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/DateTimeControls.cs b/taskt/Core/Automation/Commands/DateTimeControls.cs index 39562f3a4..5fd2c63ae 100644 --- a/taskt/Core/Automation/Commands/DateTimeControls.cs +++ b/taskt/Core/Automation/Commands/DateTimeControls.cs @@ -21,6 +21,7 @@ internal static class DateTimeControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("DateTime Variable", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Variable")] + [PropertyParameterOrder(5000)] public static string v_InputDateTime { get; } /// @@ -38,39 +39,45 @@ internal static class DateTimeControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("DateTime Variable", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Variable")] + [PropertyParameterOrder(5000)] public static string v_OutputDateTime { get; } - /// - /// Get DateTime variable from Variable Name. - /// - /// - /// - /// - /// Variable not DateTime - public static DateTime GetDateTimeVariable(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) - { - Script.ScriptVariable v = variableName.GetRawVariable(engine); - if (v.VariableValue is DateTime time) - { - return time; - } - else - { - throw new Exception("Variable " + variableName + " is not DateTime"); - } - } + ///// + ///// Expand user variable As DateTime + ///// + ///// + ///// + ///// + ///// Value is not DateTime + //public static DateTime ExpandUserVariableAsDateTime(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) + //{ + // Script.ScriptVariable v = variableName.GetRawVariable(engine); + // if (v.VariableValue is DateTime time) + // { + // return time; + // } + // else + // { + // throw new Exception("Variable " + variableName + " is not DateTime"); + // } + //} + + //public static void StoreInUserVariable(this DateTime value, Core.Automation.Engine.AutomationEngineInstance engine, string targetVariable) + //{ + // ExtensionMethods.StoreInUserVariable(targetVariable, value, engine, false); + //} /// - /// expand user variable as DateTime + /// Convert value to DateTime /// /// /// /// /// - /// - public static DateTime ConvertToUserVariableAsDateTime(this string str, string parameterName, object sender) - { - string convertedText = str.ConvertToUserVariable(sender); + /// fail convert value to DateTime + public static DateTime ConvertValueToDateTime(this string str, string parameterName, Core.Automation.Engine.AutomationEngineInstance engine) + { + string convertedText = str.ExpandValueOrUserVariable(engine); if (DateTime.TryParse(convertedText, out DateTime v)) { return v; @@ -80,10 +87,5 @@ public static DateTime ConvertToUserVariableAsDateTime(this string str, string p throw new Exception(parameterName + " '" + str + "' is not a DateTime."); } } - - public static void StoreInUserVariable(this DateTime value, Core.Automation.Engine.AutomationEngineInstance sender, string targetVariable) - { - ExtensionMethods.StoreInUserVariable(targetVariable, value, sender, false); - } } } diff --git a/taskt/Core/Automation/Commands/DialogMessage/ShowFileDialogCommand.cs b/taskt/Core/Automation/Commands/DialogMessage/ShowFileDialogCommand.cs index 36852e088..f1d69340f 100644 --- a/taskt/Core/Automation/Commands/DialogMessage/ShowFileDialogCommand.cs +++ b/taskt/Core/Automation/Commands/DialogMessage/ShowFileDialogCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dialog/Message Commands")] + [Attributes.ClassAttributes.Group("Dialog/Message")] [Attributes.ClassAttributes.CommandSettings("Show File Dialog")] [Attributes.ClassAttributes.Description("Show OpenFileDialog or SaveFileDialog")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to select file to save or open.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_input))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ShowFileDialogCommand : ScriptCommand + public sealed class ShowFileDialogCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -77,17 +78,15 @@ public ShowFileDialogCommand() //this.v_InitialDirectory = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var filter = v_Filter.ConvertToUserVariable(engine); + var filter = v_Filter.ExpandValueOrUserVariable(engine); if (!checkFileterProperty(filter)) { throw new Exception("Strange Filter Property. Value: '" + filter + "'"); } - var index = this.ConvertToUserVariableAsInteger(nameof(v_FilterIndex), engine); + var index = this.ExpandValueOrUserVariableAsInteger(nameof(v_FilterIndex), engine); if (index < 1) { throw new Exception("Strange FilterIndex Property: Value: " + index); @@ -100,11 +99,11 @@ public override void RunCommand(object sender) } else { - directory = this.ConvertToUserVariableAsFolderPath(nameof(v_InitialDirectory), engine); + directory = this.ExpandValueOrUserVariableAsFolderPath(nameof(v_InitialDirectory), engine); } Type tp = null; - switch (this.GetUISelectionValue(nameof(v_DialogType), engine)) + switch (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_DialogType), engine)) { case "open": //engine.tasktEngineUI.Invoke(new Action(() => diff --git a/taskt/Core/Automation/Commands/DialogMessage/ShowFolderDialogCommand.cs b/taskt/Core/Automation/Commands/DialogMessage/ShowFolderDialogCommand.cs index 1bce601ad..25430d7ef 100644 --- a/taskt/Core/Automation/Commands/DialogMessage/ShowFolderDialogCommand.cs +++ b/taskt/Core/Automation/Commands/DialogMessage/ShowFolderDialogCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dialog/Message Commands")] + [Attributes.ClassAttributes.Group("Dialog/Message")] [Attributes.ClassAttributes.CommandSettings("Show Folder Dialog")] [Attributes.ClassAttributes.Description("Show FolderBrowserDialog")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to select folder.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_input))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ShowFolderDialogCommand : ScriptCommand + public sealed class ShowFolderDialogCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] @@ -27,10 +28,8 @@ public ShowFolderDialogCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //object result = null; //engine.tasktEngineUI.Invoke(new Action(() => // { diff --git a/taskt/Core/Automation/Commands/DialogMessage/ShowHTMLInputDialogCommand.cs b/taskt/Core/Automation/Commands/DialogMessage/ShowHTMLInputDialogCommand.cs index c2463d7df..e23b31707 100644 --- a/taskt/Core/Automation/Commands/DialogMessage/ShowHTMLInputDialogCommand.cs +++ b/taskt/Core/Automation/Commands/DialogMessage/ShowHTMLInputDialogCommand.cs @@ -1,19 +1,22 @@ using System; +using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dialog/Message Commands")] + [Attributes.ClassAttributes.Group("Dialog/Message")] [Attributes.ClassAttributes.CommandSettings("Show HTML Input Dialog")] [Attributes.ClassAttributes.Description("Allows the entry of data into a web-enabled form")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want a fancy data collection.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'WebBrowser Control' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_input))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ShowHTMLInputDialogCommand : ScriptCommand + public sealed class ShowHTMLInputDialogCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_MultiLinesTextBox))] @@ -36,45 +39,47 @@ public class ShowHTMLInputDialogCommand : ScriptCommand
-
Directions: This a sample data collection form that can be presented to a user. You can add and implement as many fields as you need or choose standard form inputs. Note, each field will require a v_applyToVariable attribute specifying which variable should contain the respective value for the input field.
- +

Directions

+

This a sample data collection form that can be presented to a user. You can add and implement as many fields as you need or choose standard form inputs. Note, each field will require a data-variable or v_applyToVariable attribute specifying which variable should contain the respective value for the input field.
+DO NOT USE form tags to enclose the element. The variable information will not be retrieved correctly.

+

The OK button should call chrome.webview.hostObjects.fm.OK(); with onclick attribute, etc.
+Similarly, The Cancel button should call chrome.webview.hostObjects.fm.Cancel(); with onclick attribute, etc.


-
- +
- +
- +
- +
- +
- +
- +
- + @@ -82,7 +87,7 @@ Check me out
- @@ -90,9 +95,12 @@ Check me out
-


-

- +
+

Free input area

+ +
+


+

")] @@ -114,10 +122,8 @@ public ShowHTMLInputDialogCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - if (engine.tasktEngineUI == null) { engine.ReportProgress("HTML UserInput Supported With UI Only"); @@ -127,40 +133,70 @@ public override void RunCommand(object sender) //invoke ui for data collection var result = engine.tasktEngineUI.Invoke(new Action(() => - { - //sample for temp testing - var htmlInput = v_InputHTML.ConvertToUserVariable(sender); + { + //sample for temp testing + var htmlInput = v_InputHTML.ExpandValueOrUserVariable(engine); + + var errorOnClose = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ErrorOnClose), engine); - var errorOnClose = this.GetUISelectionValue(nameof(v_ErrorOnClose), engine); + var variables = engine.tasktEngineUI.ShowHTMLInput(htmlInput); - var variables = engine.tasktEngineUI.ShowHTMLInput(htmlInput); + //if user selected Ok then process variables + //null result means user cancelled/closed + if (variables != null) + { + ////store each one into context + //foreach (var variable in variables) + //{ + // variable.VariableValue.ToString().StoreInUserVariable(engine, variable.VariableName); + //} - //if user selected Ok then process variables - //null result means user cancelled/closed - if (variables != null) + Action newVariableAction; + if (engine.engineSettings.CreateMissingVariablesDuringExecution) { - //store each one into context - foreach (var variable in variables) + newVariableAction = new Action((v) => { - variable.VariableValue.ToString().StoreInUserVariable(sender, variable.VariableName); - } + engine.VariableList.Add(v); + }); } - else if (errorOnClose == "Error On Close") + else { - throw new Exception("Input Form was closed by the user"); + newVariableAction = new Action((v) => { + // nothing + }); } + + foreach(var v in variables) + { + var existsVar = engine.VariableList.FirstOrDefault(t => v.VariableName == t.VariableName); + if (existsVar != null) + { + existsVar.VariableValue = v.VariableValue; + } + else + { + newVariableAction(v); + } + } + + // DBG + //var x = engine.VariableList; + } + else if (errorOnClose == "Error On Close") + { + throw new Exception("Input Form was closed by the user"); } - )); + })); } private void ShowHTMLBuilder(object sender, EventArgs e) { - using (var htmlForm = new UI.Forms.Supplemental.frmHTMLBuilder()) + using (var htmlForm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmHTMLBuilder()) { var htmlInput = (TextBox)ControlsList[nameof(v_InputHTML)]; htmlForm.rtbHTML.Text = htmlInput.Text; - if (htmlForm.ShowDialog() == DialogResult.OK) + if (htmlForm.ShowDialog(((Control)sender).FindForm()) == DialogResult.OK) { htmlInput.Text = htmlForm.rtbHTML.Text; } diff --git a/taskt/Core/Automation/Commands/DialogMessage/ShowMessageCommand.cs b/taskt/Core/Automation/Commands/DialogMessage/ShowMessageCommand.cs index 77feb13c5..c386e5642 100644 --- a/taskt/Core/Automation/Commands/DialogMessage/ShowMessageCommand.cs +++ b/taskt/Core/Automation/Commands/DialogMessage/ShowMessageCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dialog/Message Commands")] + [Attributes.ClassAttributes.Group("Dialog/Message")] [Attributes.ClassAttributes.CommandSettings("Show Message")] [Attributes.ClassAttributes.Description("This command allows you to show a message to the user.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to present or display a value on screen to the user.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'MessageBox' and invokes VariableCommand to find variable data.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_input))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ShowMessageCommand : ScriptCommand + public sealed class ShowMessageCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_MultiLinesTextBox))] @@ -40,6 +41,27 @@ public class ShowMessageCommand : ScriptCommand [PropertyDisplayText(false, "")] public string v_AutoCloseAfter { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Font Name")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage("**MS Gothic**", "Specify MS Gothic")] + [PropertyIsOptional(true)] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + public string v_FontName { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Font Size")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage("**12**", PropertyDetailSampleUsage.ValueType.Value, "Font Size")] + [PropertyDetailSampleUsage("**{{{vFont}}}**", PropertyDetailSampleUsage.ValueType.VariableName, "Font Size")] + [PropertyIsOptional(true)] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + public string v_FontSize { get; set; } + public ShowMessageCommand() { //this.CommandName = "MessageBoxCommand"; @@ -49,10 +71,9 @@ public ShowMessageCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - string variableMessage = v_Message.ConvertToUserVariable(engine); + string variableMessage = v_Message.ExpandValueOrUserVariable(engine); variableMessage = variableMessage.Replace("\\n", Environment.NewLine); @@ -63,7 +84,7 @@ public override void RunCommand(object sender) return; } - var closeAfter = this.ConvertToUserVariableAsInteger(nameof(v_AutoCloseAfter), engine); + var closeAfter = this.ExpandValueOrUserVariableAsInteger(nameof(v_AutoCloseAfter), engine); //automatically close messageboxes for server requests if (engine.serverExecution && closeAfter <= 0) @@ -71,10 +92,21 @@ public override void RunCommand(object sender) closeAfter = 10; } + string fontName = ""; + if (!string.IsNullOrEmpty(v_FontName)) + { + fontName = this.ExpandValueOrUserVariable(nameof(v_FontName), "Font Name", engine); + } + float fontSize = 0F; + if (!string.IsNullOrEmpty(v_FontSize)) + { + fontSize = (float)this.ExpandValueOrUserVariableAsDecimal(nameof(v_FontSize), engine); + } + // TODO: support OK/cancel etc buttons var result = engine.tasktEngineUI.Invoke(new Action(() => { - engine.tasktEngineUI.ShowMessage(variableMessage, "MessageBox Command", UI.Forms.Supplemental.frmDialog.DialogType.OkOnly, closeAfter); + engine.tasktEngineUI.ShowMessage(variableMessage, "MessageBox Command", UI.Forms.General.frmDialog.DialogType.OkOnly, closeAfter, true, fontName, fontSize); } )); } diff --git a/taskt/Core/Automation/Commands/DialogMessage/ShowUserInputDialogCommand.cs b/taskt/Core/Automation/Commands/DialogMessage/ShowUserInputDialogCommand.cs index 5b93ad65e..dfef68110 100644 --- a/taskt/Core/Automation/Commands/DialogMessage/ShowUserInputDialogCommand.cs +++ b/taskt/Core/Automation/Commands/DialogMessage/ShowUserInputDialogCommand.cs @@ -8,14 +8,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dialog/Message Commands")] + [Attributes.ClassAttributes.Group("Dialog/Message")] [Attributes.ClassAttributes.CommandSettings("Show User Input Dialog")] [Attributes.ClassAttributes.Description("Sends keystrokes to a targeted window")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to send keystroke inputs to a window.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Windows.Forms.SendKeys' method to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_input))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ShowUserInputDialogCommand : ScriptCommand + public sealed class ShowUserInputDialogCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -64,10 +65,8 @@ public ShowUserInputDialogCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - if (engine.tasktEngineUI == null) { engine.ReportProgress("UserInput Supported With UI Only"); @@ -76,17 +75,18 @@ public override void RunCommand(object sender) } //create clone of original - var clonedCommand = Common.Clone(this); + //var clonedCommand = Common.Clone(this); + var clonedCommand = (ShowUserInputDialogCommand)this.Clone(); //translate variable - clonedCommand.v_InputHeader = clonedCommand.v_InputHeader.ConvertToUserVariable(engine); - clonedCommand.v_InputDirections = clonedCommand.v_InputDirections.ConvertToUserVariable(engine); + clonedCommand.v_InputHeader = clonedCommand.v_InputHeader.ExpandValueOrUserVariable(engine); + clonedCommand.v_InputDirections = clonedCommand.v_InputDirections.ExpandValueOrUserVariable(engine); //translate variables for each label foreach (DataRow rw in clonedCommand.v_UserInputConfig.Rows) { //rw["DefaultValue"] = rw["DefaultValue"].ToString().ConvertToUserVariable(engine); - rw["DefaultValue"] = (rw.Field("DefaultValue") ?? "").ConvertToUserVariable(engine); + rw["DefaultValue"] = (rw.Field("DefaultValue") ?? "").ExpandValueOrUserVariable(engine); var targetVariable = rw["ApplyToVariable"] as string; @@ -134,7 +134,7 @@ private void lnkAddInputParameter_Click(object sender, EventArgs e) v_UserInputConfig.Rows.Add(newRow); } - public override bool IsValidate(frmCommandEditor editor) + public override bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.IsValidate(editor); @@ -142,12 +142,12 @@ public override bool IsValidate(frmCommandEditor editor) { var row = v_UserInputConfig.Rows[i]; - if (String.IsNullOrEmpty(row.Field("Type"))) + if (string.IsNullOrEmpty(row.Field("Type"))) { this.validationResult += "Input Type #" + (i + 1) + " is empty.\n"; this.IsValid = false; } - if (String.IsNullOrEmpty(row.Field("Size"))) + if (string.IsNullOrEmpty(row.Field("Size"))) { this.validationResult += "Input Size #" + (i + 1) + " is empty.\n"; this.IsValid = false; @@ -156,5 +156,11 @@ public override bool IsValidate(frmCommandEditor editor) return this.IsValid; } + + public override void BeforeValidate() + { + base.BeforeValidate(); + DataTableControls.BeforeValidate_NoRowAdding((DataGridView)ControlsList[nameof(v_UserInputConfig)], v_UserInputConfig); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/ADictionaryAddCreateCommands.cs b/taskt/Core/Automation/Commands/Dictionary/ADictionaryAddCreateCommands.cs new file mode 100644 index 000000000..8909e88ef --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/ADictionaryAddCreateCommands.cs @@ -0,0 +1,55 @@ +using System; +using System.Data; +using System.Collections.Generic; +using System.Windows.Forms; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Add Dictionary Items or Create Dictionary commands + /// + public abstract class ADictionaryAddCreateCommands : ADictionaryInputDictionaryCommands, IDictionaryAddCreateProperties + { + [XmlElement] + [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_KeyAndValue))] + [PropertyParameterOrder(6000)] + public virtual DataTable v_ColumnNameDataTable { get; set; } + + public override void BeforeValidate() + { + base.BeforeValidate(); + DataTableControls.BeforeValidate((DataGridView)ControlsList[nameof(v_ColumnNameDataTable)], v_ColumnNameDataTable); + } + + /// + /// Add new item to Dictionary from DataTable. check key name is empty + /// + /// + /// + /// + public void AddDataAndValueFromDataTable(Dictionary dic, Engine.AutomationEngineInstance engine) + { + // Check Items + int rows = 0; + foreach (DataRow row in v_ColumnNameDataTable.Rows) + { + rows++; + var k = (row.Field("Keys") ?? "").ExpandValueOrUserVariable(engine); + if (k == "") + { + throw new Exception($"Key name is empty. Row: {rows}"); + } + } + + // Add Items + foreach (DataRow row in v_ColumnNameDataTable.Rows) + { + var key = row.Field("Keys").ExpandValueOrUserVariable(engine); + var value = (row.Field("Values") ?? "").ExpandValueOrUserVariable(engine); + dic.Add(key, value); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/ADictionaryCreateFromDictionaryCommands.cs b/taskt/Core/Automation/Commands/Dictionary/ADictionaryCreateFromDictionaryCommands.cs new file mode 100644 index 000000000..e9b6b4934 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/ADictionaryCreateFromDictionaryCommands.cs @@ -0,0 +1,21 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Create Dictionary From Dictionary commands + /// + public abstract class ADictionaryCreateFromDictionaryCommands : ScriptCommand, ILDictionaryCreateFromDictionary + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + [PropertyParameterOrder(5000)] + public abstract string v_TargetDictionary { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_NewOutputDictionaryName))] + [PropertyParameterOrder(10000)] + public virtual string v_NewDictionary { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/ADictionaryGetFromDictionaryCommands.cs b/taskt/Core/Automation/Commands/Dictionary/ADictionaryGetFromDictionaryCommands.cs new file mode 100644 index 000000000..56690958f --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/ADictionaryGetFromDictionaryCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Get from Dictionary, or Dictionary convert to something commands + /// + public abstract class ADictionaryGetFromDictionaryCommands : ADictionaryInputDictionaryCommands, IDictionaryGetFromDictionaryProperties + { + [XmlAttribute] + [PropertyParameterOrder(7000)] + public abstract string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/ADictionaryInputDictionaryCommands.cs b/taskt/Core/Automation/Commands/Dictionary/ADictionaryInputDictionaryCommands.cs new file mode 100644 index 000000000..16bc2bf42 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/ADictionaryInputDictionaryCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Input Dictionary commands + /// + public abstract class ADictionaryInputDictionaryCommands : ScriptCommand, ILDictionaryProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + [PropertyParameterOrder(5000)] + public virtual string v_Dictionary { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/ADictionaryKeyActionCommands.cs b/taskt/Core/Automation/Commands/Dictionary/ADictionaryKeyActionCommands.cs new file mode 100644 index 000000000..d6d6af763 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/ADictionaryKeyActionCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Dictionary Key Action commands + /// + public abstract class ADictionaryKeyActionCommands : ADictionaryKeyCommands, IDictionaryKeyActionProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_WhenKeyDoesNotExists))] + [PropertyParameterOrder(10000)] + public virtual string v_WhenKeyDoesNotExists { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/ADictionaryKeyCommands.cs b/taskt/Core/Automation/Commands/Dictionary/ADictionaryKeyCommands.cs new file mode 100644 index 000000000..dc8eb7486 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/ADictionaryKeyCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Dictionary key commands + /// + public abstract class ADictionaryKeyCommands : ADictionaryInputDictionaryCommands, IDictionaryKeyProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Key))] + [PropertyParameterOrder(6000)] + public virtual string v_Key { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/AddDictionaryCommand.cs b/taskt/Core/Automation/Commands/Dictionary/AddDictionaryCommand.cs deleted file mode 100644 index cc7d70ea0..000000000 --- a/taskt/Core/Automation/Commands/Dictionary/AddDictionaryCommand.cs +++ /dev/null @@ -1,52 +0,0 @@ -using System; -using System.Xml.Serialization; -using System.Data; -using System.Collections.Generic; -using System.Windows.Forms; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] - [Attributes.ClassAttributes.SubGruop("Dictionary Item")] - [Attributes.ClassAttributes.CommandSettings("Add Dictionary Item")] - [Attributes.ClassAttributes.Description("This command Adds a key and value to a existing Dictionary")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add to a dictionary")] - [Attributes.ClassAttributes.ImplementationDescription("")] - [Attributes.ClassAttributes.EnableAutomateRender(true)] - [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class AddDictionaryItemCommand : ScriptCommand - { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_BothDictionaryName))] - public string v_DictionaryName { get; set; } - - [XmlElement] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_KeyAndValue))] - public DataTable v_ColumnNameDataTable { get; set; } - - public AddDictionaryItemCommand() - { - //this.CommandName = "AddDictionaryItemCommand"; - //this.SelectionName = "Add Dictionary Item"; - //this.CommandEnabled = true; - //this.CustomRendering = true; - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - var outputDictionary = v_DictionaryName.GetDictionaryVariable(engine); - - outputDictionary.AddDataAndValueFromDataTable(v_ColumnNameDataTable, engine); - } - - public override void BeforeValidate() - { - base.BeforeValidate(); - DataTableControls.BeforeValidate((DataGridView)ControlsList[nameof(v_ColumnNameDataTable)], v_ColumnNameDataTable); - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/AddDictionaryItemCommand.cs b/taskt/Core/Automation/Commands/Dictionary/AddDictionaryItemCommand.cs new file mode 100644 index 000000000..5b9a892d7 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/AddDictionaryItemCommand.cs @@ -0,0 +1,51 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Dictionary")] + [Attributes.ClassAttributes.SubGruop("Dictionary Item")] + [Attributes.ClassAttributes.CommandSettings("Add Dictionary Item")] + [Attributes.ClassAttributes.Description("This command Adds a key and value to a existing Dictionary")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add to a dictionary")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class AddDictionaryItemCommand : ADictionaryAddCreateCommands, IHaveDataTableElements + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_BothDictionaryName))] + public override string v_Dictionary { get; set; } + + //[XmlElement] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_KeyAndValue))] + //[PropertyParameterOrder(6000)] + //public DataTable v_ColumnNameDataTable { get; set; } + + public AddDictionaryItemCommand() + { + //this.CommandName = "AddDictionaryItemCommand"; + //this.SelectionName = "Add Dictionary Item"; + //this.CommandEnabled = true; + //this.CustomRendering = true; + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //var outputDictionary = v_Dictionary.ExpandUserVariableAsDictinary(engine); + var outputDictionary = this.ExpandUserVariableAsDictionary(engine); + + //outputDictionary.AddDataAndValueFromDataTable(v_ColumnNameDataTable, engine); + AddDataAndValueFromDataTable(outputDictionary, engine); + } + + //public override void BeforeValidate() + //{ + // base.BeforeValidate(); + // DataTableControls.BeforeValidate((DataGridView)ControlsList[nameof(v_ColumnNameDataTable)], v_ColumnNameDataTable); + //} + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/CheckDictionaryKeyExistsCommand.cs b/taskt/Core/Automation/Commands/Dictionary/CheckDictionaryKeyExistsCommand.cs index 50c3c1d8f..8d06e4790 100644 --- a/taskt/Core/Automation/Commands/Dictionary/CheckDictionaryKeyExistsCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/CheckDictionaryKeyExistsCommand.cs @@ -5,29 +5,31 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Key")] [Attributes.ClassAttributes.CommandSettings("Check Dictionary Key Exists")] [Attributes.ClassAttributes.Description("This command allows you to check key existance in Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check key existance in Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CheckDictionaryKeyExistsCommand : ScriptCommand + public sealed class CheckDictionaryKeyExistsCommand : ADictionaryKeyCommands, IDictionaryGetFromDictionaryProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] - public string v_InputData { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + //public string v_Dictionary { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Key))] - [PropertyDescription("Name of the Dictionary Key to Check")] - public string v_Key { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Key))] + //[PropertyDescription("Name of the Dictionary Key to Check")] + //public string v_Key { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] [Remarks("When the Key Exists, the Result is **True**")] - public string v_applyToVariable { get; set; } + [PropertyParameterOrder(7000)] + public string v_Result { get; set; } public CheckDictionaryKeyExistsCommand() { @@ -37,13 +39,21 @@ public CheckDictionaryKeyExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var vKey = v_Key.ConvertToUserVariable(sender); + //var vKey = v_Key.ExpandValueOrUserVariable(engine); - var dic = v_InputData.GetDictionaryVariable(engine); - dic.ContainsKey(vKey).StoreInUserVariable(engine, v_applyToVariable); + //var dic = v_Dictionary.ExpandUserVariableAsDictinary(engine); + //dic.ContainsKey(vKey).StoreInUserVariable(engine, v_Result); + try + { + this.ExpandValueOrUserVariableAsDictionaryKeyAndValue(engine); + true.StoreInUserVariable(engine, v_Result); + } + catch + { + false.StoreInUserVariable(engine, v_Result); + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/ConcatenateDictionaryCommand.cs b/taskt/Core/Automation/Commands/Dictionary/ConcatenateDictionaryCommand.cs index 170874d6a..e53805096 100644 --- a/taskt/Core/Automation/Commands/Dictionary/ConcatenateDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/ConcatenateDictionaryCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Action")] [Attributes.ClassAttributes.CommandSettings("Concatenate Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to concatenate two Dictionaries.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to concatenate two Dictionaries.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConcatenateDictionaryCommand : ScriptCommand + public sealed class ConcatenateDictionaryCommand : ScriptCommand, ICanHandleDictionary { [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] @@ -24,7 +25,7 @@ public class ConcatenateDictionaryCommand : ScriptCommand [PropertyDetailSampleUsage("**{{{vDictionary1}}}**", PropertyDetailSampleUsage.ValueType.VariableName)] [PropertyValidationRule("Dictionary1", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Dictionary1")] - public string v_InputDataA { get; set; } + public string v_DictionaryA { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] @@ -34,7 +35,7 @@ public class ConcatenateDictionaryCommand : ScriptCommand [PropertyDetailSampleUsage("**{{{vDictionary2}}}**", PropertyDetailSampleUsage.ValueType.VariableName)] [PropertyValidationRule("Dictionary2", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Dictionary2")] - public string v_InputDataB { get; set; } + public string v_DictionaryB { get; set; } [XmlAttribute] [PropertyDescription("When Key already Exists")] @@ -54,7 +55,7 @@ public class ConcatenateDictionaryCommand : ScriptCommand [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_NewOutputDictionaryName))] [Remarks("Concatenate Dictionary 1, Dictionary 2 in that order")] - public string v_OutputName { get; set; } + public string v_NewDictionary { get; set; } public ConcatenateDictionaryCommand() { @@ -64,17 +65,18 @@ public ConcatenateDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //var dicA = v_DictionaryA.ExpandUserVariableAsDictinary(engine); - var dicA = v_InputDataA.GetDictionaryVariable(engine); + //var dicB = v_DictionaryB.ExpandUserVariableAsDictinary(engine); - var dicB = v_InputDataB.GetDictionaryVariable(engine); + var dicA = this.ExpandUserVariableAsDictionary(nameof(v_DictionaryA), engine); + var dicB = this.ExpandUserVariableAsDictionary(nameof(v_DictionaryB), engine); var myDic = new Dictionary(dicA); - string keyExists = this.GetUISelectionValue(nameof(v_KeyExists), "When Key Exists", engine); + string keyExists = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_KeyExists), "When Key Exists", engine); switch (keyExists) { @@ -114,7 +116,9 @@ public override void RunCommand(object sender) } break; } - myDic.StoreInUserVariable(engine, v_OutputName); + + //myDic.StoreInUserVariable(engine, v_NewDictionary); + this.StoreDictionaryInUserVariable(myDic, nameof(v_NewDictionary), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToDataTableCommand.cs b/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToDataTableCommand.cs index 99460c747..c1954cedd 100644 --- a/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToDataTableCommand.cs @@ -6,23 +6,24 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Convert")] [Attributes.ClassAttributes.CommandSettings("Convert Dictionary To DataTable")] [Attributes.ClassAttributes.Description("This command allows you to convert Dictionary to DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert Dictionary to DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDictionaryToDataTableCommand : ScriptCommand + public sealed class ConvertDictionaryToDataTableCommand : ADictionaryGetFromDictionaryCommands, IDataTableResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] - public string v_InputData { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + //public string v_Dictionary { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] - public string v_OutputVariable { get; set; } + public override string v_Result { get; set; } public ConvertDictionaryToDataTableCommand() { @@ -32,20 +33,21 @@ public ConvertDictionaryToDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var dic = v_InputData.GetDictionaryVariable(engine); + //var dic = v_Dictionary.ExpandUserVariableAsDictinary(engine); + var dic = this.ExpandUserVariableAsDictionary(engine); - DataTable DT = new DataTable(); - DT.Rows.Add(); + DataTable myDT = new DataTable(); + myDT.Rows.Add(); foreach(var item in dic) { - DT.Columns.Add(item.Key); - DT.Rows[0][item.Key] = item.Value; + myDT.Columns.Add(item.Key); + myDT.Rows[0][item.Key] = item.Value; } - DT.StoreInUserVariable(engine, v_OutputVariable); + + //DT.StoreInUserVariable(engine, v_Result); + this.StoreDataTableInUserVariable(myDT, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToJSONCommand.cs b/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToJSONCommand.cs index 974b4e8e5..f76a9c4e0 100644 --- a/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToJSONCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToJSONCommand.cs @@ -5,23 +5,24 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Convert")] - [Attributes.ClassAttributes.CommandSettings("Convert Dictionary To DataTable")] + [Attributes.ClassAttributes.CommandSettings("Convert Dictionary To JSON")] [Attributes.ClassAttributes.Description("This command allows you to get JSON from Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get JSON from Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDictionaryToJSONCommand : ScriptCommand + public sealed class ConvertDictionaryToJSONCommand : ADictionaryGetFromDictionaryCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] - public string v_InputData { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + //public string v_Dictionary { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_OutputJSONName))] - public string v_OutputVariable { get; set; } + public override string v_Result { get; set; } public ConvertDictionaryToJSONCommand() { @@ -31,14 +32,13 @@ public ConvertDictionaryToJSONCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var dic = v_InputData.GetDictionaryVariable(engine); + //var dic = v_Dictionary.ExpandUserVariableAsDictinary(engine); + var dic = this.ExpandUserVariableAsDictionary(engine); var json = Newtonsoft.Json.JsonConvert.SerializeObject(dic); - json.StoreInUserVariable(engine, v_OutputVariable); + json.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToListCommand.cs b/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToListCommand.cs index a8a2e35e0..30d853273 100644 --- a/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToListCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/ConvertDictionaryToListCommand.cs @@ -6,23 +6,24 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Convert")] [Attributes.ClassAttributes.CommandSettings("Convert Dictionary To List")] [Attributes.ClassAttributes.Description("This command allows you to get List from Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get List from Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertDictionaryToListCommand : ScriptCommand + public sealed class ConvertDictionaryToListCommand : ADictionaryGetFromDictionaryCommands, IListResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] - public string v_InputData { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + //public string v_Dictionary { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] - public string v_OutputVariable { get; set; } + public override string v_Result { get; set; } public ConvertDictionaryToListCommand() { @@ -32,13 +33,13 @@ public ConvertDictionaryToListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var dic = v_InputData.GetDictionaryVariable(engine); + //var dic = v_Dictionary.ExpandUserVariableAsDictinary(engine); + var dic = this.ExpandUserVariableAsDictionary(engine); - dic.Values.ToList().StoreInUserVariable(engine, v_OutputVariable); + //dic.Values.ToList().StoreInUserVariable(engine, v_Result); + this.StoreListInUserVariable(dic.Values.ToList(), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/CopyDictionaryCommand.cs b/taskt/Core/Automation/Commands/Dictionary/CopyDictionaryCommand.cs index ada2f71c6..2a04221dd 100644 --- a/taskt/Core/Automation/Commands/Dictionary/CopyDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/CopyDictionaryCommand.cs @@ -6,26 +6,27 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Action")] [Attributes.ClassAttributes.CommandSettings("Copy Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to copy a Dictionary.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to copy a Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CopyDictionaryCommand : ScriptCommand + public sealed class CopyDictionaryCommand : ADictionaryCreateFromDictionaryCommands { [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] [PropertyDescription("Dictionary Variable Name to Copy")] [PropertyValidationRule("Dictionary to Copy", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Dictionary to Copy")] - public string v_InputData { get; set; } + public override string v_TargetDictionary { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_NewOutputDictionaryName))] - public string v_OutputName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_NewOutputDictionaryName))] + //public string v_NewDictionary { get; set; } public CopyDictionaryCommand() { @@ -35,15 +36,19 @@ public CopyDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //var srcDic = v_TargetDictionary.ExpandUserVariableAsDictinary(engine); + + //var newDic = new Dictionary(srcDic); + + //newDic.StoreInUserVariable(engine, v_NewDictionary); - var srcDic = v_InputData.GetDictionaryVariable(engine); + var srcDic = this.ExpandUserVariableAsDictionary(engine); var newDic = new Dictionary(srcDic); - newDic.StoreInUserVariable(engine, v_OutputName); + this.StoreDictionaryInUserVariable(newDic, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/CovnertDictionaryToTextCommand.cs b/taskt/Core/Automation/Commands/Dictionary/CovnertDictionaryToTextCommand.cs new file mode 100644 index 000000000..0bdef988e --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/CovnertDictionaryToTextCommand.cs @@ -0,0 +1,95 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Dictionary")] + [Attributes.ClassAttributes.SubGruop("Convert")] + [Attributes.ClassAttributes.CommandSettings("Covnert Dictionary To Text")] + [Attributes.ClassAttributes.Description("This command allows you to Covnert Dictionary to Text.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Covnert Dictionary to Text.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ConvertDictionaryToTextCommand : ADictionaryGetFromDictionaryCommands + { + //public string v_Dictionary { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(6000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Header")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Header", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7000)] + public string v_ExportHeader { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Index")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7001)] + public string v_ExportIndex { get; set; } + + public ConvertDictionaryToTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var dic = this.ExpandUserVariableAsDictionary(engine); + + var exportHeader = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportHeader), engine); + var exportIndex = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportIndex), engine); + + string txt = ""; + if (exportHeader) + { + if (exportIndex) + { + txt = "index,key,value\r\n"; + } + else + { + txt = "key,value\r\n"; + } + } + Func textAction; + if (exportIndex) + { + textAction = new Func((key, value, idx) => + { + return $"{idx},{key},{value}\r\n"; + }); + } + else + { + textAction = new Func((key, value, idx) => + { + return $"{key},{value}\r\n"; + }); + } + + int index = 0; + foreach (var item in dic) + { + txt += textAction(item.Key, item.Value, index); + index++; + } + + txt.Trim().StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/CovnertDictionaryToVisualizedTextCommand.cs b/taskt/Core/Automation/Commands/Dictionary/CovnertDictionaryToVisualizedTextCommand.cs new file mode 100644 index 000000000..62b773320 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/CovnertDictionaryToVisualizedTextCommand.cs @@ -0,0 +1,95 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Dictionary")] + [Attributes.ClassAttributes.SubGruop("Convert")] + [Attributes.ClassAttributes.CommandSettings("Covnert Dictionary To Visualized Text")] + [Attributes.ClassAttributes.Description("This command allows you to Covnert Dictionary to Visualized Text.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Covnert Dictionary to Visualized Text.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ConvertDictionaryToVisualizedTextCommand : ADictionaryGetFromDictionaryCommands + { + //public string v_Dictionary { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + public override string v_Result { get; set; } + + public ConvertDictionaryToVisualizedTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var dic = this.ExpandUserVariableAsDictionary(engine); + + var maxValueLength = 0; + var maxKeyLength = 0; + foreach (var item in dic) + { + var vs = item.Value.Length; + if (maxValueLength < vs) + { + maxValueLength = vs; + } + var ks = item.Key.Length; + if (maxKeyLength < ks) + { + maxKeyLength = ks; + } + } + if (maxValueLength < 5) + { + maxValueLength = 5; // Value + } + if (maxKeyLength < 3) + { + maxKeyLength = 3; // Key + } + + int size = dic.Count; + int indexDigits = (int)Math.Log10(size) + 1; + if (indexDigits < 3) + { + indexDigits = 3; // No. + } + + string indexFormat = $"{{0,{indexDigits}}}"; + string keyFormat = $"{{0,-{maxKeyLength}}}"; + string valueFormat = $"{{0,-{maxValueLength}}}"; + + string txt = $"{string.Format(indexFormat, "No.")} | {string.Format(keyFormat, "Key")} | {string.Format(valueFormat, "Value")}\r\n"; + for (int i = 0; i < indexDigits; i++) + { + txt += "-"; + } + txt += "-|-"; + for (int i = 0; i < maxKeyLength; i++) + { + txt += "-"; + } + txt += "-|-"; + for (int i=0; i< maxValueLength; i++) + { + txt += "-"; + } + txt += "\r\n"; + + int cnt = 0; + foreach (var item in dic) + { + txt += $"{string.Format(indexFormat, cnt)} | {string.Format(keyFormat, item.Key)} | {string.Format(valueFormat, item.Value)}\r\n"; + cnt++; + } + + txt.StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/CreateDictionaryCommand.cs b/taskt/Core/Automation/Commands/Dictionary/CreateDictionaryCommand.cs index 92df93bd5..99da02ac7 100644 --- a/taskt/Core/Automation/Commands/Dictionary/CreateDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/CreateDictionaryCommand.cs @@ -1,30 +1,30 @@ using System; using System.Xml.Serialization; -using System.Data; using System.Collections.Generic; -using System.Windows.Forms; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Action")] [Attributes.ClassAttributes.CommandSettings("Create Dictionary")] [Attributes.ClassAttributes.Description("This command created a DataTable with the column names provided")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create a new Dictionary")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateDictionaryCommand : ScriptCommand + public sealed class CreateDictionaryCommand : ADictionaryAddCreateCommands { [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_OutputDictionaryName))] - public string v_DictionaryName { get; set; } + public override string v_Dictionary { get; set; } - [XmlElement] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_KeyAndValue))] - public DataTable v_ColumnNameDataTable { get; set; } + //[XmlElement] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_KeyAndValue))] + //[PropertyParameterOrder(6000)] + //public DataTable v_ColumnNameDataTable { get; set; } public CreateDictionaryCommand() { @@ -34,21 +34,22 @@ public CreateDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var outputDictionary = new Dictionary(); - outputDictionary.AddDataAndValueFromDataTable(v_ColumnNameDataTable, engine); + //outputDictionary.AddDataAndValueFromDataTable(v_ColumnNameDataTable, engine); + AddDataAndValueFromDataTable(outputDictionary, engine); - outputDictionary.StoreInUserVariable(engine, v_DictionaryName); - } + //outputDictionary.StoreInUserVariable(engine, v_Dictionary); - public override void BeforeValidate() - { - base.BeforeValidate(); - DataTableControls.BeforeValidate((DataGridView)ControlsList[nameof(v_ColumnNameDataTable)], v_ColumnNameDataTable); + this.StoreDictionaryInUserVariable(outputDictionary, nameof(v_Dictionary), engine); } + + //public override void BeforeValidate() + //{ + // base.BeforeValidate(); + // DataTableControls.BeforeValidate((DataGridView)ControlsList[nameof(v_ColumnNameDataTable)], v_ColumnNameDataTable); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/EM_CanHandleDictionary.cs b/taskt/Core/Automation/Commands/Dictionary/EM_CanHandleDictionary.cs new file mode 100644 index 000000000..709360998 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/EM_CanHandleDictionary.cs @@ -0,0 +1,102 @@ +using System; +using System.Collections.Generic; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_CanHandleDictionary + { + /// + /// check object is Dictionary + /// + /// + /// + /// + public static bool IsDictionary(object value, out Dictionary dic) + { + // TODO: it's OK? + dic = default; + if (value is Dictionary d) + { + dic = d; + return true; + } + else + { + return false; + } + } + + /// + /// create new Empty Dictioanry + /// + /// + public static Dictionary CreateEmptyDictionary(this ICanHandleDictionary command) + { + // todo: is it ok? + return new Dictionary(); + } + + /// + /// Expand User Variable As Dictioanry + /// + /// + /// + /// + /// + public static Dictionary ExpandUserVariableAsDictionary(ScriptVariable variable) + { + // TODO: it's ok? + if (IsDictionary(variable.VariableValue, out Dictionary dictionary)) + { + return dictionary; + } + else + { + throw new Exception($"Variable '{variable.VariableName}' is not Dictionary"); + } + } + + /// + /// Expand user variable as Dictionary<string, string> + /// + /// + /// + /// + /// Value is not Dictionary + public static Dictionary ExpandUserVariableAsDictionary(this ICanHandleDictionary command, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "Dictionary Variable"); + //var v = variableName.GetRawVariable(engine); + //if (v.VariableValue is Dictionary dictionary) + //{ + // return dictionary; + //} + //else + //{ + // throw new Exception($"Variable '{variableName}' is not Dictionary"); + //} + try + { + return ExpandUserVariableAsDictionary(variableName.GetRawVariable(engine)); + } + catch + { + throw new Exception($"Variable '{variableName}' is not Dictionary"); + } + } + + /// + /// store Dictionary in User Variable + /// + /// + /// + /// + /// + public static void StoreDictionaryInUserVariable(this ICanHandleDictionary command, Dictionary dic, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "Dictionary Variable"); + ExtensionMethods.StoreInUserVariable(variableName, dic, engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/EM_DicitionaryCreateFromDictionaryExtensionMethods.cs b/taskt/Core/Automation/Commands/Dictionary/EM_DicitionaryCreateFromDictionaryExtensionMethods.cs new file mode 100644 index 000000000..769418090 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/EM_DicitionaryCreateFromDictionaryExtensionMethods.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DicitionaryCreateFromDictionaryExtensionMethods + { + /// + /// Expand user variable as Dictionary + /// + /// + /// + /// + public static Dictionary ExpandUserVariableAsDictionary(this ILDictionaryCreateFromDictionary command, Engine.AutomationEngineInstance engine) + { + return command.ExpandUserVariableAsDictionary(nameof(command.v_TargetDictionary), engine); + } + + /// + /// store Dictionary in User Variable + /// + /// + /// + /// + /// + public static void StoreDictionaryInUserVariable(this ILDictionaryCreateFromDictionary command, Dictionary dic, Engine.AutomationEngineInstance engine) + { + command.StoreDictionaryInUserVariable(dic, nameof(command.v_NewDictionary), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/EM_DictionaryKeyPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Dictionary/EM_DictionaryKeyPropertiesExtensionMethods.cs new file mode 100644 index 000000000..69050c940 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/EM_DictionaryKeyPropertiesExtensionMethods.cs @@ -0,0 +1,29 @@ +using System; +using System.Collections.Generic; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DictionaryKeyPropertiesExtensionMethods + { + /// + /// Expand value or UserVariable as Dictionary, Key, and Value + /// + /// + /// + /// (Dictionary, key, value) + /// + public static (Dictionary dic, string key, string value) ExpandValueOrUserVariableAsDictionaryKeyAndValue(this IDictionaryKeyProperties command, Engine.AutomationEngineInstance engine) + { + var dic = command.ExpandUserVariableAsDictionary(nameof(command.v_Dictionary), engine); + var key = ((ScriptCommand)command).ExpandValueOrUserVariable(nameof(command.v_Key), "Dictionary Key", engine); + if (dic.ContainsKey(key)) + { + return (dic, key, dic[key]); + } + else + { + throw new Exception($"Key does not Exists in Dictionary. Key: '{command.v_Key}', Expand Value: '{key}'"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/EM_DictionaryPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Dictionary/EM_DictionaryPropertiesExtensionMethods.cs new file mode 100644 index 000000000..e0517b5a8 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/EM_DictionaryPropertiesExtensionMethods.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DictionaryPropertiesExtensionMethods + { + /// + /// Expand user variable as Dictionary + /// + /// + /// + /// + public static Dictionary ExpandUserVariableAsDictionary(this ILDictionaryProperties command, Engine.AutomationEngineInstance engine) + { + return command.ExpandUserVariableAsDictionary(nameof(command.v_Dictionary), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/EM_DictionaryResultPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Dictionary/EM_DictionaryResultPropertiesExtensionMethods.cs new file mode 100644 index 000000000..0f8dfef0f --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/EM_DictionaryResultPropertiesExtensionMethods.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_DictionaryResultPropertiesExtensionMethods + { + /// + /// Store Dictionary in User Variable + /// + /// + /// + /// + public static void StoreDictionaryInUserVariable(this IDictionaryResultProperties command, Dictionary dic, Engine.AutomationEngineInstance engine) + { + command.StoreDictionaryInUserVariable(dic, nameof(command.v_Result), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/ExportDictionaryAsTextFileCommand.cs b/taskt/Core/Automation/Commands/Dictionary/ExportDictionaryAsTextFileCommand.cs new file mode 100644 index 000000000..b8358a33b --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/ExportDictionaryAsTextFileCommand.cs @@ -0,0 +1,101 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Dictionary")] + [Attributes.ClassAttributes.SubGruop("File")] + [Attributes.ClassAttributes.CommandSettings("Export Dictionary As Text File")] + [Attributes.ClassAttributes.Description("This command allows you to Export Dictionary as Text File.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Export Dictionary as Text File.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ExportDictionaryAsTextFileCommand : ADictionaryInputDictionaryCommands + { + //public string v_Dictionary { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_FilePath))] + [PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtension, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "txt")] + [PropertyParameterOrder(6000)] + public string v_FilePath { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Header")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Header", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7000)] + public string v_ExportHeader { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Index")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7001)] + public string v_ExportIndex { get; set; } + + public ExportDictionaryAsTextFileCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var dic = this.ExpandUserVariableAsDictionary(engine); + + var exportHeader = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportHeader), engine); + var exportIndex = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportIndex), engine); + + string txt = ""; + if (exportHeader) + { + if (exportIndex) + { + txt = "index,key,value\r\n"; + } + else + { + txt = "key,value\r\n"; + } + } + Func textAction; + if (exportIndex) + { + textAction = new Func((key, value, idx) => + { + return $"{idx},{key},{value}\r\n"; + }); + } + else + { + textAction = new Func((key, value, idx) => + { + return $"{key},{value}\r\n"; + }); + } + + int index = 0; + foreach (var item in dic) + { + txt += textAction(item.Key, item.Value, index); + index++; + } + + var writeText = new WriteTextFileCommand() + { + v_FilePath = this.v_FilePath, + v_TextToWrite = txt.Trim(), + }; + writeText.RunCommand(engine); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/FilterDictionaryCommand.cs b/taskt/Core/Automation/Commands/Dictionary/FilterDictionaryCommand.cs index 2cf9e67d0..d7f3e12e5 100644 --- a/taskt/Core/Automation/Commands/Dictionary/FilterDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/FilterDictionaryCommand.cs @@ -8,40 +8,44 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Action")] [Attributes.ClassAttributes.CommandSettings("Filter Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to filter Dictionary value.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to filter Dictionary value.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class FilterDictionaryCommand : ScriptCommand + public sealed class FilterDictionaryCommand : ADictionaryCreateFromDictionaryCommands, ILFilterValueProperties, IHaveDataTableElements { [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] [PropertyDescription("Dictionary Variable Name to Filter")] [PropertyValidationRule("Dictionary to Filter", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Dictionary to Filter")] - public string v_InputDictionary { get; set; } + public override string v_TargetDictionary { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_FilterValueType))] [PropertySelectionChangeEvent(nameof(cmbTargetType_SelectionChangeCommited))] - public string v_TargetType { get; set; } + [PropertyParameterOrder(6000)] + public string v_ValueType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_FilterAction))] [PropertySelectionChangeEvent(nameof(cmbFilterAction_SelectionChangeCommited))] + [PropertyParameterOrder(7000)] public string v_FilterAction { get; set; } [XmlElement] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ActionParameterTable))] + [PropertyParameterOrder(8000)] public DataTable v_FilterActionParameterTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_NewOutputDictionaryName))] - public string v_OutputDictionary { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_NewOutputDictionaryName))] + //public string v_NewDictionary { get; set; } public FilterDictionaryCommand() { @@ -51,14 +55,13 @@ public FilterDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetDic = v_InputDictionary.GetDictionaryVariable(engine); + //var targetDic = v_TargetDictionary.ExpandUserVariableAsDictinary(engine); + var targetDic = this.ExpandUserVariableAsDictionary(engine); var parameters = DataTableControls.GetFieldValues(v_FilterActionParameterTable, "ParameterName", "ParameterValue", engine); - var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_TargetType), nameof(v_FilterAction), parameters, engine, this); + var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_ValueType), nameof(v_FilterAction), parameters, engine, this); var res = new Dictionary(); @@ -70,12 +73,13 @@ public override void RunCommand(object sender) } } - res.StoreInUserVariable(engine, v_OutputDictionary); + //res.StoreInUserVariable(engine, v_NewDictionary); + this.StoreDictionaryInUserVariable(res, engine); } private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) { - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var FilterActionComboboxHelper = (ComboBox)ControlsList[nameof(v_FilterAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, FilterActionComboboxHelper); } @@ -83,18 +87,26 @@ private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) private void cmbFilterAction_SelectionChangeCommited(object sender, EventArgs e) { var FilterParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_FilterActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var FilterActionComboboxHelper = (ComboBox)ControlsList[nameof(v_FilterAction)]; ConditionControls.RenderFilter(v_FilterActionParameterTable, FilterParametersGridViewHelper, FilterActionComboboxHelper, TargetTypeComboboxHelper); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var FilterParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_FilterActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var FilterActionComboboxHelper = (ComboBox)ControlsList[nameof(v_FilterAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, FilterActionComboboxHelper); ConditionControls.RenderFilter(v_FilterActionParameterTable, FilterParametersGridViewHelper, FilterActionComboboxHelper, TargetTypeComboboxHelper); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_FilterActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_FilterActionParameterTable); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/GetDictionaryKeyFromValueCommand.cs b/taskt/Core/Automation/Commands/Dictionary/GetDictionaryKeyFromValueCommand.cs index a1ecd4af8..5c55ada54 100644 --- a/taskt/Core/Automation/Commands/Dictionary/GetDictionaryKeyFromValueCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/GetDictionaryKeyFromValueCommand.cs @@ -6,29 +6,31 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Key")] [Attributes.ClassAttributes.CommandSettings("Get Dictionary Key From Value")] [Attributes.ClassAttributes.Description("This command allows you to get Dictionary key Name from Value")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Dictionary key Name from Value.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetDictionaryKeyFromValueCommand : ScriptCommand + public sealed class GetDictionaryKeyFromValueCommand : ADictionaryGetFromDictionaryCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] - public string v_InputData { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + //public string v_Dictionary { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Value))] + [PropertyParameterOrder(6000)] public string v_Value { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] [PropertyDescription("Variable Name to Store Key name")] [Remarks("When value not found, Result is Empty")] - public string v_OutputVariable { get; set; } + public override string v_Result { get; set; } public GetDictionaryKeyFromValueCommand() { @@ -38,22 +40,21 @@ public GetDictionaryKeyFromValueCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var vValue = v_Value.ConvertToUserVariable(sender); + //var dic = v_Dictionary.ExpandUserVariableAsDictinary(engine); + var dic = this.ExpandUserVariableAsDictionary(engine); - var dic = v_InputData.GetDictionaryVariable(engine); - - foreach(KeyValuePair item in dic) + var vValue = v_Value.ExpandValueOrUserVariable(engine); + foreach (KeyValuePair item in dic) { if (item.Value == vValue) { - item.Key.StoreInUserVariable(engine, v_OutputVariable); + item.Key.StoreInUserVariable(engine, v_Result); return; } } - "".StoreInUserVariable(engine, v_OutputVariable); + "".StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/GetDictionaryKeysListCommand.cs b/taskt/Core/Automation/Commands/Dictionary/GetDictionaryKeysListCommand.cs index fed8e8035..04a7624b7 100644 --- a/taskt/Core/Automation/Commands/Dictionary/GetDictionaryKeysListCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/GetDictionaryKeysListCommand.cs @@ -1,29 +1,29 @@ using System; using System.Linq; using System.Xml.Serialization; -using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Key")] [Attributes.ClassAttributes.CommandSettings("Get Dictionary Keys List")] [Attributes.ClassAttributes.Description("This command allows you to get Keys List in Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Keys List in Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetDictionaryKeysListCommand : ScriptCommand + public sealed class GetDictionaryKeysListCommand : ADictionaryGetFromDictionaryCommands, IListResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] - public string v_InputData { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + //public string v_Dictionary { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] - public string v_OutputVariable { get; set; } + public override string v_Result { get; set; } public GetDictionaryKeysListCommand() { @@ -33,12 +33,13 @@ public GetDictionaryKeysListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //var dic = v_Dictionary.ExpandUserVariableAsDictinary(engine); + var dic = this.ExpandUserVariableAsDictionary(engine); - var dic = v_InputData.GetDictionaryVariable(engine); - dic.Keys.ToList().StoreInUserVariable(engine, v_OutputVariable); + //dic.Keys.ToList().StoreInUserVariable(engine, v_Result); + this.StoreListInUserVariable(dic.Keys.ToList(), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/GetDictionaryValueCommand.cs b/taskt/Core/Automation/Commands/Dictionary/GetDictionaryValueCommand.cs index 27017c189..9e3c1e24b 100644 --- a/taskt/Core/Automation/Commands/Dictionary/GetDictionaryValueCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/GetDictionaryValueCommand.cs @@ -1,37 +1,56 @@ using System; using System.Xml.Serialization; +using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Item")] [Attributes.ClassAttributes.CommandSettings("Get Dictionary Value")] [Attributes.ClassAttributes.Description("This command allows you to get value in Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get value in Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetDictionaryValueCommand : ScriptCommand + public sealed class GetDictionaryValueCommand : ADictionaryKeyActionCommands, IDictionaryGetFromDictionaryProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] - public string v_InputData { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + //public string v_Dictionary { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Key))] - public string v_Key { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Key))] + //public string v_Key { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_OutputVariable { get; set; } + [PropertyParameterOrder(7000)] + public string v_Result { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_WhenKeyDoesNotExists))] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_WhenKeyDoesNotExists))] [PropertyUISelectionOption("Set Empty")] [PropertyDetailSampleUsage("**Set Empty**", "Result is Empty Value")] - public string v_IfKeyDoesNotExists { get; set; } + public override string v_WhenKeyDoesNotExists { get; set; } + + [XmlAttribute] + [PropertyDescription("Key Type")] + [InputSpecification("")] + [Remarks("")] + [PropertyUISelectionOption("Key")] + [PropertyUISelectionOption("Index")] + [PropertyDetailSampleUsage("**Key**", "Key Value is Dictionary Key Name")] + [PropertyDetailSampleUsage("**Key**", "Key Value is Dictionary Key Index")] + [PropertyIsOptional(true, "Key")] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyValidationRule("Key Type", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "Result")] + [PropertyParameterOrder(11000)] + public string v_KeyType { get; set; } public GetDictionaryValueCommand() { @@ -41,29 +60,95 @@ public GetDictionaryValueCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_KeyType), engine) == "index") + { + //var getKeys = new GetDictionaryKeysListCommand() + //{ + // v_Dictionary = this.v_Dictionary, + // v_Result = VariableNameControls.GetInnerVariableName(0, engine), + //}; + //getKeys.RunCommand(engine); + //var keys = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; + //var index = this.ExpandValueOrUserVariableAsInteger(nameof(v_Key), "Key", engine); + //if (index < 0) + //{ + // index += keys.Count; + //} + //if (index >= 0 && index < keys.Count) + //{ + // v_Key = keys[index]; // override Key name + //} + //else + //{ + // throw new Exception($"Index value is Out of Range. Value: '{v_Key}', Expand Value: '{index}'"); + //} - (var dic, var vKey) = this.GetDictionaryVariableAndKey(nameof(v_InputData), nameof(v_Key), engine); + using (var myDic = new InnerScriptVariable(engine)) + { + var getKeys = new GetDictionaryKeysListCommand() + { + v_Dictionary = this.v_Dictionary, + v_Result = myDic.VariableName, + }; + getKeys.RunCommand(engine); + //var keys = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; + //var keys = (List)myDic.VariableValue; + var keys = EM_CanHandleListExtensionMethods.ExpandUserVariableAsList(myDic); + var index = this.ExpandValueOrUserVariableAsInteger(nameof(v_Key), "Key", engine); + if (index < 0) + { + index += keys.Count; + } + if (index >= 0 && index < keys.Count) + { + v_Key = keys[index]; // override Key name + } + else + { + throw new Exception($"Index value is Out of Range. Value: '{v_Key}', Expand Value: '{index}'"); + } + } + } - if (dic.ContainsKey(vKey)) + //(var dic, var vKey) = this.ExpandUserVariablesAsDictionaryAndKey(nameof(v_Dictionary), nameof(v_Key), engine); + + try { - dic[vKey].StoreInUserVariable(engine, v_OutputVariable); + (_, _, var value) = this.ExpandValueOrUserVariableAsDictionaryKeyAndValue(engine); + value.StoreInUserVariable(engine, v_Result); } - else + catch (Exception ex) { - string ifNotExists = this.GetUISelectionValue(nameof(v_IfKeyDoesNotExists), "Key Not Exists", engine); - switch (ifNotExists) + switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenKeyDoesNotExists), "Key Not Exists", engine)) { - case "error": - throw new Exception("Key " + v_Key + " does not exists in the Dictionary"); - case "set empty": - "".StoreInUserVariable(engine, v_OutputVariable); + "".StoreInUserVariable(engine, v_Result); break; + + case "error": + throw ex; } } + + //if (dic.ContainsKey(vKey)) + //{ + // dic[vKey].StoreInUserVariable(engine, v_Result); + //} + //else + //{ + // string ifNotExists = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenKeyDoesNotExists), "Key Not Exists", engine); + // switch (ifNotExists) + // { + // case "error": + // throw new Exception("Key " + v_Key + " does not exists in the Dictionary"); + + // case "set empty": + // "".StoreInUserVariable(engine, v_Result); + // break; + // } + //} } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/ICanHandleDictionary.cs b/taskt/Core/Automation/Commands/Dictionary/ICanHandleDictionary.cs new file mode 100644 index 000000000..0d2c2ba88 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/ICanHandleDictionary.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for handle Dictionary + /// + public interface ICanHandleDictionary : ILExpandableProperties + { + // nothing + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/IDictionaryAddCreateProperties.cs b/taskt/Core/Automation/Commands/Dictionary/IDictionaryAddCreateProperties.cs new file mode 100644 index 000000000..24335dfc1 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/IDictionaryAddCreateProperties.cs @@ -0,0 +1,15 @@ +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + /// + /// Add Items to Dictionary or Create Dictionary properties + /// + public interface IDictionaryAddCreateProperties : ILDictionaryProperties + { + /// + /// Dictionary Keys & Values + /// + DataTable v_ColumnNameDataTable { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/IDictionaryGetFromDictionaryProperties.cs b/taskt/Core/Automation/Commands/Dictionary/IDictionaryGetFromDictionaryProperties.cs new file mode 100644 index 000000000..48b505db2 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/IDictionaryGetFromDictionaryProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Get something from Dictionary properties + /// + public interface IDictionaryGetFromDictionaryProperties : ILResultProperties + { + //string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/IDictionaryKeyActionProperties.cs b/taskt/Core/Automation/Commands/Dictionary/IDictionaryKeyActionProperties.cs new file mode 100644 index 000000000..f4f2cc705 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/IDictionaryKeyActionProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Dictionary & Key action properties + /// + public interface IDictionaryKeyActionProperties : IDictionaryKeyProperties + { + /// + /// When Key does not exists action + /// + string v_WhenKeyDoesNotExists { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/IDictionaryKeyProperties.cs b/taskt/Core/Automation/Commands/Dictionary/IDictionaryKeyProperties.cs new file mode 100644 index 000000000..734032c3c --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/IDictionaryKeyProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Dictionary & Key properties + /// + public interface IDictionaryKeyProperties : ILDictionaryProperties + { + /// + /// Dictionary key name + /// + string v_Key { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/IDictionaryResultProperties.cs b/taskt/Core/Automation/Commands/Dictionary/IDictionaryResultProperties.cs new file mode 100644 index 000000000..a89ed0808 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/IDictionaryResultProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Result is Dictionary Properties + /// + public interface IDictionaryResultProperties : ILResultProperties, ICanHandleDictionary + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/ILDictionaryCreateFromDictionary.cs b/taskt/Core/Automation/Commands/Dictionary/ILDictionaryCreateFromDictionary.cs new file mode 100644 index 000000000..a49dfa31d --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/ILDictionaryCreateFromDictionary.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Create Dictionary from Dictionary properties + /// + public interface ILDictionaryCreateFromDictionary: ILExpandableProperties, ICanHandleDictionary + { + /// + /// Dictionary variable name to Create New Dictionary + /// + string v_TargetDictionary { get; set; } + + /// + /// Dictionary variable name to Store New Dictionary + /// + string v_NewDictionary { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/ILDictionaryProperties.cs b/taskt/Core/Automation/Commands/Dictionary/ILDictionaryProperties.cs new file mode 100644 index 000000000..6b0545ee5 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/ILDictionaryProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Dictionary properties + /// + public interface ILDictionaryProperties : ICanHandleDictionary, ILExpandableProperties + { + /// + /// Dictionary variable name + /// + string v_Dictionary { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/JoinDictionaryValuesAsTextCommand.cs b/taskt/Core/Automation/Commands/Dictionary/JoinDictionaryValuesAsTextCommand.cs new file mode 100644 index 000000000..e94b190a0 --- /dev/null +++ b/taskt/Core/Automation/Commands/Dictionary/JoinDictionaryValuesAsTextCommand.cs @@ -0,0 +1,91 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Dictionary")] + [Attributes.ClassAttributes.SubGruop("Dictionary Item")] + [Attributes.ClassAttributes.CommandSettings("Join Dictionary Values As Text")] + [Attributes.ClassAttributes.Description("This command allows you to join Dictionary Values")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to join Dictionary Values")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class JoinDictionaryValuesAsTextCommand : ADictionaryGetFromDictionaryCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + //public string v_Dictionary { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Separator of List Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage(",", PropertyDetailSampleUsage.ValueType.Value, "Separator")] + [PropertyDetailSampleUsage("{{{vSep}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Separator")] + [PropertyValidationRule("Separator", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyDisplayText(true, "Separator")] + [PropertyParameterOrder(6000)] + public string v_Separator { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(7000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Text before Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyIsOptional(true)] + [PropertyDetailSampleUsage("\"", PropertyDetailSampleUsage.ValueType.Value, "Text before Values")] + [PropertyDetailSampleUsage("{{{vText}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Text before Values")] + [PropertyValidationRule("Text before Values", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(8000)] + public string v_BeforeText { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Text after Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyIsOptional(true)] + [PropertyDetailSampleUsage("\"", PropertyDetailSampleUsage.ValueType.Value, "Text after Values")] + [PropertyDetailSampleUsage("{{{vText}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Text after Values")] + [PropertyValidationRule("Text after Values", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(8001)] + public string v_AfterText { get; set; } + + public JoinDictionaryValuesAsTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + using (var myList = new InnerScriptVariable(engine)) + { + var convList = new ConvertDictionaryToListCommand() + { + v_Dictionary = this.v_Dictionary, + v_Result = myList.VariableName, + }; + convList.RunCommand(engine); + + var joinList = new JoinListValuesAsTextCommand() + { + v_List = myList.VariableName, + v_Result = this.v_Result, + v_Separator = this.v_Separator, + v_BeforeText = this.v_BeforeText, + v_AfterText = this.v_AfterText, + }; + joinList.RunCommand(engine); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Dictionary/LoadDictionaryCommand.cs b/taskt/Core/Automation/Commands/Dictionary/LoadDictionaryCommand.cs deleted file mode 100644 index 20343fcd9..000000000 --- a/taskt/Core/Automation/Commands/Dictionary/LoadDictionaryCommand.cs +++ /dev/null @@ -1,177 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Data; -using System.Linq; -using System.Windows.Forms; -using System.Xml.Serialization; -using taskt.UI.CustomControls; -using taskt.UI.Forms; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] - [Attributes.ClassAttributes.SubGruop("Dictionary Action")] - [Attributes.ClassAttributes.Description("This command Reads a Config file and stores it into a Dictionary.")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to load a config file.")] - [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop and OLEDB to achieve automation.")] - [Attributes.ClassAttributes.EnableAutomateRender(true)] - [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class LoadDictionaryCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Please Enter the Dictionary Variable Name")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter a name for a Dictionary.")] - [SampleUsage("**myDictionary** or **{{{vDictionary}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.Dictionary)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - [PropertyIsVariablesList(true)] - [PropertyValidationRule("Dictionary", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "Dictionary")] - public string v_DictionaryName { get; set; } - - [XmlAttribute] - [PropertyDescription("Please indicate the Workbook File Path")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowFileSelectionHelper)] - [InputSpecification("Enter or Select the path to the applicable file that should be loaded into the Dictionary.")] - [SampleUsage("**C:\\temp\\myfile.xlsx** or **{{{vFilePath}}}**")] - [Remarks("If file does not contain extension, supplement extensions supported by Excel.\nIf file does not contain folder path, file will be opened in the same folder as script file.")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - [PropertyValidationRule("File Path", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "File Path")] - public string v_FilePath { get; set; } - - [XmlAttribute] - [PropertyDescription("Please indicate the Sheet Name")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter the sheet name of the workbook to be read.")] - [SampleUsage("**Sheet1** or **{{{vSheet}}}**")] - [Remarks("Sheet has one table")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - [PropertyValidationRule("Sheet Name", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "Sheet Name")] - public string v_SheetName { get; set; } - - [XmlAttribute] - [PropertyDescription("Please indicate the Key Column")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter the key column name to create a Dictionary off of.")] - [SampleUsage("**Key** or **{{{vKeyColumn}}}**")] - [Remarks("This value is NOT Column Index Value like A, B. Please specify table column name.")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - [PropertyValidationRule("Key Column", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "Key Column")] - public string v_KeyColumn { get; set; } - - [XmlAttribute] - [PropertyDescription("Please indicate the Value Column")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter a value column name to create a Dictionary off of.")] - [SampleUsage("**Value** or **{{{vValueColumn}}}**")] - [Remarks("This value is NOT Column Index Value like A, B. Please specify table column name.")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - [PropertyValidationRule("Value Colmun", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "Value Column")] - public string v_ValueColumn { get; set; } - - public LoadDictionaryCommand() - { - this.CommandName = "LoadDictionaryCommand"; - this.SelectionName = "Load Dictionary"; - this.CommandEnabled = true; - this.CustomRendering = true; - } - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - //var vInstance = DateTime.Now.ToString(); - - var vSheet = v_SheetName.ConvertToUserVariable(sender); - var vKeyColumn = v_KeyColumn.ConvertToUserVariable(sender); - var vValueColumn = v_ValueColumn.ConvertToUserVariable(sender); - - //string vFilePath = FilePathControls.FormatFilePath_NoFileCounter(v_FilePath, engine, new List() { "xlsx", "xlsm", "xls" }, true); - var vFilePath = v_FilePath.ConvertToUserVariable(sender); - - //Query required from workbook using OLEDB - //DataTableControls dataSetCommand = new DataTableControls(); - - string param = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" + vFilePath + @""";Extended Properties=""Excel 12.0;HDR=YES;IMEX=1"""; - string queue = "Select " + vKeyColumn + "," + vValueColumn + " From " + "[" + vSheet + "$]"; - - // DBG - //MessageBox.Show(param + "\n" + queue); - - DataTable requiredData = DataTableControls.CreateDataTable(param, queue); - var dictlist = requiredData.AsEnumerable().Select(x => new - { - keys = (string)x[v_KeyColumn], - values = (string)x[v_ValueColumn] - }).ToList(); - Dictionary outputDictionary = new Dictionary(); - foreach (var dict in dictlist) - { - outputDictionary.Add(dict.keys, dict.values); - } - - outputDictionary.StoreInUserVariable(engine, v_DictionaryName); - } - - //public override List Render(frmCommandEditor editor) - //{ - // base.Render(editor); - - // var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); - // RenderedControls.AddRange(ctrls); - - // return RenderedControls; - - //} - //public override string GetDisplayValue() - //{ - // return base.GetDisplayValue() + " [Load Dictionary from '" + v_FilePath + "' and store in: '" +v_DictionaryName+ "']"; - //} - - //public override bool IsValidate(frmCommandEditor editor) - //{ - // base.IsValidate(editor); - - // if (String.IsNullOrEmpty(v_DictionaryName)) - // { - // this.IsValid = false; - // this.validationResult += "Dictionary Variable Name is empty.\n"; - // } - // if (String.IsNullOrEmpty(v_FilePath)) - // { - // this.IsValid = false; - // this.validationResult += "Workbook file path is empty.\n"; - // } - // if (String.IsNullOrEmpty(v_SheetName)) - // { - // this.IsValid = false; - // this.validationResult += "Sheet name is empty.\n"; - // } - // if (String.IsNullOrEmpty(v_KeyColumn)) - // { - // this.IsValid = false; - // this.validationResult += "Key column is empty.\n"; - // } - // if (String.IsNullOrEmpty(v_ValueColumn)) - // { - // this.IsValid = false; - // this.validationResult += "Value column is empty.\n"; - // } - - // return this.IsValid; - //} - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/RemoveDictionaryItemCommand.cs b/taskt/Core/Automation/Commands/Dictionary/RemoveDictionaryItemCommand.cs index de43033ed..f94e45b01 100644 --- a/taskt/Core/Automation/Commands/Dictionary/RemoveDictionaryItemCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/RemoveDictionaryItemCommand.cs @@ -5,29 +5,30 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Item")] [Attributes.ClassAttributes.CommandSettings("Remove Dictionary Item")] [Attributes.ClassAttributes.Description("This command allows you to remove item in Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to remove item in Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RemoveDictionaryItemCommand : ScriptCommand + public sealed class RemoveDictionaryItemCommand : ADictionaryKeyActionCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_BothDictionaryName))] - public string v_InputData { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_BothDictionaryName))] + //public string v_Dictionary { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Key))] - public string v_Key { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Key))] + //public string v_Key { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_WhenKeyDoesNotExists))] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_WhenKeyDoesNotExists))] [PropertyUISelectionOption("Ignore")] [PropertyDetailSampleUsage("**Ignore**", "Don't Remove the Dictionary Item")] - public string v_IfKeyDoesNotExists { get; set; } + public override string v_WhenKeyDoesNotExists { get; set; } public RemoveDictionaryItemCommand() { @@ -37,19 +38,31 @@ public RemoveDictionaryItemCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var dic, var vKey) = this.ExpandUserVariablesAsDictionaryAndKey(nameof(v_Dictionary), nameof(v_Key), engine); - (var dic, var vKey) = this.GetDictionaryVariableAndKey(nameof(v_InputData), nameof(v_Key), engine); + //if (!dic.Remove(vKey)) + //{ + // string ifNotExists = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenKeyDoesNotExists), "Key Not Exists", engine); + // switch (ifNotExists) + // { + // case "error": + // throw new Exception("Dictionary does not has key name " + vKey); + // } + //} - if (!dic.Remove(vKey)) + try + { + (var dic, var key, _) = this.ExpandValueOrUserVariableAsDictionaryKeyAndValue(engine); + dic.Remove(key); + } + catch (Exception ex) { - string ifNotExists = this.GetUISelectionValue(nameof(v_IfKeyDoesNotExists), "Key Not Exists", engine); - switch (ifNotExists) + switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenKeyDoesNotExists), engine)) { case "error": - throw new Exception("Dictionary does not has key name " + vKey); + throw ex; } } } diff --git a/taskt/Core/Automation/Commands/Dictionary/ReplaceDictionaryCommand.cs b/taskt/Core/Automation/Commands/Dictionary/ReplaceDictionaryCommand.cs index 3196eee93..713665719 100644 --- a/taskt/Core/Automation/Commands/Dictionary/ReplaceDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/ReplaceDictionaryCommand.cs @@ -8,40 +8,45 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Action")] [Attributes.ClassAttributes.CommandSettings("Replace Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to relace Dictionary value.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to relpace Dictionary value.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ReplaceDictionaryCommand : ScriptCommand + public sealed class ReplaceDictionaryCommand : ADictionaryInputDictionaryCommands, ILReplaceValueProperties, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_BothDictionaryName))] [PropertyDescription("Dictionary Variable Name to Replace")] [PropertyValidationRule("Dictionary to Replace", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Dictionary to Replace")] - public string v_TargetDictionary { get; set; } + public override string v_Dictionary { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValueType))] [PropertySelectionChangeEvent(nameof(cmbTargetType_SelectionChangeCommited))] - public string v_TargetType { get; set; } + [PropertyParameterOrder(6000)] + public string v_ValueType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceAction))] [PropertySelectionChangeEvent(nameof(cmbReplaceAction_SelectionChangeCommited))] + [PropertyParameterOrder(7000)] public string v_ReplaceAction { get; set; } [XmlElement] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ActionParameterTable))] + [PropertyParameterOrder(8000)] public DataTable v_ReplaceActionParameterTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValue))] - public string v_ReplaceValue { get; set; } + [PropertyParameterOrder(9000)] + public string v_NewValue { get; set; } public ReplaceDictionaryCommand() { @@ -51,16 +56,15 @@ public ReplaceDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetDic = v_TargetDictionary.GetDictionaryVariable(engine); + //var targetDic = v_Dictionary.ExpandUserVariableAsDictinary(engine); + var targetDic = this.ExpandUserVariableAsDictionary(engine); var parameters = DataTableControls.GetFieldValues(v_ReplaceActionParameterTable, "ParameterName", "ParameterValue", engine); - var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_TargetType), nameof(v_ReplaceAction), parameters, engine, this); + var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_ValueType), nameof(v_ReplaceAction), parameters, engine, this); - string newValue = v_ReplaceValue.ConvertToUserVariable(engine); + string newValue = v_NewValue.ExpandValueOrUserVariable(engine); var keys = targetDic.Keys.ToList(); @@ -75,7 +79,7 @@ public override void RunCommand(object sender) private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) { - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, ReplaceActionComboboxHelper); } @@ -83,18 +87,26 @@ private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) private void cmbReplaceAction_SelectionChangeCommited(object sender, EventArgs e) { var ReplaceParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.RenderFilter(v_ReplaceActionParameterTable, ReplaceParametersGridViewHelper, ReplaceActionComboboxHelper, TargetTypeComboboxHelper); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var ReplaceParametersGridViewHelper = (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)]; - var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_TargetType)]; + var TargetTypeComboboxHelper = (ComboBox)ControlsList[nameof(v_ValueType)]; var ReplaceActionComboboxHelper = (ComboBox)ControlsList[nameof(v_ReplaceAction)]; ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, ReplaceActionComboboxHelper); ConditionControls.RenderFilter(v_ReplaceActionParameterTable, ReplaceParametersGridViewHelper, ReplaceActionComboboxHelper, TargetTypeComboboxHelper); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_ReplaceActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_ReplaceActionParameterTable); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Dictionary/SetDictionaryValueCommand.cs b/taskt/Core/Automation/Commands/Dictionary/SetDictionaryValueCommand.cs index 3948cd357..6ba05bbd4 100644 --- a/taskt/Core/Automation/Commands/Dictionary/SetDictionaryValueCommand.cs +++ b/taskt/Core/Automation/Commands/Dictionary/SetDictionaryValueCommand.cs @@ -1,39 +1,42 @@ using System; +using System.Data; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Dictionary Commands")] + [Attributes.ClassAttributes.Group("Dictionary")] [Attributes.ClassAttributes.SubGruop("Dictionary Item")] [Attributes.ClassAttributes.CommandSettings("Set Dictionary Value")] [Attributes.ClassAttributes.Description("This command allows you to set value in Dictionary")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set value in Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetDictionaryValueCommand : ScriptCommand + public sealed class SetDictionaryValueCommand : ADictionaryKeyActionCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_BothDictionaryName))] - public string v_InputData { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_BothDictionaryName))] + //public string v_Dictionary { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Key))] - public string v_Key { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Key))] + //public string v_Key { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_Value))] + [PropertyParameterOrder(7000)] public string v_Value { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_WhenKeyDoesNotExists))] + //[PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_WhenKeyDoesNotExists))] [PropertyUISelectionOption("Ignore")] [PropertyUISelectionOption("Add")] [PropertyDetailSampleUsage("**Ignore**", "Don't Set the Dictionary Item")] [PropertyDetailSampleUsage("**Add**", "Add New Dictionary Item")] - public string v_IfKeyDoesNotExists { get; set; } + public override string v_WhenKeyDoesNotExists { get; set; } public SetDictionaryValueCommand() { @@ -43,30 +46,59 @@ public SetDictionaryValueCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var dic, var vKey) = this.ExpandUserVariablesAsDictionaryAndKey(nameof(v_Dictionary), nameof(v_Key), engine); - (var dic, var vKey) = this.GetDictionaryVariableAndKey(nameof(v_InputData), nameof(v_Key), engine); + //string valueToSet = v_Value.ExpandValueOrUserVariable(engine); + //if (dic.ContainsKey(vKey)) + //{ + // dic[vKey] = valueToSet; + //} + //else + //{ + // string ifNotExits = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenKeyDoesNotExists), "Key Not Exists", engine); + // switch (ifNotExits) + // { + // case "error": + // throw new Exception("Key " + v_Key + " does not exists in the Dictionary"); - string valueToSet = v_Value.ConvertToUserVariable(engine); - if (dic.ContainsKey(vKey)) + // case "ignore": + // break; + // case "add": + // dic.Add(vKey, valueToSet); + // break; + // } + //} + + try { - dic[vKey] = valueToSet; + (var dic, var key, _) = this.ExpandValueOrUserVariableAsDictionaryKeyAndValue(engine); + var valueToSet = v_Value.ExpandValueOrUserVariable(engine); + dic[key] = valueToSet; } - else + catch (Exception ex) { - string ifNotExits = this.GetUISelectionValue(nameof(v_IfKeyDoesNotExists), "Key Not Exists", engine); - switch (ifNotExits) + switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenKeyDoesNotExists), "Key Not Exists", engine)) { - case "error": - throw new Exception("Key " + v_Key + " does not exists in the Dictionary"); - case "ignore": break; + case "add": - dic.Add(vKey, valueToSet); + var tbl = new DataTable(); + tbl.Columns.Add("Keys"); + tbl.Columns.Add("Values"); + tbl.Rows.Add(new object[] { v_Key, v_Value }); + var addDictionary = new AddDictionaryItemCommand() + { + v_Dictionary = this.v_Dictionary, + v_ColumnNameDataTable = tbl, + }; + addDictionary.RunCommand(engine); break; + + case "error": + throw ex; } } } diff --git a/taskt/Core/Automation/Commands/DictionaryControls.cs b/taskt/Core/Automation/Commands/DictionaryControls.cs index e508303a1..7e45ee642 100644 --- a/taskt/Core/Automation/Commands/DictionaryControls.cs +++ b/taskt/Core/Automation/Commands/DictionaryControls.cs @@ -1,7 +1,5 @@ using System; -using System.Data; using System.Collections.Generic; -using System.Linq; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; @@ -28,6 +26,7 @@ internal static class DictionaryControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyValidationRule("Dictionary", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Dictionary")] + [PropertyParameterOrder(5000)] public static string v_OutputDictionaryName { get; } /// @@ -45,6 +44,7 @@ internal static class DictionaryControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyValidationRule("New Dictionary", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "New Dictionary")] + [PropertyParameterOrder(5000)] public static string v_NewOutputDictionaryName { get; } /// @@ -62,6 +62,7 @@ internal static class DictionaryControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyValidationRule("Dictionary", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Dictionary")] + [PropertyParameterOrder(5000)] public static string v_InputDictionaryName { get; } /// @@ -79,6 +80,7 @@ internal static class DictionaryControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyValidationRule("Dictionary", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Dictionary")] + [PropertyParameterOrder(5000)] public static string v_BothDictionaryName { get; } /// @@ -94,6 +96,7 @@ internal static class DictionaryControls [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Key", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Key")] + [PropertyParameterOrder(5000)] public static string v_Key { get; } /// @@ -121,6 +124,7 @@ internal static class DictionaryControls | Keys | Values | |---|---| | **{{{vKey}}}** | **{{{vValue}}}** |", "Add an item whose key is Value of Variable **vKey** and value is Value of Variable **vValue**")] + [PropertyParameterOrder(5000)] public static string v_KeyAndValue { get; } /// @@ -133,6 +137,7 @@ internal static class DictionaryControls [PropertyUISelectionOption("Error")] [PropertyIsOptional(true, "Error")] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyParameterOrder(5000)] public static string v_WhenKeyDoesNotExists { get; } /// @@ -147,111 +152,124 @@ internal static class DictionaryControls [PropertyShowSampleUsageInDescription(true)] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.TextBox)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(5000)] public static string v_Value { get; } - /// - /// get Dictionary<string, string> Variable from variable name - /// - /// - /// - /// - /// - public static Dictionary GetDictionaryVariable(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) - { - Script.ScriptVariable v = variableName.GetRawVariable(engine); - if (v.VariableValue is Dictionary dictionary) - { - return dictionary; - } - else - { - throw new Exception("Variable " + variableName + " is not Dictionary"); - } - } + ///// + ///// Expand user variable as Dictionary<string, string> + ///// + ///// + ///// + ///// + ///// Value is not Dictionary + //public static Dictionary ExpandUserVariableAsDictinary(this string variableName, Engine.AutomationEngineInstance engine) + //{ + // Script.ScriptVariable v = variableName.GetRawVariable(engine); + // if (v.VariableValue is Dictionary dictionary) + // { + // return dictionary; + // } + // else + // { + // throw new Exception("Variable " + variableName + " is not Dictionary"); + // } + //} - /// - /// get Dictionary<string, string> and key name from property names. It supports current position to key. - /// - /// - /// - /// - /// - /// - /// - public static (Dictionary, string) GetDictionaryVariableAndKey(this ScriptCommand command, string dictionaryName, string keyName, Core.Automation.Engine.AutomationEngineInstance engine) - { - string dicVariable = command.ConvertToUserVariable(dictionaryName, "Dictionary", engine); - var v = dicVariable.GetRawVariable(engine); - if (v.VariableValue is Dictionary dictionary) - { - string keyVariable = command.ConvertToUserVariable(keyName, "Key", engine); - string key; - if (String.IsNullOrEmpty(keyVariable)) - { - int pos = v.CurrentPosition; - string[] keys = dictionary.Keys.ToArray(); - if ((pos >= 0) && (pos < keys.Length)) - { - key = keys[pos]; - } - else - { - throw new Exception("Strange Current Position in Dictionary " + pos); - } - } - else - { - key = keyVariable.ConvertToUserVariable(engine); - } - return (dictionary, key); - } - else - { - throw new Exception("Variable " + dicVariable + " is not Dictionary"); - } - } + //public static void StoreInUserVariable(this Dictionary value, Engine.AutomationEngineInstance engine, string targetVariable) + //{ + // ExtensionMethods.StoreInUserVariable(targetVariable, value, engine, false); + //} - public static void StoreInUserVariable(this Dictionary value, Core.Automation.Engine.AutomationEngineInstance sender, string targetVariable) - { - ExtensionMethods.StoreInUserVariable(targetVariable, value, sender, false); - } - - /// - /// add new item to Dictionary from DataTable. check key name is empty - /// - /// - /// - /// - /// - public static void AddDataAndValueFromDataTable(this Dictionary dic, DataTable table, Automation.Engine.AutomationEngineInstance engine) - { - //var keys = new List(); + ///// + ///// expand user variables as Dictionary<string, string> and key name from property names. It supports current position to key. + ///// + ///// + ///// + ///// + ///// + ///// + ///// + //public static (Dictionary, string) ExpandUserVariablesAsDictionaryAndKey(this ScriptCommand command, string dictionaryName, string keyName, Engine.AutomationEngineInstance engine) + //{ + // string dicVariable = command.ExpandValueOrUserVariable(dictionaryName, "Dictionary", engine); + // //var v = dicVariable.GetRawVariable(engine); + // //if (v.VariableValue is Dictionary dictionary) + // //{ + // // string keyVariable = command.ConvertToUserVariable(keyName, "Key", engine); + // // string key; + // // if (String.IsNullOrEmpty(keyVariable)) + // // { + // // int pos = v.CurrentPosition; + // // string[] keys = dictionary.Keys.ToArray(); + // // if ((pos >= 0) && (pos < keys.Length)) + // // { + // // key = keys[pos]; + // // } + // // else + // // { + // // throw new Exception("Strange Current Position in Dictionary " + pos); + // // } + // // } + // // else + // // { + // // key = keyVariable.ConvertToUserVariable(engine); + // // } + // // return (dictionary, key); + // //} + // //else + // //{ + // // throw new Exception("Variable " + dicVariable + " is not Dictionary"); + // //} + // var dictionary = dicVariable.ExpandUserVariableAsDictinary(engine); + // var v = dicVariable.GetRawVariable(engine); + // string keyVariable = command.ExpandValueOrUserVariable(keyName, "Key", engine); + // string key; + // if (string.IsNullOrEmpty(keyVariable)) + // { + // int pos = v.CurrentPosition; + // string[] keys = dictionary.Keys.ToArray(); + // if ((pos >= 0) && (pos < keys.Length)) + // { + // key = keys[pos]; + // } + // else + // { + // throw new Exception("Strange Current Position in Dictionary " + pos); + // } + // } + // else + // { + // key = keyVariable.ExpandValueOrUserVariable(engine); + // } + // return (dictionary, key); + //} - // Check Items - foreach (DataRow row in table.Rows) - { - string k = (row.Field("Keys") ?? "").ConvertToUserVariable(engine); - if (k == "") - { - throw new Exception("Key value is empty."); - } - //if (keys.Contains(k)) - //{ - // throw new Exception("Duplicate Key. Name: '" + k + "'"); - //} - //else - //{ - // keys.Add(k); - //} - } + ///// + ///// add new item to Dictionary from DataTable. check key name is empty + ///// + ///// + ///// + ///// + ///// + //public static void AddDataAndValueFromDataTable(this Dictionary dic, DataTable table, Engine.AutomationEngineInstance engine) + //{ + // // Check Items + // foreach (DataRow row in table.Rows) + // { + // string k = (row.Field("Keys") ?? "").ExpandValueOrUserVariable(engine); + // if (k == "") + // { + // throw new Exception("Key value is empty."); + // } + // } - // Add Items - foreach (DataRow row in table.Rows) - { - var key = row.Field("Keys").ConvertToUserVariable(engine); - var value = (row.Field("Values") ?? "").ConvertToUserVariable(engine); - dic.Add(key, value); - } - } + // // Add Items + // foreach (DataRow row in table.Rows) + // { + // var key = row.Field("Keys").ExpandValueOrUserVariable(engine); + // var value = (row.Field("Values") ?? "").ExpandValueOrUserVariable(engine); + // dic.Add(key, value); + // } + //} } } diff --git a/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsDataTableCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsDataTableCommand.cs index d70c8fda8..cde1248f5 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsDataTableCommand.cs @@ -8,15 +8,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Get Addresses As DataTable")] [Attributes.ClassAttributes.Description("This command allows you to get Addresses from EMail.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Addresses from EMail.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitGetAddressesAsDataTableCommand : ScriptCommand + public sealed class MailKitGetAddressesAsDataTableCommand : ScriptCommand, ICanHandleDataTable { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_InputEMailName))] @@ -38,10 +39,8 @@ public MailKitGetAddressesAsDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var lst = this.GetMailKitEMailAddresses(nameof(v_MailName), nameof(v_AddressesType), engine); DataTable addresses = new DataTable(); @@ -51,7 +50,8 @@ public override void RunCommand(object sender) { addresses.Rows.Add(new object[] { item.Name, item.Address }); } - addresses.StoreInUserVariable(engine, v_AddressesDataTable); + //addresses.StoreInUserVariable(engine, v_AddressesDataTable); + this.StoreDataTableInUserVariable(addresses, nameof(v_AddressesDataTable), engine); } } } diff --git a/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsDictionaryCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsDictionaryCommand.cs index 500e37ad2..b14b5c07c 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsDictionaryCommand.cs @@ -8,15 +8,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Get Addresses As Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to get Addresses from EMail.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Addresses from EMail.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitGetAddressesAsDictionaryCommand : ScriptCommand + public sealed class MailKitGetAddressesAsDictionaryCommand : ScriptCommand, ICanHandleDictionary { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_InputEMailName))] @@ -38,10 +39,8 @@ public MailKitGetAddressesAsDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var lst = this.GetMailKitEMailAddresses(nameof(v_MailName), nameof(v_AddressesType), engine); Dictionary addresses = new Dictionary(); @@ -49,7 +48,9 @@ public override void RunCommand(object sender) { addresses.Add(item.Name, item.Address); } - addresses.StoreInUserVariable(engine, v_AddressesDictionary); + + //addresses.StoreInUserVariable(engine, v_AddressesDictionary); + this.StoreDictionaryInUserVariable(addresses, nameof(v_AddressesDictionary), engine); } } } diff --git a/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsListCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsListCommand.cs index 2ab8303c9..77098ad33 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsListCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitGetAddressesAsListCommand.cs @@ -8,15 +8,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Get Addresses As List")] [Attributes.ClassAttributes.Description("This command allows you to get Addresses from EMail.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Addresses from EMail.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitGetAddressesAsListCommand : ScriptCommand + public sealed class MailKitGetAddressesAsListCommand : ScriptCommand, ICanHandleList { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_InputEMailName))] @@ -38,18 +39,17 @@ public MailKitGetAddressesAsListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var lst = this.GetMailKitEMailAddresses(nameof(v_MailName), nameof(v_AddressesType), engine); - List addresses = new List(); + var addresses = new List(); foreach(MimeKit.MailboxAddress item in lst.Cast()) { addresses.Add(item.Address); } - addresses.StoreInUserVariable(engine, v_AddressesList); + //addresses.StoreInUserVariable(engine, v_AddressesList); + this.StoreListInUserVariable(addresses, nameof(v_AddressesList), engine); } } } diff --git a/taskt/Core/Automation/Commands/EMail/MailKitGetEMailFromEMailListCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitGetEMailFromEMailListCommand.cs index d9cd93dc6..c639dcc80 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitGetEMailFromEMailListCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitGetEMailFromEMailListCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Get EMail From EMailList")] [Attributes.ClassAttributes.Description("This command allows you to get EMail from EMailList.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get EMail from EMailList.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitGetEMailFromEMailListCommand : ScriptCommand + public sealed class MailKitGetEMailFromEMailListCommand : ScriptCommand { [XmlAttribute] [PropertyDescription("EMailList Variable Name")] @@ -55,11 +56,9 @@ public MailKitGetEMailFromEMailListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var mails = v_MailListName.GetMailKitEMailListVariable(engine); + var mails = v_MailListName.ExpandUserVariableAsEMailList(engine); int index; if (String.IsNullOrEmpty(v_Index)) @@ -69,7 +68,7 @@ public override void RunCommand(object sender) } else { - index = this.ConvertToUserVariableAsInteger(nameof(v_Index), engine); + index = this.ExpandValueOrUserVariableAsInteger(nameof(v_Index), engine); } if (index < 0) diff --git a/taskt/Core/Automation/Commands/EMail/MailKitGetEMailTextCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitGetEMailTextCommand.cs index 2a7231c0c..61f87d4fc 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitGetEMailTextCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitGetEMailTextCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Get EMail Text")] [Attributes.ClassAttributes.Description("This command allows you to get Text from EMail.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Text from EMail.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitGetEMailTextCommand : ScriptCommand + public sealed class MailKitGetEMailTextCommand : ScriptCommand, ICanHandleDateTime { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_InputEMailName))] @@ -41,19 +42,17 @@ public class MailKitGetEMailTextCommand : ScriptCommand public MailKitGetEMailTextCommand() { - this.CommandName = "MailKitGetEMailTextCommand"; - this.SelectionName = "Get EMail Text"; - this.CommandEnabled = true; - this.CustomRendering = true; + //this.CommandName = "MailKitGetEMailTextCommand"; + //this.SelectionName = "Get EMail Text"; + //this.CommandEnabled = true; + //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var mail = v_MailName.ExpandUserVariableAsEmail(engine); - var mail = v_MailName.GetMailKitEMailVariable(engine); - - var textType = this.GetUISelectionValue(nameof(v_TextType), engine); + var textType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_TextType), engine); string res = ""; switch (textType) @@ -93,11 +92,13 @@ public override void RunCommand(object sender) // Date case "date": - (mail.Date.DateTime).StoreInUserVariable(engine, v_ResultVariable); + //(mail.Date.DateTime).StoreInUserVariable(engine, v_ResultVariable); + this.StoreDateTimeInUserVariable((mail.Date.DateTime), nameof(v_ResultVariable), engine); return; case "resent-date": - (mail.ResentDate.DateTime).StoreInUserVariable(engine, v_ResultVariable); + //(mail.ResentDate.DateTime).StoreInUserVariable(engine, v_ResultVariable); + this.StoreDateTimeInUserVariable((mail.ResentDate.Date), nameof(v_ResultVariable), engine); return; } diff --git a/taskt/Core/Automation/Commands/EMail/MailKitGetEmailAttachmentsNameCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitGetEmailAttachmentsNameCommand.cs index 3a6d9c352..1b50d1e50 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitGetEmailAttachmentsNameCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitGetEmailAttachmentsNameCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] - [Attributes.ClassAttributes.CommandSettings("Get Email Attachments Name")] - [Attributes.ClassAttributes.Description("This command allows you to get Attachment File Name.")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Attachment File Name.")] + [Attributes.ClassAttributes.CommandSettings("Get EMail Attachments Name")] + [Attributes.ClassAttributes.Description("This command allows you to get EMail Attachment File Name.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get EMail Attachment File Name.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitGetEmailAttachmentsNameCommand : ScriptCommand + public sealed class MailKitGetEMailAttachmentsNameCommand : ScriptCommand, ICanHandleList { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_InputEMailName))] @@ -24,7 +25,7 @@ public class MailKitGetEmailAttachmentsNameCommand : ScriptCommand [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] public string v_AttachmentsList { get; set; } - public MailKitGetEmailAttachmentsNameCommand() + public MailKitGetEMailAttachmentsNameCommand() { //this.CommandName = "MailKitGetEmailAttachmentsNameCommand"; //this.SelectionName = "Get Email Attachments Name"; @@ -32,15 +33,14 @@ public MailKitGetEmailAttachmentsNameCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var mail = v_MailName.GetMailKitEMailVariable(engine); + var mail = v_MailName.ExpandUserVariableAsEmail(engine); var attachments = mail.Attachments.Cast().Select(a => a.FileName).ToList(); - attachments.StoreInUserVariable(engine, v_AttachmentsList); + //attachments.StoreInUserVariable(engine, v_AttachmentsList); + this.StoreListInUserVariable(attachments, nameof(v_AttachmentsList), engine); } } } diff --git a/taskt/Core/Automation/Commands/EMail/MailKitLoadEmailCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitLoadEmailCommand.cs index ab599b9f0..8d96882c3 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitLoadEmailCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitLoadEmailCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] - [Attributes.ClassAttributes.CommandSettings("Load Email")] + [Attributes.ClassAttributes.CommandSettings("Load EMail")] [Attributes.ClassAttributes.Description("This command allows you to load EMail from File.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to load EMail from File.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitLoadEmailCommand : ScriptCommand + public sealed class MailKitLoadEMailCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_EMailPath))] @@ -38,7 +39,7 @@ public class MailKitLoadEmailCommand : ScriptCommand [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_WaitTime))] public string v_WaitForFile { get; set; } - public MailKitLoadEmailCommand() + public MailKitLoadEMailCommand() { //this.CommandName = "MailKitLoadEmailCommand"; //this.SelectionName = "Load Email"; @@ -46,10 +47,8 @@ public MailKitLoadEmailCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //string path = FilePathControls.FormatFilePath_NoFileCounter(v_FilePath, engine, new List() { "eml", "msg", "txt" }, true); string path = FilePathControls.WaitForFile(this, nameof(v_FilePath), nameof(v_WaitForFile), engine); diff --git a/taskt/Core/Automation/Commands/EMail/MailKitRecieveEmailListUsingIMAPCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitRecieveEmailListUsingIMAPCommand.cs index 5c82271ca..f44d7812b 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitRecieveEmailListUsingIMAPCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitRecieveEmailListUsingIMAPCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Recieve EMailList Using IMAP")] [Attributes.ClassAttributes.Description("This command allows you to get EMailList(Emails) using IMAP protocol.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get EMailList(Emails) using IMAP protocol. Result Variable Type is EMailList.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitRecieveEmailListUsingIMAPCommand : ScriptCommand + public sealed class MailKitRecieveEMailListUsingIMAPCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_Host))] @@ -44,7 +45,7 @@ public class MailKitRecieveEmailListUsingIMAPCommand : ScriptCommand [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_OutputMailListName))] public string v_MailListName { get; set; } - public MailKitRecieveEmailListUsingIMAPCommand() + public MailKitRecieveEMailListUsingIMAPCommand() { //this.CommandName = "MailKitRecieveEMailListUsingIMAPCommand"; //this.SelectionName = "Recieve EMailList Using IMAP"; @@ -52,17 +53,15 @@ public MailKitRecieveEmailListUsingIMAPCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - // imap host - string pop = v_IMAPHost.ConvertToUserVariable(engine); - var port = this.ConvertToUserVariableAsInteger(nameof(v_IMAPPort), engine); + string pop = v_IMAPHost.ExpandValueOrUserVariable(engine); + var port = this.ExpandValueOrUserVariableAsInteger(nameof(v_IMAPPort), engine); // auth - string user = v_IMAPUserName.ConvertToUserVariable(engine); - string pass = v_IMAPPassword.ConvertToUserVariable(engine); + string user = v_IMAPUserName.ExpandValueOrUserVariable(engine); + string pass = v_IMAPPassword.ExpandValueOrUserVariable(engine); using (var client = new MailKit.Net.Imap.ImapClient()) { diff --git a/taskt/Core/Automation/Commands/EMail/MailKitRecieveEmailListUsingPOPCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitRecieveEmailListUsingPOPCommand.cs index 1c50e1656..a5268aa38 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitRecieveEmailListUsingPOPCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitRecieveEmailListUsingPOPCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] [Attributes.ClassAttributes.CommandSettings("Recieve EMailList Using POP")] [Attributes.ClassAttributes.Description("This command allows you to get EMailList(EMails) using POP protocol.")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get MailList(EMails) using POP protocol. Result Variable Type is EMailList.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get EMailList(EMails) using POP protocol. Result Variable Type is EMailList.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitRecieveEmailListUsingPOPCommand : ScriptCommand + public sealed class MailKitRecieveEMailListUsingPOPCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_Host))] @@ -44,7 +45,7 @@ public class MailKitRecieveEmailListUsingPOPCommand : ScriptCommand [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_OutputMailListName))] public string v_MailListName { get; set; } - public MailKitRecieveEmailListUsingPOPCommand() + public MailKitRecieveEMailListUsingPOPCommand() { //this.CommandName = "MailKitRecieveEMailListUsingPOPCommand"; //this.SelectionName = "Recieve EMailList Using POP"; @@ -52,17 +53,15 @@ public MailKitRecieveEmailListUsingPOPCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - // pop host - string pop = v_POPHost.ConvertToUserVariable(engine); - var port = this.ConvertToUserVariableAsInteger(nameof(v_POPPort), engine); + string pop = v_POPHost.ExpandValueOrUserVariable(engine); + var port = this.ExpandValueOrUserVariableAsInteger(nameof(v_POPPort), engine); // auth - string user = v_POPUserName.ConvertToUserVariable(engine); - string pass = v_POPPassword.ConvertToUserVariable(engine); + string user = v_POPUserName.ExpandValueOrUserVariable(engine); + string pass = v_POPPassword.ExpandValueOrUserVariable(engine); using (var client = new MailKit.Net.Pop3.Pop3Client()) { diff --git a/taskt/Core/Automation/Commands/EMail/MailKitSaveEmailAttachmentsCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitSaveEmailAttachmentsCommand.cs index 4d4a495e4..e3d2bb0c3 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitSaveEmailAttachmentsCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitSaveEmailAttachmentsCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] - [Attributes.ClassAttributes.CommandSettings("Save Email Attachments")] + [Attributes.ClassAttributes.CommandSettings("Save EMail Attachments")] [Attributes.ClassAttributes.Description("This command allows you to save EMail Attachments.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to save EMail Attachments.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitSaveEmailAttachmentsCommand : ScriptCommand + public sealed class MailKitSaveEMailAttachmentsCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_InputEMailName))] @@ -30,7 +31,7 @@ public class MailKitSaveEmailAttachmentsCommand : ScriptCommand [PropertyDisplayText(true, "Path")] public string v_SaveFolder { get; set; } - public MailKitSaveEmailAttachmentsCommand() + public MailKitSaveEMailAttachmentsCommand() { //this.CommandName = "MailKitSaveEmailAttachmentsCommand"; //this.SelectionName = "Save Email Attachments"; @@ -38,13 +39,11 @@ public MailKitSaveEmailAttachmentsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var mail = v_MailName.ExpandUserVariableAsEmail(engine); - var mail = v_MailName.GetMailKitEMailVariable(engine); - - var path = v_SaveFolder.ConvertToUserVariable(engine); + var path = v_SaveFolder.ExpandValueOrUserVariable(engine); foreach(var attachment in mail.Attachments) { diff --git a/taskt/Core/Automation/Commands/EMail/MailKitSaveEmailCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitSaveEmailCommand.cs index e613aa8b9..098eda377 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitSaveEmailCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitSaveEmailCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] - [Attributes.ClassAttributes.CommandSettings("Save Email")] + [Attributes.ClassAttributes.CommandSettings("Save EMail")] [Attributes.ClassAttributes.Description("This command allows you to Save EMail.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Save EMail.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitSaveEmailCommand : ScriptCommand + public sealed class MailKitSaveEMailCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_InputEMailName))] @@ -34,7 +35,7 @@ public class MailKitSaveEmailCommand : ScriptCommand //[PropertyDisplayText(true, "Path")] public string v_SavePath { get; set; } - public MailKitSaveEmailCommand() + public MailKitSaveEMailCommand() { //this.CommandName = "MailKitSaveEmailCommand"; //this.SelectionName = "Save Email"; @@ -42,11 +43,9 @@ public MailKitSaveEmailCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var mail = v_MailName.GetMailKitEMailVariable(engine); + var mail = v_MailName.ExpandUserVariableAsEmail(engine); //string path; //if (FilePathControls.ContainsFileCounter(v_SavePath, engine)) @@ -57,7 +56,7 @@ public override void RunCommand(object sender) //{ // path = FilePathControls.FormatFilePath_NoFileCounter(v_SavePath, engine, "eml"); //} - var path = this.ConvertToUserVariableAsFilePath(nameof(v_SavePath), engine); + var path = this.ExpandValueOrUserVariableAsFilePath(nameof(v_SavePath), engine); mail.WriteTo(path); } diff --git a/taskt/Core/Automation/Commands/EMail/MailKitSendEmailCommand.cs b/taskt/Core/Automation/Commands/EMail/MailKitSendEmailCommand.cs index f997958e1..afe9710b3 100644 --- a/taskt/Core/Automation/Commands/EMail/MailKitSendEmailCommand.cs +++ b/taskt/Core/Automation/Commands/EMail/MailKitSendEmailCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("EMail Commands")] + [Attributes.ClassAttributes.Group("EMail")] [Attributes.ClassAttributes.SubGruop("")] - [Attributes.ClassAttributes.CommandSettings("Send Email")] + [Attributes.ClassAttributes.CommandSettings("Send EMail")] [Attributes.ClassAttributes.Description("This command allows you to send EMail using SMTP protocol.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to send an EMail and have access to SMTP server credentials to generate an EMail.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MailKitSendEmailCommand : ScriptCommand + public sealed class MailKitSendEMailCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_Host))] @@ -56,14 +57,16 @@ public class MailKitSendEmailCommand : ScriptCommand [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_EmailAddress))] [PropertyDescription("CC EMail Address")] - [PropertyValidationRule("CC Email", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyValidationRule("CC", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyIsOptional(true, "")] [PropertyDisplayText(true, "CC")] public string v_SMTPCCEmail { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_EmailAddress))] [PropertyDescription("BCC EMail Address")] - [PropertyValidationRule("BCC Email", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyValidationRule("BCC", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyIsOptional(true, "")] [PropertyDisplayText(true, "BCC")] public string v_SMTPBCCEmail { get; set; } @@ -105,7 +108,7 @@ public class MailKitSendEmailCommand : ScriptCommand [PropertyVirtualProperty(nameof(EMailControls), nameof(EMailControls.v_SecureOption))] public string v_SMTPSecureOption { get; set; } - public MailKitSendEmailCommand() + public MailKitSendEMailCommand() { //this.CommandName = "MailKitSendEmailCommand"; //this.SelectionName = "Send Email"; @@ -113,32 +116,30 @@ public MailKitSendEmailCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - // from, to, cc, bcc, subject, body - string from = v_SMTPFromEmail.ConvertToUserVariable(engine); - string to = v_SMTPToEmail.ConvertToUserVariable(engine); - string cc = v_SMTPCCEmail.ConvertToUserVariable(engine); - string bcc = v_SMTPBCCEmail.ConvertToUserVariable(engine); - string subject = v_SMTPSubject.ConvertToUserVariable(engine); - string body = v_SMTPBody.ConvertToUserVariable(engine); + string from = v_SMTPFromEmail.ExpandValueOrUserVariable(engine); + string to = v_SMTPToEmail.ExpandValueOrUserVariable(engine); + string cc = v_SMTPCCEmail.ExpandValueOrUserVariable(engine); + string bcc = v_SMTPBCCEmail.ExpandValueOrUserVariable(engine); + string subject = v_SMTPSubject.ExpandValueOrUserVariable(engine); + string body = v_SMTPBody.ExpandValueOrUserVariable(engine); // smtp host - string smtp = v_SMTPHost.ConvertToUserVariable(engine); - var port = this.ConvertToUserVariableAsInteger(nameof(v_SMTPPort), engine); + string smtp = v_SMTPHost.ExpandValueOrUserVariable(engine); + var port = this.ExpandValueOrUserVariableAsInteger(nameof(v_SMTPPort), engine); // auth - string user = v_SMTPUserName.ConvertToUserVariable(engine); - if (String.IsNullOrEmpty(user)) + string user = v_SMTPUserName.ExpandValueOrUserVariable(engine); + if (string.IsNullOrEmpty(user)) { user = from; } - string pass = v_SMTPPassword.ConvertToUserVariable(engine); + string pass = v_SMTPPassword.ExpandValueOrUserVariable(engine); // attachment - string attachmentFilePath = v_SMTPAttachment.ConvertToUserVariable(engine); + string attachmentFilePath = v_SMTPAttachment.ExpandValueOrUserVariable(engine); var message = new MimeKit.MimeMessage(); message.From.Add(new MimeKit.MailboxAddress(from, from)); @@ -149,7 +150,7 @@ public override void RunCommand(object sender) message.To.Add(new MimeKit.MailboxAddress(address, address)); } - if (!String.IsNullOrEmpty(cc)) + if (!string.IsNullOrEmpty(cc)) { var ccArray = cc.Split(';'); foreach(string address in ccArray) @@ -158,7 +159,7 @@ public override void RunCommand(object sender) } } - if (!String.IsNullOrEmpty(bcc)) + if (!string.IsNullOrEmpty(bcc)) { var bccArray = bcc.Split(';'); foreach (string address in bccArray) @@ -172,7 +173,7 @@ public override void RunCommand(object sender) // has attachment file? if (!string.IsNullOrEmpty(attachmentFilePath)) { - if (!System.IO.File.Exists(pass)) + if (!System.IO.File.Exists(attachmentFilePath)) { throw new Exception("Attachment File '" + v_SMTPAttachment + "' does not Exists"); } diff --git a/taskt/Core/Automation/Commands/EMailControls.cs b/taskt/Core/Automation/Commands/EMailControls.cs index 3fb4d80f8..8fad02b01 100644 --- a/taskt/Core/Automation/Commands/EMailControls.cs +++ b/taskt/Core/Automation/Commands/EMailControls.cs @@ -24,6 +24,7 @@ internal static class EMailControls [PropertyInstanceType(PropertyInstanceType.InstanceType.MailKitEMail, true)] [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyDisplayText(true, "EMail")] + [PropertyParameterOrder(5000)] public static string v_InputEMailName { get; } /// @@ -40,6 +41,7 @@ internal static class EMailControls [PropertyInstanceType(PropertyInstanceType.InstanceType.MailKitEMail, true)] [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyDisplayText(true, "EMail")] + [PropertyParameterOrder(5000)] public static string v_OutputEMailName { get; } /// @@ -57,6 +59,7 @@ internal static class EMailControls [PropertyInstanceType(PropertyInstanceType.InstanceType.MailKitEMailList, true)] [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyDisplayText(true, "EMailList")] + [PropertyParameterOrder(5000)] public static string v_OutputMailListName { get; } /// @@ -78,6 +81,7 @@ internal static class EMailControls [PropertyUISelectionOption("Resent-Reply-To")] [PropertyValidationRule("Address Type", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Type")] + [PropertyParameterOrder(5000)] public static string v_AddressType { get; } /// @@ -92,6 +96,7 @@ internal static class EMailControls [PropertyValidationRule("Host", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyTextBoxSetting(1, false)] [PropertyDisplayText(true, "Host")] + [PropertyParameterOrder(5000)] public static string v_Host { get; set; } /// @@ -105,6 +110,7 @@ internal static class EMailControls [PropertyValueRange(0, 65535)] [PropertyTextBoxSetting(1, false)] [PropertyDisplayText(true, "Port")] + [PropertyParameterOrder(5000)] public static string v_Port { get; } /// @@ -119,6 +125,7 @@ internal static class EMailControls [PropertyShowSampleUsageInDescription(true)] [PropertyTextBoxSetting(1, false)] [PropertyDisplayText(true, "User")] + [PropertyParameterOrder(5000)] public static string v_UserName { get; } /// @@ -132,6 +139,7 @@ internal static class EMailControls [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("Password", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyTextBoxSetting(1, false)] + [PropertyParameterOrder(5000)] public static string v_Password { get; set; } /// @@ -149,6 +157,7 @@ internal static class EMailControls [PropertyUISelectionOption("Use SSL or TLS")] [PropertyUISelectionOption("STARTTLS")] [PropertyUISelectionOption("STARTTLS When Available")] + [PropertyParameterOrder(5000)] public static string v_SecureOption { get; } /// @@ -163,6 +172,7 @@ internal static class EMailControls [PropertyValidationRule("EMail Address", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyTextBoxSetting(1, false)] [PropertyDisplayText(true, "EMail Address")] + [PropertyParameterOrder(5000)] public static string v_EmailAddress { get; } /// @@ -178,16 +188,17 @@ internal static class EMailControls [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Path", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Path")] + [PropertyParameterOrder(5000)] public static string v_EMailPath { get; } /// - /// get EMailList Variable from variable name specified argument + /// expand user variable as EMailList /// /// /// /// - /// - public static List GetMailKitEMailListVariable(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) + /// value is not EMailList + public static List ExpandUserVariableAsEMailList(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) { Script.ScriptVariable v = variableName.GetRawVariable(engine); if (v.VariableValue is List ml) @@ -201,13 +212,13 @@ internal static class EMailControls } /// - /// get EMail Variable from variable name specified argument + /// expand user variable as EMail /// /// /// /// - /// - public static MimeKit.MimeMessage GetMailKitEMailVariable(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) + /// value is not EMail + public static MimeKit.MimeMessage ExpandUserVariableAsEmail(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) { Script.ScriptVariable v = variableName.GetRawVariable(engine); if (v.VariableValue is MimeKit.MimeMessage mail) @@ -220,28 +231,44 @@ public static MimeKit.MimeMessage GetMailKitEMailVariable(this string variableNa } } - private static MimeKit.MimeMessage GetMailKitEMailVariable(this ScriptCommand command, string mailParameterName, Engine.AutomationEngineInstance engine) + /// + /// expand user variable as EMail from specified parameter + /// + /// + /// + /// + /// + private static MimeKit.MimeMessage ExpandUserVariableAsEmail(this ScriptCommand command, string mailParameterName, Engine.AutomationEngineInstance engine) { var prop = command.GetProperty(mailParameterName); string mailName = prop.GetValue(command)?.ToString() ?? ""; - return mailName.GetMailKitEMailVariable(engine); + return mailName.ExpandUserVariableAsEmail(engine); } - public static void StoreInUserVariable(this List value, Core.Automation.Engine.AutomationEngineInstance sender, string targetVariable) + public static void StoreInUserVariable(this List value, Core.Automation.Engine.AutomationEngineInstance engine, string targetVariable) { - ExtensionMethods.StoreInUserVariable(targetVariable, value, sender, false); + ExtensionMethods.StoreInUserVariable(targetVariable, value, engine, false); } - public static void StoreInUserVariable(this MimeKit.MimeMessage value, Core.Automation.Engine.AutomationEngineInstance sender, string targetVariable) + public static void StoreInUserVariable(this MimeKit.MimeMessage value, Core.Automation.Engine.AutomationEngineInstance engine, string targetVariable) { - ExtensionMethods.StoreInUserVariable(targetVariable, value, sender, false); + ExtensionMethods.StoreInUserVariable(targetVariable, value, engine, false); } + /// + /// get address from EMail + /// + /// + /// + /// + /// + /// + /// public static MimeKit.InternetAddressList GetMailKitEMailAddresses(this ScriptCommand command, string mailParameterName, string typeParameterName, Engine.AutomationEngineInstance engine) { - var mail = command.GetMailKitEMailVariable(mailParameterName, engine); + var mail = command.ExpandUserVariableAsEmail(mailParameterName, engine); - var addressType = command.GetUISelectionValue(typeParameterName, engine); + var addressType = command.ExpandValueOrUserVariableAsSelectionItem(typeParameterName, engine); switch (addressType) { case "from": @@ -269,9 +296,16 @@ public static MimeKit.InternetAddressList GetMailKitEMailAddresses(this ScriptCo } } + /// + /// get security option + /// + /// + /// + /// + /// public static MailKit.Security.SecureSocketOptions GetMailKitSecureOption(this ScriptCommand command, string propertyName, Engine.AutomationEngineInstance engine) { - var secureOption = command.GetUISelectionValue(propertyName, engine); + var secureOption = command.ExpandValueOrUserVariableAsSelectionItem(propertyName, engine); var option = MailKit.Security.SecureSocketOptions.Auto; switch (secureOption) diff --git a/taskt/Core/Automation/Commands/Engine/ErrorHandlingCommand.cs b/taskt/Core/Automation/Commands/Engine/ErrorHandlingCommand.cs index bc3319ed5..0020da53c 100644 --- a/taskt/Core/Automation/Commands/Engine/ErrorHandlingCommand.cs +++ b/taskt/Core/Automation/Commands/Engine/ErrorHandlingCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Engine Commands")] + [Attributes.ClassAttributes.Group("Engine")] [Attributes.ClassAttributes.CommandSettings("Error Handling")] [Attributes.ClassAttributes.Description("This command specifies what to do after an error is encountered.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to define how your script should behave when an error is encountered.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Thread.Sleep' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_error))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ErrorHandlingCommand : ScriptCommand + public sealed class ErrorHandlingCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -35,11 +36,9 @@ public ErrorHandlingCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var act = this.GetUISelectionValue(nameof(v_ErrorHandlingAction), engine); + var act = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ErrorHandlingAction), engine); switch (act) { case "stop processing": diff --git a/taskt/Core/Automation/Commands/Engine/GetBotStoreDataCommand.cs b/taskt/Core/Automation/Commands/Engine/GetBotStoreDataCommand.cs index 56905eecd..77d06e28a 100644 --- a/taskt/Core/Automation/Commands/Engine/GetBotStoreDataCommand.cs +++ b/taskt/Core/Automation/Commands/Engine/GetBotStoreDataCommand.cs @@ -20,14 +20,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Engine Commands")] + [Attributes.ClassAttributes.Group("Engine")] [Attributes.ClassAttributes.CommandSettings("Get BotStore Data")] [Attributes.ClassAttributes.Description("This command allows you to get data from tasktServer.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to retrieve data from tasktServer")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_server))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetBotStoreDataCommand : ScriptCommand + public sealed class GetBotStoreDataCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -62,13 +63,11 @@ public GetBotStoreDataCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var keyName = v_KeyName.ExpandValueOrUserVariable(engine); - var keyName = v_KeyName.ConvertToUserVariable(engine); - - var dataOption = this.GetUISelectionValue(nameof(v_DataOption), engine); + var dataOption = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_DataOption), engine); BotStoreRequest.RequestType requestType; if (dataOption == "Retrieve Entire Record") { diff --git a/taskt/Core/Automation/Commands/Engine/PauseScriptCommand.cs b/taskt/Core/Automation/Commands/Engine/PauseScriptCommand.cs index 3bc098abb..4b5650d8c 100644 --- a/taskt/Core/Automation/Commands/Engine/PauseScriptCommand.cs +++ b/taskt/Core/Automation/Commands/Engine/PauseScriptCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Engine Commands")] + [Attributes.ClassAttributes.Group("Engine")] [Attributes.ClassAttributes.CommandSettings("Pause Script")] [Attributes.ClassAttributes.Description("This command pauses the script for a set amount of time specified in milliseconds.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to pause your script for a specific amount of time. After the specified time is finished, the script will resume execution.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Thread.Sleep' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_pause))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class PauseScriptCommand : ScriptCommand + public sealed class PauseScriptCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -32,11 +33,9 @@ public PauseScriptCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var pauseLength = this.ConvertToUserVariableAsInteger(nameof(v_PauseLength), engine); + var pauseLength = this.ExpandValueOrUserVariableAsInteger(nameof(v_PauseLength), engine); System.Threading.Thread.Sleep(pauseLength); } diff --git a/taskt/Core/Automation/Commands/Engine/SetEngineDelayCommand.cs b/taskt/Core/Automation/Commands/Engine/SetEngineDelayCommand.cs index ab5b21d46..4ca303c41 100644 --- a/taskt/Core/Automation/Commands/Engine/SetEngineDelayCommand.cs +++ b/taskt/Core/Automation/Commands/Engine/SetEngineDelayCommand.cs @@ -8,14 +8,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Engine Commands")] + [Attributes.ClassAttributes.Group("Engine")] [Attributes.ClassAttributes.CommandSettings("Set Engine Delay")] [Attributes.ClassAttributes.Description("This command allows you to set delays between execution of commands in a running instance.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to change the execution speed between commands.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_pause))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetEngineDelayCommand : ScriptCommand + public sealed class SetEngineDelayCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -36,15 +37,13 @@ public SetEngineDelayCommand() //this.v_EngineSpeed = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var delay = this.ConvertToUserVariableAsInteger(nameof(v_EngineSpeed), engine); + var delay = this.ExpandValueOrUserVariableAsInteger(nameof(v_EngineSpeed), engine); engine.engineSettings.DelayBetweenCommands = delay; } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); diff --git a/taskt/Core/Automation/Commands/Engine/SetEnginePreferenceCommand.cs b/taskt/Core/Automation/Commands/Engine/SetEnginePreferenceCommand.cs index 9cdf0cf43..42b3c6ab8 100644 --- a/taskt/Core/Automation/Commands/Engine/SetEnginePreferenceCommand.cs +++ b/taskt/Core/Automation/Commands/Engine/SetEnginePreferenceCommand.cs @@ -6,13 +6,14 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Engine Commands")] + [Attributes.ClassAttributes.Group("Engine")] [Attributes.ClassAttributes.CommandSettings("Set Engine Preference")] [Attributes.ClassAttributes.Description("This command allows you to set preferences for engine behavior.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to change the engine behavior.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] - public class SetEnginePreferenceCommand : ScriptCommand + public sealed class SetEnginePreferenceCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -22,7 +23,6 @@ public class SetEnginePreferenceCommand : ScriptCommand [PropertyUISelectionOption("Start Variable Marker")] [PropertyUISelectionOption("End Variable Marker")] [PropertyUISelectionOption("Engine Delay")] - [PropertyUISelectionOption("Current Window Keyword")] [PropertyValidationRule("Parameter Type", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Parameter Type")] [PropertySelectionChangeEvent(nameof(cmbPreferenceCombobox_SelectedChanged))] @@ -43,13 +43,11 @@ public SetEnginePreferenceCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var preference = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_PreferenceType), engine); - var preference = this.GetUISelectionValue(nameof(v_PreferenceType), engine); - - var parameterValue = v_ParameterValue.ConvertToUserVariable(engine); + var parameterValue = v_ParameterValue.ExpandValueOrUserVariable(engine); switch (preference) { @@ -84,10 +82,6 @@ public override void RunCommand(object sender) throw new Exception("Engine Delay is not Number. Value: '" + parameterValue + "'"); } break; - - case "current window keyword": - engine.engineSettings.CurrentWindowKeyword = parameterValue; - break; } } @@ -98,11 +92,11 @@ private void cmbPreferenceCombobox_SelectedChanged(object sender, EventArgs e) { case "Enable Automatic Calculations": case "Disable Automatic Calculations": - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_ParameterValue), false); + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_ParameterValue), false); break; default: - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_ParameterValue), true); + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_ParameterValue), true); break; } } diff --git a/taskt/Core/Automation/Commands/Engine/ShowEngineContextCommand.cs b/taskt/Core/Automation/Commands/Engine/ShowEngineContextCommand.cs index 5bcef45fe..388bde51b 100644 --- a/taskt/Core/Automation/Commands/Engine/ShowEngineContextCommand.cs +++ b/taskt/Core/Automation/Commands/Engine/ShowEngineContextCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Engine Commands")] + [Attributes.ClassAttributes.Group("Engine")] [Attributes.ClassAttributes.CommandSettings("Show Engine Context")] [Attributes.ClassAttributes.Description("This command allows you to show a message to the user.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to present or display a value on screen to the user.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'MessageBox' and invokes VariableCommand to find variable data.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ShowEngineContextCommand : ScriptCommand + public sealed class ShowEngineContextCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -36,11 +37,9 @@ public ShowEngineContextCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var closeValue = this.ConvertToUserVariableAsInteger(nameof(v_AutoCloseAfter), engine); + var closeValue = this.ExpandValueOrUserVariableAsInteger(nameof(v_AutoCloseAfter), engine); //automatically close messageboxes for server requests if (engine.serverExecution && closeValue <= 0) diff --git a/taskt/Core/Automation/Commands/Engine/UploadBotStoreDataCommand.cs b/taskt/Core/Automation/Commands/Engine/UploadBotStoreDataCommand.cs index baa23f872..bd352d265 100644 --- a/taskt/Core/Automation/Commands/Engine/UploadBotStoreDataCommand.cs +++ b/taskt/Core/Automation/Commands/Engine/UploadBotStoreDataCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Engine Commands")] + [Attributes.ClassAttributes.Group("Engine")] [Attributes.ClassAttributes.CommandSettings("Upload BotStore Data")] [Attributes.ClassAttributes.Description("This command allows you to upload data to a local tasktServer bot store")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to upload or share data across bots.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_server))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UploadBotStoreDataCommand : ScriptCommand + public sealed class UploadBotStoreDataCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -45,12 +46,10 @@ public UploadBotStoreDataCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var keyName = v_KeyName.ConvertToUserVariable(engine); - var keyValue = v_InputValue.ConvertToUserVariable(engine); + var keyName = v_KeyName.ExpandValueOrUserVariable(engine); + var keyValue = v_InputValue.ExpandValueOrUserVariable(engine); try { diff --git a/taskt/Core/Automation/Commands/Error/CatchExceptionCommand.cs b/taskt/Core/Automation/Commands/Error/CatchExceptionCommand.cs index a26b4399b..3902b34eb 100644 --- a/taskt/Core/Automation/Commands/Error/CatchExceptionCommand.cs +++ b/taskt/Core/Automation/Commands/Error/CatchExceptionCommand.cs @@ -4,14 +4,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Error Handling Commands")] + [Attributes.ClassAttributes.Group("Error Handling")] [Attributes.ClassAttributes.CommandSettings("Catch Exception")] [Attributes.ClassAttributes.Description("This command allows you to define actions that should occur after encountering an error.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to define how your script should behave when an error is encountered.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_try))] [Attributes.ClassAttributes.EnableAutomateRender(true, true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CatchExceptionCommand : ScriptCommand + public sealed class CatchExceptionCommand : ScriptCommand, IDelimitersOfStructuredCommands { public string ErrorMessage { get; set; } public string StackTrace { get; set; } @@ -24,7 +25,7 @@ public CatchExceptionCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //no execution required, used as a marker by the Automation Engine } diff --git a/taskt/Core/Automation/Commands/Error/EndTryCommand.cs b/taskt/Core/Automation/Commands/Error/EndTryCommand.cs index e26ec7e60..8ceddb63f 100644 --- a/taskt/Core/Automation/Commands/Error/EndTryCommand.cs +++ b/taskt/Core/Automation/Commands/Error/EndTryCommand.cs @@ -4,14 +4,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Error Handling Commands")] + [Attributes.ClassAttributes.Group("Error Handling")] [Attributes.ClassAttributes.CommandSettings("End Try")] [Attributes.ClassAttributes.Description("This command specifies the end of a try/catch block.")] [Attributes.ClassAttributes.UsesDescription("Use this command to enclose your try/catch block.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_try))] [Attributes.ClassAttributes.EnableAutomateRender(true, true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class EndTryCommand : ScriptCommand + public sealed class EndTryCommand : ScriptCommand, IEndOfStacturedCommand { public EndTryCommand() { @@ -21,7 +22,7 @@ public EndTryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //no execution required, used as a marker by the Automation Engine } diff --git a/taskt/Core/Automation/Commands/Error/FinallyCommand.cs b/taskt/Core/Automation/Commands/Error/FinallyCommand.cs index 233a52221..54e701bf8 100644 --- a/taskt/Core/Automation/Commands/Error/FinallyCommand.cs +++ b/taskt/Core/Automation/Commands/Error/FinallyCommand.cs @@ -4,14 +4,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Error Handling Commands")] + [Attributes.ClassAttributes.Group("Error Handling")] [Attributes.ClassAttributes.CommandSettings("Finally")] [Attributes.ClassAttributes.Description("This command specifies execution that should occur whether or not an error occured")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to always execute a specific command before leaving the try/catch block")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_try))] [Attributes.ClassAttributes.EnableAutomateRender(true, true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class FinallyCommand : ScriptCommand + public sealed class FinallyCommand : ScriptCommand, IDelimitersOfStructuredCommands { public FinallyCommand() { @@ -21,7 +22,7 @@ public FinallyCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender, Script.ScriptAction parentCommand) + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) { //no execution required, used as a marker by the Automation Engine } diff --git a/taskt/Core/Automation/Commands/Error/IHaveTryAdditionalCommands.cs b/taskt/Core/Automation/Commands/Error/IHaveTryAdditionalCommands.cs new file mode 100644 index 000000000..ac137ed14 --- /dev/null +++ b/taskt/Core/Automation/Commands/Error/IHaveTryAdditionalCommands.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// this command has Additional Commands for Error + /// + public interface IHaveErrorAdditionalCommands : IHaveAdditionalCommands + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/Error/ThrowExceptionCommand.cs b/taskt/Core/Automation/Commands/Error/ThrowExceptionCommand.cs index 9b1cd5896..00add7bc0 100644 --- a/taskt/Core/Automation/Commands/Error/ThrowExceptionCommand.cs +++ b/taskt/Core/Automation/Commands/Error/ThrowExceptionCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Error Handling Commands")] + [Attributes.ClassAttributes.Group("Error Handling")] [Attributes.ClassAttributes.CommandSettings("Throw Exception")] [Attributes.ClassAttributes.Description("This command allows you to throw an exception error.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to throw an exception error")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_try))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ThrowExceptionCommand : ScriptCommand + public sealed class ThrowExceptionCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_MultiLinesTextBox))] @@ -34,10 +35,8 @@ public ThrowExceptionCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - string message; if (String.IsNullOrEmpty(v_Message)) { @@ -45,7 +44,7 @@ public override void RunCommand(object sender) } else { - message = v_Message.ConvertToUserVariable(engine); + message = v_Message.ExpandValueOrUserVariable(engine); } throw new Exception(message); diff --git a/taskt/Core/Automation/Commands/Error/TryCommand.cs b/taskt/Core/Automation/Commands/Error/TryCommand.cs index 4ddbddf37..f461a26aa 100644 --- a/taskt/Core/Automation/Commands/Error/TryCommand.cs +++ b/taskt/Core/Automation/Commands/Error/TryCommand.cs @@ -1,17 +1,19 @@ using System; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Error Handling Commands")] + [Attributes.ClassAttributes.Group("Error Handling")] [Attributes.ClassAttributes.CommandSettings("Try")] [Attributes.ClassAttributes.Description("This command allows embedding commands and will automatically move to the 'catch' handler")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to handle potential errors that could occur.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_try))] [Attributes.ClassAttributes.EnableAutomateRender(true, true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class TryCommand : ScriptCommand + public sealed class TryCommand : ScriptCommand, IHaveErrorAdditionalCommands { public TryCommand() { @@ -21,11 +23,8 @@ public TryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender, Script.ScriptAction parentCommand) + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) { - //get engine - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - //get indexes of commands var startIndex = 0; var catchIndex = parentCommand.AdditionalScriptCommands.FindIndex(a => a.ScriptCommand is CatchExceptionCommand); @@ -49,10 +48,11 @@ public override void RunCommand(object sender, Script.ScriptAction parentCommand var catchCommandItem = parentCommand.AdditionalScriptCommands[catchIndex]; var catchCommand = (CatchExceptionCommand)catchCommandItem.ScriptCommand; - catchCommand.StackTrace = ex.ToString(); - catchCommand.ErrorMessage = ex.Message; - engine.AddVariable("Catch:StackTrace", catchCommand.StackTrace); - engine.AddVariable("Catch:ErrorMessage", catchCommand.ErrorMessage); + //catchCommand.StackTrace = ex.ToString(); + //catchCommand.ErrorMessage = ex.Message; + //engine.AddVariable("Catch:StackTrace", catchCommand.StackTrace); + //engine.AddVariable("Catch:ErrorMessage", catchCommand.ErrorMessage); + SystemVariables.Update_ErrorCatch(catchCommand, ex); //assify = (input >= 0) ? "nonnegative" : "negative"; var endCatch = (finallyIndex != -1) ? finallyIndex : endTryIndex; diff --git a/taskt/Core/Automation/Commands/Excel/AExcelCellActionCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelCellActionCommands.cs new file mode 100644 index 000000000..5a44bb2ff --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelCellActionCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for commands that using Excel Cell get, set, etc... + /// + public abstract class AExcelCellActionCommands : AExcelCellCommands, IExcelCellActionProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + [PropertyParameterOrder(8000)] + public virtual string v_ValueType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelCellCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelCellCommands.cs new file mode 100644 index 000000000..c45b72dcb --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelCellCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for commands that using Excel Cell + /// + public abstract class AExcelCellCommands : AExcelInstanceCommands, IExcelCellProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CellRangeLocation))] + [PropertyParameterOrder(6000)] + public virtual string v_CellLocation { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelColumnRangeCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelColumnRangeCommands.cs new file mode 100644 index 000000000..bebee2581 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelColumnRangeCommands.cs @@ -0,0 +1,36 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Excel column Range commands + /// + public abstract class AExcelColumnRangeCommands : AExcelInstanceCommands, IExcelColumnRangeProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + [PropertyParameterOrder(6000)] + public virtual string v_ColumnType { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + [PropertyParameterOrder(7000)] + public virtual string v_ColumnIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] + [PropertyParameterOrder(8000)] + public virtual string v_RowStart { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] + [PropertyParameterOrder(9000)] + public virtual string v_RowEnd { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + [PropertyParameterOrder(11000)] + public virtual string v_ValueType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelColumnRangeGetCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelColumnRangeGetCommands.cs new file mode 100644 index 000000000..b504dae7f --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelColumnRangeGetCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for excel column range get commands + /// + public abstract class AExcelColumnRangeGetCommands : AExcelColumnRangeCommands, IExcelColumnRangeGetProperties + { + [XmlAttribute] + [PropertyParameterOrder(10000)] + public abstract string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelColumnRangeSetCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelColumnRangeSetCommands.cs new file mode 100644 index 000000000..32bb37aea --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelColumnRangeSetCommands.cs @@ -0,0 +1,13 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + public abstract class AExcelColumnRangeSetCommands : AExcelColumnRangeCommands, IExcelColumnRangeSetProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] + [PropertyParameterOrder(12000)] + public abstract string v_WhenItemNotEnough { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelColumnRowRangeCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelColumnRowRangeCommands.cs new file mode 100644 index 000000000..3e2d6085d --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelColumnRowRangeCommands.cs @@ -0,0 +1,42 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Excel Column Row Range (2D-Range) commands + /// + public abstract class AExcelColumnRowRangeCommands : AExcelInstanceCommands, IExcelColumnRowRangeProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + [PropertyParameterOrder(6000)] + public virtual string v_ColumnType { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] + [PropertyParameterOrder(7000)] + public virtual string v_ColumnStart { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] + [PropertyParameterOrder(8000)] + public virtual string v_ColumnEnd { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] + [PropertyIsOptional(false)] + [PropertyParameterOrder(9000)] + public virtual string v_RowStart { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] + [PropertyParameterOrder(10000)] + public virtual string v_RowEnd { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + [PropertyParameterOrder(12000)] + public virtual string v_ValueType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelColumnRowRangeGetCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelColumnRowRangeGetCommands.cs new file mode 100644 index 000000000..ca1654106 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelColumnRowRangeGetCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Excel Column Row Range (2D-Range) Get commands + /// + public abstract class AExcelColumnRowRangeGetCommands : AExcelColumnRowRangeCommands, IExcelColumnRowRangeGetProperties + { + [XmlAttribute] + [PropertyParameterOrder(11000)] + public abstract string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelColumnSpecifiedCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelColumnSpecifiedCommands.cs new file mode 100644 index 000000000..ed899b6c7 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelColumnSpecifiedCommands.cs @@ -0,0 +1,28 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for excel column specified commands + /// + public abstract class AExcelColumnSpecifiedCommands : AExcelInstanceCommands, IExcelColumnSpecifiedProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + [PropertyParameterOrder(7000)] + public virtual string v_ColumnType { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + [PropertyIsOptional(true)] + [PropertyValidationRule("Column", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(8000)] + public virtual string v_ColumnIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + [PropertyParameterOrder(9000)] + public virtual string v_ValueType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelInstanceCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelInstanceCommands.cs new file mode 100644 index 000000000..fe5f1fa11 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelInstanceCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for commands that using Excel instance + /// + public abstract class AExcelInstanceCommands : ScriptCommand, ILExcelInstanceProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + [PropertyParameterOrder(5000)] + public virtual string v_InstanceName { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelRCLocationActionCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelRCLocationActionCommands.cs new file mode 100644 index 000000000..bde2c604e --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelRCLocationActionCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Excel RC Location Action commands + /// + public abstract class AExcelRCLocationActionCommands : AExcelRCLocationCommands, IExcelRCLocationActionProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + [PropertyParameterOrder(9000)] + public virtual string v_ValueType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelRCLocationCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelRCLocationCommands.cs new file mode 100644 index 000000000..9dfa85eaf --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelRCLocationCommands.cs @@ -0,0 +1,21 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Excel RC Location commands + /// + public abstract class AExcelRCLocationCommands : AExcelInstanceCommands, IExcelRCLocationProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + [PropertyParameterOrder(6000)] + public virtual string v_CellRow { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + [PropertyParameterOrder(7000)] + public virtual string v_CellColumn { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelRowRangeCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelRowRangeCommands.cs new file mode 100644 index 000000000..3eea0f0a0 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelRowRangeCommands.cs @@ -0,0 +1,36 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for row Range some action commands + /// + public abstract class AExcelRowRangeCommands : AExcelInstanceCommands, IExcelRowRangeProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + [PropertyParameterOrder(6000)] + public virtual string v_RowIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + [PropertyParameterOrder(7000)] + public virtual string v_ColumnType { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] + [PropertyParameterOrder(8000)] + public virtual string v_ColumnStart { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] + [PropertyParameterOrder(9000)] + public virtual string v_ColumnEnd { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + [PropertyParameterOrder(11000)] + public virtual string v_ValueType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelRowRangeGetCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelRowRangeGetCommands.cs new file mode 100644 index 000000000..b1d14ef5d --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelRowRangeGetCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for row Range Get commands + /// + public abstract class AExcelRowRangeGetCommands : AExcelRowRangeCommands, IExcelRowRangeGetProperties + { + [XmlAttribute] + [PropertyParameterOrder(10000)] + public abstract string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelRowRangeSetCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelRowRangeSetCommands.cs new file mode 100644 index 000000000..fe138b18c --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelRowRangeSetCommands.cs @@ -0,0 +1,14 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + public abstract class AExcelRowRangeSetCommands : AExcelRowRangeCommands, IExcelRowRangeSetProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] + [PropertyDescription("When Items Not Enough")] + [PropertyParameterOrder(12000)] + public abstract string v_WhenItemNotEnough { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/AExcelSheetCommands.cs b/taskt/Core/Automation/Commands/Excel/AExcelSheetCommands.cs new file mode 100644 index 000000000..957ee9fd6 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/AExcelSheetCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for commands that using Excel Sheet + /// + public abstract class AExcelSheetCommands : AExcelInstanceCommands, IExcelWorksheetProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] + [PropertyParameterOrder(6000)] + public virtual string v_SheetName { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelApplicationExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelApplicationExtensionMethods.cs new file mode 100644 index 000000000..3d6be00fd --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelApplicationExtensionMethods.cs @@ -0,0 +1,171 @@ +using System; +using Microsoft.Office.Interop.Excel; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelApplicationExtensionMethods + { + /// + /// check Correct Cell Location + /// + /// + /// + /// + /// + public static bool CellLocationTryParse(this Application excelInstance, string range, out Range rg) + { + try + { + rg = excelInstance.Range[range]; + return true; + } + catch + { + rg = null; + return false; + } + } + + /// + /// try parse RC Location + /// + /// + /// + /// + /// + /// + public static bool RCLocationTryParse(this Application excelInstance, int row, int column, out Range rg) + { + try + { + rg = excelInstance.Cells[row, column]; + return true; + } + catch + { + rg = null; + return false; + } + } + + /// + /// try parse RC row + /// + /// + /// + /// + /// + public static bool RowTryParse(this Application excelInstance, int r, out int row) + { + if (excelInstance.RCLocationTryParse(r, 1, out _)) + { + row = r; + return true; + } + else + { + row = 0; + return false; + } + } + + /// + /// try parse RC column (index) + /// + /// + /// + /// + /// + public static bool ColumnIndexTryParse(this Application excelInstance, int c, out int column) + { + if (excelInstance.RCLocationTryParse(1, c, out _)) + { + column = c; + return true; + } + else + { + column = 0; + return false; + } + } + + /// + /// try parse coulmn name + /// + /// + /// + /// + /// + public static bool ColumnNameTryParse(this Application excelInstance, string c, out string column) + { + if (excelInstance.CellLocationTryParse($"{c}1", out _)) + { + column = c; + return true; + } + else + { + column = ""; + return false; + } + } + + /// + /// convert column Name to column Index + /// + /// + /// + /// + /// + public static int ToColumnIndex(this Application excelInstance, string columnName) + { + try + { + return ((Range)excelInstance.Columns[columnName]).Column; + } + catch + { + throw new Exception($"Strange Column Name '{columnName}'."); + } + } + + /// + /// convert column Index to column Name + /// + /// + /// + /// + public static string ToColumnName(this Application excelInstance, int columnIndex) + { + try + { + return ((Range)excelInstance.Cells[1, columnIndex]).Address.Split('$')[1]; + } + catch + { + return ""; + } + } + + /// + /// convert RC Location to Cell Location + /// + /// + /// + /// + /// + /// + public static string ToCellLocation(this Application excelInstance, int row, int column) + { + try + { + return ((Range)excelInstance.Cells[row, column]).Address.Replace("$", ""); + } + catch + { + throw new Exception($"Strange Excel RC Location. Row: '{row}', Column: '{column}'"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelCellPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelCellPropertiesExtensionMethods.cs new file mode 100644 index 000000000..8d98b1e97 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelCellPropertiesExtensionMethods.cs @@ -0,0 +1,37 @@ +using System; +using Microsoft.Office.Interop.Excel; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelCellPropertiesExtensionMethods + { + /// + /// expand value or variable as Single Cell Location + /// + /// + /// + /// + /// + public static Range ExpandValueOrVariableAsExcelSingleCellLocation(this IExcelCellProperties command, Engine.AutomationEngineInstance engine) + { + var excelInstance = command.ExpandValueOrVariableAsExcelInstance(engine); + + var r = command.v_CellLocation.ExpandValueOrUserVariable(engine); + if (excelInstance.CellLocationTryParse(r, out Range rg)) + { + if (rg.Count == 1) + { + return rg; + } + else + { + throw new Exception($"Cell Location '{r}' is not single Cell."); + } + } + else + { + throw new Exception($"Invalid Cell Location. Value: '{command.v_CellLocation}', Expand Value: '{r}'"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelCellValueTypePropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelCellValueTypePropertiesExtensionMethods.cs new file mode 100644 index 000000000..025bcaa08 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelCellValueTypePropertiesExtensionMethods.cs @@ -0,0 +1,148 @@ +using System; +using Microsoft.Office.Interop.Excel; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelCellValueTypePropertiesExtensionMethods + { + /// + /// expand value or variable as Check Range Value Function + /// + /// + /// + /// + /// + public static Func ExpandValueOrVariableAsCheckValueFunction(this IExcelCellValueTypeProperties command, Engine.AutomationEngineInstance engine) + { + Func func = null; + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), "Value Type", engine)) + { + case "cell": + func = (rg) => + { + return !string.IsNullOrEmpty((string)rg.Text); + }; + break; + + case "formula": + func = (rg) => + { + return ((string)rg.Formula).StartsWith("="); + }; + break; + + case "back color": + func = (rg) => + { + return ((long)rg.Interior.Color) != ExcelControls.EXCEL_WHITE_COLOR; + }; + break; + } + return func; + } + + /// + /// expand value or variable as Get Range Value Function + /// + /// + /// + /// + public static Func ExpandValueOrVariableAsGetValueFunction(this IExcelCellValueTypeProperties command, Engine.AutomationEngineInstance engine) + { + Func getFunc = null; + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), "Value Type", engine)) + { + case "cell": + getFunc = (rg) => + { + return (string)rg.Text; + }; + break; + case "formula": + getFunc = (rg) => + { + return (string)rg.Formula; + }; + break; + case "format": + getFunc = (rg) => + { + return (string)rg.NumberFormatLocal; + }; + break; + case "font color": + getFunc = (rg) => + { + return ((long)rg.Font.Color).ToString(); + }; + break; + case "back color": + getFunc = (rg) => + { + return ((long)rg.Interior.Color).ToString(); + }; + break; + } + return getFunc; + } + + /// + /// expand value or variable as Set Range Value Action + /// + /// + /// + /// + /// + public static Action ExpandValueOrVariableAsSetValueAction(this IExcelCellValueTypeProperties command, Engine.AutomationEngineInstance engine) + { + Func longConvert = (str) => + { + if (long.TryParse(str, out long v)) + { + return v; + } + else + { + throw new Exception($"Value '{str}' is not Color Value."); + } + }; + + Action setFunc = null; + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), "Value Type", engine)) + { + case "cell": + setFunc = (rg, value) => + { + rg.Value = value; + }; + break; + case "formula": + setFunc = (rg, value) => + { + rg.Formula = value; + }; + break; + case "format": + setFunc = (rg, value) => + { + rg.NumberFormatLocal = value; + }; + break; + case "font color": + setFunc = (rg, value) => + { + rg.Font.Color = longConvert(value); + }; + break; + case "back color": + setFunc = (rg, value) => + { + rg.Interior.Color = longConvert(value); + }; + break; + } + + return setFunc; + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRangeGetPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRangeGetPropertiesExtensionMethods.cs new file mode 100644 index 000000000..da46b2aad --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRangeGetPropertiesExtensionMethods.cs @@ -0,0 +1,30 @@ +using System; +using Microsoft.Office.Interop.Excel; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelColumnRangeGetPropertiesExtensionMethods + { + /// + /// Column Range Action + /// + /// + /// args is (Worksheet, value, column, row, count) + /// + public static void ColumnRangeAction(this IExcelColumnRangeGetProperties command, Action loopAction, AutomationEngineInstance engine) + { + (_, var sheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + (var columnIndex, var rowStartIndex, var rowEndIndex) = command.ExpandValueOrVariableAsExcelRangeIndicies(engine); + var getFunc = command.ExpandValueOrVariableAsGetValueFunction(engine); + + int max = rowEndIndex - rowStartIndex + 1; + for (int i = 0; i < max; i++) + { + var row = rowStartIndex + i; + loopAction(sheet, getFunc(sheet, columnIndex, row), columnIndex, row, i); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRangePropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRangePropertiesExtensionMethods.cs new file mode 100644 index 000000000..a562c29fc --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRangePropertiesExtensionMethods.cs @@ -0,0 +1,70 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelColumnRangePropertiesExtensionMethods + { + /// + /// expand value or variable as Excel Range Indicies (Column Index, Row Start Index, Row End Index) + /// + /// + /// + /// + /// + /// + /// + public static (int columnIndex, int rowStartIndex, int rowEndIndex) ExpandValueOrVariableAsExcelRangeIndicies(this IExcelColumnRangeProperties command, Engine.AutomationEngineInstance engine, Func objectSizeFunc = null) + { + (_, var sheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + // get column index + int columnIndex = 0; + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ColumnType), "Column Type", engine)) + { + case "range": + columnIndex = sheet.ToColumnIndex(command.v_ColumnIndex.ExpandValueOrUserVariable(engine)); + break; + case "rc": + //columnIndex = command.ExpandValueOrUserVariableAsInteger(columnValueName, "Column", engine); + columnIndex = ((ScriptCommand)command).ExpandValueOrUserVariableAsInteger(nameof(command.v_ColumnIndex), "Column", engine); + break; + } + + //int rowStartIndex = command.ExpandValueOrUserVariableAsInteger(rowStartName, "Start Row", engine); + var rowStartIndex = ((ScriptCommand)command).ExpandValueOrUserVariableAsInteger(nameof(command.v_RowStart), "Start Row", engine); + + //string rowEndValue = command.GetRawPropertyValueAsString(rowEndName, "End Row"); + var rowEndValue = ((ScriptCommand)command).GetRawPropertyValueAsString(nameof(command.v_RowEnd), "End Row"); + int rowEndIndex; + if (string.IsNullOrEmpty(rowEndValue)) + { + if (objectSizeFunc == null) + { + var valueType = ((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), "Value Type", engine); + rowEndIndex = sheet.LastRowIndex(columnIndex, rowStartIndex, valueType); + } + else + { + rowEndIndex = rowStartIndex + objectSizeFunc() - 1; + } + } + else + { + rowEndIndex = rowEndValue.ExpandValueOrUserVariableAsInteger("End Row", engine); + } + + // swap values + if (rowStartIndex > rowEndIndex) + { + (rowEndIndex, rowStartIndex) = (rowStartIndex, rowEndIndex); + } + + if (!sheet.RCRangeTryParse(rowStartIndex, columnIndex, rowEndIndex, columnIndex, out _)) + { + throw new Exception($"Invalid Range. Row Start Index: '{rowStartIndex}', Row End Index: '{rowEndIndex}', Column Index: '{columnIndex}'"); + } + + return (columnIndex, rowStartIndex, rowEndIndex); + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRangeSetPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRangeSetPropertiesExtensionMethods.cs new file mode 100644 index 000000000..e4eee91a6 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRangeSetPropertiesExtensionMethods.cs @@ -0,0 +1,59 @@ +using System; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelColumnRangeSetPropertiesExtensionMethods + { + /// + /// expand value or variable as Excel Range Indicies (Column Index, Row Start Index, Row End Index) + /// + /// + /// + /// + /// + /// + public static (int columnIndex, int rowStartIndex, int rowEndIndex) ExpandValueOrVariableAsExcelRangeIndicies(this IExcelColumnRangeSetProperties command, Engine.AutomationEngineInstance engine, Func objectSizeFunc) + { + (var columnIndex, var rowStartIndex, var rowEndIndex) = ((IExcelColumnRangeProperties)command).ExpandValueOrVariableAsExcelRangeIndicies(engine, objectSizeFunc); + + var whenItemNotEnough = ((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_WhenItemNotEnough), "When Item Not Enough", engine); + + var range = rowEndIndex - rowStartIndex + 1; + var size = objectSizeFunc(); + if (range > objectSizeFunc()) + { + switch (whenItemNotEnough) + { + case "error": + throw new Exception("Size of Object Item(s) to Set is Not Enough."); + default: + rowEndIndex = rowStartIndex + size - 1; + break; + } + } + return (columnIndex, rowStartIndex, rowEndIndex); + } + + /// + /// column range action + /// + /// + /// + /// arg is (index) + /// + public static void ColumnRangeAction(this IExcelColumnRangeSetProperties command, Func objectSizeFunc, Func valueFunc, AutomationEngineInstance engine) + { + (_, var excelSheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + (var columnIndex, var rowStartIndex, var rowEndIndex) = command.ExpandValueOrVariableAsExcelRangeIndicies(engine, objectSizeFunc); + var setFunc = command.ExpandValueOrVaribleAsSetValueAction(engine); + + int max = rowEndIndex - rowStartIndex + 1; + for (int i = 0; i < max; i++) + { + setFunc(valueFunc(i), excelSheet, columnIndex, rowStartIndex + i); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRowRangePropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRowRangePropertiesExtensionMethods.cs new file mode 100644 index 000000000..0013b235d --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnRowRangePropertiesExtensionMethods.cs @@ -0,0 +1,95 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelColumnRowRangePropertiesExtensionMethods + { + /// + /// expand value or variable as Excel Range Indicies (rowStart, columnStart, rowEnd, columnEnd) + /// + /// + /// + /// + /// + /// + /// + public static (int rowStartIndex, int columnStartIndex, int rowEndIndex, int columnEndIndex) ExpandValueOrVariableAsExcelRangeIndicies(this IExcelColumnRowRangeProperties command, Engine.AutomationEngineInstance engine, Func rowSizeFunc = null, Func columnSizeFunc = null) + { + (_, var excelSheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + var valueType = ((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), "Value Type", engine); + + var rowStartIndex = command.v_RowStart.ExpandValueOrUserVariableAsInteger("Start Row", engine); + + var columnFunc = new Func((row, column, tp) => + { + if (columnSizeFunc != null) + { + return columnSizeFunc(); + } + else + { + return excelSheet.GetLastColumnIndex(row, column, tp); + } + }); + + int columnStartIndex = 0; + int columnEndIndex = 0; + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ColumnType), "Column Type", engine)) + { + case "range": + columnStartIndex = excelSheet.ToColumnIndex(command.v_ColumnStart.ExpandValueOrUserVariable(engine)); + if (string.IsNullOrEmpty(command.v_ColumnEnd)) + { + columnEndIndex = columnFunc(rowStartIndex, columnStartIndex, valueType); + } + else + { + columnEndIndex = excelSheet.ToColumnIndex(command.v_ColumnEnd.ExpandValueOrUserVariable(engine)); + } + break; + + case "rc": + columnStartIndex = command.v_ColumnStart.ExpandValueOrUserVariableAsInteger("Column Start", engine); + if (string.IsNullOrEmpty(command.v_ColumnEnd)) + { + columnEndIndex = columnFunc(rowStartIndex, columnStartIndex, valueType); + } + else + { + columnEndIndex = command.v_ColumnEnd.ExpandValueOrUserVariableAsInteger("Column End", engine); + } + break; + } + + // swap values + if (columnStartIndex > columnEndIndex) + { + (columnEndIndex, columnStartIndex) = (columnStartIndex, columnEndIndex); + } + + int rowEndIndex; + if (string.IsNullOrEmpty(command.v_RowEnd)) + { + rowEndIndex = (rowSizeFunc != null) ? rowSizeFunc() : excelSheet.LastRowIndex(columnStartIndex, rowStartIndex, valueType); + } + else + { + rowEndIndex = command.v_RowEnd.ExpandValueOrUserVariableAsInteger("Row End", engine); + } + + // swap values + if (rowStartIndex > rowEndIndex) + { + (rowEndIndex, rowStartIndex) = (rowStartIndex, rowEndIndex); + } + + if (!excelSheet.RCRangeTryParse(rowStartIndex, columnStartIndex, rowEndIndex, columnEndIndex, out _)) + { + throw new Exception($"Invalid Range. Row Start Index: '{rowStartIndex}', Row End Index: '{rowEndIndex}', Column Start Index: '{columnStartIndex}', Column End Index: '{columnEndIndex}'"); + } + + return (rowStartIndex, columnStartIndex, rowEndIndex, columnEndIndex); + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnSpecifiedPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnSpecifiedPropertiesExtensionMethods.cs new file mode 100644 index 000000000..c1a5de8ec --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelColumnSpecifiedPropertiesExtensionMethods.cs @@ -0,0 +1,62 @@ +using System; +using Microsoft.Office.Interop.Excel; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelColumnSpecifiedPropertiesExtensionMethods + { + /// + /// expand value or variable as Excel Column Index + /// + /// + /// + /// + /// + public static int ExpandValueOrVariableAsExcelColumnIndex(this IExcelColumnSpecifiedProperties command, Engine.AutomationEngineInstance engine) + { + (_, var sheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + string columnIndexValue = ((ScriptCommand)command).GetRawPropertyValueAsString(nameof(command.v_ColumnIndex), "Column Index"); + int columnIndex = 0; + + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ColumnType), "Column Type", engine)) + { + case "range": + if (string.IsNullOrEmpty(columnIndexValue)) + { + columnIndexValue = "A"; + } + columnIndex = sheet.ToColumnIndex(columnIndexValue); + break; + case "rc": + if (string.IsNullOrEmpty(columnIndexValue)) + { + columnIndexValue = "1"; + } + columnIndex = columnIndexValue.ExpandValueOrUserVariableAsInteger("Column Index", engine); + break; + } + + if (!sheet.RCLocationTryParse(1, columnIndex, out _)) + { + throw new Exception($"Invalid Column Index. Type: '{command.v_ColumnType}', Value: '{command.v_ColumnIndex}', Expand Value: '{columnIndex}'"); + } + + return columnIndex; + } + + /// + /// expand value or variable as Excel current worksheet and column index + /// + /// + /// + /// + public static (Worksheet, int) ExpandValueOrVariableAsExcelCurrentWorksheetAndColumnIndex(this IExcelColumnSpecifiedProperties command, Engine.AutomationEngineInstance engine) + { + (_, var sheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + var index = command.ExpandValueOrVariableAsExcelColumnIndex(engine); + + return (sheet, index); + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelInstancePropertiesExtenstionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelInstancePropertiesExtenstionMethods.cs new file mode 100644 index 000000000..eaa1c9119 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelInstancePropertiesExtenstionMethods.cs @@ -0,0 +1,181 @@ +using System; +using Microsoft.Office.Interop.Excel; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelInstancePropertiesExtenstionMethods + { + /// + /// expand value or variable as Excel Instance + /// + /// + /// + /// + /// + public static Application ExpandValueOrVariableAsExcelInstance(this ILExcelInstanceProperties command, Engine.AutomationEngineInstance engine) + { + string ins = command.v_InstanceName.ExpandValueOrUserVariable(engine); + var instanceObject = engine.GetAppInstance(ins); + if (instanceObject is Application app) + { + return app; + } + else + { + throw new Exception($"Instance '{command.v_InstanceName}' is not Excel Instance"); + } + } + + /// + /// expand value or variable as Excel Instance and CurrentWorksheet + /// + /// + /// + /// + public static (Application, Worksheet) ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(this ILExcelInstanceProperties command, Engine.AutomationEngineInstance engine) + { + var ins = command.ExpandValueOrVariableAsExcelInstance(engine); + if (ins.Worksheets.Count > 0) + { + return (ins, ins.ActiveSheet); + } + else + { + throw new Exception($"Instance '{command.v_InstanceName} has no Worksheets"); + } + } + + /// + /// get next worksheet + /// + /// + /// + /// + /// + private static Worksheet GetNextWorksheet(Application instance, Worksheet currentSheet) + { + int idx = 1; + foreach (Worksheet sht in instance.Worksheets) + { + if (sht.Name == currentSheet.Name) + { + break; + } + idx++; + } + if (idx < instance.Worksheets.Count) + { + return (Worksheet)instance.Worksheets[idx + 1]; + } + else + { + throw new Exception($"No Next Worksheet. CurrentSheet: '{currentSheet.Name}'"); + } + } + + /// + /// get previous worksheet + /// + /// + /// + /// + /// + private static Worksheet GetPreviousWorksheet(Application instance, Worksheet currentSheet) + { + int idx = 1; + foreach (Worksheet sht in instance.Worksheets) + { + if (sht.Name == currentSheet.Name) + { + break; + } + idx++; + } + if (idx > 1) + { + return (Worksheet)instance.Worksheets[idx - 1]; + } + else + { + throw new Exception($"No Previous Worksheet. CurrentSheet: '{currentSheet.Name}'"); + } + } + + /// + /// expand value or variable as Excel Worksheet + /// + /// + /// + /// + /// + /// + public static Worksheet ExpandValueOrVariableAsExcelWorksheet(this ILExcelInstanceProperties command, string sheetName, Engine.AutomationEngineInstance engine) + { + (var ins, var currentSheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + if (sheetName == VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Excel_CurrentWorkSheet.VariableName, engine)) + { + return currentSheet; + } + else if (sheetName == VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Excel_NextWorkSheet.VariableName, engine)) + { + return GetNextWorksheet(ins, currentSheet); + } + else if (sheetName == VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Excel_PreviousWorkSheet.VariableName, engine)) + { + return GetPreviousWorksheet(ins, currentSheet); + } + else + { + var expandSheetName = sheetName.ExpandValueOrUserVariable(engine); + try + { + return (Worksheet)ins.Worksheets[expandSheetName]; + } + catch + { + throw new Exception($"Worksheet '{expandSheetName}' does not exists."); + } + } + } + + /// + /// Expand value or variable as Worksheet Name + /// + /// not used + /// + /// + /// + /// + public static string ExpandValueOrVariableAsExcelWorksheetName(this ILExcelInstanceProperties command, string sheet, Engine.AutomationEngineInstance engine) + { + var newSheet = sheet.ExpandValueOrUserVariable(engine); + + if (string.IsNullOrEmpty(newSheet)) + { + throw new Exception("Worksheet name is Empty."); + } + else if (newSheet.Length >= 31) + { + throw new Exception($"Worksheet name is too long. Must be less than 31 characters."); + } + + foreach(var s in ExcelControls.Disallow_Contains_Worksheet_Charactors) + { + if (newSheet.Contains(s)) + { + throw new Exception($"Worksheet name contains invalid character '{s}'. Worksheet: '{newSheet}'"); + } + } + foreach(var s in ExcelControls.Disallow_Starts_Ends_Worksheet_Charactors) + { + if (newSheet.StartsWith(s) || newSheet.EndsWith(s)) + { + throw new Exception($"Worksheet name starts or ends with a character that is invalid '{s}'. Worksheet: '{newSheet}'"); + } + } + + return newSheet; + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelRCLocationPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelRCLocationPropertiesExtensionMethods.cs new file mode 100644 index 000000000..7adfca680 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelRCLocationPropertiesExtensionMethods.cs @@ -0,0 +1,44 @@ +using System; +using Microsoft.Office.Interop.Excel; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelRCLocationPropertiesExtensionMethods + { + /// + /// expand value or variable as Cell Row Index and Column Index (row, column) + /// + /// + /// + /// + /// + public static (int, int) ExpandValueOrVariableAsCellRowAndColumnIndex(this IExcelRCLocationProperties command, Engine.AutomationEngineInstance engine) + { + var row = ((ScriptCommand)command).ExpandValueOrUserVariableAsInteger(nameof(command.v_CellRow), "Cell Row", engine); + var column = ((ScriptCommand)command).ExpandValueOrUserVariableAsInteger(nameof(command.v_CellColumn), "Cell Column", engine); + + var excelInstance = command.ExpandValueOrVariableAsExcelInstance(engine); + if (excelInstance.RCLocationTryParse(row, column, out _)) + { + return (row, column); + } + else + { + throw new Exception($"Invalid Cell Location. Row: '{command.v_CellRow}', Column: '{command.v_CellColumn}', Row Expanded: '{row}', Column Expanded: '{command}'"); + } + } + + /// + /// RC Location Action + /// + /// + /// arguments (sheet, column, row) + /// + public static void RCLocationAction(this IExcelRCLocationProperties command, Action actionFunc, Engine.AutomationEngineInstance engine) + { + (_, var sheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + (var row, var column) = command.ExpandValueOrVariableAsCellRowAndColumnIndex(engine); + actionFunc(sheet, column, row); + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelRCValueTypePropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelRCValueTypePropertiesExtensionMethods.cs new file mode 100644 index 000000000..bf7bddd9a --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelRCValueTypePropertiesExtensionMethods.cs @@ -0,0 +1,148 @@ +using System; +using Microsoft.Office.Interop.Excel; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelRCValueTypePropertiesExtensionMethods + { + /// + /// expand value or variable as get cell value Function(sheet, column, row) + /// + /// + /// + /// + public static Func ExpandValueOrVariableAsGetValueFunction(this IExcelRCValueTypeProperties command, Engine.AutomationEngineInstance engine) + { + Func getFunc = null; + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), "Value Type", engine)) + { + case "cell": + getFunc = (sheet, column, row) => + { + //return (string)((Range)sheet.Cells[row, column]).Text; + return sheet.CellText(row, column); + }; + break; + case "formula": + getFunc = (sheet, column, row) => + { + //return (string)((Range)sheet.Cells[row, column]).Formula; + return sheet.CellFormula(row, column); + }; + break; + case "format": + getFunc = (sheet, column, row) => + { + //return (string)((Range)sheet.Cells[row, column]).NumberFormatLocal; + return sheet.CellFormat(row, column); + }; + break; + case "font color": + getFunc = (sheet, column, row) => + { + //return ((long)((Range)sheet.Cells[row, column]).Font.Color).ToString(); + return sheet.CellFontColor(row, column).ToString(); + }; + break; + case "back color": + getFunc = (sheet, column, row) => + { + //return ((long)((Range)sheet.Cells[row, column]).Interior.Color).ToString(); + return sheet.CellBackColor(row, column).ToString(); + }; + break; + } + return getFunc; + } + + /// + /// expand value or variable as set cell value Action(value, sheet, column, row) + /// + /// + /// + /// + public static Action ExpandValueOrVaribleAsSetValueAction(this IExcelRCValueTypeProperties command, Engine.AutomationEngineInstance engine) + { + Action setFunc = null; + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), "Value Type", engine)) + { + case "cell": + setFunc = (value, sheet, column, row) => + { + //((Range)sheet.Cells[row, column]).Value = value; + sheet.CellRange(row, column).Value = value; + }; + break; + case "formula": + setFunc = (value, sheet, column, row) => + { + //((Range)sheet.Cells[row, column]).Formula = value; + sheet.CellRange(row, column).Formula = value; + }; + break; + case "format": + setFunc = (value, sheet, column, row) => + { + //((Range)sheet.Cells[row, column]).NumberFormatLocal = value; + sheet.CellRange(row, column).NumberFormatLocal = value; + }; + break; + case "font color": + setFunc = (value, sheet, column, row) => + { + //((Range)sheet.Cells[row, column]).Font.Color = long.Parse(value); + sheet.CellRange(row, column).Font.Color = long.Parse(value); + }; + break; + case "back color": + setFunc = (value, sheet, column, row) => + { + //((Range)sheet.Cells[row, column]).Interior.Color = long.Parse(value); + sheet.CellRange(row, column).Interior.Color = long.Parse(value); + }; + break; + } + + return setFunc; + } + + /// + /// expand value or variable as Check Range Value Function(sheet, column, row) + /// + /// + /// + /// + /// + public static Func ExpandValueOrVariableAsCheckValueFunction(this IExcelRCValueTypeProperties command, Engine.AutomationEngineInstance engine) + { + Func func = null; + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), "Value Type", engine)) + { + case "cell": + func = (sheet, column, row) => + { + //return !string.IsNullOrEmpty(((Range)sheet.Cells[row, column]).Text); + return !string.IsNullOrEmpty(sheet.CellText(row, column)); + }; + break; + + case "formula": + func = (sheet, column, row) => + { + //return ((Range)sheet.Cells[row, column]).Formula.StartsWith("="); + return sheet.CellFormula(row, column).StartsWith("="); + }; + break; + + case "back color": + func = (sheet, column, row) => + { + //return ((Range)sheet.Cells[row, column]).Interior.Color != 16777215; + return sheet.CellBackColor(row, column) != ExcelControls.EXCEL_WHITE_COLOR; + }; + break; + } + return func; + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelRowRangeGetPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelRowRangeGetPropertiesExtensionMethods.cs new file mode 100644 index 000000000..433036fea --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelRowRangeGetPropertiesExtensionMethods.cs @@ -0,0 +1,30 @@ +using System; +using Microsoft.Office.Interop.Excel; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelRowRangeGetPropertiesExtensionMethods + { + /// + /// row range action + /// + /// + /// args is (Worksheet, value, column, row, count) + /// + public static void RowRangeAction(this IExcelRowRangeGetProperties command, Action loopAction, AutomationEngineInstance engine) + { + (_, var sheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + (int rowIndex, int columnStartIndex, int columnEndIndex) = command.ExpandValueOrVariableAsExcelRangeIndecies(engine); + + var getFunc = command.ExpandValueOrVariableAsGetValueFunction(engine); + + int max = columnEndIndex - columnStartIndex + 1; + for (int i = 0; i < max; i++) + { + var pos = columnStartIndex + i; + loopAction(sheet, getFunc(sheet, pos, rowIndex), pos, rowIndex, i); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelRowRangePropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelRowRangePropertiesExtensionMethods.cs new file mode 100644 index 000000000..4cc375da4 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelRowRangePropertiesExtensionMethods.cs @@ -0,0 +1,94 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelRowRangePropertiesExtensionMethods + { + /// + /// expand value or variable As Range Indecies (Row-Start, Column-Start, Row-End, Column-End) + /// + /// + /// + /// + /// + /// + public static (int rowIndex, int columnStartIndex, int columnEndIndex) ExpandValueOrVariableAsExcelRangeIndecies(this IExcelRowRangeProperties command, Engine.AutomationEngineInstance engine, Func objectSizeFunc = null) + { + (_, var sheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + var rowIndex = ((ScriptCommand)command).ExpandValueOrUserVariableAsInteger(nameof(command.v_RowIndex), "Row Index", engine); + + var innerLastColumnFunc = new Func((rowStart, columnStart) => + { + if (objectSizeFunc != null) + { + return columnStart + objectSizeFunc() - 1; + } + else + { + var valueType = ((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), "Value Type", engine); + return sheet.GetLastColumnIndex(rowStart, columnStart, valueType); + } + }); + + int columnStartIndex = 0; + int columnEndIndex = 0; + + string columnStartValue = ((ScriptCommand)command).GetRawPropertyValueAsString(nameof(command.v_ColumnStart), "Start Column"); + string columnEndValue = ((ScriptCommand)command).GetRawPropertyValueAsString(nameof(command.v_ColumnEnd), "End Column"); + + switch (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ColumnType), "Column Type", engine)) + { + case "range": + if (string.IsNullOrEmpty(columnStartValue)) + { + columnStartValue = "A"; + } + columnStartIndex = sheet.ToColumnIndex(columnStartValue.ExpandValueOrUserVariable(engine)); + + + if (string.IsNullOrEmpty(columnEndValue)) + { + //columnEndIndex = (lastColumnFunc != null) ? lastColumnFunc() : sheetLastColumn(rowIndex, columnStartIndex); + columnEndIndex = innerLastColumnFunc(rowIndex, columnStartIndex); + } + else + { + columnEndIndex = sheet.ToColumnIndex(columnEndValue.ExpandValueOrUserVariable(engine)); + } + break; + + case "rc": + if (string.IsNullOrEmpty(columnStartValue)) + { + columnStartValue = "1"; + } + columnStartIndex = columnStartValue.ExpandValueOrUserVariableAsInteger("Start Column", engine); + + if (string.IsNullOrEmpty(columnEndValue)) + { + //columnEndIndex = (lastColumnFunc != null) ? lastColumnFunc() : sheetLastColumn(rowIndex, columnStartIndex); + columnEndIndex = innerLastColumnFunc(rowIndex, columnStartIndex); + } + else + { + columnEndIndex = columnEndValue.ExpandValueOrUserVariableAsInteger("Column End", engine); + } + break; + } + + // swap values + if (columnStartIndex > columnEndIndex) + { + (columnEndIndex, columnStartIndex) = (columnStartIndex, columnEndIndex); + } + + if (!sheet.RCRangeTryParse(rowIndex, columnStartIndex, rowIndex, columnEndIndex, out _)) + { + throw new Exception($"Invalid Range. Row Index: '{rowIndex}', Column Start Index: '{columnStartIndex}', Column End Index: '{columnEndIndex}'"); + } + + return (rowIndex, columnStartIndex, columnEndIndex); + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelRowRangeSetPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelRowRangeSetPropertiesExtensionMethods.cs new file mode 100644 index 000000000..0d9a10d3a --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelRowRangeSetPropertiesExtensionMethods.cs @@ -0,0 +1,59 @@ +using System; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelRowRangeSetPropertiesExtensionMethods + { + /// + /// expand value or variable as Range Indecies (Row-Start, Column-Start, Row-End, Column-End) + /// + /// + /// + /// + /// + /// + public static (int rowIndex, int columnStartIndex, int columnEndIndex) ExpandValueOrVariableAsExcelRangeIndecies(this IExcelRowRangeSetProperties command, Engine.AutomationEngineInstance engine, Func objectSizeFunc) + { + (var row, var columnStart, var columnEnd) = ((IExcelRowRangeProperties)command).ExpandValueOrVariableAsExcelRangeIndecies(engine, objectSizeFunc); + + var whenItemNotEnough = ((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_WhenItemNotEnough), "When Item Not Enough", engine); + + var range = columnEnd - columnStart + 1; + var size = objectSizeFunc(); + if (range > objectSizeFunc()) + { + switch (whenItemNotEnough) + { + case "error": + throw new Exception("Size of Object Item(s) to Set is Not Enough."); + default: + columnEnd = columnStart + size - 1; + break; + } + } + return (row, columnStart, columnEnd); + } + + /// + /// row range index + /// + /// + /// + /// args is (count) + /// + public static void RowRangeAction(this IExcelRowRangeSetProperties command, Func objectSizeFunc, Func valueFunc, AutomationEngineInstance engine) + { + (_, var excelSheet) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + (var rowIndex, var columnStartIndex, var columnEndIndex) = command.ExpandValueOrVariableAsExcelRangeIndecies(engine, objectSizeFunc); + + var setFunc = command.ExpandValueOrVaribleAsSetValueAction(engine); + var max = columnEndIndex - columnStartIndex + 1; + for (int i = 0; i < max; i++) + { + setFunc(valueFunc(i), excelSheet, columnStartIndex + i, rowIndex); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelWorksheetActionPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelWorksheetActionPropertiesExtensionMethods.cs new file mode 100644 index 000000000..7c0f123ed --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelWorksheetActionPropertiesExtensionMethods.cs @@ -0,0 +1,30 @@ +using Microsoft.Office.Interop.Excel; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelWorksheetActionPropertiesExtensionMethods + { + /// + /// expand value or variable as worksheet + /// + /// + /// + /// + public static Worksheet ExpandValueOrVariableAsExcelTargetWorksheet(this IExcelWorksheetActionProperties command, Engine.AutomationEngineInstance engine) + { + return command.ExpandValueOrVariableAsExcelWorksheet(command.v_TargetSheetName, engine); + } + + /// + /// expand value or variable as Excel Instance and Target Worksheet + /// + /// + /// + /// + public static (Application, Worksheet) ExpandValueOrVariableAsExcelInstanceAndTargetWorksheet(this IExcelWorksheetActionProperties command, Engine.AutomationEngineInstance engine) + { + return (command.ExpandValueOrVariableAsExcelInstance(engine), + command.ExpandValueOrVariableAsExcelTargetWorksheet(engine)); + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelWorksheetExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelWorksheetExtensionMethods.cs new file mode 100644 index 000000000..3e86acf14 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelWorksheetExtensionMethods.cs @@ -0,0 +1,498 @@ +using System; +using Microsoft.Office.Interop.Excel; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelWorksheetExtensionMethods + { + /// + /// check Correct Cell Location + /// + /// + /// + /// + /// + public static bool CellLocationTryParse(this Worksheet sheet, string range, out Range rg) + { + try + { + rg = sheet.Range[range]; + return true; + } + catch + { + rg = null; + return false; + } + } + + /// + /// try parse RC Location + /// + /// + /// + /// + /// + /// + public static bool RCLocationTryParse(this Worksheet sheet, int row, int column, out Range rg) + { + try + { + rg = sheet.Cells[row, column]; + return true; + } + catch + { + rg = null; + return false; + } + } + + /// + /// try parse RC Range + /// + /// + /// + /// + /// + /// + /// + /// + public static bool RCRangeTryParse(this Worksheet sheet, int startRow, int startColumn, int endRow, int endColumn, out (int startRow, int startColumn, int endRow, int endColumn) ret) + { + ret = (0, 0, 0, 0); + if (!sheet.RCLocationTryParse(startRow, endColumn, out _)) + { + return false; + } + if (!sheet.RCLocationTryParse(endRow, endColumn, out _)) + { + return false; + } + + ret = (startRow, startColumn, endRow, endColumn); + return true; + } + + /// + /// try parse RC row + /// + /// + /// + /// + /// + public static bool RowTryParse(this Worksheet sheet, int r, out int row) + { + if (sheet.RCLocationTryParse(r, 1, out _)) + { + row = r; + return true; + } + else + { + row = 0; + return false; + } + } + + /// + /// try parse RC column (index) + /// + /// + /// + /// + /// + public static bool ColumnIndexTryParse(this Worksheet sheet, int c, out int column) + { + if (sheet.RCLocationTryParse(1, c, out _)) + { + column = c; + return true; + } + else + { + column = 0; + return false; + } + } + + /// + /// try parse coulmn name + /// + /// + /// + /// + /// + public static bool ColumnNameTryParse(this Worksheet sheet, string c, out string column) + { + if (sheet.CellLocationTryParse($"{c}1", out _)) + { + column = c; + return true; + } + else + { + column = ""; + return false; + } + } + + /// + /// convert column Name to column Index + /// + /// + /// + /// + /// + public static int ToColumnIndex(this Worksheet sheet, string columnName) + { + //if (CheckCorrectColumnName(columnName, sheet)) + //{ + // return ((Range)sheet.Columns[columnName]).Column; + //} + //else + //{ + // throw new Exception("Strange Column Name '" + columnName + "'"); + //} + try + { + return ((Range)sheet.Columns[columnName]).Column; + } + catch + { + throw new Exception($"Strange Column Name '{columnName}'."); + } + } + + /// + /// convert column Index to column Name + /// + /// + /// + /// + public static string ToColumnName(this Worksheet sheet, int columnIndex) + { + //if (columnIndex < 1) + //{ + // return ""; + //} + //else + //{ + // return ((Range)sheet.Cells[1, columnIndex]).Address.Split('$')[1]; + //} + try + { + return ((Range)sheet.Cells[1, columnIndex]).Address.Split('$')[1]; + } + catch + { + return ""; + } + } + + /// + /// convert RC Location to Cell Location + /// + /// + /// + /// + /// + /// + public static string ToCellLocation(this Worksheet sheet, int row, int column) + { + //if (CheckCorrectRC(row, column, sheet)) + //{ + // return ((Range)sheet.Cells[row, column]).Address.Replace("$", ""); + //} + //else + //{ + // throw new Exception("Strange Excel Location. Row: " + row + ", Column: " + column); + //} + try + { + return sheet.CellRange(row, column).Address.Replace("$", ""); + } + catch + { + throw new Exception($"Strange Excel RC Location. Row: '{row}', Column: '{column}'"); + } + } + + /// + /// get last row index + /// + /// + /// Column Index + /// + /// + /// + public static int LastRowIndex(this Worksheet sheet, int column, int startRow, string targetType) + { + int lastRow = startRow; + //switch (targetType.ToLower()) + //{ + // case "formula": + // //while ((string)(((Range)sheet.Cells[lastRow, column]).Formula) != "") + // while (!string.IsNullOrEmpty(sheet.CellFormula(lastRow, column))) + // { + // lastRow++; + // } + // break; + + // default: + // //while ((string)(((Range)sheet.Cells[lastRow, column]).Text) != "") + // while(!string.IsNullOrEmpty(sheet.CellText(lastRow, column))) + // { + // lastRow++; + // } + // break; + //} + + var func = GetCheckNotEmptyFunction(targetType); + while(func(sheet, lastRow, column)) + { + lastRow++; + } + + return --lastRow; + } + + /// + /// get first blank row index + /// + /// + /// + /// + /// + /// + public static int FirstBlankRowIndex(this Worksheet sheet, int column, int startRow, string targetType) + { + var rowIndex = sheet.LastRowIndex(column, startRow, targetType); + + if (rowIndex < 1) + { + rowIndex = 1; + } + + //switch (targetType.ToLower()) + //{ + // case "formula": + // //if ((string)(((Range)sheet.Cells[rowIndex, column]).Formula) != "") + // if (!string.IsNullOrEmpty(sheet.CellFormula(rowIndex, column))) + // { + // rowIndex++; + // } + // break; + + // default: + // //if ((string)(((Range)sheet.Cells[rowIndex, column]).Text) != "") + // if (!string.IsNullOrEmpty(sheet.CellText(rowIndex, column))) + // { + // rowIndex++; + // } + // break; + //} + + var func = GetCheckNotEmptyFunction(targetType); + if (func(sheet, rowIndex, column)) + { + rowIndex++; + } + + return rowIndex; + } + + /// + /// get last column Index + /// + /// + /// + /// + /// + /// + public static int GetLastColumnIndex(this Worksheet sheet, int row, int startColumn, string targetType) + { + int lastColumn = startColumn; + //switch (targetType.ToLower()) + //{ + // case "formula": + // //while ((string)(((Range)sheet.Cells[row, lastColumn]).Formula) != "") + // while(!string.IsNullOrEmpty(sheet.CellFormula(row, lastColumn))) + // { + // lastColumn++; + // } + // break; + + // default: + // //while ((string)(((Range)sheet.Cells[row, lastColumn]).Text) != "") + // while(!string.IsNullOrEmpty(sheet.CellText(row, lastColumn))) + // { + // lastColumn++; + // } + // break; + //} + + var func = GetCheckNotEmptyFunction(targetType); + while(func(sheet, row, lastColumn)) + { + lastColumn++; + } + + return --lastColumn; + } + + /// + /// get empty check Func + /// + /// + /// args is (Worksheet, row, column) + private static Func GetCheckNotEmptyFunction(string targetType) + { + switch (targetType.ToLower()) + { + case "formula": + return new Func((sheet, row, column) => + { + return !string.IsNullOrEmpty(sheet.CellFormula(row, column)); + }); + + case "back color": + return new Func((sheet, row, column) => + { + return (sheet.CellBackColor(row, column) != ExcelControls.EXCEL_WHITE_COLOR); + }); + default: + return new Func((sheet, row, column) => { + return !string.IsNullOrEmpty(sheet.CellText(row, column)); + }); + } + } + + /// + /// get cell range from row, column index + /// + /// + /// + /// + /// + public static Range CellRange(this Worksheet sheet, int row, int column) + { + return (Range)sheet.Cells[row, column]; + } + + /// + /// get cell text from RC + /// + /// + /// + /// + /// + public static string CellText(this Worksheet sheet, int row, int column) + { + return (string)sheet.CellRange(row, column).Text; + } + + /// + /// get cell text from range + /// + /// + /// + /// + public static string CellText(this Worksheet sheet, string range) + { + return (string)sheet.Range[range].Text; + } + + /// + /// get cell formula from RC + /// + /// + /// + /// + /// + public static string CellFormula(this Worksheet sheet, int row, int column) + { + return (string)sheet.CellRange(row, column).Formula; + } + + /// + /// get cell formula from range + /// + /// + /// + /// + public static string CellFormula(this Worksheet sheet, string range) + { + return (string)sheet.Range[range].Formula; + } + + /// + /// get cell format from RC + /// + /// + /// + /// + /// + public static string CellFormat(this Worksheet sheet, int row, int column) + { + return (string)sheet.CellRange(row, column).NumberFormatLocal; + } + + /// + /// get cell format from range + /// + /// + /// + /// + public static string CellFormat(this Worksheet sheet, string range) + { + return (string)sheet.Range[range].NumberFormatLocal; + } + + /// + /// get cell font color from RC + /// + /// + /// + /// + /// + public static long CellFontColor(this Worksheet sheet, int row, int column) + { + return (long)sheet.CellRange(row, column).Font.Color; + } + + /// + /// get cell font color from range + /// + /// + /// + /// + public static long CellFontColor(this Worksheet sheet, string range) + { + return (long)sheet.Range[range].Font.Color; + } + + /// + /// get cell back color from RC + /// + /// + /// + /// + /// + public static long CellBackColor(this Worksheet sheet, int row, int column) + { + return (long)sheet.CellRange(row, column).Interior.Color; + } + + /// + /// get cell back color from range + /// + /// + /// + /// + public static long CellBackColor(this Worksheet sheet, string range) + { + return (long)sheet.Range[range].Interior.Color; + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/EM_ExcelWorksheetPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Excel/EM_ExcelWorksheetPropertiesExtensionMethods.cs new file mode 100644 index 000000000..6df9177f3 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/EM_ExcelWorksheetPropertiesExtensionMethods.cs @@ -0,0 +1,45 @@ +using System; +using Microsoft.Office.Interop.Excel; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ExcelWorksheetPropertiesExtensionMethods + { + /// + /// expand value or variable as Excel Worksheet + /// + /// + /// + /// + /// + public static Worksheet ExpandValueOrVariableAsExcelWorksheet(this IExcelWorksheetProperties command, Engine.AutomationEngineInstance engine) + { + return command.ExpandValueOrVariableAsExcelWorksheet(command.v_SheetName, engine); + } + + /// + /// expand value or variable as Excel Instance, Worksheet + /// + /// + /// + /// + public static (Application, Worksheet) ExpandValueOrVariableAsExcelInstanceAndWorksheet(this IExcelWorksheetProperties command, Engine.AutomationEngineInstance engine) + { + return (command.ExpandValueOrVariableAsExcelInstance(engine), + command.ExpandValueOrVariableAsExcelWorksheet(engine)); + } + + /// + /// expand value or variable as Excel Instance, Worksheet, and CurrentWorksheet + /// + /// + /// + /// + public static (Application instance, Worksheet targetSheet, Worksheet currentSheet) ExpandValueOrVariableAsExcelInstnaceAndWorksheetAndCurrentSheet(this IExcelWorksheetProperties command, Engine.AutomationEngineInstance engine) + { + (var ins, var current) = command.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + var sht = command.ExpandValueOrVariableAsExcelWorksheet(engine); + return (ins, sht, current); + } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/ExcelActivateSheetCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelActivateSheetCommand.cs deleted file mode 100644 index c8a0558aa..000000000 --- a/taskt/Core/Automation/Commands/Excel/ExcelActivateSheetCommand.cs +++ /dev/null @@ -1,48 +0,0 @@ -using System; -using System.Xml.Serialization; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] - [Attributes.ClassAttributes.SubGruop("Sheet")] - [Attributes.ClassAttributes.CommandSettings("Activate Sheet")] - [Attributes.ClassAttributes.Description("This command allows you to activate a specific worksheet in a workbook")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to switch to a specific worksheet")] - [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] - [Attributes.ClassAttributes.EnableAutomateRender(true)] - [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelActivateSheetCommand : ScriptCommand - { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] - public string v_SheetName { get; set; } - - public ExcelActivateSheetCommand() - { - //this.CommandName = "ExcelActivateSheetCommand"; - //this.SelectionName = "Activate Sheet"; - //this.CommandEnabled = true; - //this.CustomRendering = true; - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - (var excelInstance, var currentSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); - - Microsoft.Office.Interop.Excel.Worksheet targetSheet = v_SheetName.GetExcelWorksheet(engine, excelInstance); - - if (currentSheet.Name != targetSheet.Name) - { - targetSheet.Select(); - } - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelActivateWorksheetCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelActivateWorksheetCommand.cs new file mode 100644 index 000000000..8e4887b7f --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/ExcelActivateWorksheetCommand.cs @@ -0,0 +1,47 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("Worksheet")] + [Attributes.ClassAttributes.CommandSettings("Activate Worksheet")] + [Attributes.ClassAttributes.Description("This command allows you to activate a specific worksheet in a workbook")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to switch to a specific worksheet")] + [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ExcelActivateWorksheetCommand : AExcelSheetCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] + //public string v_SheetName { get; set; } + + public ExcelActivateWorksheetCommand() + { + //this.CommandName = "ExcelActivateSheetCommand"; + //this.SelectionName = "Activate Sheet"; + //this.CommandEnabled = true; + //this.CustomRendering = true; + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //(var excelInstance, var currentSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //Microsoft.Office.Interop.Excel.Worksheet targetSheet = v_SheetName.ExpandValueOrUserVariableAsExcelWorksheet(engine, excelInstance); + + (_, var targetSheet, var currentSheet) = this.ExpandValueOrVariableAsExcelInstnaceAndWorksheetAndCurrentSheet(engine); + + if (currentSheet.Name != targetSheet.Name) + { + targetSheet.Select(); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelAddWorkbookCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelAddWorkbookCommand.cs index 4fdc30258..e7e00c72b 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelAddWorkbookCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelAddWorkbookCommand.cs @@ -5,19 +5,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("File/Book")] [Attributes.ClassAttributes.CommandSettings("Add Workbook")] [Attributes.ClassAttributes.Description("This command adds a new Excel Workbook.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a new workbook to an Exel Instance")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelAddWorkbookCommand : ScriptCommand + public sealed class ExcelAddWorkbookCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyDescription("When Workbook Exists")] @@ -31,6 +32,7 @@ public class ExcelAddWorkbookCommand : ScriptCommand [PropertyUISelectionOption("Error")] [PropertyUISelectionOption("Add")] [PropertyIsOptional(true, "Error")] + [PropertyParameterOrder(6000)] public string v_IfWorkbookExists { get; set; } public ExcelAddWorkbookCommand() @@ -40,20 +42,19 @@ public ExcelAddWorkbookCommand() //this.CommandEnabled = true; //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var excelInstance = v_InstanceName.GetExcelInstance(engine); + //var excelInstance = v_InstanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + var excelInstance = this.ExpandValueOrVariableAsExcelInstance(engine); - var ifWorkbookExists = this.GetUISelectionValue(nameof(v_IfWorkbookExists), engine); + var ifWorkbookExists = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfWorkbookExists), "When Workbook Exists", engine); if (excelInstance.Workbooks.Count > 0) { switch (ifWorkbookExists) { case "error": - throw new Exception("Excel Instance '" + v_InstanceName + "' has Workbook."); + throw new Exception($"Excel Instance '{v_InstanceName}' has Workbooks."); case "ignore": break; diff --git a/taskt/Core/Automation/Commands/Excel/ExcelAddWorksheetCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelAddWorksheetCommand.cs index 2e06989c8..b50b533ff 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelAddWorksheetCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelAddWorksheetCommand.cs @@ -5,27 +5,29 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] - [Attributes.ClassAttributes.SubGruop("Sheet")] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("Worksheet")] [Attributes.ClassAttributes.CommandSettings("Add Worksheet")] [Attributes.ClassAttributes.Description("This command adds a new Excel Worksheet.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a new worksheet to an Excel Instance")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelAddWorksheetCommand : ScriptCommand + public sealed class ExcelAddWorksheetCommand : AExcelSheetCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] - [PropertyDescription("New Sheet Name")] + [PropertyDescription("New Worksheet Name")] [PropertyDetailSampleUsageBehavior(MultiAttributesBehavior.Overwrite)] - [PropertyDetailSampleUsage("**mySheet**", PropertyDetailSampleUsage.ValueType.Value, "Sheet Name")] - [PropertyDetailSampleUsage("**{{{vSheet}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Sheet Name")] - public string v_NewSheetName { get; set; } + [PropertyDetailSampleUsage("**mySheet**", PropertyDetailSampleUsage.ValueType.Value, "Worksheet Name")] + [PropertyDetailSampleUsage("**{{{vSheet}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Worksheet Name")] + [PropertyAvailableSystemVariableBehavior(MultiAttributesBehavior.Overwrite)] + [PropertyAvailableSystemVariable(Engine.SystemVariables.LimitedSystemVariableNames.None)] + public override string v_SheetName { get; set; } public ExcelAddWorksheetCommand() { @@ -34,18 +36,20 @@ public ExcelAddWorksheetCommand() //this.CommandEnabled = true; //this.CustomRendering = true; } - public override void RunCommand(object sender) + + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var excelInstance = v_InstanceName.GetExcelInstance(engine); + //var excelInstance = v_InstanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + var excelInstance = this.ExpandValueOrVariableAsExcelInstance(engine); excelInstance.Worksheets.Add(); - var sheetName = v_NewSheetName.ConvertToUserVariable(engine); - if (!String.IsNullOrEmpty(sheetName)) - { - ((Microsoft.Office.Interop.Excel.Worksheet)excelInstance.ActiveSheet).Name = sheetName; - } + //var sheetName = v_SheetName.ExpandValueOrUserVariable(engine); + var sheetName = this.ExpandValueOrVariableAsExcelWorksheetName(v_SheetName, engine); + ((Microsoft.Office.Interop.Excel.Worksheet)excelInstance.ActiveSheet).Name = sheetName; + //if (!string.IsNullOrEmpty(sheetName)) + //{ + // ((Microsoft.Office.Interop.Excel.Worksheet)excelInstance.ActiveSheet).Name = sheetName; + //} } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelAppendCellCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelAppendCellCommand.cs index 0c10fdf71..2e000a110 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelAppendCellCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelAppendCellCommand.cs @@ -1,40 +1,52 @@ using System; -using System.Collections.Generic; -using System.Windows.Forms; using System.Xml.Serialization; -using System.Linq; -using taskt.UI.CustomControls; -using taskt.UI.Forms; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Cell")] [Attributes.ClassAttributes.CommandSettings("Append Cell")] [Attributes.ClassAttributes.Description("Append input to last row of sheet into the first cell.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a value to the last cell.")] [Attributes.ClassAttributes.ImplementationDescription("")] - public class ExcelAppendCellCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ExcelAppendCellCommand : AExcelColumnSpecifiedCommands { + //[XmlAttribute] + //[PropertyDescription("Please Enter the instance name")] + //[InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] + //[SampleUsage("**myInstance** or **excelInstance**")] + //[Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //public string v_InstanceName { get; set; } + [XmlAttribute] - [PropertyDescription("Please Enter the instance name")] - [InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] - [SampleUsage("**myInstance** or **excelInstance**")] - [Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyDescription("Please Enter text to set")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter the text value that will be set.")] - [SampleUsage("Hello World or {vText}")] - [Remarks("")] + //[PropertyDescription("Please Enter text to set")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Enter the text value that will be set.")] + //[SampleUsage("Hello World or {vText}")] + //[Remarks("")] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueToSet))] + [PropertyParameterOrder(6000)] public string v_TextToSet { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //public string v_ColumnType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnLocation))] + //public string v_ColumnIndex { get; set; } + + //[XmlAttribute] + //public string v_ValueType { get; set; } + public ExcelAppendCellCommand() { //this.CommandName = "ExcelAppendCellCommand"; @@ -42,45 +54,57 @@ public ExcelAppendCellCommand() //this.CommandEnabled = true; //this.CustomRendering = true; - this.v_InstanceName = ""; + //this.v_InstanceName = ""; } - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); - - int test = 0; - test = excelSheet.Columns.Count; - var lastUsedRow = excelSheet.Cells.Find("*", System.Reflection.Missing.Value, - System.Reflection.Missing.Value, System.Reflection.Missing.Value, - Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious, - false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row; - var targetAddress = "A" + (lastUsedRow + 1); - var targetText = v_TextToSet.ConvertToUserVariable(sender); - excelSheet.Range[targetAddress].Value = targetText; - } - public override List Render(frmCommandEditor editor) + + public override void RunCommand(Engine.AutomationEngineInstance engine) { - base.Render(editor); + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); - //create standard group controls - var instanceCtrls = CommandControls.CreateDefaultDropdownGroupFor("v_InstanceName", this, editor); - CommandControls.AddInstanceNames((ComboBox)instanceCtrls.Where(t => (t.Name == "v_InstanceName")).FirstOrDefault(), editor, PropertyInstanceType.InstanceType.Excel); - RenderedControls.AddRange(instanceCtrls); - //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_TextToSet", this, editor)); + //int test = 0; + //test = excelSheet.Columns.Count; + //var lastUsedRow = excelSheet.Cells.Find("*", System.Reflection.Missing.Value, + // System.Reflection.Missing.Value, System.Reflection.Missing.Value, + // Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious, + // false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row; + //var targetAddress = "A" + (lastUsedRow + 1); + //var targetText = v_TextToSet.ExpandValueOrUserVariable(engine); + //excelSheet.Range[targetAddress].Value = targetText; - if (editor.creationMode == frmCommandEditor.CreationMode.Add) - { - this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; - } + (var sheet, var columnIndex) = this.ExpandValueOrVariableAsExcelCurrentWorksheetAndColumnIndex(engine); - return RenderedControls; - } - public override string GetDisplayValue() - { - return base.GetDisplayValue() + " [Append last cell to: " + v_TextToSet + ", Instance Name: '" + v_InstanceName + "']"; + var rowIndex = sheet.FirstBlankRowIndex(columnIndex, 1, this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), "Value Type", engine)); + + var targetText = v_TextToSet.ExpandValueOrUserVariable(engine); + + var setFunc = this.ExpandValueOrVaribleAsSetValueAction(engine); + + setFunc(targetText, sheet, columnIndex, rowIndex); } + + //public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // base.Render(editor); + + // //create standard group controls + // var instanceCtrls = CommandControls.CreateDefaultDropdownGroupFor("v_InstanceName", this, editor); + // CommandControls.AddInstanceNames((ComboBox)instanceCtrls.Where(t => (t.Name == "v_InstanceName")).FirstOrDefault(), editor, PropertyInstanceType.InstanceType.Excel); + // RenderedControls.AddRange(instanceCtrls); + // //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); + // RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_TextToSet", this, editor)); + + // if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) + // { + // this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; + // } + + // return RenderedControls; + //} + + //public override string GetDisplayValue() + //{ + // return base.GetDisplayValue() + " [Append last cell to: " + v_TextToSet + ", Instance Name: '" + v_InstanceName + "']"; + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelAppendRowCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelAppendRowCommand.cs index 2edf1b134..3cd9c69af 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelAppendRowCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelAppendRowCommand.cs @@ -1,40 +1,66 @@ using System; -using System.Collections.Generic; -using System.Windows.Forms; using System.Xml.Serialization; -using System.Linq; -using taskt.UI.CustomControls; -using taskt.UI.Forms; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Row")] [Attributes.ClassAttributes.CommandSettings("Append Row")] [Attributes.ClassAttributes.Description("Append to last row of sheet.")] [Attributes.ClassAttributes.UsesDescription("Use this command will take in a comma seprerated value and append it to the end of an excel sheet.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automations.")] - public class ExcelAppendRowCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ExcelAppendRowCommand : AExcelColumnSpecifiedCommands { + //[XmlAttribute] + //[PropertyDescription("Please Enter the instance name")] + //[InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] + //[SampleUsage("**myInstance** or **excelInstance**")] + //[Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //public string v_InstanceName { get; set; } + [XmlAttribute] - [PropertyDescription("Please Enter the instance name")] - [InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] - [SampleUsage("**myInstance** or **excelInstance**")] - [Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_InstanceName { get; set; } + //[PropertyDescription("Please Enter the Row to set")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Enter the text value that will be set (This could be a DataRow).")] + //[SampleUsage("Hello,world or {vText}")] + //[Remarks("")] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueToSet))] + [PropertyDetailSampleUsageBehavior(MultiAttributesBehavior.Overwrite)] + [PropertyDetailSampleUsage("**Hello,World**", "Specified **Hello** and **World**.")] + [PropertyDetailSampleUsage("**{{{vText}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Value To Set")] + [PropertyParameterOrder(6000)] + public string v_TextToSet { get; set; } [XmlAttribute] - [PropertyDescription("Please Enter the Row to set")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter the text value that will be set (This could be a DataRow).")] - [SampleUsage("Hello,world or {vText}")] + [PropertyDescription("Text Separator")] + [InputSpecification("")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage("**,**", PropertyDetailSampleUsage.ValueType.Value, "Text Separator")] + [PropertyDetailSampleUsage("**{{{vSep}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Text Separator")] + [PropertyTextBoxSetting(1, false)] + [PropertyIsOptional(true, ",")] + [PropertyFirstValue(",")] [Remarks("")] - public string v_TextToSet { get; set; } + [PropertyDisplayText(false, "Text Separator")] + [PropertyParameterOrder(6500)] + public string v_TextSeparator { get; set; } + + //[XmlAttribute] + //public string v_ColumnType { get; set; } + + //[XmlAttribute] + //public string v_ColumnIndex { get; set; } + + //[XmlAttribute] + //public string v_ValueType { get; set; } public ExcelAppendRowCommand() { @@ -43,66 +69,92 @@ public ExcelAppendRowCommand() //this.CommandEnabled = true; //this.CustomRendering = true; - this.v_InstanceName = ""; + //this.v_InstanceName = ""; } - public override void RunCommand(object sender) + + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var splittext = v_TextToSet.Split(','); + //var splittext = v_TextToSet.Split(','); - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + ////(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); - int i = 1; - int lastUsedRow; - try - { - lastUsedRow = excelSheet.Cells.Find("*", System.Reflection.Missing.Value, - System.Reflection.Missing.Value, System.Reflection.Missing.Value, - Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious, - false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row; - } - catch(Exception) + //int i = 1; + //int lastUsedRow; + //try + //{ + // lastUsedRow = excelSheet.Cells.Find("*", System.Reflection.Missing.Value, + // System.Reflection.Missing.Value, System.Reflection.Missing.Value, + // Microsoft.Office.Interop.Excel.XlSearchOrder.xlByRows, Microsoft.Office.Interop.Excel.XlSearchDirection.xlPrevious, + // false, System.Reflection.Missing.Value, System.Reflection.Missing.Value).Row; + //} + //catch(Exception) + //{ + // lastUsedRow = 0; + //} + + //var targetText = v_TextToSet.ExpandValueOrUserVariable(engine); + //splittext = targetText.Split(','); + + //foreach (var item in splittext) + //{ + // string output = item; + // if (item.Contains("[") || item.Contains("]")) + // output = item.Trim('[', ']'); + // output = output.Trim('"'); + // if (output=="null") + // { + // output = string.Empty; + // } + // excelSheet.Cells[lastUsedRow + 1, i] = output; + // i++; + //} + + (var sheet, var columnIndex) = this.ExpandValueOrVariableAsExcelCurrentWorksheetAndColumnIndex(engine); + + var rowIndex = sheet.FirstBlankRowIndex(columnIndex, 1, this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), "Value Type", engine)); + + var setFunc = this.ExpandValueOrVaribleAsSetValueAction(engine); + + var targetText = v_TextToSet.ExpandValueOrUserVariable(engine); + var separator = v_TextSeparator.ExpandValueOrUserVariable(engine); + + if (separator.Length > 1) { - lastUsedRow = 0; + throw new Exception($"Separator must specify only one character. Value: '{v_TextSeparator}', Expand Value: '{separator}'"); } - var targetText = v_TextToSet.ConvertToUserVariable(sender); - splittext = targetText.Split(','); + var lst = targetText.Split(separator[0]); - foreach (var item in splittext) + int index = 0; + foreach(var v in lst) { - string output = item; - if (item.Contains("[") || item.Contains("]")) - output = item.Trim('[', ']'); - output = output.Trim('"'); - if (output=="null") - { - output = string.Empty; - } - excelSheet.Cells[lastUsedRow + 1, i] = output; - i++; + setFunc(v, sheet, columnIndex + index, rowIndex); + index++; } } - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - var instanceCtrls = CommandControls.CreateDefaultDropdownGroupFor("v_InstanceName", this, editor); - CommandControls.AddInstanceNames((ComboBox)instanceCtrls.Where(t => (t.Name == "v_InstanceName")).FirstOrDefault(), editor, PropertyInstanceType.InstanceType.Excel); - RenderedControls.AddRange(instanceCtrls); - //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_TextToSet", this, editor)); + //public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // base.Render(editor); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) - { - this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; - } + // var instanceCtrls = CommandControls.CreateDefaultDropdownGroupFor("v_InstanceName", this, editor); + // CommandControls.AddInstanceNames((ComboBox)instanceCtrls.Where(t => (t.Name == "v_InstanceName")).FirstOrDefault(), editor, PropertyInstanceType.InstanceType.Excel); + // RenderedControls.AddRange(instanceCtrls); + // //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); + // RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_TextToSet", this, editor)); - return RenderedControls; - } - public override string GetDisplayValue() - { - return base.GetDisplayValue() + " [Append Row '" +v_TextToSet+ " to last row of workboook with Instance Name: '" + v_InstanceName + "']"; - } + // if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) + // { + // this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; + // } + + // return RenderedControls; + //} + + //public override string GetDisplayValue() + //{ + // return base.GetDisplayValue() + " [Append Row '" +v_TextToSet+ " to last row of workboook with Instance Name: '" + v_InstanceName + "']"; + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelCheckCellValueExistsCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelCheckCellValueExistsCommand.cs index f9caba97c..236cfd19e 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelCheckCellValueExistsCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelCheckCellValueExistsCommand.cs @@ -7,33 +7,37 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Cell")] [Attributes.ClassAttributes.CommandSettings("Check Cell Value Exists")] [Attributes.ClassAttributes.Description("This command checks existance value from a specified Excel Cell.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a value from a specific cell.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Excel Interop' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelCheckCellValueExistsCommand : ScriptCommand + public sealed class ExcelCheckCellValueExistsCommand : AExcelCellActionCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CellRangeLocation))] - public string v_ExcelCellAddress { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CellRangeLocation))] + //[PropertyParameterOrder(6000)] + //public string v_CellLocation { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] [Remarks("When the Value Exists, Result is **True**")] - public string v_userVariableName { get; set; } + [PropertyParameterOrder(6500)] + public string v_Result { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CheckableValueType))] [PropertySelectionChangeEvent(nameof(cmbValueType_SelectedIndexChanged))] - public string v_ValueType { get; set; } + //[PropertyParameterOrder(6002)] + public override string v_ValueType { get; set; } public ExcelCheckCellValueExistsCommand() { @@ -43,19 +47,22 @@ public ExcelCheckCellValueExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //var rg = v_CellLocation.GetExcelRange(engine, excelInstance, excelSheet, this); - var rg = v_ExcelCellAddress.GetExcelRange(engine, excelInstance, excelSheet, this); + ////var valueType = this.GetUISelectionValue(nameof(v_ValueType), engine); - var valueType = this.GetUISelectionValue(nameof(v_ValueType), engine); + ////var chkFunc = ExcelControls.CheckCellValueFunctionFromRange(valueType); + //var chkFunc = ExcelControls.CheckCellValueFunctionFromRange(nameof(v_ValueType), this, engine); - var chkFunc = ExcelControls.CheckCellValueFunctionFromRange(valueType); + //chkFunc(rg).StoreInUserVariable(engine, v_Result); - chkFunc(rg).StoreInUserVariable(engine, v_userVariableName); + var rg = this.ExpandValueOrVariableAsExcelSingleCellLocation(engine); + var chkFunc = this.ExpandValueOrVariableAsCheckValueFunction(engine); + chkFunc(rg).StoreInUserVariable(engine, v_Result); } private void cmbValueType_SelectedIndexChanged(object sender, EventArgs e) diff --git a/taskt/Core/Automation/Commands/Excel/ExcelCheckCellValueExistsRCCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelCheckCellValueExistsRCCommand.cs index 4fa9716ea..3aa7df6ed 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelCheckCellValueExistsRCCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelCheckCellValueExistsRCCommand.cs @@ -7,37 +7,42 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Cell")] [Attributes.ClassAttributes.CommandSettings("Check Cell Value Exists RC")] [Attributes.ClassAttributes.Description("This command checks existance value from a specified Excel Cell.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a value from a specific cell.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Excel Interop' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelCheckCellValueExistsRCCommand : ScriptCommand + public sealed class ExcelCheckCellValueExistsRCCommand : AExcelRCLocationActionCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] - public string v_CellRow { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + //[PropertyParameterOrder(6001)] + //public string v_CellRow { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnLocation))] - public string v_CellColumn { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnLocation))] + //[PropertyParameterOrder(6002)] + //public string v_CellColumn { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] [Remarks("When the Value Exists, Result is **True**")] - public string v_userVariableName { get; set; } + [PropertyParameterOrder(8000)] + public string v_Result { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CheckableValueType))] [PropertySelectionChangeEvent(nameof(cmbValueType_SelectedIndexChanged))] - public string v_ValueType { get; set; } + //[PropertyParameterOrder(6004)] + public override string v_ValueType { get; set; } public ExcelCheckCellValueExistsRCCommand() { @@ -47,19 +52,34 @@ public ExcelCheckCellValueExistsRCCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //var rg = this.GetExcelRange(nameof(v_CellRow), nameof(v_CellColumn), engine, excelInstance, excelSheet); + + ////var valueType = this.GetUISelectionValue(nameof(v_ValueType), engine); + + ////var chkFunc = ExcelControls.CheckCellValueFunctionFromRange(valueType); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //var chkFunc = ExcelControls.CheckCellValueFunctionFromRange(nameof(v_ValueType), this, engine); - var rg = this.GetExcelRange(nameof(v_CellRow), nameof(v_CellColumn), engine, excelInstance, excelSheet); + //chkFunc(rg).StoreInUserVariable(engine, v_Result); - var valueType = this.GetUISelectionValue(nameof(v_ValueType), engine); + //var rg = this.ExpandValueOrVariableAsExcelCellLocation(engine); + //var chkFunc = this.ExpandValueOrVariableAsCheckRangeFunction(engine); + //chkFunc(rg).StoreInUserVariable(engine, v_Result); - var chkFunc = ExcelControls.CheckCellValueFunctionFromRange(valueType); + //(_, var sheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(var row, var column) = this.ExpandValueOrVariableAsCellRowAndColumnIndex(engine); + //var chkFunc = this.ExpandValueOrVariableAsCheckValueFunction(engine); + //chkFunc(sheet, column, row).StoreInUserVariable(engine, v_Result); - chkFunc(rg).StoreInUserVariable(engine, v_userVariableName); + this.RCLocationAction(new Action((sheet, column, row) => + { + var chkFunc = this.ExpandValueOrVariableAsCheckValueFunction(engine); + chkFunc(sheet, column, row).StoreInUserVariable(engine, v_Result); + }), engine); } private void cmbValueType_SelectedIndexChanged(object sender, EventArgs e) diff --git a/taskt/Core/Automation/Commands/Excel/ExcelCheckExcelInstanceExistsCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelCheckExcelInstanceExistsCommand.cs index 409317d43..592b271eb 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelCheckExcelInstanceExistsCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelCheckExcelInstanceExistsCommand.cs @@ -5,24 +5,26 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Instance")] [Attributes.ClassAttributes.CommandSettings("Check Excel Instance Exists")] [Attributes.ClassAttributes.Description("This command returns existance of Excel instance.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check Excel instance.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelCheckExcelInstanceExistsCommand : ScriptCommand + public sealed class ExcelCheckExcelInstanceExistsCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] [Remarks("When the Excel Instance Exists, Result is **True**")] - public string v_applyToVariableName { get; set; } + [PropertyParameterOrder(6000)] + public string v_Result { get; set; } public ExcelCheckExcelInstanceExistsCommand() { @@ -32,17 +34,17 @@ public ExcelCheckExcelInstanceExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; try { - var excelInstance = v_InstanceName.GetExcelInstance(engine); - true.StoreInUserVariable(engine, v_applyToVariableName); + //var excelInstance = v_InstanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + this.ExpandValueOrVariableAsExcelInstance(engine); + true.StoreInUserVariable(engine, v_Result); } catch { - false.StoreInUserVariable(engine, v_applyToVariableName); + false.StoreInUserVariable(engine, v_Result); } } } diff --git a/taskt/Core/Automation/Commands/Excel/ExcelCheckWorksheetExistsCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelCheckWorksheetExistsCommand.cs index b529a79b6..a97469983 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelCheckWorksheetExistsCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelCheckWorksheetExistsCommand.cs @@ -5,28 +5,30 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] - [Attributes.ClassAttributes.SubGruop("Sheet")] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("Worksheet")] [Attributes.ClassAttributes.CommandSettings("Check Worksheet Exists")] [Attributes.ClassAttributes.Description("This command allows you to check existance sheet")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to switch to a specific worksheet")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelCheckWorksheetExistsCommand : ScriptCommand + public sealed class ExcelCheckWorksheetExistsCommand : AExcelSheetCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] - public string v_SheetName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] + //public string v_SheetName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] [Remarks("When the Sheet Exists, Result is **True**")] - public string v_applyToVariable { get; set; } + [PropertyParameterOrder(7000)] + public string v_Result { get; set; } public ExcelCheckWorksheetExistsCommand() { @@ -35,13 +37,28 @@ public ExcelCheckWorksheetExistsCommand() //this.CommandEnabled = true; //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var sht) = (v_InstanceName, v_SheetName).GetExcelInstanceAndWorksheet(engine, true); + //(_, var sht) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(v_SheetName, engine, true); - (sht != null).StoreInUserVariable(engine, v_applyToVariable); + //(sht != null).StoreInUserVariable(engine, v_applyToVariable); + try + { + this.ExpandValueOrVariableAsExcelInstanceAndWorksheet(engine); + true.StoreInUserVariable(engine, v_Result); + } + catch (Exception ex) + { + var msg = ex.Message; + if (msg.StartsWith("Worksheet '") && msg.EndsWith("' does not exists.")) + { + false.StoreInUserVariable(engine, v_Result); + } + else + { + throw ex; + } + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelCloseExcelInstanceCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelCloseExcelInstanceCommand.cs index 915bfedac..3716be521 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelCloseExcelInstanceCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelCloseExcelInstanceCommand.cs @@ -5,19 +5,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Instance")] [Attributes.ClassAttributes.CommandSettings("Close Excel Instance")] [Attributes.ClassAttributes.Description("This command allows you to close Excel instance.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to close an open instance of Excel.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelCloseExcelInstanceCommand : ScriptCommand + public sealed class ExcelCloseExcelInstanceCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyDescription("If the Workbook should be Saved")] @@ -29,6 +30,7 @@ public class ExcelCloseExcelInstanceCommand : ScriptCommand [PropertyDetailSampleUsage("**False**", "Whether the Workbook needs to be Saved or not, Close it without saving")] [PropertyIsOptional(true, "False")] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyParameterOrder(6000)] public string v_ExcelSaveOnExit { get; set; } public ExcelCloseExcelInstanceCommand() @@ -39,19 +41,19 @@ public ExcelCloseExcelInstanceCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var vInstance = v_InstanceName.ConvertToUserVariable(engine); - var excelInstance = v_InstanceName.GetExcelInstance(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); + //var excelInstance = v_InstanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + var excelInstance = this.ExpandValueOrVariableAsExcelInstance(engine); //check if workbook exists and save if (excelInstance.ActiveWorkbook != null) { - string vSaved = this.GetUISelectionValue(nameof(v_ExcelSaveOnExit), "Save Setting", engine); + //string vSaved = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ExcelSaveOnExit), "Save Setting", engine); + var isSaved = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExcelSaveOnExit), engine); - excelInstance.ActiveWorkbook.Close((vSaved == "true")); + excelInstance.ActiveWorkbook.Close(isSaved); } //close excel diff --git a/taskt/Core/Automation/Commands/Excel/ExcelCopyWorksheetCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelCopyWorksheetCommand.cs index 9d6961adf..2faa52288 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelCopyWorksheetCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelCopyWorksheetCommand.cs @@ -5,34 +5,39 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] - [Attributes.ClassAttributes.SubGruop("Sheet")] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("Worksheet")] [Attributes.ClassAttributes.CommandSettings("Copy Worksheet")] [Attributes.ClassAttributes.Description("This command copy a Excel Worksheet.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to copy a new worksheet to an Excel Instance")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelCopyWorksheetCommand : ScriptCommand + public sealed class ExcelCopyWorksheetCommand : AExcelInstanceCommands, IExcelWorksheetCopyRenameProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] [PropertyDescription("Sheet Name to Copy")] [PropertyValidationRule("Sheet Name to Copy", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Sheet Name to Copy")] - public string v_sourceSheet { get; set; } + [PropertyAvailableSystemVariable(Engine.SystemVariables.LimitedSystemVariableNames.Excel_Worksheet)] + [PropertyParameterOrder(6000)] + public string v_TargetSheetName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] [PropertyDescription("New Sheet Name")] [PropertyDisplayText(true, "New Sheet Name")] [PropertyIsOptional(true)] + [PropertyValidationRule("New Sheet Name", PropertyValidationRule.ValidationRuleFlags.None)] [PropertyIntermediateConvert("", "")] - public string v_newSheetName { get; set; } + [PropertyParameterOrder(7000)] + public string v_NewSheetName { get; set; } public ExcelCopyWorksheetCommand() { @@ -41,19 +46,32 @@ public ExcelCopyWorksheetCommand() //this.CommandEnabled = true; //this.CustomRendering = true; } - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - (var excelInstance, var targetSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //(var excelInstance, var targetSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (var excelInstance, var targetSheet) = this.ExpandValueOrVariableAsExcelInstanceAndTargetWorksheet(engine); targetSheet.Copy(Before: excelInstance.Worksheets[1]); - var newName = v_newSheetName.ConvertToUserVariable(sender); - if (!String.IsNullOrEmpty(newName)) + try { + var newName = this.ExpandValueOrVariableAsExcelWorksheetName(v_NewSheetName, engine); ((Microsoft.Office.Interop.Excel.Worksheet)excelInstance.ActiveSheet).Name = newName; } + catch (Exception ex) + { + if (ex.Message != "Worksheet name is Empty.") + { + throw ex; + } + } + + //var newName = v_NewSheetName.ExpandValueOrUserVariable(engine); + //if (!string.IsNullOrEmpty(newName)) + //{ + // ((Microsoft.Office.Interop.Excel.Worksheet)excelInstance.ActiveSheet).Name = newName; + //} } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelCreateDataTableFromExcelFile.cs b/taskt/Core/Automation/Commands/Excel/ExcelCreateDataTableFromExcelFile.cs new file mode 100644 index 000000000..f149997f4 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/ExcelCreateDataTableFromExcelFile.cs @@ -0,0 +1,183 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("File/Book")] + [Attributes.ClassAttributes.CommandSettings("Create DataTable From Excel File")] + [Attributes.ClassAttributes.Description("This command Open a File and Get Cell Values as a DataTable")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Open a File and Get Cell Values as a DataTable")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ExcelCreateDataTableFromExcelFile : ScriptCommand + { + [XmlAttribute] + //[PropertyDescription("Please create a DataTable Variable Name")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Indicate a unique reference name for later use")] + //[SampleUsage("**vMyDataset** or **{{{vMyDataset}}}**")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //[PropertyIsVariablesList(true)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] + //[PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] + //[PropertyValidationRule("DataTable", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "DataTable")] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] + public string v_DataTableName { get; set; } + + [XmlAttribute] + //[PropertyDescription("Please indicate the workbook file path")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowFileSelectionHelper)] + //[InputSpecification("Enter or Select the path to the workbook file")] + //[SampleUsage("**C:\\temp\\myfile.xlsx** or **{{{vFilePath}}}**")] + //[Remarks("This command does not require Excel to be opened. A snapshot will be taken of the workbook as it exists at the time this command runs.")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyTextBoxSetting(1, false)] + //[PropertyValidationRule("File", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "File")] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_FilePath))] + [PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtensionAndExists, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "xlsx,xlsm,xls,xlm,csv,ods")] + public string v_FilePath { get; set; } + + [XmlAttribute] + //[PropertyDescription("Please indicate the sheet name")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Indicate the specific sheet that should be retrieved.")] + //[SampleUsage("**Sheet1** or **mySheet** or **{{{vSheet}}}**")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyTextBoxSetting(1, false)] + //[PropertyValidationRule("Sheet", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "Sheet")] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] + public string v_SheetName { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + public string v_ColumnType { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + [PropertyValidationRule("Column Index", PropertyValidationRule.ValidationRuleFlags.None)] + public string v_ColumnIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + [PropertyIsOptional(true, "1")] + [PropertyValidationRule("Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + public string v_RowIndex { get; set; } + + [XmlAttribute] + //[PropertyDescription("Indicate if Header Row Exists")] + //[PropertyUISelectionOption("Yes")] + //[PropertyUISelectionOption("No")] + //[InputSpecification("Select the necessary indicator")] + //[SampleUsage("Select **Yes**, **No**. Data will be loaded as column headers if **YES** is selected.")] + //[Remarks("")] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Use the First Row as the Column Names (Value Type is Cell only)")] + [PropertyIsOptional(true, "No")] + public string v_FirstRowAsColumnName { get; set; } + + public ExcelCreateDataTableFromExcelFile() + { + //this.CommandName = "LoadDataTableCommand"; + //this.SelectionName = "Load DataTable"; + //this.CommandEnabled = true; + //this.CustomRendering = true; + + //this.v_ContainsHeaderRow = "Yes"; + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //DataTableControls dataSetCommand = new DataTableControls(); + + //string filePath = FilePathControls.FormatFilePath_NoFileCounter(v_FilePath, engine, new List() { "xlsx", "xlsm", "xls" }, true); + //var filePath = v_FilePath.ExpandValueOrUserVariable(engine); + + //DataTable requiredData = DataTableControls.CreateDataTable(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + $@";Extended Properties=""Excel 12.0;HDR={v_ContainsHeaderRow.ExpandValueOrUserVariable(engine)};IMEX=1""", "Select * From [" + v_SheetName.ExpandValueOrUserVariable(engine) + "$]"); + + //requiredData.StoreInUserVariable(engine, v_DataSetName); + + var instanceName = engine.GetNewAppInstanceName(); + + var createInstance = new ExcelCreateExcelInstanceCommand() + { + v_InstanceName = instanceName, + }; + createInstance.RunCommand(engine); + + var openFile = new ExcelOpenWorkbookCommand() + { + v_InstanceName = instanceName, + v_FilePath = this.v_FilePath, + }; + openFile.RunCommand(engine); + + var activateSheet = new ExcelActivateWorksheetCommand() + { + v_InstanceName = instanceName, + v_SheetName = this.v_SheetName, + }; + activateSheet.RunCommand(engine); + + var columnType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ColumnType), "Column Type", engine); + var columnIndex = this.ExpandValueOrUserVariable(nameof(v_ColumnIndex), "Column Index", engine); + if (string.IsNullOrEmpty(columnIndex)) + { + switch (columnType) + { + case "range": + columnIndex = "A"; + break; + case "rc": + columnIndex = "1"; + break; + } + } + var rowIndex = this.ExpandValueOrUserVariableAsInteger(nameof(v_RowIndex), "Row Index", engine); + + var convertDataTable = new ExcelGetRangeValuesAsDataTableCommand() + { + v_InstanceName = instanceName, + v_RowStart = rowIndex.ToString(), + v_ColumnStart = columnIndex, + v_ColumnType = this.v_ColumnType, + v_Result = this.v_DataTableName, + v_FirstRowAsColumnName = this.v_FirstRowAsColumnName, + }; + convertDataTable.RunCommand(engine); + + var closeInstance = new ExcelCloseExcelInstanceCommand() + { + v_InstanceName = instanceName, + }; + closeInstance.RunCommand(engine); + } + + //public override List Render(frmCommandEditor editor) + //{ + // base.Render(editor); + + // var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); + // RenderedControls.AddRange(ctrls); + + // return RenderedControls; + //} + + //public override string GetDisplayValue() + //{ + // return base.GetDisplayValue() + " [Get '" + v_SheetName + "' from '" + v_FilePath + "' and apply to '" + v_DataSetName + "']"; + //} + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelCreateDictionaryFromExcelFile.cs b/taskt/Core/Automation/Commands/Excel/ExcelCreateDictionaryFromExcelFile.cs new file mode 100644 index 000000000..27183112e --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/ExcelCreateDictionaryFromExcelFile.cs @@ -0,0 +1,299 @@ +using System; +using System.Collections.Generic; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("File/Book")] + [Attributes.ClassAttributes.CommandSettings("Create Dictionary From Excel File")] + [Attributes.ClassAttributes.Description("This command Open a File and Get Cell Values as a Dictionary")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Open a File and Get Cell Values as a Dictionary")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_dictionary))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ExcelCreateDictionaryFromExcelFile : ScriptCommand, ICanHandleDictionary, ICanHandleList + { + [XmlAttribute] + //[PropertyDescription("Please Enter the Dictionary Variable Name")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Enter a name for a Dictionary.")] + //[SampleUsage("**myDictionary** or **{{{vDictionary}}}**")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.Dictionary)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //[PropertyIsVariablesList(true)] + //[PropertyValidationRule("Dictionary", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "Dictionary")] + [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_OutputDictionaryName))] + public string v_DictionaryName { get; set; } + + [XmlAttribute] + //[PropertyDescription("Please indicate the Workbook File Path")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowFileSelectionHelper)] + //[InputSpecification("Enter or Select the path to the applicable file that should be loaded into the Dictionary.")] + //[SampleUsage("**C:\\temp\\myfile.xlsx** or **{{{vFilePath}}}**")] + //[Remarks("If file does not contain extension, supplement extensions supported by Excel.\nIf file does not contain folder path, file will be opened in the same folder as script file.")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyTextBoxSetting(1, false)] + //[PropertyValidationRule("File Path", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "File Path")] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_FilePath))] + [PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtensionAndExists, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "xlsx,xlsm,xls,xlm,csv,ods")] + public string v_FilePath { get; set; } + + [XmlAttribute] + //[PropertyDescription("Please indicate the Sheet Name")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Enter the sheet name of the workbook to be read.")] + //[SampleUsage("**Sheet1** or **{{{vSheet}}}**")] + //[Remarks("Sheet has one table")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyTextBoxSetting(1, false)] + //[PropertyValidationRule("Sheet Name", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "Sheet Name")] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] + public string v_SheetName { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + public string v_ColumnType { get; set; } + + [XmlAttribute] + //[PropertyDescription("Please indicate the Key Column")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Enter the key column name to create a Dictionary off of.")] + //[SampleUsage("**Key** or **{{{vKeyColumn}}}**")] + //[Remarks("This value is NOT Column Index Value like A, B. Please specify table column name.")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyTextBoxSetting(1, false)] + //[PropertyValidationRule("Key Column", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "Key Column")] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + [PropertyDescription("Key Column")] + public string v_KeyColumn { get; set; } + + [XmlAttribute] + //[PropertyDescription("Please indicate the Value Column")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Enter a value column name to create a Dictionary off of.")] + //[SampleUsage("**Value** or **{{{vValueColumn}}}**")] + //[Remarks("This value is NOT Column Index Value like A, B. Please specify table column name.")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyTextBoxSetting(1, false)] + //[PropertyValidationRule("Value Colmun", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "Value Column")] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + [PropertyDescription("Value Column")] + public string v_ValueColumn { get; set; } + + public ExcelCreateDictionaryFromExcelFile() + { + //this.CommandName = "LoadDictionaryCommand"; + //this.SelectionName = "Load Dictionary"; + //this.CommandEnabled = true; + //this.CustomRendering = true; + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + ////var vInstance = DateTime.Now.ToString(); + + //var vSheet = v_SheetName.ExpandValueOrUserVariable(engine); + //var vKeyColumn = v_KeyColumn.ExpandValueOrUserVariable(engine); + //var vValueColumn = v_ValueColumn.ExpandValueOrUserVariable(engine); + + ////string vFilePath = FilePathControls.FormatFilePath_NoFileCounter(v_FilePath, engine, new List() { "xlsx", "xlsm", "xls" }, true); + //var vFilePath = v_FilePath.ExpandValueOrUserVariable(engine); + + ////Query required from workbook using OLEDB + ////DataTableControls dataSetCommand = new DataTableControls(); + + //string param = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=""" + vFilePath + @""";Extended Properties=""Excel 12.0;HDR=YES;IMEX=1"""; + //string queue = "Select " + vKeyColumn + "," + vValueColumn + " From " + "[" + vSheet + "$]"; + + //// DBG + ////MessageBox.Show(param + "\n" + queue); + + //DataTable requiredData = DataTableControls.CreateDataTable(param, queue); + //var dictlist = requiredData.AsEnumerable().Select(x => new + //{ + // keys = (string)x[v_KeyColumn], + // values = (string)x[v_ValueColumn] + //}).ToList(); + //Dictionary outputDictionary = new Dictionary(); + //foreach (var dict in dictlist) + //{ + // outputDictionary.Add(dict.keys, dict.values); + //} + + //outputDictionary.StoreInUserVariable(engine, v_DictionaryName); + + var instanceName = engine.GetNewAppInstanceName(); + + var createInstance = new ExcelCreateExcelInstanceCommand() + { + v_InstanceName = instanceName, + }; + createInstance.RunCommand(engine); + + var openFile = new ExcelOpenWorkbookCommand() + { + v_InstanceName = instanceName, + v_FilePath = this.v_FilePath, + }; + openFile.RunCommand(engine); + + var activateSheet = new ExcelActivateWorksheetCommand() + { + v_InstanceName = instanceName, + v_SheetName = this.v_SheetName, + }; + activateSheet.RunCommand(engine); + + //var keyListName = VariableNameControls.GetInnerVariableName(0, engine); + //var getListKey = new ExcelGetColumnValuesAsListCommand() + //{ + // v_InstanceName = instanceName, + // v_ColumnType = this.v_ColumnType, + // v_ColumnIndex = this.v_KeyColumn, + // v_Result = keyListName, + //}; + //getListKey.RunCommand(engine); + + //var valueListName = VariableNameControls.GetInnerVariableName(1, engine); + //var getListValue = new ExcelGetColumnValuesAsListCommand() + //{ + // v_InstanceName = instanceName, + // v_ColumnType = this.v_ColumnType, + // v_ColumnIndex = this.v_ValueColumn, + // v_Result = valueListName, + //}; + //getListValue.RunCommand(engine); + + //var closeInstance = new ExcelCloseExcelInstanceCommand() + //{ + // v_InstanceName = instanceName, + //}; + //closeInstance.RunCommand(engine); + + //var keyList = (List)VariableNameControls.GetInnerVariable(0, engine).VariableValue; + + //var valueList = (List)VariableNameControls.GetInnerVariable(1, engine).VariableValue; + + //var myDic = new Dictionary(); + //foreach(var key in keyList) + //{ + // myDic.Add(key, ""); + //} + //int max = (keyList.Count <= valueList.Count) ? keyList.Count : valueList.Count; + //for (int i = 0; i < max; i++) + //{ + // myDic[keyList[i]] = valueList[i]; + //} + + //this.StoreDictionaryInUserVariable(myDic, nameof(v_DictionaryName), engine); + + using (var myKey = new InnerScriptVariable(engine)) + { + using (var myValue = new InnerScriptVariable(engine)) + { + var getListKey = new ExcelGetColumnValuesAsListCommand() + { + v_InstanceName = instanceName, + v_ColumnType = this.v_ColumnType, + v_ColumnIndex = this.v_KeyColumn, + v_Result = myKey.VariableName, + }; + getListKey.RunCommand(engine); + + var getListValue = new ExcelGetColumnValuesAsListCommand() + { + v_InstanceName = instanceName, + v_ColumnType = this.v_ColumnType, + v_ColumnIndex = this.v_ValueColumn, + v_Result = myValue.VariableName, + }; + getListValue.RunCommand(engine); + + var closeInstance = new ExcelCloseExcelInstanceCommand() + { + v_InstanceName = instanceName, + }; + closeInstance.RunCommand(engine); + + var keyList = EM_CanHandleListExtensionMethods.ExpandUserVariableAsList(myKey); + + var valueList = EM_CanHandleListExtensionMethods.ExpandUserVariableAsList(myValue); + + var myDic = new Dictionary(); + foreach (var key in keyList) + { + myDic.Add(key, ""); + } + int max = (keyList.Count <= valueList.Count) ? keyList.Count : valueList.Count; + for (int i = 0; i < max; i++) + { + myDic[keyList[i]] = valueList[i]; + } + + this.StoreDictionaryInUserVariable(myDic, nameof(v_DictionaryName), engine); + } + } + } + + //public override List Render(frmCommandEditor editor) + //{ + // base.Render(editor); + + // var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); + // RenderedControls.AddRange(ctrls); + + // return RenderedControls; + + //} + //public override string GetDisplayValue() + //{ + // return base.GetDisplayValue() + " [Load Dictionary from '" + v_FilePath + "' and store in: '" +v_DictionaryName+ "']"; + //} + + //public override bool IsValidate(frmCommandEditor editor) + //{ + // base.IsValidate(editor); + + // if (String.IsNullOrEmpty(v_DictionaryName)) + // { + // this.IsValid = false; + // this.validationResult += "Dictionary Variable Name is empty.\n"; + // } + // if (String.IsNullOrEmpty(v_FilePath)) + // { + // this.IsValid = false; + // this.validationResult += "Workbook file path is empty.\n"; + // } + // if (String.IsNullOrEmpty(v_SheetName)) + // { + // this.IsValid = false; + // this.validationResult += "Sheet name is empty.\n"; + // } + // if (String.IsNullOrEmpty(v_KeyColumn)) + // { + // this.IsValid = false; + // this.validationResult += "Key column is empty.\n"; + // } + // if (String.IsNullOrEmpty(v_ValueColumn)) + // { + // this.IsValid = false; + // this.validationResult += "Value column is empty.\n"; + // } + + // return this.IsValid; + //} + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelCreateExcelInstanceCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelCreateExcelInstanceCommand.cs index 56a5e0aa7..793d0155f 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelCreateExcelInstanceCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelCreateExcelInstanceCommand.cs @@ -5,22 +5,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Instance")] [Attributes.ClassAttributes.CommandSettings("Create Excel Instance")] [Attributes.ClassAttributes.Description("This command opens the Excel Instance.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to launch a new instance of Excel.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelCreateExcelInstanceCommand : ScriptCommand + public sealed class ExcelCreateExcelInstanceCommand : AExcelInstanceCommands { [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.TextBox)] [PropertyTextBoxSetting(1, false)] - public string v_InstanceName { get; set; } + public override string v_InstanceName { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + [PropertyParameterOrder(6000)] + public string v_WindowHandle { get; set; } public ExcelCreateExcelInstanceCommand() { @@ -30,10 +36,9 @@ public ExcelCreateExcelInstanceCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var vInstance = v_InstanceName.ConvertToUserVariable(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); var newExcelSession = new Microsoft.Office.Interop.Excel.Application { @@ -41,6 +46,11 @@ public override void RunCommand(object sender) }; engine.AddAppInstance(vInstance, newExcelSession); + + if (!string.IsNullOrEmpty(v_WindowHandle)) + { + newExcelSession.Hwnd.StoreInUserVariable(engine, v_WindowHandle); + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelDeleteCellCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelDeleteCellCommand.cs index 6430e8e9f..1516935e0 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelDeleteCellCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelDeleteCellCommand.cs @@ -4,29 +4,29 @@ using System.Xml.Serialization; using System.Linq; using taskt.UI.CustomControls; -using taskt.UI.Forms; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Cell")] [Attributes.ClassAttributes.CommandSettings("Delete Cell")] [Attributes.ClassAttributes.Description("This command allows you to delete a specified cell in Excel")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to delete a specific cell from the current sheet.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] - public class ExcelDeleteCellCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + public sealed class ExcelDeleteCellCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyDescription("Please Enter the instance name")] - [InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] - [SampleUsage("**myInstance** or **excelInstance**")] - [Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyDescription("Please Enter the instance name")] + //[InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] + //[SampleUsage("**myInstance** or **excelInstance**")] + //[Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] @@ -34,7 +34,8 @@ public class ExcelDeleteCellCommand : ScriptCommand [InputSpecification("Enter the actual location of the cell.")] [SampleUsage("A1, B10, {vAddress}")] [Remarks("")] - public string v_Range { get; set; } + [PropertyParameterOrder(6000)] + public string v_CellLocation { get; set; } [XmlAttribute] [PropertyDescription("Should the cells below shift upward after deletion?")] @@ -43,7 +44,8 @@ public class ExcelDeleteCellCommand : ScriptCommand [InputSpecification("Indicate whether the row below will be shifted up to replace the old row.")] [SampleUsage("Select 'Yes' or 'No'")] [Remarks("")] - public string v_ShiftUp { get; set; } + [PropertyParameterOrder(6001)] + public string v_Shift { get; set; } public ExcelDeleteCellCommand() { @@ -53,15 +55,15 @@ public ExcelDeleteCellCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); - string range = v_Range.ConvertToUserVariable(sender); + string range = v_CellLocation.ExpandValueOrUserVariable(engine); var cells = excelSheet.Range[range, Type.Missing]; - if (v_ShiftUp == "Yes") + if (v_Shift == "Yes") { cells.Delete(); } @@ -70,7 +72,8 @@ public override void RunCommand(object sender) cells.Clear(); } } - public override List Render(frmCommandEditor editor) + + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -79,19 +82,20 @@ public override List Render(frmCommandEditor editor) CommandControls.AddInstanceNames((ComboBox)instanceCtrls.Where(t => (t.Name == "v_InstanceName")).FirstOrDefault(), editor, PropertyInstanceType.InstanceType.Excel); RenderedControls.AddRange(instanceCtrls); //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_Range", this, editor)); - RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_ShiftUp", this, editor)); + RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_CellLocation", this, editor)); + RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_Shift", this, editor)); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; } return RenderedControls; } + public override string GetDisplayValue() { - return base.GetDisplayValue() + " [Range: " + v_Range + ", Instance Name: '" + v_InstanceName + "']"; + return base.GetDisplayValue() + " [Range: " + v_CellLocation + ", Instance Name: '" + v_InstanceName + "']"; } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelDeleteRowCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelDeleteRowCommand.cs index df2fe43a2..b8b3a1148 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelDeleteRowCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelDeleteRowCommand.cs @@ -4,29 +4,29 @@ using System.Xml.Serialization; using System.Linq; using taskt.UI.CustomControls; -using taskt.UI.Forms; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Row")] [Attributes.ClassAttributes.CommandSettings("Delete Row")] [Attributes.ClassAttributes.Description("This command allows you to delete a specified row in Excel")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to delete an entire row from the current sheet.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] - public class ExcelDeleteRowCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + public sealed class ExcelDeleteRowCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyDescription("Please Enter the instance name")] - [InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] - [SampleUsage("**myInstance** or **excelInstance**")] - [Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyDescription("Please Enter the instance name")] + //[InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] + //[SampleUsage("**myInstance** or **excelInstance**")] + //[Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] @@ -34,7 +34,8 @@ public class ExcelDeleteRowCommand : ScriptCommand [InputSpecification("Enter the number of the row that should be deleted.")] [SampleUsage("1, 5, {vNumber}")] [Remarks("")] - public string v_RowNumber { get; set; } + [PropertyParameterOrder(6000)] + public string v_RowIndex { get; set; } [XmlAttribute] [PropertyDescription("Should the cells below shift upward after deletion?")] @@ -43,7 +44,8 @@ public class ExcelDeleteRowCommand : ScriptCommand [InputSpecification("Indicate whether the row below will be shifted up to replace the old row.")] [SampleUsage("Select 'Yes' or 'No'")] [Remarks("")] - public string v_ShiftUp { get; set; } + [PropertyParameterOrder(6001)] + public string v_Shift { get; set; } public ExcelDeleteRowCommand() { @@ -53,17 +55,16 @@ public ExcelDeleteRowCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); - - string rowToDelete = v_RowNumber.ConvertToUserVariable(sender); + string rowToDelete = v_RowIndex.ExpandValueOrUserVariable(engine); var cells = excelSheet.Range["A" + rowToDelete, Type.Missing]; var entireRow = cells.EntireRow; - if (v_ShiftUp == "Yes") + if (v_Shift == "Yes") { entireRow.Delete(); } @@ -73,7 +74,7 @@ public override void RunCommand(object sender) } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -82,19 +83,20 @@ public override List Render(frmCommandEditor editor) CommandControls.AddInstanceNames((ComboBox)instanceCtrls.Where(t => (t.Name == "v_InstanceName")).FirstOrDefault(), editor, PropertyInstanceType.InstanceType.Excel); RenderedControls.AddRange(instanceCtrls); //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_RowNumber", this, editor)); - RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_ShiftUp", this, editor)); + RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_RowIndex", this, editor)); + RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_Shift", this, editor)); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; } return RenderedControls; } + public override string GetDisplayValue() { - return base.GetDisplayValue() + " [Row Number: " + v_RowNumber + ", Instance Name: '" + v_InstanceName + "']"; + return base.GetDisplayValue() + " [Row Number: " + v_RowIndex + ", Instance Name: '" + v_InstanceName + "']"; } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelDeleteWorksheetCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelDeleteWorksheetCommand.cs index 14720d6d2..4213e4ec4 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelDeleteWorksheetCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelDeleteWorksheetCommand.cs @@ -1,27 +1,26 @@ using System; -using System.Xml.Serialization; -using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] - [Attributes.ClassAttributes.SubGruop("Sheet")] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("Worksheet")] [Attributes.ClassAttributes.CommandSettings("Delete Worksheet")] [Attributes.ClassAttributes.Description("This command delete a Excel Worksheet.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a new worksheet to an Excel Instance")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelDeleteWorksheetCommand : ScriptCommand + public sealed class ExcelDeleteWorksheetCommand : AExcelSheetCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] - public string v_SheetName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] + //public string v_SheetName { get; set; } public ExcelDeleteWorksheetCommand() { @@ -31,11 +30,10 @@ public ExcelDeleteWorksheetCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var targetSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //(_, var targetSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (_, var targetSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); targetSheet.Delete(); } diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetCellCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetCellCommand.cs index a5d609f5e..694023001 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetCellCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetCellCommand.cs @@ -5,31 +5,35 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Cell")] [Attributes.ClassAttributes.CommandSettings("Get Cell")] [Attributes.ClassAttributes.Description("This command gets text from a specified Excel Cell.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a value from a specific cell.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Excel Interop' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetCellCommand : ScriptCommand + public sealed class ExcelGetCellCommand : AExcelCellActionCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CellRangeLocation))] - public string v_ExcelCellAddress { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CellRangeLocation))] + //[PropertyParameterOrder(6000)] + //public string v_CellLocation { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_userVariableName { get; set; } + [PropertyParameterOrder(6500)] + public string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6002)] + //public string v_ValueType { get; set; } public ExcelGetCellCommand() { @@ -39,19 +43,21 @@ public ExcelGetCellCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //var rg = v_CellLocation.GetExcelRange(engine, excelInstance, excelSheet, this); - var rg = v_ExcelCellAddress.GetExcelRange(engine, excelInstance, excelSheet, this); + //var valueType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), engine); - var valueType = this.GetUISelectionValue(nameof(v_ValueType), engine); + //var func = ExcelControls.GetCellValueFunctionFromRange(valueType); - var func = ExcelControls.GetCellValueFunctionFromRange(valueType); + //func(rg).StoreInUserVariable(engine, v_Result); - func(rg).StoreInUserVariable(sender, v_userVariableName); + var rg = this.ExpandValueOrVariableAsExcelSingleCellLocation(engine); + var func = this.ExpandValueOrVariableAsGetValueFunction(engine); + func(rg).StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetCellRCCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetCellRCCommand.cs index 84658a216..e18da72e4 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetCellRCCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetCellRCCommand.cs @@ -5,35 +5,40 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Cell")] [Attributes.ClassAttributes.CommandSettings("Get Cell RC")] [Attributes.ClassAttributes.Description("This command gets text from a specified Excel Cell.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a value from a specific cell.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Excel Interop' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetCellRCCommand : ScriptCommand + public sealed class ExcelGetCellRCCommand : AExcelRCLocationActionCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] - public string v_ExcelCellRow { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + //[PropertyParameterOrder(6000)] + //public string v_CellRow { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnLocation))] - public string v_ExcelCellColumn { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnLocation))] + //[PropertyParameterOrder(6001)] + //public string v_CellColumn { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_userVariableName { get; set; } + [PropertyParameterOrder(8000)] + public string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + ////[XmlAttribute] + ////[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + ////[PropertyParameterOrder(6003)] + ////public string v_ValueType { get; set; } public ExcelGetCellRCCommand() { @@ -43,19 +48,30 @@ public ExcelGetCellRCCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //var rg = this.GetExcelRange(nameof(v_CellRow), nameof(v_CellColumn), engine, excelInstance, excelSheet); + + //var valueType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //var func = ExcelControls.GetCellValueFunctionFromRange(valueType); - var rg = this.GetExcelRange(nameof(v_ExcelCellRow), nameof(v_ExcelCellColumn), engine, excelInstance, excelSheet); + //func(rg).StoreInUserVariable(engine, v_Result); - var valueType = this.GetUISelectionValue(nameof(v_ValueType), engine); + //var rg = this.ExpandValueOrVariableAsExcelCellLocation(engine); - var func = ExcelControls.GetCellValueFunctionFromRange(valueType); + //(_, var sheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(int row, int column) = this.ExpandValueOrVariableAsCellRowAndColumnIndex(engine); + //var getFunc = this.ExpandValueOrVariableAsGetValueFunction(engine); + //getFunc(sheet, column, row).StoreInUserVariable(engine, v_Result); - func(rg).StoreInUserVariable(sender, v_userVariableName); + this.RCLocationAction(new Action((sheet, column, row) => + { + var getFunc = this.ExpandValueOrVariableAsGetValueFunction(engine); + getFunc(sheet, column, row).StoreInUserVariable(engine, v_Result); + }), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsDataTableCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsDataTableCommand.cs index f23fe1a9a..d467d24e6 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsDataTableCommand.cs @@ -6,43 +6,50 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Column")] [Attributes.ClassAttributes.CommandSettings("Get Column Values As DataTable")] [Attributes.ClassAttributes.Description("This command get Column values as DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Column values as DatTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetColumnValuesAsDataTableCommand : ScriptCommand + public sealed class ExcelGetColumnValuesAsDataTableCommand : AExcelColumnRangeGetCommands, IDataTableResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6000)] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] - public string v_ColumnIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] - public string v_RowStart { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] + //[PropertyParameterOrder(6002)] + //public string v_RowStart { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] - public string v_RowEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] + //[PropertyParameterOrder(6003)] + //public string v_RowEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] - public string v_userVariableName { get; set; } + //[PropertyParameterOrder(6004)] + public override string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6005)] + //public string v_ValueType { get; set; } public ExcelGetColumnValuesAsDataTableCommand() { @@ -52,33 +59,65 @@ public ExcelGetColumnValuesAsDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //(int columnIndex, int rowStart, int rowEnd, string valueType) = + // ExcelControls.GetRangeIndeiesColumnDirection( + // nameof(v_ColumnIndex), nameof(v_ColumnType), + // nameof(v_RowStart), nameof(v_RowEnd), nameof(v_ValueType), + // engine, excelSheet, this + // ); + + //Func getFunc = ExcelControls.GetCellValueFunction(valueType); + + //DataTable newDT = new DataTable(); + //newDT.Columns.Add(ExcelControls.GetColumnName(excelSheet, columnIndex)); + + //int tblRow = 0; + //for (int i = rowStart; i <= rowEnd; i++) + //{ + // newDT.Rows.Add(); + // newDT.Rows[tblRow][0] = getFunc(excelSheet, columnIndex, i); + // tblRow++; + //} + + //newDT.StoreInUserVariable(engine, v_Result); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //(_, var sheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(var columnIndex, var rowStartIndex, var rowEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndicies(engine); + //var getFunc = this.ExpandValueOrVariableAsGetValueFunction(engine); - (int columnIndex, int rowStart, int rowEnd, string valueType) = - ExcelControls.GetRangeIndeiesColumnDirection( - nameof(v_ColumnIndex), nameof(v_ColumnType), - nameof(v_RowStart), nameof(v_RowEnd), nameof(v_ValueType), - engine, excelSheet, this - ); + //var newDT = new DataTable(); + //newDT.Columns.Add(sheet.ToColumnName(columnIndex)); - Func getFunc = ExcelControls.GetCellValueFunction(valueType); + //int max = rowEndIndex - rowStartIndex + 1; + ////int rowCnt = 0; + //for (int i = 0; i < max; i++) + //{ + // newDT.Rows.Add(); + // newDT.Rows[i][0] = getFunc(sheet, columnIndex, rowStartIndex + i); + // //rowCnt++; + //} + //newDT.StoreInUserVariable(engine, v_Result); - DataTable newDT = new DataTable(); - newDT.Columns.Add(ExcelControls.GetColumnName(excelSheet, columnIndex)); + var newDT = new DataTable(); - int tblRow = 0; - for (int i = rowStart; i <= rowEnd; i++) - { - newDT.Rows.Add(); - newDT.Rows[tblRow][0] = getFunc(excelSheet, columnIndex, i); - tblRow++; - } + this.ColumnRangeAction( + new Action((sheet, value, column, row, count) => + { + if (count == 0) + { + newDT.Columns.Add(sheet.ToColumnName(column)); + } + newDT.Rows.Add(); + newDT.Rows[count][0] = value; + }), engine + ); - newDT.StoreInUserVariable(engine, v_userVariableName); + //newDT.StoreInUserVariable(engine, v_Result); + this.StoreDataTableInUserVariable(newDT, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsDictionaryCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsDictionaryCommand.cs index 707ecfa0b..a900a6017 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsDictionaryCommand.cs @@ -6,43 +6,50 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Column")] [Attributes.ClassAttributes.CommandSettings("Get Column Values As Dictionary")] [Attributes.ClassAttributes.Description("This command get Column values as Dictionary.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Column values as Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetColumnValuesAsDictionaryCommand : ScriptCommand + public sealed class ExcelGetColumnValuesAsDictionaryCommand : AExcelColumnRangeGetCommands, IDictionaryResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6000)] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] - public string v_ColumnIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] - public string v_RowStart { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] + //[PropertyParameterOrder(6002)] + //public string v_RowStart { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] - public string v_RowEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] + //[PropertyParameterOrder(6003)] + //public string v_RowEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_OutputDictionaryName))] - public string v_userVariableName { get; set; } + //[PropertyParameterOrder(6004)] + public override string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6005)] + //public string v_ValueType { get; set; } public ExcelGetColumnValuesAsDictionaryCommand() { @@ -52,30 +59,58 @@ public ExcelGetColumnValuesAsDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //(int columnIndex, int rowStart, int rowEnd, string valueType) = + // ExcelControls.GetRangeIndeiesColumnDirection( + // nameof(v_ColumnIndex), nameof(v_ColumnType), + // nameof(v_RowStart), nameof(v_RowEnd), nameof(v_ValueType), + // engine, excelSheet, this + // ); + + //Func getFunc = ExcelControls.GetCellValueFunction(valueType); + + //Dictionary newDic = new Dictionary(); + + //for (int i = rowStart; i <= rowEnd; i++) + //{ + // string address = ExcelControls.GetAddress(excelSheet, i, columnIndex); + // newDic.Add(address, getFunc(excelSheet, columnIndex, i)); + //} + + //newDic.StoreInUserVariable(engine, v_Result); + + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(var columnIndex, var rowStartIndex, var rowEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndicies(engine); + + //var getFunc = this.ExpandValueOrVariableAsGetValueFunction(engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //var newDic = new Dictionary(); - (int columnIndex, int rowStart, int rowEnd, string valueType) = - ExcelControls.GetRangeIndeiesColumnDirection( - nameof(v_ColumnIndex), nameof(v_ColumnType), - nameof(v_RowStart), nameof(v_RowEnd), nameof(v_ValueType), - engine, excelSheet, this - ); + //int max = rowEndIndex - rowStartIndex + 1; + //for (int i = 0; i < max; i++) + //{ + // var pos = rowStartIndex + i; + // string address = excelSheet.ToCellLocation(pos, columnIndex); + // newDic.Add(address, getFunc(excelSheet, columnIndex, pos)); + //} - Func getFunc = ExcelControls.GetCellValueFunction(valueType); + //newDic.StoreInUserVariable(engine, v_Result); - Dictionary newDic = new Dictionary(); + var newDic = new Dictionary(); - for (int i = rowStart; i <= rowEnd; i++) - { - string address = ExcelControls.GetAddress(excelSheet, i, columnIndex); - newDic.Add(address, getFunc(excelSheet, columnIndex, i)); - } + this.ColumnRangeAction( + new Action((sheet, value, column, row, count) => + { + string address = sheet.ToCellLocation(row, column); + newDic.Add(address, value); + }), engine + ); - newDic.StoreInUserVariable(engine, v_userVariableName); + //newDic.StoreInUserVariable(engine, v_Result); + this.StoreDictionaryInUserVariable(newDic, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsListCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsListCommand.cs index 367d904dd..7c4a84f96 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsListCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetColumnValuesAsListCommand.cs @@ -6,43 +6,50 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Column")] [Attributes.ClassAttributes.CommandSettings("Get Column Values As List")] [Attributes.ClassAttributes.Description("This command get Column values as List.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Column values as List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetColumnValuesAsListCommand : ScriptCommand + public sealed class ExcelGetColumnValuesAsListCommand : AExcelColumnRangeGetCommands, IListResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6000)] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] - public string v_ColumnIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] - public string v_RowStart { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] + //[PropertyParameterOrder(6002)] + //public string v_RowStart { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] - public string v_RowEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] + //[PropertyParameterOrder(6003)] + //public string v_RowEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] - public string v_userVariableName { get; set; } + //[PropertyParameterOrder(6004)] + public override string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6005)] + //public string v_ValueType { get; set; } public ExcelGetColumnValuesAsListCommand() { @@ -52,29 +59,44 @@ public ExcelGetColumnValuesAsListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //(int columnIndex, int rowStart, int rowEnd, string valueType) = + // ExcelControls.GetRangeIndeiesColumnDirection( + // nameof(v_ColumnIndex), nameof(v_ColumnType), + // nameof(v_RowStart), nameof(v_RowEnd), nameof(v_ValueType), + // engine, excelSheet, this + // ); + + //Func getFunc = ExcelControls.GetCellValueFunction(valueType); + + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(var columnIndex, var rowStartIndex, var rowEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndicies(engine); + //var getFunc = this.ExpandValueOrVariableAsGetValueFunction(engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //var newList = new List(); - (int columnIndex, int rowStart, int rowEnd, string valueType) = - ExcelControls.GetRangeIndeiesColumnDirection( - nameof(v_ColumnIndex), nameof(v_ColumnType), - nameof(v_RowStart), nameof(v_RowEnd), nameof(v_ValueType), - engine, excelSheet, this - ); + //int max = rowEndIndex - rowStartIndex + 1; + //for (int i = 0; i < max; i++) + //{ + // newList.Add(getFunc(excelSheet, columnIndex, rowStartIndex + i)); + //} - Func getFunc = ExcelControls.GetCellValueFunction(valueType); + //newList.StoreInUserVariable(engine, v_Result); - List newList = new List(); + var newList = new List(); - for (int i = rowStart; i <= rowEnd; i++) - { - newList.Add(getFunc(excelSheet, columnIndex, i)); - } + this.ColumnRangeAction( + new Action((sheet, value, column, row, count) => + { + newList.Add(value); + }), engine + ); - newList.StoreInUserVariable(engine, v_userVariableName); + //newList.StoreInUserVariable(engine, v_Result); + this.StoreListInUserVariable(newList, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetCurrentWorksheetCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetCurrentWorksheetCommand.cs index bb6472e5b..5af4e0552 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetCurrentWorksheetCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetCurrentWorksheetCommand.cs @@ -5,23 +5,25 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] - [Attributes.ClassAttributes.SubGruop("Sheet")] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("Worksheet")] [Attributes.ClassAttributes.CommandSettings("Get Current Worksheet")] [Attributes.ClassAttributes.Description("This command allows you to get current sheet name.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to launch a new instance of Excel.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetCurrentWorksheetCommand : ScriptCommand + public sealed class ExcelGetCurrentWorksheetCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_applyToVariable { get; set; } + [PropertyParameterOrder(6000)] + public string v_Result { get; set; } public ExcelGetCurrentWorksheetCommand() { @@ -31,13 +33,12 @@ public ExcelGetCurrentWorksheetCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); - excelSheet.Name.StoreInUserVariable(engine, v_applyToVariable); + excelSheet.Name.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetExcelInfoCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetExcelInfoCommand.cs index e9ca02988..f186d0db8 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetExcelInfoCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetExcelInfoCommand.cs @@ -1,23 +1,25 @@ using System; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; +using Microsoft.Office.Interop.Excel; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Other")] [Attributes.ClassAttributes.CommandSettings("Get Excel Info")] [Attributes.ClassAttributes.Description("This command allows you to get current sheet name.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to launch a new instance of Excel.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetExcelInfoCommand : ScriptCommand + public sealed class ExcelGetExcelInfoCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyDescription("Please select the information type to receive")] @@ -33,11 +35,13 @@ public class ExcelGetExcelInfoCommand : ScriptCommand [PropertyUISelectionOption("Last sheet")] [PropertyValidationRule("Type", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Type")] + [PropertyParameterOrder(6000)] public string v_InfoType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_applyToVariable { get; set; } + [PropertyParameterOrder(6001)] + public string v_Result { get; set; } public ExcelGetExcelInfoCommand() { @@ -47,15 +51,13 @@ public ExcelGetExcelInfoCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var excelInstance = v_InstanceName.GetExcelInstance(engine); + //var excelInstance = v_InstanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + var excelInstance = this.ExpandValueOrVariableAsExcelInstance(engine); - var infoType = this.GetUISelectionValue(nameof(v_InfoType), "Info Type", engine); string ret = ""; - switch (infoType) + switch (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_InfoType), "Info Type", engine)) { case "file name": ret = excelInstance.ActiveWorkbook?.Name ?? ""; @@ -64,8 +66,9 @@ public override void RunCommand(object sender) ret = excelInstance.ActiveWorkbook?.FullName ?? ""; break; case "current sheet": - var sheet = engine.engineSettings.CurrentWorksheetKeyword.GetExcelWorksheet(engine, excelInstance, true); - ret = (sheet == null) ? "" : sheet.Name; + //var sheet = engine.engineSettings.CurrentWorksheetKeyword.ExpandValueOrUserVariableAsExcelWorksheet(engine, excelInstance, true); + //ret = (sheet == null) ? "" : sheet.Name; + ret = (excelInstance.Worksheets.Count > 0) ? excelInstance.ActiveSheet.Name : ""; break; case "number of sheets": try @@ -81,7 +84,7 @@ public override void RunCommand(object sender) try { - ret = ((Microsoft.Office.Interop.Excel.Worksheet)excelInstance.Worksheets[1]).Name; + ret = ((Worksheet)excelInstance.Worksheets[1]).Name; } catch { @@ -91,7 +94,7 @@ public override void RunCommand(object sender) case "last sheet": try { - ret = ((Microsoft.Office.Interop.Excel.Worksheet)excelInstance.Worksheets[excelInstance.Worksheets.Count]).Name; + ret = ((Worksheet)excelInstance.Worksheets[excelInstance.Worksheets.Count]).Name; } catch { @@ -100,7 +103,7 @@ public override void RunCommand(object sender) break; } - ret.StoreInUserVariable(sender, v_applyToVariable); + ret.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetLastRowCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetLastRowCommand.cs index 3999deb96..bd6f2b654 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetLastRowCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetLastRowCommand.cs @@ -5,38 +5,48 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Row")] [Attributes.ClassAttributes.CommandSettings("Get Last Row Index")] [Attributes.ClassAttributes.Description("This command allows you to find the last row in a used range in an Excel Workbook.")] [Attributes.ClassAttributes.UsesDescription("Use this command to determine how many rows have been used in the Excel Workbook. You can use this value in a **Number Of Times** Loop to get data.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetLastRowCommand : ScriptCommand + public sealed class ExcelGetLastRowCommand : AExcelColumnSpecifiedCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } + + //[XmlAttribute] + //public string v_ColumnType { get; set; } [XmlAttribute] - [PropertyDescription("Letter of the Column to check")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Column Letter", true)] - //[SampleUsage("**A** or **B** or **{{{vColumn}}}**")] - [PropertyDetailSampleUsage("**A**", "Specify the Column **A**")] - [PropertyDetailSampleUsage("**B**", "Specify the Column **B**")] - [PropertyDetailSampleUsage("**{{{vColumn}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Column")] - [Remarks("")] - [PropertyTextBoxSetting(1, false)] - [PropertyShowSampleUsageInDescription(true)] + //[PropertyDescription("Letter of the Column to check")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Column Letter", true)] + ////[SampleUsage("**A** or **B** or **{{{vColumn}}}**")] + //[PropertyDetailSampleUsage("**A**", "Specify the Column **A**")] + //[PropertyDetailSampleUsage("**B**", "Specify the Column **B**")] + //[PropertyDetailSampleUsage("**{{{vColumn}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Column")] + //[Remarks("")] + //[PropertyTextBoxSetting(1, false)] + //[PropertyShowSampleUsageInDescription(true)] [PropertyIsOptional(true, "A")] - [PropertyDisplayText(true, "Column")] - public string v_ColumnLetter { get; set; } + //[PropertyDisplayText(true, "Column")] + //[PropertyParameterOrder(6000)] + public override string v_ColumnIndex { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_applyToVariableName { get; set; } + [PropertyParameterOrder(8500)] + public string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CheckableValueType))] + public override string v_ValueType { get; set; } public ExcelGetLastRowCommand() { @@ -46,21 +56,25 @@ public ExcelGetLastRowCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //if (string.IsNullOrEmpty(v_ColumnIndex)) + //{ + // v_ColumnIndex = "A"; + //} + //var columnLetter = v_ColumnIndex.ExpandValueOrUserVariable(engine); - if (String.IsNullOrEmpty(v_ColumnLetter)) - { - v_ColumnLetter = "A"; - } - var columnLetter = v_ColumnLetter.ConvertToUserVariable(engine); + //var lastRow = (int)excelSheet.Cells[excelSheet.Rows.Count, columnLetter].End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row; - var lastRow = (int)excelSheet.Cells[excelSheet.Rows.Count, columnLetter].End(Microsoft.Office.Interop.Excel.XlDirection.xlUp).Row; + var columnIndex = this.ExpandValueOrVariableAsExcelColumnIndex(engine); + var valueType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), "Value Type", engine); + var lastRow = excelSheet.LastRowIndex(columnIndex, 1, valueType); - lastRow.ToString().StoreInUserVariable(sender, v_applyToVariableName); + //lastRow.ToString().StoreInUserVariable(engine, v_Result); + lastRow.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetRangeCommand .cs b/taskt/Core/Automation/Commands/Excel/ExcelGetRangeCommand .cs index 28d284e3e..b41f2651a 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetRangeCommand .cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetRangeCommand .cs @@ -4,48 +4,54 @@ using System.Xml.Serialization; using System.Linq; using taskt.UI.CustomControls; -using taskt.UI.Forms; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Range")] [Attributes.ClassAttributes.CommandSettings("Get Range")] [Attributes.ClassAttributes.Description("This command gets text from a specified Excel Range.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a value from a specific cell.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Excel Interop' to achieve automation.")] - public class ExcelGetRangeCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + public sealed class ExcelGetRangeCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyDescription("Please Enter the instance name")] - [InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] - [SampleUsage("**myInstance** or **excelInstance**")] - [Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyDescription("Please Enter the instance name")] + //[InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] + //[SampleUsage("**myInstance** or **excelInstance**")] + //[Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //public string v_InstanceName { get; set; } + [XmlAttribute] [PropertyDescription("Please Enter the First Cell Location (ex. A1 or B2)")] [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] [InputSpecification("Enter the actual location of the cell.")] [SampleUsage("A1, B10, {vAddress}")] [Remarks("")] + [PropertyParameterOrder(6000)] public string v_ExcelCellAddress1 { get; set; } + [XmlAttribute] [PropertyDescription("Please Enter the Second Cell Location (ex. A1 or B2)")] [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] [InputSpecification("Enter the actual location of the cell.")] [SampleUsage("A1, B10, [vAddress]")] [Remarks("")] + [PropertyParameterOrder(6001)] public string v_ExcelCellAddress2 { get; set; } + [XmlAttribute] [PropertyDescription("Assign to Variable")] [InputSpecification("Select or provide a variable from the variable list")] [SampleUsage("**vSomeVariable**")] [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] + [PropertyParameterOrder(6002)] public string v_userVariableName { get; set; } public ExcelGetRangeCommand() @@ -55,17 +61,16 @@ public ExcelGetRangeCommand() //this.CommandEnabled = true; //this.CustomRendering = true; - this.v_InstanceName = ""; + //this.v_InstanceName = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); - var targetAddress1 = v_ExcelCellAddress1.ConvertToUserVariable(sender); - var targetAddress2 = v_ExcelCellAddress2.ConvertToUserVariable(sender); + var targetAddress1 = v_ExcelCellAddress1.ExpandValueOrUserVariable(engine); + var targetAddress2 = v_ExcelCellAddress2.ExpandValueOrUserVariable(engine); Microsoft.Office.Interop.Excel.Range cellValue; if (targetAddress2 != "") @@ -101,10 +106,10 @@ public override void RunCommand(object sender) string output = String.Join(",", lst); //Store Strings of comma seperated values into user variable - output.StoreInUserVariable(sender, v_userVariableName); - + output.StoreInUserVariable(engine, v_userVariableName); } - public override List Render(frmCommandEditor editor) + + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -122,7 +127,7 @@ public override List Render(frmCommandEditor editor) RenderedControls.AddRange(CommandControls.CreateDefaultUIHelpersFor("v_userVariableName", this, VariableNameControl, editor)); RenderedControls.Add(VariableNameControl); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; } diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetRangeCommandASDT.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetRangeCommandASDT.cs index a66f52944..b73330fe6 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetRangeCommandASDT.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetRangeCommandASDT.cs @@ -3,21 +3,20 @@ using System.Windows.Forms; using System.Xml.Serialization; using taskt.UI.CustomControls; -using taskt.UI.Forms; using System.Data; -using System.Text; using System.Linq; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Range")] [Attributes.ClassAttributes.CommandSettings("Get Range As Datatable")] [Attributes.ClassAttributes.Description("This command gets text from a specified Excel Range and put it into a DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a value from a specific range.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Excel Interop' to achieve automation.")] - public class ExcelGetRangeCommandAsDT : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + public sealed class ExcelGetRangeCommandAsDT : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Enter the instance name")] @@ -28,6 +27,7 @@ public class ExcelGetRangeCommandAsDT : ScriptCommand [Attributes.PropertyAttributes.PropertyInstanceType(Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Excel)] [Attributes.PropertyAttributes.PropertyRecommendedUIControl(Attributes.PropertyAttributes.PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] public string v_InstanceName { get; set; } + [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Enter the First Cell Location (ex. A1 or B2)")] [Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] @@ -35,6 +35,7 @@ public class ExcelGetRangeCommandAsDT : ScriptCommand [Attributes.PropertyAttributes.SampleUsage("A1, B10, {vAddress}")] [Attributes.PropertyAttributes.Remarks("")] public string v_ExcelCellAddress1 { get; set; } + [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please select output Option")] [Attributes.PropertyAttributes.PropertyUISelectionOption("Datatable")] @@ -43,6 +44,7 @@ public class ExcelGetRangeCommandAsDT : ScriptCommand [Attributes.PropertyAttributes.SampleUsage("Select from **Datatable** or **Delimited String**")] [Attributes.PropertyAttributes.Remarks("")] public string v_Output { get; set; } + [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Enter the Second Cell Location (ex. A1 or B2, Leave Blank for All)")] [Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] @@ -78,15 +80,12 @@ public ExcelGetRangeCommandAsDT() this.v_InstanceName = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - - - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - var vInstance = v_InstanceName.ConvertToUserVariable(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); var excelObject = engine.GetAppInstance(vInstance); - var targetAddress1 = v_ExcelCellAddress1.ConvertToUserVariable(sender); - var targetAddress2 = v_ExcelCellAddress2.ConvertToUserVariable(sender); + var targetAddress1 = v_ExcelCellAddress1.ExpandValueOrUserVariable(engine); + var targetAddress2 = v_ExcelCellAddress2.ExpandValueOrUserVariable(engine); Microsoft.Office.Interop.Excel.Application excelInstance = (Microsoft.Office.Interop.Excel.Application)excelObject; Microsoft.Office.Interop.Excel.Worksheet excelSheet = excelInstance.ActiveSheet; @@ -183,11 +182,11 @@ public override void RunCommand(object sender) string output = String.Join(",", lst); //Store Strings of comma seperated values into user variable - output.StoreInUserVariable(sender, v_userVariableName); + output.StoreInUserVariable(engine, v_userVariableName); } - } - public override List Render(frmCommandEditor editor) + + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -206,7 +205,7 @@ public override List Render(frmCommandEditor editor) RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_Output", this, editor)); RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_AddHeaders", this, editor)); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; } diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetRangeValuesAsDataTableCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetRangeValuesAsDataTableCommand.cs index aafc5a556..1df02462f 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetRangeValuesAsDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetRangeValuesAsDataTableCommand.cs @@ -6,48 +6,63 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Range")] [Attributes.ClassAttributes.CommandSettings("Get Range Values As DataTable")] [Attributes.ClassAttributes.Description("This command get Range values as DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Range values as DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetRangeValuesAsDataTableCommand : ScriptCommand + public sealed class ExcelGetRangeValuesAsDataTableCommand : AExcelColumnRowRangeGetCommands, IDataTableResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] - public string v_ColumnStart { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] - public string v_ColumnEnd { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] - [PropertyIsOptional(false)] - public string v_RowStart { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] - public string v_RowEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6000)] + //public string v_ColumnType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnStart { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] + //[PropertyParameterOrder(6002)] + //public string v_ColumnEnd { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] + //[PropertyIsOptional(false)] + //[PropertyParameterOrder(6003)] + //public string v_RowStart { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] + //[PropertyParameterOrder(6004)] + //public string v_RowEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] - public string v_userVariableName { get; set; } + //[PropertyParameterOrder(6005)] + public override string v_Result { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6006)] + //public string v_ValueType { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Use the First Row as the Column Names (Value Type is Cell only)")] + [PropertyIsOptional(true, "No")] + [PropertyParameterOrder(13000)] + public string v_FirstRowAsColumnName { get; set; } public ExcelGetRangeValuesAsDataTableCommand() { @@ -57,81 +72,83 @@ public ExcelGetRangeValuesAsDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); - - string valueType = this.GetUISelectionValue(nameof(v_ValueType), "Value Type", engine); - - int rowStartIndex = this.ConvertToUserVariableAsInteger(nameof(v_RowStart), "Start Row", engine); - - int columnStartIndex = 0; - int columnEndIndex = 0; - switch(this.GetUISelectionValue(nameof(v_ColumnType), "Column Type", engine)) - { - case "range": - columnStartIndex = ExcelControls.GetColumnIndex(excelSheet, v_ColumnStart.ConvertToUserVariable(engine)); - if (String.IsNullOrEmpty(v_ColumnEnd)) - { - columnEndIndex = ExcelControls.GetLastColumnIndex(excelSheet, rowStartIndex, columnStartIndex, valueType); - } - else - { - columnEndIndex = ExcelControls.GetColumnIndex(excelSheet, v_ColumnEnd.ConvertToUserVariable(engine)); - } - break; - - case "rc": - columnStartIndex = this.ConvertToUserVariableAsInteger(nameof(v_ColumnStart), "Column Start", engine); - if (String.IsNullOrEmpty(v_ColumnEnd)) - { - columnEndIndex = ExcelControls.GetLastColumnIndex(excelSheet, rowStartIndex, columnStartIndex, valueType); - } - else - { - columnEndIndex = this.ConvertToUserVariableAsInteger(nameof(v_ColumnEnd), "Column End", engine); - } - break; - } - - if (columnStartIndex > columnEndIndex) - { - int t = columnStartIndex; - columnStartIndex = columnEndIndex; - columnEndIndex = t; - } - - int rowEndIndex; - if (String.IsNullOrEmpty(v_RowEnd)) - { - rowEndIndex = ExcelControls.GetLastRowIndex(excelSheet, columnStartIndex, rowStartIndex, valueType); - } - else - { - rowEndIndex = this.ConvertToUserVariableAsInteger(nameof(v_RowEnd), "Row End", engine); - } - - if (rowStartIndex > rowEndIndex) - { - int t = rowStartIndex; - rowStartIndex = rowEndIndex; - rowEndIndex = t; - } - - ExcelControls.CheckCorrectRCRange(rowStartIndex, columnStartIndex, rowEndIndex, columnEndIndex, excelInstance); - - Func getFunc = ExcelControls.GetCellValueFunction(valueType); + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + //string valueType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), "Value Type", engine); + + //int rowStartIndex = this.ExpandValueOrUserVariableAsInteger(nameof(v_RowStart), "Start Row", engine); + + //int columnStartIndex = 0; + //int columnEndIndex = 0; + //switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ColumnType), "Column Type", engine)) + //{ + // case "range": + // columnStartIndex = ExcelControls.GetColumnIndex(excelSheet, v_ColumnStart.ExpandValueOrUserVariable(engine)); + // if (String.IsNullOrEmpty(v_ColumnEnd)) + // { + // columnEndIndex = ExcelControls.GetLastColumnIndex(excelSheet, rowStartIndex, columnStartIndex, valueType); + // } + // else + // { + // columnEndIndex = ExcelControls.GetColumnIndex(excelSheet, v_ColumnEnd.ExpandValueOrUserVariable(engine)); + // } + // break; + + // case "rc": + // columnStartIndex = this.ExpandValueOrUserVariableAsInteger(nameof(v_ColumnStart), "Column Start", engine); + // if (String.IsNullOrEmpty(v_ColumnEnd)) + // { + // columnEndIndex = ExcelControls.GetLastColumnIndex(excelSheet, rowStartIndex, columnStartIndex, valueType); + // } + // else + // { + // columnEndIndex = this.ExpandValueOrUserVariableAsInteger(nameof(v_ColumnEnd), "Column End", engine); + // } + // break; + //} + + //if (columnStartIndex > columnEndIndex) + //{ + // int t = columnStartIndex; + // columnStartIndex = columnEndIndex; + // columnEndIndex = t; + //} + + //int rowEndIndex; + //if (String.IsNullOrEmpty(v_RowEnd)) + //{ + // rowEndIndex = ExcelControls.GetLastRowIndex(excelSheet, columnStartIndex, rowStartIndex, valueType); + //} + //else + //{ + // rowEndIndex = this.ExpandValueOrUserVariableAsInteger(nameof(v_RowEnd), "Row End", engine); + //} + + //if (rowStartIndex > rowEndIndex) + //{ + // int t = rowStartIndex; + // rowStartIndex = rowEndIndex; + // rowEndIndex = t; + //} + (var rowStartIndex, var columnStartIndex, var rowEndIndex, var columnEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndicies(engine); + + //ExcelControls.CheckCorrectRCRange(rowStartIndex, columnStartIndex, rowEndIndex, columnEndIndex, excelInstance); + + //Func getFunc = ExcelControls.GetCellValueFunction(valueType); + var getFunc = this.ExpandValueOrVariableAsGetValueFunction(engine); int rowRange = rowEndIndex - rowStartIndex + 1; int colRange = columnEndIndex - columnStartIndex + 1; - DataTable newDT = new DataTable(); + var newDT = new DataTable(); // set columns for (int i = 0; i < colRange; i++) { - newDT.Columns.Add(ExcelControls.GetColumnName(excelSheet, columnStartIndex + i)); + //newDT.Columns.Add(ExcelControls.GetColumnName(excelSheet, columnStartIndex + i)); + newDT.Columns.Add(excelSheet.ToColumnName(columnStartIndex + i)); } for (int i = 0; i < rowRange; i++) @@ -143,7 +160,21 @@ public override void RunCommand(object sender) } } - newDT.StoreInUserVariable(engine, v_userVariableName); + var valueType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), "Value Type", engine); + if ((valueType == "cell") && (this.ExpandValueOrUserVariableAsYesNo(nameof(v_FirstRowAsColumnName), engine))) + { + if (newDT.Rows.Count > 0) + { + for (int i = newDT.Columns.Count - 1; i >= 0; i--) + { + newDT.Columns[i].ColumnName = newDT.Rows[0]?.ToString() ?? ""; + } + newDT.Rows[0].Delete(); + } + } + + //newDT.StoreInUserVariable(engine, v_Result); + this.StoreDataTableInUserVariable(newDT, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsDataTableCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsDataTableCommand.cs index 7c13b15f1..872b0ddd3 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsDataTableCommand.cs @@ -6,43 +6,49 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Row")] [Attributes.ClassAttributes.CommandSettings("Get Row Values As DataTable")] [Attributes.ClassAttributes.Description("This command get Row values as DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a Row values as DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetRowValuesAsDataTableCommand : ScriptCommand + public sealed class ExcelGetRowValuesAsDataTableCommand : AExcelRowRangeGetCommands, IDataTableResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] - public string v_RowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + //[PropertyParameterOrder(6000)] + //public string v_RowIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] - public string v_ColumnStart { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] + //[PropertyParameterOrder(6002)] + //public string v_ColumnStart { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] - public string v_ColumnEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] + //[PropertyParameterOrder(6003)] + //public string v_ColumnEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] - public string v_userVariableName { get; set; } + public override string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6005)] + //public string v_ValueType { get; set; } public ExcelGetRowValuesAsDataTableCommand() { @@ -52,33 +58,53 @@ public ExcelGetRowValuesAsDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //(int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) = + // ExcelControls.GetRangeIndeiesRowDirection( + // nameof(v_RowIndex), + // nameof(v_ColumnType), nameof(v_ColumnStart), nameof(v_ColumnEnd), + // nameof(v_ValueType), engine, excelSheet, this + // ); + + //Func getFunc = ExcelControls.GetCellValueFunction(valueType); + + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(int rowIndex, int columnStartIndex, int columnEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndecies(engine); + + //var getFunc = this.ExpandValueOrVariableAsGetValueFunction(engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //DataTable newDT = new DataTable(); + //newDT.Rows.Add(); - (int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) = - ExcelControls.GetRangeIndeiesRowDirection( - nameof(v_RowIndex), - nameof(v_ColumnType), nameof(v_ColumnStart), nameof(v_ColumnEnd), - nameof(v_ValueType), engine, excelSheet, this - ); + //int max = columnEndIndex - columnStartIndex + 1; + ////int colCnt = 0; + //for (int i = 0; i < max; i++) + //{ + // //newDT.Columns.Add(ExcelControls.GetColumnName(excelSheet, i)); + // var pos = columnStartIndex + i; + // newDT.Columns.Add(excelSheet.ToColumnName(pos)); + // newDT.Rows[0][i] = getFunc(excelSheet, pos, rowIndex); + // //colCnt++; + //} - Func getFunc = ExcelControls.GetCellValueFunction(valueType); + //newDT.StoreInUserVariable(engine, v_Result); - DataTable newDT = new DataTable(); + var newDT = new DataTable(); newDT.Rows.Add(); - int tblCol = 0; - for (int i = columnStartIndex; i <= columnEndIndex; i++) - { - newDT.Columns.Add(ExcelControls.GetColumnName(excelSheet, i)); - newDT.Rows[0][tblCol] = getFunc(excelSheet, i, rowIndex); - tblCol++; - } + this.RowRangeAction( + new Action((sheet, value, column, row, count) => + { + newDT.Columns.Add(sheet.ToColumnName(column)); + newDT.Rows[0][count] = value; + }), engine + ); - newDT.StoreInUserVariable(engine, v_userVariableName); + //newDT.StoreInUserVariable(engine, v_Result); + this.StoreDataTableInUserVariable(newDT, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsDictionaryCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsDictionaryCommand.cs index 77f864d1f..f20b9e6b1 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsDictionaryCommand.cs @@ -6,43 +6,50 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Row")] [Attributes.ClassAttributes.CommandSettings("Get Row Values As Dictionary")] [Attributes.ClassAttributes.Description("This command get Row values as Dictionary.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a Row values as Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetRowValuesAsDictionaryCommand : ScriptCommand + public sealed class ExcelGetRowValuesAsDictionaryCommand : AExcelRowRangeGetCommands, IDictionaryResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] - public string v_RowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + //[PropertyParameterOrder(6000)] + //public string v_RowIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] - public string v_ColumnStart { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] + //[PropertyParameterOrder(6002)] + //public string v_ColumnStart { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] - public string v_ColumnEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] + //[PropertyParameterOrder(6003)] + //public string v_ColumnEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_OutputDictionaryName))] - public string v_userVariableName { get; set; } + //[PropertyParameterOrder(6004)] + public override string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6005)] + //public string v_ValueType { get; set; } public ExcelGetRowValuesAsDictionaryCommand() { @@ -52,30 +59,48 @@ public ExcelGetRowValuesAsDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //(int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) = + // ExcelControls.GetRangeIndeiesRowDirection( + // nameof(v_RowIndex), + // nameof(v_ColumnType), nameof(v_ColumnStart), nameof(v_ColumnEnd), + // nameof(v_ValueType), engine, excelSheet, this + // ); + + //Func getFunc = ExcelControls.GetCellValueFunction(valueType); + + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(var rowIndex, var columnStartIndex, var columnEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndecies(engine); + //var getFunc = this.ExpandValueOrVariableAsGetValueFunction(engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //var newDic = new Dictionary(); - (int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) = - ExcelControls.GetRangeIndeiesRowDirection( - nameof(v_RowIndex), - nameof(v_ColumnType), nameof(v_ColumnStart), nameof(v_ColumnEnd), - nameof(v_ValueType), engine, excelSheet, this - ); + //int max = columnEndIndex - columnStartIndex + 1; + //for (int i = 0; i < max; i++) + //{ + // //string keyName = ExcelControls.GetAddress(excelSheet, rowIndex, i); + // var pos = columnStartIndex + i; + // var keyName = excelSheet.ToCellLocation(pos); + // newDic.Add(keyName, getFunc(excelSheet, pos, rowIndex)); + //} - Func getFunc = ExcelControls.GetCellValueFunction(valueType); + //newDic.StoreInUserVariable(engine, v_Result); - Dictionary newDic = new Dictionary(); + var newDic = new Dictionary(); - for (int i = columnStartIndex; i <= columnEndIndex; i++) - { - string keyName = ExcelControls.GetAddress(excelSheet, rowIndex, i); - newDic.Add(keyName, getFunc(excelSheet, i, rowIndex)); - } + this.RowRangeAction( + new Action((sheet, value, colum, row, count) => + { + var keyName = sheet.ToCellLocation(row, colum); + newDic.Add(keyName, value); + }), engine + ); - newDic.StoreInUserVariable(engine, v_userVariableName); + //newDic.StoreInUserVariable(engine, v_Result); + this.StoreDictionaryInUserVariable(newDic, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsListCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsListCommand.cs index e5347b706..7343d56b8 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsListCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetRowValuesAsListCommand.cs @@ -6,43 +6,50 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Row")] [Attributes.ClassAttributes.CommandSettings("Get Row Values As List")] [Attributes.ClassAttributes.Description("This command get Row values as List.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a Row values as List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetRowValuesAsListCommand : ScriptCommand + public sealed class ExcelGetRowValuesAsListCommand : AExcelRowRangeGetCommands, IListResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] - public string v_RowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + //[PropertyParameterOrder(6000)] + //public string v_RowIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] - public string v_ColumnStart { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] + //[PropertyParameterOrder(6002)] + //public string v_ColumnStart { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] - public string v_ColumnEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] + //[PropertyParameterOrder(6003)] + //public string v_ColumnEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] - public string v_userVariableName { get; set; } + //[PropertyParameterOrder(6004)] + public override string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6005)] + //public string v_ValueType { get; set; } public ExcelGetRowValuesAsListCommand() { @@ -52,29 +59,44 @@ public ExcelGetRowValuesAsListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //(int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) = + // ExcelControls.GetRangeIndeiesRowDirection( + // nameof(v_RowIndex), + // nameof(v_ColumnType), nameof(v_ColumnStart), nameof(v_ColumnEnd), + // nameof(v_ValueType), engine, excelSheet, this + // ); + + //Func getFunc = ExcelControls.GetCellValueFunction(valueType); + + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(var rowIndex, var columnStartIndex, var columnEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndecies(engine); + //var getFunc = this.ExpandValueOrVariableAsGetValueFunction(engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //List newList = new List(); - (int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) = - ExcelControls.GetRangeIndeiesRowDirection( - nameof(v_RowIndex), - nameof(v_ColumnType), nameof(v_ColumnStart), nameof(v_ColumnEnd), - nameof(v_ValueType), engine, excelSheet, this - ); + //int max = columnEndIndex - columnStartIndex + 1; + //for (int i = 0; i < max; i++) + //{ + // newList.Add(getFunc(excelSheet, columnStartIndex + i, rowIndex)); + //} - Func getFunc = ExcelControls.GetCellValueFunction(valueType); + //newList.StoreInUserVariable(engine, v_Result); - List newList = new List(); + var newList = new List(); - for (int i = columnStartIndex; i <= columnEndIndex; i++) - { - newList.Add(getFunc(excelSheet, i, rowIndex)); - } + this.RowRangeAction( + new Action((sheet, value, column, row, count) => + { + newList.Add(value); + }), engine + ); - newList.StoreInUserVariable(engine, v_userVariableName); + //newList.StoreInUserVariable(engine, v_Result); + this.StoreListInUserVariable(newList, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetWorksheetInfoCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetWorksheetInfoCommand.cs index e8cc7a305..6ddacd668 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetWorksheetInfoCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetWorksheetInfoCommand.cs @@ -5,23 +5,24 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] - [Attributes.ClassAttributes.SubGruop("Sheet")] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("Worksheet")] [Attributes.ClassAttributes.CommandSettings("Get Worksheet Info")] [Attributes.ClassAttributes.Description("This command allows you to get a sheet info.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to launch a new instance of Excel.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetWorksheetInfoCommand : ScriptCommand + public sealed class ExcelGetWorksheetInfoCommand : AExcelSheetCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] - public string v_SheetName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] + //public string v_SheetName { get; set; } [XmlAttribute] [PropertyDescription("Information Type")] @@ -38,11 +39,13 @@ public class ExcelGetWorksheetInfoCommand : ScriptCommand [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyValidationRule("Information Type", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Type")] + [PropertyParameterOrder(7000)] public string v_InfoType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_applyToVariable { get; set; } + [PropertyParameterOrder(7001)] + public string v_Result { get; set; } public ExcelGetWorksheetInfoCommand() { @@ -52,17 +55,13 @@ public ExcelGetWorksheetInfoCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var excelInstance, var targetSheet) = (v_InstanceName, v_SheetName).GetExcelInstanceAndWorksheet(engine); + //(var excelInstance, var targetSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(v_SheetName, engine); + (var excelInstance, var targetSheet) = this.ExpandValueOrVariableAsExcelInstanceAndWorksheet(engine); string ret = ""; - int idx = 1; - - var infoType = this.GetUISelectionValue(nameof(v_InfoType), "Info Type", engine); - switch (infoType) + switch (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_InfoType), "Info Type", engine)) { case "name": ret = targetSheet.Name; @@ -77,14 +76,33 @@ public override void RunCommand(object sender) ret = (((Microsoft.Office.Interop.Excel.Worksheet)excelInstance.Worksheets[excelInstance.Worksheets.Count]).Name == targetSheet.Name) ? "TRUE" : "FALSE"; break; case "next sheet": - var nextSheet = engine.engineSettings.NextWorksheetKeyword.GetExcelWorksheet(engine, excelInstance, true); - ret = (nextSheet == null) ? "" : nextSheet.Name; + //var nextSheet = engine.engineSettings.NextWorksheetKeyword.ExpandValueOrUserVariableAsExcelWorksheet(engine, excelInstance, true); + //ret = (nextSheet == null) ? "" : nextSheet.Name; + try + { + var nextSheet = this.ExpandValueOrVariableAsExcelWorksheet(VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Excel_NextWorkSheet.VariableName, engine), engine); + ret = nextSheet.Name; + } + catch + { + ret = ""; + } break; case "previous sheet": - var prevSheet = engine.engineSettings.PreviousWorksheetKeyword.GetExcelWorksheet(engine, excelInstance, true); - ret = (prevSheet == null) ? "" : prevSheet.Name; + //var prevSheet = engine.engineSettings.PreviousWorksheetKeyword.ExpandValueOrUserVariableAsExcelWorksheet(engine, excelInstance, true); + //ret = (prevSheet == null) ? "" : prevSheet.Name; + try + { + var nextSheet = this.ExpandValueOrVariableAsExcelWorksheet(VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Excel_PreviousWorkSheet.VariableName, engine), engine); + ret = nextSheet.Name; + } + catch + { + ret = ""; + } break; case "sheet index": + int idx = 1; foreach (Microsoft.Office.Interop.Excel.Worksheet sht in excelInstance.Worksheets) { if (sht.Name == targetSheet.Name) @@ -97,7 +115,7 @@ public override void RunCommand(object sender) break; } - ret.StoreInUserVariable(sender, v_applyToVariable); + ret.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGetWorksheetsCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGetWorksheetsCommand.cs index 83ba9e6c0..15158054f 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGetWorksheetsCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGetWorksheetsCommand.cs @@ -6,39 +6,44 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] - [Attributes.ClassAttributes.SubGruop("Sheet")] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("Worksheet")] [Attributes.ClassAttributes.CommandSettings("Get Worksheets")] [Attributes.ClassAttributes.Description("This command allows you to get a specific worksheet names")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to switch to a specific worksheet")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGetWorksheetsCommand : ScriptCommand + public sealed class ExcelGetWorksheetsCommand : AExcelSheetCommands, IListResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] - public string v_SheetName { get; set; } + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] + [PropertyIsOptional(true)] + [PropertyValidationRule("Worksheet", PropertyValidationRule.ValidationRuleFlags.None)] + public override string v_SheetName { get; set; } [XmlAttribute] - [PropertyDescription("Search Method")] + [PropertyDescription("Compare Method")] [InputSpecification("", true)] - [SampleUsage("**Contains** or **Start with** or **End with**")] + [SampleUsage("**Contains** or **Starts with** or **Ends with**")] [Remarks("")] [PropertyUISelectionOption("Contains")] - [PropertyUISelectionOption("Start with")] - [PropertyUISelectionOption("End with")] + [PropertyUISelectionOption("Starts with")] + [PropertyUISelectionOption("Ends with")] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyIsOptional(true, "Contains")] - public string v_SearchMethod { get; set; } + [PropertyParameterOrder(7000)] + public string v_CompareMethod { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] - public string v_applyToVariable { get; set; } + [PropertyParameterOrder(7001)] + public string v_Result { get; set; } public ExcelGetWorksheetsCommand() { @@ -48,17 +53,16 @@ public ExcelGetWorksheetsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var excelInstance = v_InstanceName.GetExcelInstance(engine); + //var excelInstance = v_InstanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + var excelInstance = this.ExpandValueOrVariableAsExcelInstance(engine); - List sheetNames = new List(); + var sheetNames = new List(); - var targetSheetName = v_SheetName.ConvertToUserVariable(sender); + var targetSheetName = v_SheetName.ExpandValueOrUserVariable(engine); - if (String.IsNullOrEmpty(targetSheetName)) + if (string.IsNullOrEmpty(targetSheetName)) { foreach (Microsoft.Office.Interop.Excel.Worksheet sh in excelInstance.Worksheets) { @@ -69,17 +73,16 @@ public override void RunCommand(object sender) { Func func = null; - var searchMethod = this.GetUISelectionValue(nameof(v_SearchMethod), "Search Method", engine); - - switch (searchMethod) + var compareMethod = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_CompareMethod), "Compare Method", engine); + switch (compareMethod) { case "contains": func = (sht, search) => { return sht.Contains(search); }; break; - case "start with": + case "starts with": func = (sht, search) => { return sht.StartsWith(search); }; break; - case "end with": + case "ends with": func = (sht, search) => { return sht.EndsWith(search); }; break; } @@ -93,7 +96,8 @@ public override void RunCommand(object sender) } } - sheetNames.StoreInUserVariable(engine, v_applyToVariable); + //sheetNames.StoreInUserVariable(engine, v_Result); + this.StoreListInUserVariable(sheetNames, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelGoToCellCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelGoToCellCommand.cs index 3ef462a81..387702946 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelGoToCellCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelGoToCellCommand.cs @@ -1,27 +1,27 @@ using System; -using System.Xml.Serialization; -using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Cell")] [Attributes.ClassAttributes.CommandSettings("Go To Cell")] [Attributes.ClassAttributes.Description("This command moves to a specific cell.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to move to a new cell from your currently selected cell.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelGoToCellCommand : ScriptCommand + public sealed class ExcelGoToCellCommand : AExcelCellCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CellRangeLocation))] - public string v_CellLocation { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CellRangeLocation))] + //[PropertyParameterOrder(6000)] + //public string v_CellLocation { get; set; } public ExcelGoToCellCommand() { @@ -31,13 +31,13 @@ public ExcelGoToCellCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //var rg = v_CellLocation.GetExcelRange(engine, excelInstance, excelSheet, this); - var rg = v_CellLocation.GetExcelRange(engine, excelInstance, excelSheet, this); + var rg = this.ExpandValueOrVariableAsExcelSingleCellLocation(engine); rg.Select(); } diff --git a/taskt/Core/Automation/Commands/Excel/ExcelOpenWorkbookCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelOpenWorkbookCommand.cs index 630d0b4ba..4522dbf13 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelOpenWorkbookCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelOpenWorkbookCommand.cs @@ -5,23 +5,25 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("File/Book")] [Attributes.ClassAttributes.CommandSettings("Open Workbook")] [Attributes.ClassAttributes.Description("This command opens an Excel Workbook.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to open an existing Excel Workbook.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelOpenWorkbookCommand : ScriptCommand + public sealed class ExcelOpenWorkbookCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_FilePath))] [PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtensionAndExists, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "xlsx,xlsm,xls,xlm,csv,ods")] + [PropertyParameterOrder(6000)] public string v_FilePath { get; set; } [XmlAttribute] @@ -33,6 +35,7 @@ public class ExcelOpenWorkbookCommand : ScriptCommand [PropertyDetailSampleUsage("**{{{vPassword}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Password")] [PropertyIsOptional(true)] [PropertyDisplayText(false, "")] + [PropertyParameterOrder(6001)] public string v_Password { get; set; } [XmlAttribute] @@ -47,10 +50,12 @@ public class ExcelOpenWorkbookCommand : ScriptCommand [PropertyUISelectionOption("Ignore")] [PropertyUISelectionOption("Open")] [PropertyIsOptional(true, "Error")] + [PropertyParameterOrder(6002)] public string v_IfWorksheetExists { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_WaitTime))] + [PropertyParameterOrder(6003)] public string v_WaitForFile { get; set; } public ExcelOpenWorkbookCommand() @@ -61,15 +66,14 @@ public ExcelOpenWorkbookCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var excelInstance = v_InstanceName.GetExcelInstance(engine); + //var excelInstance = v_InstanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + var excelInstance = this.ExpandValueOrVariableAsExcelInstance(engine); var vFilePath = FilePathControls.WaitForFile(this, nameof(v_FilePath), nameof(v_WaitForFile), engine); - var pass = v_Password.ConvertToUserVariable(sender); + var pass = v_Password.ExpandValueOrUserVariable(engine); int worksheets; try @@ -83,7 +87,7 @@ public override void RunCommand(object sender) Action openFileProcess = () => { - if (String.IsNullOrEmpty(pass)) + if (string.IsNullOrEmpty(pass)) { excelInstance.Workbooks.Open(vFilePath); } @@ -99,10 +103,10 @@ public override void RunCommand(object sender) } else { - switch(this.GetUISelectionValue(nameof(v_IfWorksheetExists), "If Worksheet Exists", engine)) + switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfWorksheetExists), "If Worksheet Exists", engine)) { case "error": - throw new Exception("Excel Instance '" + v_InstanceName + "' has Worksheets."); + throw new Exception($"Excel Instance '{v_InstanceName}' has Worksheets."); case "ignore": // nothing diff --git a/taskt/Core/Automation/Commands/Excel/ExcelRenameWorksheetCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelRenameWorksheetCommand.cs index f927cc21c..af75a719b 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelRenameWorksheetCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelRenameWorksheetCommand.cs @@ -1,30 +1,34 @@ -using System; +using Microsoft.Office.Interop.Excel; +using System; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] - [Attributes.ClassAttributes.SubGruop("Sheet")] + [Attributes.ClassAttributes.Group("Excel")] + [Attributes.ClassAttributes.SubGruop("Worksheet")] [Attributes.ClassAttributes.CommandSettings("Rename Worksheet")] [Attributes.ClassAttributes.Description("This command rename a Excel Worksheet.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a new worksheet to an Excel Instance")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelRenameWorksheetCommand : ScriptCommand + public sealed class ExcelRenameWorksheetCommand : AExcelInstanceCommands, IExcelWorksheetCopyRenameProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] [PropertyDescription("Target Worksheet Name to Rename")] [PropertyValidationRule("Target Sheet", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Target Sheet")] - public string v_sourceSheet { get; set; } + [PropertyAvailableSystemVariable(Engine.SystemVariables.LimitedSystemVariableNames.Excel_Worksheet)] + [PropertyParameterOrder(6000)] + public string v_TargetSheetName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_SheetName))] @@ -32,7 +36,8 @@ public class ExcelRenameWorksheetCommand : ScriptCommand [PropertyValidationRule("New Sheet", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "New Sheet")] [PropertyIntermediateConvert("", "")] - public string v_newName { get; set; } + [PropertyParameterOrder(6001)] + public string v_NewSheetName { get; set; } public ExcelRenameWorksheetCommand() { @@ -42,15 +47,34 @@ public ExcelRenameWorksheetCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var targetSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //(_, var targetSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (var excelInstance, var targetSheet) = this.ExpandValueOrVariableAsExcelInstanceAndTargetWorksheet(engine); - var newName = v_newName.ConvertToUserVariable(sender); + //var newName = v_NewSheetName.ExpandValueOrUserVariable(engine); + var newName = this.ExpandValueOrVariableAsExcelWorksheetName(v_NewSheetName, engine); - targetSheet.Name = newName; + if (targetSheet.Name != newName) + { + bool isExists = false; + foreach(Worksheet sht in excelInstance.Worksheets) + { + if (sht.Name == newName) + { + isExists = true; + break; + } + } + if (!isExists) + { + targetSheet.Name = newName; + } + else + { + throw new Exception($"Worksheet Name '{newName}' is already exists."); + } + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelRunMacroCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelRunMacroCommand.cs index d2cabb726..d8062ce29 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelRunMacroCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelRunMacroCommand.cs @@ -5,19 +5,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Other")] [Attributes.ClassAttributes.CommandSettings("Run Macro")] [Attributes.ClassAttributes.Description("This command runs a macro.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a run a specific macro in the Excel workbook.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelRunMacroCommand : ScriptCommand + public sealed class ExcelRunMacroCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -29,6 +30,7 @@ public class ExcelRunMacroCommand : ScriptCommand [PropertyDetailSampleUsage("**{{{vMacro}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Macro")] [PropertyValidationRule("Macro", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Macro")] + [PropertyParameterOrder(6000)] public string v_MacroName { get; set; } [XmlAttribute] @@ -39,6 +41,7 @@ public class ExcelRunMacroCommand : ScriptCommand [Remarks("")] [PropertyShowSampleUsageInDescription(true)] [PropertyIsOptional(true)] + [PropertyParameterOrder(6001)] public string v_Argument1 { get; set; } public ExcelRunMacroCommand() @@ -49,17 +52,16 @@ public ExcelRunMacroCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var excelInstance = v_InstanceName.GetExcelInstance(engine); + //var excelInstance = v_InstanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + var excelInstance = this.ExpandValueOrVariableAsExcelInstance(engine); - var vMacroName = v_MacroName.ConvertToUserVariable(engine); + var vMacroName = v_MacroName.ExpandValueOrUserVariable(engine); - var vArg1 = v_Argument1.ConvertToUserVariable(engine); + var vArg1 = v_Argument1.ExpandValueOrUserVariable(engine); - if (String.IsNullOrEmpty(vArg1)) + if (string.IsNullOrEmpty(vArg1)) { excelInstance.Run(vMacroName); } diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSaveAsCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSaveAsCommand.cs index 6f696288e..b7ec53479 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSaveAsCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSaveAsCommand.cs @@ -5,24 +5,26 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("File/Book")] [Attributes.ClassAttributes.CommandSettings("Save Workbook As")] [Attributes.ClassAttributes.Description("This command allows you to save an Excel workbook.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to save a workbook to a file.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelSaveAsCommand : ScriptCommand + public sealed class ExcelSaveAsCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_FilePath))] [PropertyDescription("Excel File Path to Save")] [PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtension, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "xlsx")] + [PropertyParameterOrder(6000)] public string v_FileName { get; set; } [XmlAttribute] @@ -38,6 +40,7 @@ public class ExcelSaveAsCommand : ScriptCommand [PropertyUISelectionOption("Overwrite")] [PropertyUISelectionOption("Ignore")] [PropertyIsOptional(true, "Error")] + [PropertyParameterOrder(6001)] public string v_IfExcelFileExists { get; set; } public ExcelSaveAsCommand() @@ -48,12 +51,10 @@ public ExcelSaveAsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get engine context - var engine = (Engine.AutomationEngineInstance)sender; - - var excelInstance = v_InstanceName.GetExcelInstance(engine); + //var excelInstance = v_InstanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + var excelInstance = this.ExpandValueOrVariableAsExcelInstance(engine); //string fileName; //if (FilePathControls.ContainsFileCounter(v_FileName, engine)) @@ -64,7 +65,7 @@ public override void RunCommand(object sender) //{ // fileName = FilePathControls.FormatFilePath_NoFileCounter(v_FileName, engine, "xlsx"); //} - string fileName = this.ConvertToUserVariableAsFilePath(nameof(v_FileName), engine); + string fileName = this.ExpandValueOrUserVariableAsFilePath(nameof(v_FileName), engine); // TODO: support xlsm Action saveAsProcess = () => @@ -83,10 +84,10 @@ public override void RunCommand(object sender) } else { - switch(this.GetUISelectionValue(nameof(v_IfExcelFileExists), "If Excel File Exists", engine)) + switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfExcelFileExists), "If Excel File Exists", engine)) { case "error": - throw new Exception("Excel file '" + v_FileName + "' is already exists."); + throw new Exception($"Excel file '{v_FileName}' is already exists."); case "overwrite": saveAsProcess(); @@ -99,7 +100,7 @@ public override void RunCommand(object sender) } else { - throw new Exception("Excel Instance '" + v_InstanceName + "' has no Workbook."); + throw new Exception($"Excel Instance '{v_InstanceName}' has Worksheets."); } } } diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSaveCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSaveCommand.cs index b85dcb81c..774b8039a 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSaveCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSaveCommand.cs @@ -5,19 +5,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("File/Book")] [Attributes.ClassAttributes.CommandSettings("Save Workbook")] [Attributes.ClassAttributes.Description("This command allows you to save an Excel workbook.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to save changes to a workbook.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelSaveCommand : ScriptCommand + public sealed class ExcelSaveCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } public ExcelSaveCommand() { @@ -27,12 +28,10 @@ public ExcelSaveCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get engine context - var engine = (Engine.AutomationEngineInstance)sender; - - var excelInstance = v_InstanceName.GetExcelInstance(engine); + //var excelInstance = v_InstanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + var excelInstance = this.ExpandValueOrVariableAsExcelInstance(engine); if (excelInstance.ActiveWorkbook != null) { @@ -43,12 +42,12 @@ public override void RunCommand(object sender) } else { - throw new Exception("Excel Instance '" + v_InstanceName + "' Workbook does not saved Excel File."); + throw new Exception($"Excel Instance '{v_InstanceName}' Workbook does not saved Excel File."); } } else { - throw new Exception("Excel Instance '" + v_InstanceName + "' has no Workbook."); + throw new Exception($"Excel Instance '{v_InstanceName}' has no Workbook."); } } } diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSetCellCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSetCellCommand.cs index f676459da..6c32a2c1e 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSetCellCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSetCellCommand.cs @@ -5,37 +5,43 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Cell")] [Attributes.ClassAttributes.CommandSettings("Set Cell")] [Attributes.ClassAttributes.Description("This command sets the value of a cell.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a value to a specific cell.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelSetCellCommand : ScriptCommand + public sealed class ExcelSetCellCommand : AExcelCellActionCommands, ILExcelValueSetProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyDescription("Text to Set")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Text to Set", true)] - [SampleUsage("**Hello** or **{{{vText}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyDisplayText(true, "Value")] - public string v_TextToSet { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CellRangeLocation))] + //[PropertyParameterOrder(6001)] + //public string v_CellLocation { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_CellRangeLocation))] - public string v_ExcelCellAddress { get; set; } + //[PropertyDescription("Text to Set")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Text to Set", true)] + //[SampleUsage("**Hello** or **{{{vText}}}**")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyDisplayText(true, "Value")] + //[PropertyParameterOrder(6500)] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueToSet))] + [PropertyParameterOrder(6500)] + public string v_TextToSet { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6002)] + //public string v_ValueType { get; set; } public ExcelSetCellCommand() { @@ -45,20 +51,23 @@ public ExcelSetCellCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //var rg = v_CellLocation.GetExcelRange(engine, excelInstance, excelSheet, this); - var rg = v_ExcelCellAddress.GetExcelRange(engine, excelInstance, excelSheet, this); + //var targetText = v_TextToSet.ExpandValueOrUserVariable(engine); - var targetText = v_TextToSet.ConvertToUserVariable(sender); + //string valueType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), "Value Type", engine); - string valueType = this.GetUISelectionValue(nameof(v_ValueType), "Value Type", engine); + //var setFunc = ExcelControls.SetCellValueFunctionFromRange(valueType); + //setFunc(targetText, excelSheet, rg); - var setFunc = ExcelControls.SetCellValueFunctionFromRange(valueType); - setFunc(targetText, excelSheet, rg); + var rg = this.ExpandValueOrVariableAsExcelSingleCellLocation(engine); + var setFunc = this.ExpandValueOrVariableAsSetValueAction(engine); + var targetText = v_TextToSet.ExpandValueOrUserVariable(engine); + setFunc(rg, targetText); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSetCellRCCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSetCellRCCommand.cs index e37b531c8..7fbb73dca 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSetCellRCCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSetCellRCCommand.cs @@ -5,41 +5,47 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Cell")] [Attributes.ClassAttributes.CommandSettings("Set Cell RC")] [Attributes.ClassAttributes.Description("This command sets the value of a cell.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a value to a specific cell.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelSetCellRCCommand : ScriptCommand + public sealed class ExcelSetCellRCCommand : AExcelRCLocationActionCommands, ILExcelValueSetProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyDescription("Text to Set")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Text to Set", true)] - [SampleUsage("**Hello World** or **{{{vText}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyDisplayText(true, "Text")] - public string v_TextToSet { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + //[PropertyParameterOrder(6001)] + //public string v_CellRow { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] - public string v_ExcelCellRow { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnLocation))] + //[PropertyParameterOrder(6002)] + //public string v_CellColumn { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnLocation))] - public string v_ExcelCellColumn { get; set; } + //[PropertyDescription("Text to Set")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Text to Set", true)] + //[SampleUsage("**Hello World** or **{{{vText}}}**")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyDisplayText(true, "Text")] + [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueToSet))] + [PropertyParameterOrder(8000)] + public string v_TextToSet { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6003)] + //public string v_ValueType { get; set; } public ExcelSetCellRCCommand() { @@ -51,21 +57,37 @@ public ExcelSetCellRCCommand() //this.v_InstanceName = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //var rg = this.GetExcelRange(nameof(v_CellRow), nameof(v_CellColumn), engine, excelInstance, excelSheet); + + //var targetText = v_TextToSet.ExpandValueOrUserVariable(engine); - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //string valueType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), "Value Type", engine); - var rg = this.GetExcelRange(nameof(v_ExcelCellRow), nameof(v_ExcelCellColumn), engine, excelInstance, excelSheet); + //var setFunc = ExcelControls.SetCellValueFunctionFromRange(valueType); - var targetText = v_TextToSet.ConvertToUserVariable(sender); + //setFunc(targetText, excelSheet, rg); - string valueType = this.GetUISelectionValue(nameof(v_ValueType), "Value Type", engine); + //var rg = this.ExpandValueOrVariableAsExcelCellLocation(engine); + //var setFunc = this.ExpandValueOrVariableAsSetRangeAction(engine); + //var targetText = v_TextToSet.ExpandValueOrUserVariable(engine); + //setFunc(rg, targetText); - var setFunc = ExcelControls.SetCellValueFunctionFromRange(valueType); + //(_, var sheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(var row, var column) = this.ExpandValueOrVariableAsCellRowAndColumnIndex(engine); + //var setFunc = this.ExpandValueOrVaribleAsSetValueAction(engine); + //var targetText = v_TextToSet.ExpandValueOrUserVariable(engine); + //setFunc(targetText, sheet, column, row); - setFunc(targetText, excelSheet, rg); + this.RCLocationAction(new Action((sheet, column, row) => + { + var setFunc = this.ExpandValueOrVaribleAsSetValueAction(engine); + var targetText = v_TextToSet.ExpandValueOrUserVariable(engine); + setFunc(targetText, sheet, column, row); + }), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromDataTableCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromDataTableCommand.cs index f3c7683f4..20fc7a62e 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromDataTableCommand.cs @@ -6,38 +6,44 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Column")] [Attributes.ClassAttributes.CommandSettings("Set Column Values From DataTable")] [Attributes.ClassAttributes.Description("This command set Column values from DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set Column values from DataTable.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.ImplementationDescription("")] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelSetColumnValuesFromDataTableCommand : ScriptCommand + public sealed class ExcelSetColumnValuesFromDataTableCommand : AExcelColumnRangeSetCommands, ICanHandleDataTable { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] - public string v_ExcelColumnIndex { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] - public string v_RowStart { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] - public string v_RowEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6000)] + //public string v_ColumnType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] + //[PropertyParameterOrder(6002)] + //public string v_RowStart { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] + //[PropertyParameterOrder(6003)] + //public string v_RowEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + [PropertyParameterOrder(10000)] public string v_DataTableVariable { get; set; } [XmlAttribute] @@ -53,16 +59,19 @@ public class ExcelSetColumnValuesFromDataTableCommand : ScriptCommand [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("Column", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] [PropertyDisplayText(true, "Column")] + [PropertyParameterOrder(10001)] public string v_DataTableColumnIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6006)] + //public string v_ValueType { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] [PropertyDescription("When DataTable Items Not Enough")] - public string v_IfDataTableNotEnough { get; set; } + //[PropertyParameterOrder(6007)] + public override string v_WhenItemNotEnough { get; set; } public ExcelSetColumnValuesFromDataTableCommand() { @@ -72,52 +81,68 @@ public ExcelSetColumnValuesFromDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); - - DataTable myDT = v_DataTableVariable.GetDataTableVariable(engine); - - (int excelColumnIndex, int rowStart, int rowEnd, string valueType) = - ExcelControls.GetRangeIndeiesColumnDirection( - nameof(v_ExcelColumnIndex), nameof(v_ColumnType), - nameof(v_RowStart), nameof(v_RowEnd), - nameof(v_ValueType), engine, excelSheet, this, - myDT - ); - - int range = rowEnd - rowStart + 1; - - int dtColumnIndex = this.ConvertToUserVariableAsInteger(nameof(v_DataTableColumnIndex), "DataTable Column Index", engine); + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //int dtColumnIndex = this.ExpandValueOrUserVariableAsInteger(nameof(v_DataTableColumnIndex), "DataTable Column Index", engine); + + //(int excelColumnIndex, int rowStart, int rowEnd, string valueType) = + // ExcelControls.GetRangeIndeiesColumnDirection( + // nameof(v_ColumnIndex), nameof(v_ColumnType), + // nameof(v_RowStart), nameof(v_RowEnd), + // nameof(v_ValueType), engine, excelSheet, this, + // myDT + // ); + + //int range = rowEnd - rowStart + 1; + + //string ifDataTableNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenItemNotEnough), "Id DataTable Not Enough", engine); + //if (ifDataTableNotEnough == "error") + //{ + // if (range > myDT.Rows.Count) + // { + // throw new Exception("DataTable items not enough"); + // } + //} + + //int max = range; + //if (range > myDT.Rows.Count) + //{ + // max = myDT.Rows.Count; + //} + + //Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.ExpandValueOrUserVariableAsSelectionItem("v_ValueType", this, engine)); + //var setFunc = ExcelControls.SetCellValueFunction(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), engine)); + + //DataTable myDT = v_DataTableVariable.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(nameof(v_DataTableVariable), engine); + + var dtColumnIndex = v_DataTableColumnIndex.ExpandValueOrUserVariableAsInteger("DataTable Column Index", engine); if ((dtColumnIndex < 0) || (dtColumnIndex >= myDT.Columns.Count)) { - throw new Exception("Column index " + v_DataTableColumnIndex + " is not exists"); + throw new Exception($"Column index '{v_DataTableColumnIndex}' is not exists"); } - string ifDataTableNotEnough = this.GetUISelectionValue(nameof(v_IfDataTableNotEnough), "Id DataTable Not Enough", engine); - if (ifDataTableNotEnough == "error") - { - if (range > myDT.Rows.Count) - { - throw new Exception("DataTable items not enough"); - } - } + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(var excelColumnIndex, var rowStartIndex, var rowEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndicies(engine, new Func(() => myDT.Rows.Count)); - int max = range; - if (range > myDT.Rows.Count) - { - max = myDT.Rows.Count; - } + //var setFunc = this.ExpandValueOrVaribleAsSetValueAction(engine); - Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.GetUISelectionValue("v_ValueType", this, engine)); + //int max = rowEndIndex - rowStartIndex + 1; + //for (int i = 0; i < max; i++) + //{ + // string value = myDT.Rows[i][dtColumnIndex]?.ToString() ?? ""; + // setFunc(value, excelSheet, excelColumnIndex, rowStartIndex + i); + //} - for (int i = 0; i < max; i++) - { - string value = myDT.Rows[i][dtColumnIndex]?.ToString() ?? ""; - setFunc(value, excelSheet, excelColumnIndex, rowStart + i); - } + this.ColumnRangeAction( + new Func(() => myDT.Rows.Count), + new Func((index) => + { + return myDT.Rows[index][dtColumnIndex]?.ToString() ?? ""; + }), engine + ); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromDictionaryCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromDictionaryCommand.cs index 94f957d93..bb1180373 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromDictionaryCommand.cs @@ -1,53 +1,60 @@ using System; -using System.Collections.Generic; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Column")] [Attributes.ClassAttributes.CommandSettings("Set Column Values From Dictionary")] [Attributes.ClassAttributes.Description("This command set Column values from Ditionary.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set Column values from Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelSetColumnValuesFromDictionaryCommand : ScriptCommand + public sealed class ExcelSetColumnValuesFromDictionaryCommand : AExcelColumnRangeSetCommands, ICanHandleDictionary { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] - public string v_ColumnIndex { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] - public string v_RowStart { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] - public string v_RowEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6000)] + //public string v_ColumnType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] + //[PropertyParameterOrder(6002)] + //public string v_RowStart { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] + //[PropertyParameterOrder(6003)] + //public string v_RowEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + [PropertyParameterOrder(10000)] public string v_DictionaryVariable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6005)] + //public string v_ValueType { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] [PropertyDescription("When Dictionary Items Not Enough")] - public string v_IfDictionaryNotEnough { get; set; } + //[PropertyParameterOrder(6006)] + public override string v_WhenItemNotEnough { get; set; } public ExcelSetColumnValuesFromDictionaryCommand() { @@ -57,49 +64,69 @@ public ExcelSetColumnValuesFromDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //(int columnIndex, int rowStart, int rowEnd, string valueType) = + // ExcelControls.GetRangeIndeiesColumnDirection( + // nameof(v_ColumnIndex), nameof(v_ColumnType), + // nameof(v_RowStart), nameof(v_RowEnd), + // nameof(v_ValueType), engine, excelSheet, this, + // myDic + // ); - Dictionary myDic = v_DictionaryVariable.GetDictionaryVariable(engine); + //int range = rowEnd - rowStart + 1; - (int columnIndex, int rowStart, int rowEnd, string valueType) = - ExcelControls.GetRangeIndeiesColumnDirection( - nameof(v_ColumnIndex), nameof(v_ColumnType), - nameof(v_RowStart), nameof(v_RowEnd), - nameof(v_ValueType), engine, excelSheet, this, - myDic - ); + //string ifDictionaryNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenItemNotEnough), "If Dictionary Not Enough", engine); + //if (ifDictionaryNotEnough == "error") + //{ + // if (range > myDic.Count) + // { + // throw new Exception("Dictionary items not enough"); + // } + //} - int range = rowEnd - rowStart + 1; + //int max = range; + //if (range > myDic.Count) + //{ + // max = myDic.Count; + //} - string ifDictionaryNotEnough = this.GetUISelectionValue(nameof(v_IfDictionaryNotEnough), "If Dictionary Not Enough", engine); - if (ifDictionaryNotEnough == "error") - { - if (range > myDic.Count) - { - throw new Exception("Dictionary items not enough"); - } - } + //Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.ExpandValueOrUserVariableAsSelectionItem("v_ValueType", this, engine)); + //var setFunc = ExcelControls.SetCellValueFunction(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), engine)); + + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); - int max = range; - if (range > myDic.Count) - { - max = myDic.Count; - } + //var myDic = v_DictionaryVariable.ExpandUserVariableAsDictinary(engine); - Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.GetUISelectionValue("v_ValueType", this, engine)); + //(var columnIndex, var rowStartIndex, var rowEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndicies(engine, new Func(() => myDic.Count)); + //var setFunc = this.ExpandValueOrVaribleAsSetValueAction(engine); + + //// copy key list + //string[] keys = new string[myDic.Keys.Count]; + //myDic.Keys.CopyTo(keys, 0); + + //int max = rowEndIndex - rowStartIndex + 1; + //for (int i = 0; i < max; i++) + //{ + // setFunc(myDic[keys[i]], excelSheet, columnIndex, rowStartIndex + i); + //} + + //var myDic = v_DictionaryVariable.ExpandUserVariableAsDictinary(engine); + var myDic = this.ExpandUserVariableAsDictionary(nameof(v_DictionaryVariable), engine); // copy key list string[] keys = new string[myDic.Keys.Count]; myDic.Keys.CopyTo(keys, 0); - for (int i = 0; i < max; i++) - { - setFunc(myDic[keys[i]], excelSheet, columnIndex, rowStart + i); - } + this.ColumnRangeAction( + new Func(() => myDic.Count), + new Func((index) => + { + return myDic[keys[index]]; + }), engine + ); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromListCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromListCommand.cs index 4c78ca7b5..573221187 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromListCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSetColumnValuesFromListCommand.cs @@ -1,53 +1,60 @@ using System; -using System.Collections.Generic; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Column")] [Attributes.ClassAttributes.CommandSettings("Set Column Values From List")] [Attributes.ClassAttributes.Description("This command set Column values from List.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set Column values from List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelSetColumnValuesFromListCommand : ScriptCommand + public sealed class ExcelSetColumnValuesFromListCommand : AExcelColumnRangeSetCommands, ICanHandleList { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] - public string v_ColumnIndex { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] - public string v_RowStart { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] - public string v_RowEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6000)] + //public string v_ColumnType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnNameOrIndex))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowStart))] + //[PropertyParameterOrder(6002)] + //public string v_RowStart { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowEnd))] + //[PropertyParameterOrder(6003)] + //public string v_RowEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + [PropertyParameterOrder(10000)] public string v_ListVariable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6005)] + //public string v_ValueType { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] [PropertyDescription("When List Items Not Enough")] - public string v_IfListNotEnough { get; set; } + //[PropertyParameterOrder(6006)] + public override string v_WhenItemNotEnough { get; set; } public ExcelSetColumnValuesFromListCommand() { @@ -57,46 +64,61 @@ public ExcelSetColumnValuesFromListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); - - - List myList = v_ListVariable.GetListVariable(engine); - - (int columnIndex, int rowStart, int rowEnd, string valueType) = - ExcelControls.GetRangeIndeiesColumnDirection( - nameof(v_ColumnIndex), nameof(v_ColumnType), - nameof(v_RowStart), nameof(v_RowEnd), - nameof(v_ValueType), engine, excelSheet, this, - myList - ); - - int range = rowEnd - rowStart + 1; - - string ifListNotEnough = this.GetUISelectionValue(nameof(v_IfListNotEnough), "If List Not Enough", engine); - if (ifListNotEnough == "error") - { - if (range > myList.Count) + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + //(int columnIndex, int rowStart, int rowEnd, string valueType) = + // ExcelControls.GetRangeIndeiesColumnDirection( + // nameof(v_ColumnIndex), nameof(v_ColumnType), + // nameof(v_RowStart), nameof(v_RowEnd), + // nameof(v_ValueType), engine, excelSheet, this, + // myList + // ); + + //int range = rowEnd - rowStart + 1; + + //string ifListNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenItemNotEnough), "If List Not Enough", engine); + //if (ifListNotEnough == "error") + //{ + // if (range > myList.Count) + // { + // throw new Exception("List items not enough"); + // } + //} + + //int max = range; + //if (range > myList.Count) + //{ + // max = myList.Count; + //} + + //Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.ExpandValueOrUserVariableAsSelectionItem("v_ValueType", this, engine)); + //var setFunc = ExcelControls.SetCellValueFunction(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), engine)); + + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + //var myList = v_ListVariable.ExpandUserVariableAsList(engine); + + //(var columnIndex, var rowStartIndex, var rowEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndicies(engine, new Func(() => myList.Count)); + //var setFunc = this.ExpandValueOrVaribleAsSetValueAction(engine); + + //int max = rowEndIndex - rowStartIndex + 1; + //for (int i = 0; i < max; i++) + //{ + // setFunc(myList[i], excelSheet, columnIndex, rowStartIndex + i); + //} + + //var myList = v_ListVariable.ExpandUserVariableAsList(engine); + var myList = this.ExpandUserVariableAsList(nameof(v_ListVariable), engine); + + this.ColumnRangeAction( + new Func(() => myList.Count), + new Func((index) => { - throw new Exception("List items not enough"); - } - } - - int max = range; - if (range > myList.Count) - { - max = myList.Count; - } - - Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.GetUISelectionValue("v_ValueType", this, engine)); - - for (int i = 0; i < max; i++) - { - setFunc(myList[i], excelSheet, columnIndex, rowStart + i); - } + return myList[index]; + }), engine + ); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormDataTableCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormDataTableCommand.cs index faaa25f53..07ed5266f 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormDataTableCommand.cs @@ -1,65 +1,72 @@ using System; -using System.Data; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Row")] [Attributes.ClassAttributes.CommandSettings("Set Row Values From DataTable")] [Attributes.ClassAttributes.Description("This command set Row values from DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a Row values from DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelSetRowValuesFromDataTableCommand : ScriptCommand + public sealed class ExcelSetRowValuesFromDataTableCommand : AExcelRowRangeSetCommands, ICanHandleDataTable { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] - public string v_ExcelRowIndex { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] - public string v_ColumnStart { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] - public string v_ColumnEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + //[PropertyParameterOrder(6000)] + //public string v_RowIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] + //[PropertyParameterOrder(6002)] + //public string v_ColumnStart { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] + //[PropertyParameterOrder(6003)] + //public string v_ColumnEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_InputDataTableName))] + [PropertyParameterOrder(10000)] public string v_DataTableVariable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] [PropertyDescription("DataTable Row Index")] [InputSpecification("DataTable Row Index", true)] - //[SampleUsage("**1** or **2** or **{{{vRow}}}**")] [PropertyDetailSampleUsage("**0**", "Specify the First Row Index")] [PropertyDetailSampleUsage("**1**", PropertyDetailSampleUsage.ValueType.Value, "Row Index")] [PropertyDetailSampleUsage("**{{{vRow}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Row Index")] [PropertyValidationRule("DataTable Row Index", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] [PropertyDisplayText(true, "DataTable Row")] + [PropertyParameterOrder(10001)] public string v_DataTableRowIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6006)] + //public string v_ValueType { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] [PropertyDescription("When DataTable Items Not Enough")] - public string v_IfDataTableNotEnough { get; set; } + //[PropertyParameterOrder(6007)] + public override string v_WhenItemNotEnough { get; set; } public ExcelSetRowValuesFromDataTableCommand() { @@ -69,52 +76,77 @@ public ExcelSetRowValuesFromDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); - - - DataTable myDT = v_DataTableVariable.GetDataTableVariable(engine); - - (int excelRowIndex, int columnStartIndex, int columnEndIndex, string valueType) = - ExcelControls.GetRangeIndeiesRowDirection( - nameof(v_ExcelRowIndex), nameof(v_ColumnType), - nameof(v_ColumnStart), nameof(v_ColumnEnd), - nameof(v_ValueType), engine, excelSheet, this, - myDT - ); - - int dtRowIndex = this.ConvertToUserVariableAsInteger(nameof(v_DataTableRowIndex), "DataTable Row Index", engine); - if (dtRowIndex >= myDT.Rows.Count) + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + + + //var myDT = v_DataTableVariable.ExpandUserVariableAsDataTable(engine); + + //(int excelRowIndex, int columnStartIndex, int columnEndIndex, string valueType) = + // ExcelControls.GetRangeIndeiesRowDirection( + // nameof(v_RowIndex), nameof(v_ColumnType), + // nameof(v_ColumnStart), nameof(v_ColumnEnd), + // nameof(v_ValueType), engine, excelSheet, this, + // myDT + // ); + + //int dtRowIndex = this.ExpandValueOrUserVariableAsInteger(nameof(v_DataTableRowIndex), "DataTable Row Index", engine); + //if (dtRowIndex >= myDT.Rows.Count) + //{ + // throw new Exception("DataTable Row " + v_DataTableRowIndex + " is not exists"); + //} + + //string ifDataTableNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenItemNotEnough), "If DataTable Not Enough", engine); + //int range = columnEndIndex - columnStartIndex + 1; + //if (ifDataTableNotEnough == "error") + //{ + // if (range > myDT.Columns.Count) + // { + // throw new Exception("DataTable Items not enough"); + // } + //} + + //int max = range; + //if (range > myDT.Columns.Count) + //{ + // max = myDT.Columns.Count; + //} + + ////Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.ExpandValueOrUserVariableAsSelectionItem("v_ValueType", this, engine)); + //var setFunc = ExcelControls.SetCellValueFunction(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), engine)); + + //for (int i = 0; i < max; i++) + //{ + // string setValue = myDT.Rows[dtRowIndex][i]?.ToString() ?? ""; + // setFunc(setValue, excelSheet, columnStartIndex + i, excelRowIndex); + //} + + //var myDT = v_DataTableVariable.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(nameof(v_DataTableVariable), engine); + var dtRowIndex = v_DataTableRowIndex.ExpandValueOrUserVariableAsInteger("DataTable Row Index", engine); + if (dtRowIndex >= myDT.Rows.Count) { - throw new Exception("DataTable Row " + v_DataTableRowIndex + " is not exists"); + throw new Exception($"DataTable Row '{v_DataTableRowIndex}' is not exists."); } - string ifDataTableNotEnough = this.GetUISelectionValue(nameof(v_IfDataTableNotEnough), "If DataTable Not Enough", engine); - int range = columnEndIndex - columnStartIndex + 1; - if (ifDataTableNotEnough == "error") - { - if (range > myDT.Columns.Count) + //(_, var sheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + //(var row, var columnStart, var columnEnd) = this.ExpandValueOrVariableAsExcelRangeIndecies(engine, new Func(() => myDT.Columns.Count)); + //int max = (columnEnd - columnStart) + 1; + //var setFunc = this.ExpandValueOrVaribleAsSetValueAction(engine); + //for (int i = 0; i < max; i++) + //{ + // string setValue = myDT.Rows[dtRowIndex][i]?.ToString() ?? ""; + // setFunc(setValue, sheet, columnStart + i, row); + //} + + this.RowRangeAction( + new Func(() => myDT.Columns.Count), + new Func((count) => { - throw new Exception("DataTable Items not enough"); - } - } - - int max = range; - if (range > myDT.Columns.Count) - { - max = myDT.Columns.Count; - } - - Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.GetUISelectionValue("v_ValueType", this, engine)); - - for (int i = 0; i < max; i++) - { - string setValue = myDT.Rows[dtRowIndex][i]?.ToString() ?? ""; - setFunc(setValue, excelSheet, columnStartIndex + i, excelRowIndex); - } + return myDT.Rows[dtRowIndex][count]?.ToString() ?? ""; + }), engine + ); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormDictionaryCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormDictionaryCommand.cs index 167f3f235..45f60bc14 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormDictionaryCommand.cs @@ -6,48 +6,56 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Row")] [Attributes.ClassAttributes.CommandSettings("Set Row Values From Dictionary")] [Attributes.ClassAttributes.Description("This command set Row values from Dictionary.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a Row values from Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelSetRowValuesFromDictionaryCommand : ScriptCommand + public sealed class ExcelSetRowValuesFromDictionaryCommand : AExcelRowRangeSetCommands, ICanHandleDictionary { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] - public string v_RowIndex { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] - public string v_ColumnStart { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] - public string v_ColumnEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + //[PropertyParameterOrder(6000)] + //public string v_RowIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] + //[PropertyParameterOrder(6002)] + //public string v_ColumnStart { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] + //[PropertyParameterOrder(6003)] + //public string v_ColumnEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_InputDictionaryName))] + [PropertyParameterOrder(10000)] public string v_DictionaryVariable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6005)] + //public string v_ValueType { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] [PropertyDescription("When Dictionary Items Not Enough")] - public string v_IfDictionaryNotEnough { get; set; } + //[PropertyParameterOrder(6006)] + public override string v_WhenItemNotEnough { get; set; } public ExcelSetRowValuesFromDictionaryCommand() { @@ -57,48 +65,65 @@ public ExcelSetRowValuesFromDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); - - Dictionary myDic = v_DictionaryVariable.GetDictionaryVariable(engine); - - (int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) = - ExcelControls.GetRangeIndeiesRowDirection( - nameof(v_RowIndex), nameof(v_ColumnType), - nameof(v_ColumnStart), nameof(v_ColumnEnd), - nameof(v_ValueType), engine, excelSheet, this, - myDic - ); - - //string ifListNotEnough = v_IfDictionaryNotEnough.GetUISelectionValue("v_IfDictionaryNotEnough", this, engine); - string ifListNotEnough = this.GetUISelectionValue(nameof(v_IfDictionaryNotEnough), "If Dictionary Not Enough", engine); - int range = columnEndIndex - columnStartIndex + 1; - if (ifListNotEnough == "error") - { - if (range > myDic.Count) - { - throw new Exception("Dictionary Items not enough"); - } - } - - int max = range; - if (range > myDic.Count) - { - max = myDic.Count; - } - - Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.GetUISelectionValue("v_ValueType", this, engine)); - + //(int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) = + // ExcelControls.GetRangeIndeiesRowDirection( + // nameof(v_RowIndex), nameof(v_ColumnType), + // nameof(v_ColumnStart), nameof(v_ColumnEnd), + // nameof(v_ValueType), engine, excelSheet, this, + // myDic + // ); + + ////string ifListNotEnough = v_IfDictionaryNotEnough.GetUISelectionValue("v_IfDictionaryNotEnough", this, engine); + //string ifListNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenItemNotEnough), "If Dictionary Not Enough", engine); + //int range = columnEndIndex - columnStartIndex + 1; + //if (ifListNotEnough == "error") + //{ + // if (range > myDic.Count) + // { + // throw new Exception("Dictionary Items not enough"); + // } + //} + + //int max = range; + //if (range > myDic.Count) + //{ + // max = myDic.Count; + //} + + //Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.ExpandValueOrUserVariableAsSelectionItem("v_ValueType", this, engine)); + //var setFunc = ExcelControls.SetCellValueFunction(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), engine)); + + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + //var myDic = v_DictionaryVariable.ExpandUserVariableAsDictinary(engine); + + //(var rowIndex, var columnStartIndex, var columnEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndecies(engine, new Func(() => myDic.Count)); + //var setFunc = this.ExpandValueOrVaribleAsSetValueAction(engine); + + //string[] keys = new string[myDic.Count]; + //myDic.Keys.CopyTo(keys, 0); + + //var max = columnEndIndex - columnStartIndex + 1; + //for (int i = 0; i < max; i++) + //{ + // setFunc(myDic[keys[i]], excelSheet, columnStartIndex + i, rowIndex); + //} + + //var myDic = v_DictionaryVariable.ExpandUserVariableAsDictinary(engine); + var myDic = this.ExpandUserVariableAsDictionary(nameof(v_DictionaryVariable), engine); + string[] keys = new string[myDic.Count]; myDic.Keys.CopyTo(keys, 0); - for (int i = 0; i < max; i++) - { - setFunc(myDic[keys[i]], excelSheet, columnStartIndex + i, rowIndex); - } + this.RowRangeAction( + new Func(() => myDic.Count), + new Func((count) => + { + return myDic[keys[count]]; + }), engine + ); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormListCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormListCommand.cs index da0694a48..b7e7070d6 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormListCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSetRowValuesFormListCommand.cs @@ -1,53 +1,60 @@ using System; -using System.Collections.Generic; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Row")] [Attributes.ClassAttributes.CommandSettings("Set Row Values From List")] [Attributes.ClassAttributes.Description("This command set Row values from List.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a Row values from List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExcelSetRowValuesFromListCommand : ScriptCommand + public sealed class ExcelSetRowValuesFromListCommand : AExcelRowRangeSetCommands, ICanHandleList { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] - public string v_InstanceName { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] - public string v_RowIndex { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] - public string v_ColumnType { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] - public string v_ColumnStart { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] - public string v_ColumnEnd { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_InputInstanceName))] + //public string v_InstanceName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_RowLocation))] + //[PropertyParameterOrder(6000)] + //public string v_RowIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnType))] + //[PropertyParameterOrder(6001)] + //public string v_ColumnType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnStart))] + //[PropertyParameterOrder(6002)] + //public string v_ColumnStart { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ColumnEnd))] + //[PropertyParameterOrder(6003)] + //public string v_ColumnEnd { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + [PropertyParameterOrder(10000)] public string v_ListVariable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_ValueType))] + //[PropertyParameterOrder(6005)] + //public string v_ValueType { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] + //[PropertyVirtualProperty(nameof(ExcelControls), nameof(ExcelControls.v_WhenItemNotEnough))] [PropertyDescription("When List Items Not Enough")] - public string v_IfListNotEnough { get; set; } + //[PropertyParameterOrder(6006)] + public override string v_WhenItemNotEnough { get; set; } public ExcelSetRowValuesFromListCommand() { @@ -57,45 +64,57 @@ public ExcelSetRowValuesFromListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); - - // get list - List myList = v_ListVariable.GetListVariable(engine); - - (int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) = - ExcelControls.GetRangeIndeiesRowDirection( - nameof(v_RowIndex), nameof(v_ColumnType), - nameof(v_ColumnStart), nameof(v_ColumnEnd), - nameof(v_ValueType), engine, excelSheet, this, - myList - ); - - string ifListNotEnough = this.GetUISelectionValue(nameof(v_IfListNotEnough), "If List Not Enough", engine); - int range = columnEndIndex - columnStartIndex + 1; - if (ifListNotEnough == "error") - { - if (range > myList.Count) + //(int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) = + // ExcelControls.GetRangeIndeiesRowDirection( + // nameof(v_RowIndex), nameof(v_ColumnType), + // nameof(v_ColumnStart), nameof(v_ColumnEnd), + // nameof(v_ValueType), engine, excelSheet, this, + // myList + // ); + + //string ifListNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenItemNotEnough), "If List Not Enough", engine); + //int range = columnEndIndex - columnStartIndex + 1; + //if (ifListNotEnough == "error") + //{ + // if (range > myList.Count) + // { + // throw new Exception("List Items not enough"); + // } + //} + + //int max = range; + //if (range > myList.Count) + //{ + // max = myList.Count; + //} + + //Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.ExpandValueOrUserVariableAsSelectionItem("v_ValueType", this, engine)); + //var setFunc = ExcelControls.SetCellValueFunction(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ValueType), engine)); + + //(_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + + //var myList = v_ListVariable.ExpandUserVariableAsList(engine); + + //(var rowIndex, var columnStartIndex, var columnEndIndex) = this.ExpandValueOrVariableAsExcelRangeIndecies(engine, new Func(() => myList.Count)); + + //var setFunc = this.ExpandValueOrVaribleAsSetValueAction(engine); + //var max = columnEndIndex - columnStartIndex + 1; + //for (int i = 0; i < max; i++) + //{ + // setFunc(myList[i], excelSheet, columnStartIndex + i, rowIndex); + //} + + //var myList = v_ListVariable.ExpandUserVariableAsList(engine); + var myList = this.ExpandUserVariableAsList(nameof(v_ListVariable), engine); + this.RowRangeAction( + new Func(() => myList.Count), + new Func((count) => { - throw new Exception("List Items not enough"); - } - } - - int max = range; - if (range > myList.Count) - { - max = myList.Count; - } - - Action setFunc = ExcelControls.SetCellValueFunction(v_ValueType.GetUISelectionValue("v_ValueType", this, engine)); - - for (int i = 0; i < max; i++) - { - setFunc(myList[i], excelSheet, columnStartIndex + i, rowIndex); - } + return myList[count]; + }), engine + ); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/ExcelSplitRangeByColumnCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelSplitRangeByColumnCommand.cs index 861d6eac9..5d07c25e0 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelSplitRangeByColumnCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelSplitRangeByColumnCommand.cs @@ -3,7 +3,6 @@ using System.Windows.Forms; using System.Xml.Serialization; using taskt.UI.CustomControls; -using taskt.UI.Forms; using System.Data; using System.Linq; using System.IO; @@ -12,23 +11,24 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Range")] [Attributes.ClassAttributes.CommandSettings("Split Range By Column")] [Attributes.ClassAttributes.Description("This command gets text from a specified Excel Range and splits it into separate ranges by column.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to split a range into separate ranges.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Excel Interop' to achieve automation.")] - public class ExcelSplitRangeByColumnCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + public sealed class ExcelSplitRangeByColumnCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyDescription("Please Enter the instance name")] - [InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] - [SampleUsage("**myInstance** or **excelInstance**")] - [Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyDescription("Please Enter the instance name")] + //[InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] + //[SampleUsage("**myInstance** or **excelInstance**")] + //[Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //public string v_InstanceName { get; set; } [XmlAttribute] [PropertyDescription("Please Enter the First Cell Location (ex. A1 or B2)")] @@ -36,6 +36,7 @@ public class ExcelSplitRangeByColumnCommand : ScriptCommand [InputSpecification("Enter the actual location of the cell.")] [SampleUsage("A1, B10, {vAddress}")] [Remarks("")] + [PropertyParameterOrder(6000)] public string v_ExcelCellAddress1 { get; set; } [XmlAttribute] @@ -44,6 +45,7 @@ public class ExcelSplitRangeByColumnCommand : ScriptCommand [InputSpecification("Enter the actual location of the cell.")] [SampleUsage("A1, B10, {vAddress}")] [Remarks("")] + [PropertyParameterOrder(6001)] public string v_ExcelCellAddress2 { get; set; } [XmlAttribute] @@ -52,6 +54,7 @@ public class ExcelSplitRangeByColumnCommand : ScriptCommand [InputSpecification("Enter the name of the column you wish to split by.")] [SampleUsage("ColA, {vColumn}")] [Remarks("")] + [PropertyParameterOrder(6003)] public string v_ColumnName { get; set; } [XmlAttribute] @@ -61,6 +64,7 @@ public class ExcelSplitRangeByColumnCommand : ScriptCommand [InputSpecification("Enter or Select the new directory for the split Excel Files.")] [SampleUsage("C:\\temp\\new path\\ or {vTextFolderPath}")] [Remarks("")] + [PropertyParameterOrder(6004)] public string v_OutputDirectory { get; set; } [XmlAttribute] @@ -70,6 +74,7 @@ public class ExcelSplitRangeByColumnCommand : ScriptCommand [InputSpecification("Specify the file format type for the split ranges")] [SampleUsage("Select either **xlsx* or **csv**")] [Remarks("")] + [PropertyParameterOrder(6005)] public string v_FileType { get; set; } [XmlAttribute] @@ -77,6 +82,7 @@ public class ExcelSplitRangeByColumnCommand : ScriptCommand [InputSpecification("Select or provide a variable from the variable list")] [SampleUsage("**vSomeVariable**")] [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] + [PropertyParameterOrder(6006)] public string v_userVariableName { get; set; } public ExcelSplitRangeByColumnCommand() @@ -86,20 +92,19 @@ public ExcelSplitRangeByColumnCommand() //this.CommandEnabled = true; //this.CustomRendering = true; + //this.v_InstanceName = ""; this.v_FileType = "xlsx"; - this.v_InstanceName = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (var excelInstance, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); - var vTargetAddress1 = v_ExcelCellAddress1.ConvertToUserVariable(sender); - var vTargetAddress2 = v_ExcelCellAddress2.ConvertToUserVariable(sender); - var vColumnName = v_ColumnName.ConvertToUserVariable(sender); - var vOutputDirectory = v_OutputDirectory.ConvertToUserVariable(sender); + var vTargetAddress1 = v_ExcelCellAddress1.ExpandValueOrUserVariable(engine); + var vTargetAddress2 = v_ExcelCellAddress2.ExpandValueOrUserVariable(engine); + var vColumnName = v_ColumnName.ExpandValueOrUserVariable(engine); + var vOutputDirectory = v_OutputDirectory.ExpandValueOrUserVariable(engine); excelInstance.Visible = false; excelInstance.DisplayAlerts = false; @@ -220,7 +225,7 @@ public override void RunCommand(object sender) } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -242,7 +247,7 @@ public override List Render(frmCommandEditor editor) //RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_Output", this, editor)); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; } diff --git a/taskt/Core/Automation/Commands/Excel/ExcelWriteRangeCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelWriteRangeCommand.cs index 17805e2bd..4dd60da2c 100644 --- a/taskt/Core/Automation/Commands/Excel/ExcelWriteRangeCommand.cs +++ b/taskt/Core/Automation/Commands/Excel/ExcelWriteRangeCommand.cs @@ -3,7 +3,6 @@ using System.Windows.Forms; using System.Xml.Serialization; using taskt.UI.CustomControls; -using taskt.UI.Forms; using System.Data; using System.Linq; using System.Text.RegularExpressions; @@ -12,36 +11,41 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] + [Attributes.ClassAttributes.Group("Excel")] [Attributes.ClassAttributes.SubGruop("Range")] [Attributes.ClassAttributes.CommandSettings("Write Range")] [Attributes.ClassAttributes.Description("This command writes a datatable to an excel sheet starting from the given cell address.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a value to a specific cell.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] - public class ExcelWriteRangeCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] + public sealed class ExcelWriteRangeCommand : AExcelInstanceCommands { - [XmlAttribute] - [PropertyDescription("Please Enter the instance name")] - [InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] - [SampleUsage("**myInstance** or **excelInstance**")] - [Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_InstanceName { get; set; } + //[XmlAttribute] + //[PropertyDescription("Please Enter the instance name")] + //[InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] + //[SampleUsage("**myInstance** or **excelInstance**")] + //[Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //public string v_InstanceName { get; set; } + [XmlAttribute] [PropertyDescription("Please Enter the Datatable Variable Name to Set")] [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] [InputSpecification("Enter the text value that will be set.")] [SampleUsage("Hello World or {vText}")] [Remarks("")] + [PropertyParameterOrder(6000)] public string v_DataTableToSet { get; set; } + [XmlAttribute] [PropertyDescription("Please Enter the Cell Location to start from (ex. A1 or B2)")] [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] [InputSpecification("Enter the actual location of the cell.")] [SampleUsage("A1, B10, {vAddress}")] [Remarks("")] + [PropertyParameterOrder(6001)] public string v_ExcelCellAddress { get; set; } [XmlAttribute] @@ -51,7 +55,9 @@ public class ExcelWriteRangeCommand : ScriptCommand [InputSpecification("When selected, the column headers from the specified spreadsheet range are also written.")] [SampleUsage("Select from **Yes** or **No**")] [Remarks("")] + [PropertyParameterOrder(6002)] public string v_AddHeaders { get; set; } + public ExcelWriteRangeCommand() { //this.CommandName = "ExcelWriteRangeCommand"; @@ -59,17 +65,17 @@ public ExcelWriteRangeCommand() //this.CommandEnabled = true; //this.CustomRendering = true; - this.v_InstanceName = ""; + //this.v_InstanceName = ""; this.v_AddHeaders = "Yes"; } - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - (_, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //(_, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); + (_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); var dataSetVariable = LookupVariable(engine); - var targetAddress = v_ExcelCellAddress.ConvertToUserVariable(sender); + var targetAddress = v_ExcelCellAddress.ExpandValueOrUserVariable(engine); DataTable Dt = (DataTable)dataSetVariable.VariableValue; if (string.IsNullOrEmpty(targetAddress)) throw new ArgumentNullException("columnName"); @@ -144,7 +150,8 @@ private Script.ScriptVariable LookupVariable(Engine.AutomationEngineInstance sen return requiredVariable; } - public override List Render(frmCommandEditor editor) + + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -157,13 +164,14 @@ public override List Render(frmCommandEditor editor) RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_ExcelCellAddress", this, editor)); RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_AddHeaders", this, editor)); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; } return RenderedControls; } + public override string GetDisplayValue() { return base.GetDisplayValue() + " [Writing Cells starting from '" + v_ExcelCellAddress + "', Instance Name: '" + v_InstanceName + "']"; diff --git a/taskt/Core/Automation/Commands/Excel/ExcelWriteRowCommand.cs b/taskt/Core/Automation/Commands/Excel/ExcelWriteRowCommand.cs deleted file mode 100644 index 1762a7a00..000000000 --- a/taskt/Core/Automation/Commands/Excel/ExcelWriteRowCommand.cs +++ /dev/null @@ -1,147 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; -using System.Xml.Serialization; -using taskt.UI.CustomControls; -using taskt.UI.Forms; -using System.Data; -using System.Linq; -using System.Text.RegularExpressions; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("Excel Commands")] - [Attributes.ClassAttributes.SubGruop("Row")] - [Attributes.ClassAttributes.CommandSettings("Write Row")] - [Attributes.ClassAttributes.Description("This command writes a DataRow to an excel sheet starting from the given cell address.")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a value to a specific cell.")] - [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] - public class ExcelWriteRowCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Please Enter the instance name")] - [InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] - [SampleUsage("**myInstance** or **excelInstance**")] - [Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - public string v_InstanceName { get; set; } - [XmlAttribute] - [PropertyDescription("Please Enter the Row to Set")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter the text value that will be set (This could be a DataRow).")] - [SampleUsage("Hello,World or {vText}")] - [Remarks("")] - public string v_DataRowToSet { get; set; } - [XmlAttribute] - [PropertyDescription("Please Enter the Cell Location to start from (ex. A1 or B2)")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Enter the actual location of the cell.")] - [SampleUsage("A1, B10, {vAddress}")] - [Remarks("")] - public string v_ExcelCellAddress { get; set; } - - public ExcelWriteRowCommand() - { - //this.CommandName = "ExcelWriteRowCommand"; - //this.SelectionName = "Write Row"; - //this.CommandEnabled = true; - //this.CustomRendering = true; - - this.v_InstanceName = ""; - } - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - (var excelInstance, var excelSheet) = v_InstanceName.GetExcelInstanceAndWorksheet(engine); - - var dataRowVariable = LookupVariable(engine); - var variableList = engine.VariableList; - DataRow row; - - var targetAddress = v_ExcelCellAddress.ConvertToUserVariable(sender); - - //check in case of looping through datatable using BeginListLoopCommand - if (dataRowVariable.VariableValue is DataTable && engine.VariableList.Exists(x => x.VariableName == "Loop.CurrentIndex")) - { - var loopIndexVariable = engine.VariableList.Where(x => x.VariableName == "Loop.CurrentIndex").FirstOrDefault(); - int loopIndex = int.Parse(loopIndexVariable.VariableValue.ToString()); - row = ((DataTable)dataRowVariable.VariableValue).Rows[loopIndex - 1]; - } - - else row = (DataRow)dataRowVariable.VariableValue; - - - if (string.IsNullOrEmpty(targetAddress)) throw new ArgumentNullException("columnName"); - - var numberOfRow = Regex.Match(targetAddress, @"\d+").Value; - targetAddress = Regex.Replace(targetAddress, @"[\d-]", string.Empty); - targetAddress = targetAddress.ToUpperInvariant(); - - int sum = 0; - - for (int i = 0; i < targetAddress.Length; i++) - { - sum *= 26; - sum += (targetAddress[i] - 'A' + 1); - } - - - //Write row - string cellValue; - for (int j = 0; j < row.ItemArray.Length; j++) - { - if (row.ItemArray[j] == null) - cellValue = string.Empty; - - else - cellValue = row.ItemArray[j].ToString(); - - excelSheet.Cells[Int32.Parse(numberOfRow), j + sum] = cellValue; - } - } - - private Script.ScriptVariable LookupVariable(Engine.AutomationEngineInstance sendingInstance) - { - //search for the variable - var requiredVariable = sendingInstance.VariableList.Where(var => var.VariableName == v_DataRowToSet).FirstOrDefault(); - - //if variable was not found but it starts with variable naming pattern - if ((requiredVariable == null) && (v_DataRowToSet.StartsWith(sendingInstance.engineSettings.VariableStartMarker)) && (v_DataRowToSet.EndsWith(sendingInstance.engineSettings.VariableEndMarker))) - { - //reformat and attempt - var reformattedVariable = v_DataRowToSet.Replace(sendingInstance.engineSettings.VariableStartMarker, "").Replace(sendingInstance.engineSettings.VariableEndMarker, ""); - requiredVariable = sendingInstance.VariableList.Where(var => var.VariableName == reformattedVariable).FirstOrDefault(); - } - - return requiredVariable; - } - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - - //create standard group controls - var instanceCtrls = CommandControls.CreateDefaultDropdownGroupFor("v_InstanceName", this, editor); - CommandControls.AddInstanceNames((ComboBox)instanceCtrls.Where(t => (t.Name == "v_InstanceName")).FirstOrDefault(), editor, PropertyInstanceType.InstanceType.Excel); - RenderedControls.AddRange(instanceCtrls); - //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_DataRowToSet", this, editor)); - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_ExcelCellAddress", this, editor)); - - if (editor.creationMode == frmCommandEditor.CreationMode.Add) - { - this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; - } - - return RenderedControls; - } - public override string GetDisplayValue() - { - return base.GetDisplayValue() + " [Writing Cells starting from '" + v_ExcelCellAddress + "', Instance Name: '" + v_InstanceName + "']"; - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Excel/IExcelCellActionProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelCellActionProperties.cs new file mode 100644 index 000000000..ac10903fd --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelCellActionProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Excel **Single** cell action properties + /// + public interface IExcelCellActionProperties : IExcelCellProperties, IExcelCellValueTypeProperties + { + // only implememnts + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelCellProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelCellProperties.cs new file mode 100644 index 000000000..cf0311bc4 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelCellProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Excel **Single** Cell properties + /// + public interface IExcelCellProperties : ILExcelInstanceProperties + { + /// + /// cell location + /// + string v_CellLocation { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelCellValueTypeProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelCellValueTypeProperties.cs new file mode 100644 index 000000000..4b6e21a14 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelCellValueTypeProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for Cell value type properties + /// + public interface IExcelCellValueTypeProperties : ILExcelValueTypeProperties + { + // only implements + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelColumnRangeGetProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelColumnRangeGetProperties.cs new file mode 100644 index 000000000..675365981 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelColumnRangeGetProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// excel column range get properties + /// + public interface IExcelColumnRangeGetProperties : IExcelColumnRangeProperties, ILExcelRangeGetProperties + { + // only implements + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelColumnRangeProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelColumnRangeProperties.cs new file mode 100644 index 000000000..5b7a7e0ee --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelColumnRangeProperties.cs @@ -0,0 +1,23 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for Excel Column Range properties + /// + public interface IExcelColumnRangeProperties : IExcelRCRangeProperties + { + /// + /// column index + /// + string v_ColumnIndex { get; set; } + + /// + /// row index start + /// + string v_RowStart { get; set; } + + /// + /// row index end + /// + string v_RowEnd { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelColumnRangeSetProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelColumnRangeSetProperties.cs new file mode 100644 index 000000000..f0bf53a11 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelColumnRangeSetProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// excel column range set properties + /// + public interface IExcelColumnRangeSetProperties : IExcelColumnRangeProperties, ILExcelRangeSetProperties + { + // only implements + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelColumnRowRangeGetProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelColumnRowRangeGetProperties.cs new file mode 100644 index 000000000..3eb5dc3fb --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelColumnRowRangeGetProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for excel column-row range (2D-range) get properties + /// + public interface IExcelColumnRowRangeGetProperties : IExcelColumnRowRangeProperties, ILExcelRangeGetProperties + { + // only implements + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelColumnRowRangeProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelColumnRowRangeProperties.cs new file mode 100644 index 000000000..1d1e85a2a --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelColumnRowRangeProperties.cs @@ -0,0 +1,28 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for Excel Column-Row Range (2D-Range) Properties + /// + public interface IExcelColumnRowRangeProperties : ILExcelInstanceProperties, IExcelRCRangeProperties + { + /// + /// column start index + /// + string v_ColumnStart { get; set; } + + /// + /// column end index + /// + string v_ColumnEnd { get; set; } + + /// + /// row start index + /// + string v_RowStart { get; set; } + + /// + /// row end index + /// + string v_RowEnd { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelColumnRowRangeSetProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelColumnRowRangeSetProperties.cs new file mode 100644 index 000000000..7172514b6 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelColumnRowRangeSetProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for Excel column-row range (2D-Range) set properties + /// + public interface IExcelColumnRowRangeSetProperties : IExcelColumnRowRangeProperties, ILExcelRangeSetProperties + { + // only implements + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelColumnSpecifiedProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelColumnSpecifiedProperties.cs new file mode 100644 index 000000000..eab6208f4 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelColumnSpecifiedProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// column index/name specified properties + /// + public interface IExcelColumnSpecifiedProperties : IExcelRCRangeProperties + { + /// + /// column index or Name + /// + string v_ColumnIndex { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelRCLocationActionProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelRCLocationActionProperties.cs new file mode 100644 index 000000000..b2beda0ac --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelRCLocationActionProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// cell RC row/column action properties + /// + public interface IExcelRCLocationActionProperties : IExcelRCLocationProperties, IExcelRCValueTypeProperties + { + // only implements + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelRCLocationProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelRCLocationProperties.cs new file mode 100644 index 000000000..2e6a954cf --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelRCLocationProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// cell RC row, column properties + /// + public interface IExcelRCLocationProperties : ILExcelInstanceProperties + { + /// + /// cell row index + /// + string v_CellRow { get; set; } + + /// + /// cell column index + /// + string v_CellColumn { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelRCRangeProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelRCRangeProperties.cs new file mode 100644 index 000000000..5599bc473 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelRCRangeProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Range properties specified Row, Column + /// + public interface IExcelRCRangeProperties : ILExcelInstanceProperties, IExcelRCValueTypeProperties + { + /// + /// column type Name(Range) or Index + /// + string v_ColumnType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelRCValueTypeProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelRCValueTypeProperties.cs new file mode 100644 index 000000000..f61bb9c75 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelRCValueTypeProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for Excel RC Value Type properties + /// + public interface IExcelRCValueTypeProperties : ILExcelValueTypeProperties + { + // only implements + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelRowRangeGetProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelRowRangeGetProperties.cs new file mode 100644 index 000000000..39a01deb7 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelRowRangeGetProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// row Range Get commands properties + /// + public interface IExcelRowRangeGetProperties : IExcelRowRangeProperties, ILExcelRangeGetProperties + { + // only implements + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelRowRangeProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelRowRangeProperties.cs new file mode 100644 index 000000000..af5d9826c --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelRowRangeProperties.cs @@ -0,0 +1,23 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// row Range properties + /// + public interface IExcelRowRangeProperties : IExcelRCRangeProperties + { + /// + /// row index + /// + string v_RowIndex { get; set; } + + /// + /// column start + /// + string v_ColumnStart { get; set; } + + /// + /// column end + /// + string v_ColumnEnd { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelRowRangeSetProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelRowRangeSetProperties.cs new file mode 100644 index 000000000..e3ba5e4be --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelRowRangeSetProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for Excel Row Range Set properties + /// + public interface IExcelRowRangeSetProperties : IExcelRowRangeProperties, ILExcelRangeSetProperties + { + // only implements + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelWorksheetActionProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelWorksheetActionProperties.cs new file mode 100644 index 000000000..565989391 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelWorksheetActionProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + public interface IExcelWorksheetActionProperties : ILExcelInstanceProperties + { + /// + /// worksheet name for action + /// + string v_TargetSheetName { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelWorksheetCopyRenameProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelWorksheetCopyRenameProperties.cs new file mode 100644 index 000000000..1f3df3e19 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelWorksheetCopyRenameProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + public interface IExcelWorksheetCopyRenameProperties : IExcelWorksheetActionProperties + { + /// + /// new sheet name + /// + string v_NewSheetName { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/IExcelWorksheetProperties.cs b/taskt/Core/Automation/Commands/Excel/IExcelWorksheetProperties.cs new file mode 100644 index 000000000..5b5db4e76 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/IExcelWorksheetProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// excel worksheet properties + /// + public interface IExcelWorksheetProperties : ILExcelInstanceProperties + { + /// + /// excel worksheet name + /// + string v_SheetName { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/ILExcelInstanceProperties.cs b/taskt/Core/Automation/Commands/Excel/ILExcelInstanceProperties.cs new file mode 100644 index 000000000..7456a5bc9 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/ILExcelInstanceProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// excel instance properties + /// + public interface ILExcelInstanceProperties : ILExpandableProperties + { + /// + /// excel instance name + /// + string v_InstanceName { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/ILExcelRangeGetProperties.cs b/taskt/Core/Automation/Commands/Excel/ILExcelRangeGetProperties.cs new file mode 100644 index 000000000..88e1b0284 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/ILExcelRangeGetProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// excel Range get properties + /// + public interface ILExcelRangeGetProperties : ILExpandableProperties + { + /// + /// variable name to store result + /// + string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/ILExcelRangeSetProperties.cs b/taskt/Core/Automation/Commands/Excel/ILExcelRangeSetProperties.cs new file mode 100644 index 000000000..03f367ef6 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/ILExcelRangeSetProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// excel range Set properties + /// + public interface ILExcelRangeSetProperties : ILExpandableProperties + { + /// + /// behavior when specified Item(List/Dictionary/DataTable) items not enough + /// + string v_WhenItemNotEnough { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/ILExcelValueSetProperties.cs b/taskt/Core/Automation/Commands/Excel/ILExcelValueSetProperties.cs new file mode 100644 index 000000000..b4ba3a7af --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/ILExcelValueSetProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + public interface ILExcelValueSetProperties : ILExpandableProperties + { + /// + /// text to set + /// + string v_TextToSet { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Excel/ILExcelValueTypeProperties.cs b/taskt/Core/Automation/Commands/Excel/ILExcelValueTypeProperties.cs new file mode 100644 index 000000000..960a15463 --- /dev/null +++ b/taskt/Core/Automation/Commands/Excel/ILExcelValueTypeProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// excel value type properties + /// + public interface ILExcelValueTypeProperties : ILExpandableProperties + { + /// + /// value type + /// + string v_ValueType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/ExcelControls.cs b/taskt/Core/Automation/Commands/ExcelControls.cs index bbdd94989..0f0fa538d 100644 --- a/taskt/Core/Automation/Commands/ExcelControls.cs +++ b/taskt/Core/Automation/Commands/ExcelControls.cs @@ -1,7 +1,6 @@ -using System; -using System.Collections.Generic; -using Microsoft.Office.Interop.Excel; +using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; namespace taskt.Core.Automation.Commands { @@ -10,6 +9,50 @@ namespace taskt.Core.Automation.Commands /// internal static class ExcelControls { + #region const, field + /// + /// internal current worksheet keyword + /// + public const string INTERNAL_EXCEL_CURRENT_WORKSHEET_KEYWORD = "%kwd_excel_current_worksheet%"; + /// + /// internal next worksheet keyword + /// + public const string INTERNAL_EXCEL_NEXT_WORKSHEET_KEYWORD = "%kwd_excel_next_worksheet%"; + /// + /// internal previous worksheet keyword + /// + public const string INTERNAL_EXCEL_PREVIOUS_WORKSHEET_KEYWORD = "%kwd_excel_previous_worksheet%"; + /// + /// white color value + /// + public const long EXCEL_WHITE_COLOR = 16777215; + /// + /// black color valur + /// + public const long EXCEL_BLACK_COLOR= 0; + /// + /// default format (NumberFormat) + /// + public const string EXCEL_DEFAULT_FORMAT = "General"; + + /// + /// disallow contains worksheet charactors + /// + public static readonly List Disallow_Contains_Worksheet_Charactors = new List() + { + "/", "\\", "?", "*", + ":", "[", "]", + }; + /// + /// disallow starts/ends worksheet charactors + /// + public static readonly List Disallow_Starts_Ends_Worksheet_Charactors = new List() + { + "'", + }; + #endregion + + #region virtual property /// /// excel instance property /// @@ -25,22 +68,24 @@ internal static class ExcelControls [PropertyFirstValue("%kwd_default_excel_instance%")] [PropertyValidationRule("Instance", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Instance")] + [PropertyParameterOrder(5000)] public static string v_InputInstanceName { get; } /// - /// sheet name property + /// worksheet name property /// - [PropertyDescription("Sheet Name")] - [InputSpecification("Sheet Name", true)] - [PropertyDetailSampleUsage("**mySheet**", PropertyDetailSampleUsage.ValueType.Value, "Sheet Name")] - [PropertyDetailSampleUsage("**{{{vSheet}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Sheet Name")] - [PropertyDetailSampleUsage("**%kwd_current_worksheet%**", "Specify Current Sheet Name")] + [PropertyDescription("Worksheet Name")] + [InputSpecification("Worksheet Name", true)] + [PropertyDetailSampleUsage("**mySheet**", PropertyDetailSampleUsage.ValueType.Value, "Worksheet Name")] + [PropertyDetailSampleUsage("**{{{vSheet}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Worksheet Name")] + [PropertyDetailSampleUsage("**%kwd_excel_current_worksheet%**", "Specify Current Worksheet Name")] [Remarks("")] [PropertyTextBoxSetting(1, false)] [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("Sheet", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Sheet")] - [PropertyIntermediateConvert(nameof(ApplicationSettings.EngineSettings.convertToIntermediateExcelSheet), nameof(ApplicationSettings.EngineSettings.convertToRawExcelSheet))] + [PropertyAvailableSystemVariable(Engine.SystemVariables.LimitedSystemVariableNames.Excel_Worksheet)] + [PropertyParameterOrder(5000)] public static string v_SheetName { get; } /// @@ -56,6 +101,7 @@ internal static class ExcelControls [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("Cell Location", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Cell")] + [PropertyParameterOrder(5000)] public static string v_CellRangeLocation { get; } /// @@ -71,6 +117,7 @@ internal static class ExcelControls [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("Row", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] [PropertyDisplayText(true, "Row")] + [PropertyParameterOrder(5000)] public static string v_RowLocation { get; } /// @@ -86,6 +133,7 @@ internal static class ExcelControls [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("Column", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] [PropertyDisplayText(true, "Column")] + [PropertyParameterOrder(5000)] public static string v_ColumnLocation { get; } /// @@ -107,6 +155,7 @@ internal static class ExcelControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyIsOptional(true, "Cell")] [PropertyDisplayText(true, "Type")] + [PropertyParameterOrder(5000)] public static string v_ValueType { get; } /// @@ -125,6 +174,7 @@ internal static class ExcelControls [PropertyAddtionalParameterInfo("Formula", "Check the Cell has Formula or Not")] [PropertyAddtionalParameterInfo("Back Color", "Check the Cell Background Color is Not White")] [PropertyDisplayText(true, "Type")] + [PropertyParameterOrder(5000)] public static string v_CheckableValueType { get; } /// @@ -141,6 +191,7 @@ internal static class ExcelControls [PropertyUISelectionOption("RC")] [PropertySelectionValueSensitive(false)] [PropertyDisplayText(true, "Column Type")] + [PropertyParameterOrder(5000)] public static string v_ColumnType { get; } /// @@ -156,6 +207,7 @@ internal static class ExcelControls [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("Column", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.LessThanZero | PropertyValidationRule.ValidationRuleFlags.EqualsZero)] [PropertyDisplayText(true, "Column")] + [PropertyParameterOrder(5000)] public static string v_ColumnNameOrIndex { get; } /// @@ -171,6 +223,7 @@ internal static class ExcelControls [PropertyShowSampleUsageInDescription(true)] [PropertyIsOptional(true, "1")] [PropertyDisplayText(true, "Start Row")] + [PropertyParameterOrder(5000)] public static string v_RowStart { get; } /// @@ -186,6 +239,7 @@ internal static class ExcelControls [PropertyIsOptional(true, "Last Row")] [PropertyShowSampleUsageInDescription(true)] [PropertyDisplayText(true, "End Row")] + [PropertyParameterOrder(5000)] public static string v_RowEnd { get; } /// @@ -202,6 +256,7 @@ internal static class ExcelControls [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("Start Column", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.LessThanZero | PropertyValidationRule.ValidationRuleFlags.EqualsZero)] [PropertyDisplayText(true, "Start Column")] + [PropertyParameterOrder(5000)] public static string v_ColumnStart { get; } /// @@ -218,6 +273,7 @@ internal static class ExcelControls [PropertyTextBoxSetting(1, false)] [PropertyShowSampleUsageInDescription(true)] [PropertyDisplayText(true, "End Column")] + [PropertyParameterOrder(5000)] public static string v_ColumnEnd { get; } /// @@ -232,6 +288,7 @@ internal static class ExcelControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyUISelectionOption("Ignore")] [PropertyUISelectionOption("Error")] + [PropertyParameterOrder(5000)] public static string v_WhenItemNotEnough { get; } /// @@ -248,834 +305,941 @@ internal static class ExcelControls [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("File", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "File")] + [PropertyParameterOrder(5000)] public static string v_FilePath { get; } + /// + /// value to set + /// + [PropertyDescription("Value to Set")] + [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + [InputSpecification("Value to Set", true)] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage("**Hello**", PropertyDetailSampleUsage.ValueType.Value, "Value to Set")] + [PropertyDetailSampleUsage("**{{{vText}}}**", PropertyDetailSampleUsage.ValueType.VariableName, "Value to Set")] + [Remarks("")] + [PropertyTextBoxSetting(1, true)] + [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(5000)] + public static string v_ValueToSet { get; } + #endregion - #region instance, worksheet methods - public static Application GetExcelInstance(this string instanceName, Automation.Engine.AutomationEngineInstance engine) - { - string ins = instanceName.ConvertToUserVariable(engine); - var instanceObject = engine.GetAppInstance(ins); - if (instanceObject is Application) - { - return (Application)instanceObject; - } - else - { - throw new Exception("Instance '" + instanceName + "' is not Excel Instance"); - } - } - - public static (Application instance, Worksheet sheet) GetExcelInstanceAndWorksheet(this string instanceName, Automation.Engine.AutomationEngineInstance engine) - { - var instanceObject = instanceName.GetExcelInstance(engine); - return (instanceObject, GetCurrentWorksheet(instanceObject)); - } + #region keyword convert method - public static (Application instance, Worksheet sheet) GetExcelInstanceAndWorksheet(this (string instanceName, string sheetName) info, Automation.Engine.AutomationEngineInstance engine, bool returnNullIfSheetDoesNotExists = false) + /// + /// Replace Internal Keywords to SystemVariable Names + /// + /// + /// + /// + public static string ReplaceKeywordsToSystemVariable(string txt, Engine.AutomationEngineInstance engine) { - var instanceObject = info.instanceName.GetExcelInstance(engine); - var sheet = info.sheetName.GetExcelWorksheet(engine, instanceObject, returnNullIfSheetDoesNotExists); - return (instanceObject, sheet); + return txt.Replace(INTERNAL_EXCEL_CURRENT_WORKSHEET_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Excel_CurrentWorkSheet.VariableName, engine)) + .Replace(INTERNAL_EXCEL_NEXT_WORKSHEET_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Excel_NextWorkSheet.VariableName, engine)) + .Replace(INTERNAL_EXCEL_PREVIOUS_WORKSHEET_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Excel_PreviousWorkSheet.VariableName, engine)); } - public static Worksheet GetExcelWorksheet(this string sheetVariable, Automation.Engine.AutomationEngineInstance engine, Application excelInstance, bool returnNullIfSheetDoesNotExists = false) + /// + /// Replace Internal Keywords to SystemVariable Names + /// + /// + /// + /// + public static string ReplaceKeywordsToSystemVariable(string txt, ApplicationSettings settings) { - var sheet = sheetVariable.ConvertToUserVariable(engine); - if (sheet == engine.engineSettings.CurrentWorksheetKeyword) - { - try - { - //return (Worksheet)excelInstance.ActiveSheet; - return GetCurrentWorksheet(excelInstance); - } - catch - { - if (returnNullIfSheetDoesNotExists) - { - return null; - } - else - { - throw new Exception("No Worksheet exists."); - } - } - } - else if (sheet == engine.engineSettings.NextWorksheetKeyword) - { - try - { - return GetNextWorksheet(excelInstance); - } - catch - { - if (returnNullIfSheetDoesNotExists) - { - return null; - } - else - { - throw new Exception("Next Worksheet not found."); - } - } - } - else if (sheet == engine.engineSettings.PreviousWorksheetKeyword) - { - try - { - return GetPreviousWorksheet(excelInstance); - } - catch - { - if (returnNullIfSheetDoesNotExists) - { - return null; - } - else - { - throw new Exception("Previous Worksheet not found."); - } - } - } - else - { - try - { - return (Worksheet)excelInstance.Worksheets[sheet]; - } - catch - { - if (returnNullIfSheetDoesNotExists) - { - return null; - } - else - { - throw new Exception("Worksheet " + sheet + " does not exists."); - } - } - } + return txt.Replace(INTERNAL_EXCEL_CURRENT_WORKSHEET_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Excel_CurrentWorkSheet.VariableName, settings)) + .Replace(INTERNAL_EXCEL_NEXT_WORKSHEET_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Excel_NextWorkSheet.VariableName, settings)) + .Replace(INTERNAL_EXCEL_PREVIOUS_WORKSHEET_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Excel_PreviousWorkSheet.VariableName, settings)); } - private static Worksheet GetCurrentWorksheet(Application excelInstance) - { - if (excelInstance.Sheets.Count == 0) - { - return null; - } - else - { - return excelInstance.ActiveSheet; - } - } + #endregion - private static Worksheet GetNextWorksheet(Application excelInstance, Worksheet mySheet = null) - { - Worksheet currentSheet; - if (mySheet == null) - { - try - { - //currentSheet = (Worksheet)excelInstance.ActiveSheet; - currentSheet = GetCurrentWorksheet(excelInstance); - } - catch - { - return null; - } - } - else - { - currentSheet = mySheet; - } - - int idx = 1; - foreach (Worksheet sht in excelInstance.Worksheets) - { - if (sht.Name == currentSheet.Name) - { - break; - } - idx++; - } - if (idx < excelInstance.Worksheets.Count) - { - return (Worksheet)excelInstance.Worksheets[idx + 1]; - } - else - { - return null; - } - } - private static Worksheet GetPreviousWorksheet(Application excelInstance, Worksheet mySheet = null) - { - Worksheet currentSheet; - if (mySheet == null) - { - try - { - //currentSheet = (Worksheet)excelInstance.ActiveSheet; - currentSheet = GetCurrentWorksheet(excelInstance); - } - catch - { - return null; - } - } - else - { - currentSheet = mySheet; - } - - int idx = 1; - foreach (Worksheet sht in excelInstance.Worksheets) - { - if (sht.Name == currentSheet.Name) - { - break; - } - idx++; - } - if (idx > 1) - { - return (Worksheet)excelInstance.Worksheets[idx - 1]; - } - else - { - return null; - } - } + #region instance, worksheet methods + ///// + ///// expand value or UserVariable as Excel Instance + ///// + ///// + ///// + ///// + ///// value is not Excel Instance + //public static Application ExpandValueOrUserVariableAsExcelInstance(this string instanceName, Automation.Engine.AutomationEngineInstance engine) + //{ + // string ins = instanceName.ExpandValueOrUserVariable(engine); + // var instanceObject = engine.GetAppInstance(ins); + // if (instanceObject is Application app) + // { + // return app; + // } + // else + // { + // throw new Exception("Instance '" + instanceName + "' is not Excel Instance"); + // } + //} + + ///// + ///// expancd value or UserVariable as Excel instance and worksheet + ///// + ///// + ///// + ///// + ///// value is not Excel Instance + //public static (Application instance, Worksheet sheet) ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(this string instanceName, Automation.Engine.AutomationEngineInstance engine) + //{ + // var instanceObject = instanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + // return (instanceObject, GetCurrentWorksheet(instanceObject)); + //} + + ///// + ///// expand value or UserVariable as Excel instance and worksheet + ///// + ///// + ///// + ///// + ///// + //public static (Application instance, Worksheet sheet) ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(this string instanceName, string sheetName, Automation.Engine.AutomationEngineInstance engine, bool returnNullIfSheetDoesNotExists = false) + //{ + // var instanceObject = instanceName.ExpandValueOrUserVariableAsExcelInstance(engine); + // var sheet = sheetName.ExpandValueOrUserVariableAsExcelWorksheet(engine, instanceObject, returnNullIfSheetDoesNotExists); + // return (instanceObject, sheet); + //} + + ///// + ///// expand value or user variable as Excel Worksheet + ///// + ///// + ///// + ///// + ///// + ///// + ///// worksheet does not exists + //public static Worksheet ExpandValueOrUserVariableAsExcelWorksheet(this string sheetVariable, Automation.Engine.AutomationEngineInstance engine, Application excelInstance, bool returnNullIfSheetDoesNotExists = false) + //{ + // var sheet = sheetVariable.ExpandValueOrUserVariable(engine); + // if (sheet == engine.engineSettings.CurrentWorksheetKeyword) + // { + // try + // { + // //return (Worksheet)excelInstance.ActiveSheet; + // return GetCurrentWorksheet(excelInstance); + // } + // catch + // { + // if (returnNullIfSheetDoesNotExists) + // { + // return null; + // } + // else + // { + // throw new Exception("No Worksheet exists."); + // } + // } + // } + // else if (sheet == engine.engineSettings.NextWorksheetKeyword) + // { + // try + // { + // return GetNextWorksheet(excelInstance); + // } + // catch + // { + // if (returnNullIfSheetDoesNotExists) + // { + // return null; + // } + // else + // { + // throw new Exception("Next Worksheet not found."); + // } + // } + // } + // else if (sheet == engine.engineSettings.PreviousWorksheetKeyword) + // { + // try + // { + // return GetPreviousWorksheet(excelInstance); + // } + // catch + // { + // if (returnNullIfSheetDoesNotExists) + // { + // return null; + // } + // else + // { + // throw new Exception("Previous Worksheet not found."); + // } + // } + // } + // else + // { + // try + // { + // return (Worksheet)excelInstance.Worksheets[sheet]; + // } + // catch + // { + // if (returnNullIfSheetDoesNotExists) + // { + // return null; + // } + // else + // { + // throw new Exception("Worksheet " + sheet + " does not exists."); + // } + // } + // } + //} + + ///// + ///// get current worksheet + ///// + ///// + ///// + //private static Worksheet GetCurrentWorksheet(Application excelInstance) + //{ + // if (excelInstance.Sheets.Count == 0) + // { + // return null; + // } + // else + // { + // return excelInstance.ActiveSheet; + // } + //} + + ///// + ///// get next worksheet + ///// + ///// + ///// + ///// + //private static Worksheet GetNextWorksheet(Application excelInstance, Worksheet mySheet = null) + //{ + // Worksheet currentSheet; + // if (mySheet == null) + // { + // try + // { + // //currentSheet = (Worksheet)excelInstance.ActiveSheet; + // currentSheet = GetCurrentWorksheet(excelInstance); + // } + // catch + // { + // return null; + // } + // } + // else + // { + // currentSheet = mySheet; + // } + + // int idx = 1; + // foreach (Worksheet sht in excelInstance.Worksheets) + // { + // if (sht.Name == currentSheet.Name) + // { + // break; + // } + // idx++; + // } + // if (idx < excelInstance.Worksheets.Count) + // { + // return (Worksheet)excelInstance.Worksheets[idx + 1]; + // } + // else + // { + // return null; + // } + //} + + ///// + ///// get previous worksheet + ///// + ///// + ///// + ///// + //private static Worksheet GetPreviousWorksheet(Application excelInstance, Worksheet mySheet = null) + //{ + // Worksheet currentSheet; + // if (mySheet == null) + // { + // try + // { + // //currentSheet = (Worksheet)excelInstance.ActiveSheet; + // currentSheet = GetCurrentWorksheet(excelInstance); + // } + // catch + // { + // return null; + // } + // } + // else + // { + // currentSheet = mySheet; + // } + + // int idx = 1; + // foreach (Worksheet sht in excelInstance.Worksheets) + // { + // if (sht.Name == currentSheet.Name) + // { + // break; + // } + // idx++; + // } + // if (idx > 1) + // { + // return (Worksheet)excelInstance.Worksheets[idx - 1]; + // } + // else + // { + // return null; + // } + //} #endregion #region Func methods - public static Func CheckCellValueFunctionFromRange(string valueType) - { - Func func = null; - switch (valueType) - { - case "cell": - func = (rg) => { return !String.IsNullOrEmpty((string)rg.Text); }; - break; - - case "formula": - func = (rg) => { return ((string)rg.Formula).StartsWith("="); }; - break; - - case "back color": - func = (rg) => { return ((long)rg.Interior.Color) != 16777215; }; - break; - } - return func; - } - - public static Func GetCellValueFunctionFromRange(string valueType) - { - Func getFunc = null; - switch (valueType) - { - case "cell": - getFunc = (rg) => - { - return (string)rg.Text; - }; - break; - case "formula": - getFunc = (rg) => - { - return (string)rg.Formula; - }; - break; - case "format": - getFunc = (rg) => - { - return (string)rg.NumberFormatLocal; - }; - break; - case "fore color": - getFunc = (rg) => - { - return ((long)rg.Font.Color).ToString(); - }; - break; - case "back color": - getFunc = (rg) => - { - return ((long)rg.Interior.Color).ToString(); - }; - break; - } - return getFunc; - } - - public static Func GetCellValueFunction(string valueType) - { - Func getFunc = null; - switch (valueType) - { - case "cell": - getFunc = (sheet, column, row) => - { - return (string)((Range)sheet.Cells[row, column]).Text; - }; - break; - case "formula": - getFunc = (sheet, column, row) => - { - return (string)((Range)sheet.Cells[row, column]).Formula; - }; - break; - case "format": - getFunc = (sheet, column, row) => - { - return (string)((Range)sheet.Cells[row, column]).NumberFormatLocal; - }; - break; - case "fore color": - getFunc = (sheet, column, row) => - { - return ((long)((Range)sheet.Cells[row, column]).Font.Color).ToString(); - }; - break; - case "back color": - getFunc = (sheet, column, row) => - { - return ((long)((Range)sheet.Cells[row, column]).Interior.Color).ToString(); - }; - break; - } - return getFunc; - } - - public static Action SetCellValueFunctionFromRange(string valueType) - { - Action setFunc = null; - - Func longConvert = (str) => - { - if (long.TryParse(str, out long v)) - { - return v; - } - else - { - throw new Exception("Value '" + str + "' is not color."); - } - }; - - switch (valueType) - { - case "cell": - setFunc = (value, sheet, rg) => - { - rg.Value = value; - }; - break; - case "formula": - setFunc = (value, sheet, rg) => - { - rg.Formula = value; - }; - break; - case "format": - setFunc = (value, sheet, rg) => - { - rg.NumberFormatLocal = value; - }; - break; - case "fore color": - setFunc = (value, sheet, rg) => - { - rg.Font.Color = longConvert(value); - }; - break; - case "back color": - setFunc = (value, sheet, rg) => - { - rg.Interior.Color = longConvert(value); - }; - break; - } - - return setFunc; - } - public static Action SetCellValueFunction(string valueType) - { - Action setFunc = null; - switch (valueType) - { - case "cell": - setFunc = (value, sheet, column, row) => - { - ((Range)sheet.Cells[row, column]).Value = value; - }; - break; - case "formula": - setFunc = (value, sheet, column, row) => - { - ((Range)sheet.Cells[row, column]).Formula = value; - }; - break; - case "format": - setFunc = (value, sheet, column, row) => - { - ((Range)sheet.Cells[row, column]).NumberFormatLocal = value; - }; - break; - case "fore color": - setFunc = (value, sheet, column, row) => - { - ((Range)sheet.Cells[row, column]).Font.Color = long.Parse(value); - }; - break; - case "back color": - setFunc = (value, sheet, column, row) => - { - ((Range)sheet.Cells[row, column]).Interior.Color = long.Parse(value); - }; - break; - } - - return setFunc; - } + ///// + ///// get CheckCellValueFunction + ///// + ///// + ///// + ///// + ///// + //public static Func CheckCellValueFunctionFromRange(string parameterName, ScriptCommand command, Engine.AutomationEngineInstance engine) + //{ + // var valueType = command.ExpandValueOrUserVariableAsSelectionItem(parameterName, engine); + // Func func = null; + // switch (valueType) + // { + // case "cell": + // func = (rg) => { return !String.IsNullOrEmpty((string)rg.Text); }; + // break; + + // case "formula": + // func = (rg) => { return ((string)rg.Formula).StartsWith("="); }; + // break; + + // case "back color": + // func = (rg) => { return ((long)rg.Interior.Color) != 16777215; }; + // break; + // } + // return func; + //} + + //public static Func GetCellValueFunctionFromRange(string valueType) + //{ + // Func getFunc = null; + // switch (valueType) + // { + // case "cell": + // getFunc = (rg) => + // { + // return (string)rg.Text; + // }; + // break; + // case "formula": + // getFunc = (rg) => + // { + // return (string)rg.Formula; + // }; + // break; + // case "format": + // getFunc = (rg) => + // { + // return (string)rg.NumberFormatLocal; + // }; + // break; + // case "fore color": + // getFunc = (rg) => + // { + // return ((long)rg.Font.Color).ToString(); + // }; + // break; + // case "back color": + // getFunc = (rg) => + // { + // return ((long)rg.Interior.Color).ToString(); + // }; + // break; + // } + // return getFunc; + //} + + //public static Func GetCellValueFunction(string valueType) + //{ + // Func getFunc = null; + // switch (valueType) + // { + // case "cell": + // getFunc = (sheet, column, row) => + // { + // return (string)((Range)sheet.Cells[row, column]).Text; + // }; + // break; + // case "formula": + // getFunc = (sheet, column, row) => + // { + // return (string)((Range)sheet.Cells[row, column]).Formula; + // }; + // break; + // case "format": + // getFunc = (sheet, column, row) => + // { + // return (string)((Range)sheet.Cells[row, column]).NumberFormatLocal; + // }; + // break; + // case "fore color": + // getFunc = (sheet, column, row) => + // { + // return ((long)((Range)sheet.Cells[row, column]).Font.Color).ToString(); + // }; + // break; + // case "back color": + // getFunc = (sheet, column, row) => + // { + // return ((long)((Range)sheet.Cells[row, column]).Interior.Color).ToString(); + // }; + // break; + // } + // return getFunc; + //} + + //public static Action SetCellValueFunctionFromRange(string valueType) + //{ + // Action setFunc = null; + + // Func longConvert = (str) => + // { + // if (long.TryParse(str, out long v)) + // { + // return v; + // } + // else + // { + // throw new Exception("Value '" + str + "' is not color."); + // } + // }; + + // switch (valueType) + // { + // case "cell": + // setFunc = (value, sheet, rg) => + // { + // rg.Value = value; + // }; + // break; + // case "formula": + // setFunc = (value, sheet, rg) => + // { + // rg.Formula = value; + // }; + // break; + // case "format": + // setFunc = (value, sheet, rg) => + // { + // rg.NumberFormatLocal = value; + // }; + // break; + // case "fore color": + // setFunc = (value, sheet, rg) => + // { + // rg.Font.Color = longConvert(value); + // }; + // break; + // case "back color": + // setFunc = (value, sheet, rg) => + // { + // rg.Interior.Color = longConvert(value); + // }; + // break; + // } + + // return setFunc; + //} + + //public static Action SetCellValueFunction(string valueType) + //{ + // Action setFunc = null; + // switch (valueType) + // { + // case "cell": + // setFunc = (value, sheet, column, row) => + // { + // ((Range)sheet.Cells[row, column]).Value = value; + // }; + // break; + // case "formula": + // setFunc = (value, sheet, column, row) => + // { + // ((Range)sheet.Cells[row, column]).Formula = value; + // }; + // break; + // case "format": + // setFunc = (value, sheet, column, row) => + // { + // ((Range)sheet.Cells[row, column]).NumberFormatLocal = value; + // }; + // break; + // case "fore color": + // setFunc = (value, sheet, column, row) => + // { + // ((Range)sheet.Cells[row, column]).Font.Color = long.Parse(value); + // }; + // break; + // case "back color": + // setFunc = (value, sheet, column, row) => + // { + // ((Range)sheet.Cells[row, column]).Interior.Color = long.Parse(value); + // }; + // break; + // } + + // return setFunc; + //} #endregion - public static int GetColumnIndex(Worksheet sheet, string columnName) - { - if (CheckCorrectColumnName(columnName, sheet)) - { - return ((Range)sheet.Columns[columnName]).Column; - } - else - { - throw new Exception("Strange Column Name '" + columnName + "'"); - } - } - - public static string GetColumnName(Worksheet sheet, int columnIndex) - { - if (columnIndex < 1) - { - return ""; - } - else - { - return ((Range)sheet.Cells[1, columnIndex]).Address.Split('$')[1]; - } - } - - public static string GetAddress(Worksheet sheet, int row, int column) - { - if (CheckCorrectRC(row, column, sheet)) - { - return ((Range)sheet.Cells[row, column]).Address.Replace("$", ""); - } - else - { - throw new Exception("Strange Excel Location. Row: " + row + ", Column: " + column); - } - } - - public static int GetLastRowIndex(Worksheet sheet, string column, int startRow, string targetType) - { - return GetLastRowIndex(sheet, GetColumnIndex(sheet, column), startRow, targetType); - } - - public static int GetLastRowIndex(Worksheet sheet, int column, int startRow, string targetType) - { - int lastRow = startRow; - switch (targetType.ToLower()) - { - case "formula": - while ((string)(((Range)sheet.Cells[lastRow, column]).Formula) != "") - { - lastRow++; - } - break; - - default: - while((string)(((Range)sheet.Cells[lastRow, column]).Text) != "") - { - lastRow++; - } - break; - } - return --lastRow; - } - - public static int GetLastColumnIndex(Worksheet sheet, int row, string startColum, string targetType) - { - return GetLastColumnIndex(sheet, row, GetColumnIndex(sheet, startColum), targetType); - } - - public static int GetLastColumnIndex(Worksheet sheet, int row, int startColum, string targetType) - { - int lastColumn = startColum; - switch (targetType.ToLower()) - { - case "formula": - while ((string)(((Range)sheet.Cells[row, lastColumn]).Formula) != "") - { - lastColumn++; - } - break; - - default: - while ((string)(((Range)sheet.Cells[row, lastColumn]).Text) != "") - { - lastColumn++; - } - break; - } - return --lastColumn; - } - - public static (int columnIndex, int rowStartIndex, int rowEndIndex, string valueType) GetRangeIndeiesColumnDirection(string columnValueName, string columnTypeName, string rowStartName, string rowEndName, string valueTypeName, Automation.Engine.AutomationEngineInstance engine, Worksheet excelSheet, ScriptCommand command, object targetObject = null) - { - string columnType = command.GetUISelectionValue(columnTypeName, "Column Type", engine); - - int columnIndex = 0; - switch (columnType) - { - case "range": - string col = command.ConvertToUserVariable(columnValueName, "Column", engine); - columnIndex = GetColumnIndex(excelSheet, col); - break; - case "rc": - columnIndex = command.ConvertToUserVariableAsInteger(columnValueName, "Column", engine); - break; - } - - string valueType = command.GetUISelectionValue(valueTypeName, "Value Type", engine); - - int rowStartIndex = command.ConvertToUserVariableAsInteger(rowStartName, "Start Row", engine); - string rowEndValue = command.GetRawPropertyString(rowEndName, "End Row"); - int rowEndIndex; - if (String.IsNullOrEmpty(rowEndValue)) - { - if (targetObject == null) - { - rowEndIndex = GetLastRowIndex(excelSheet, columnIndex, rowStartIndex, valueType); - } - else - { - int size; - if (targetObject is List) - { - size = ((List)targetObject).Count; - } - else if (targetObject is Dictionary) - { - size = ((Dictionary)targetObject).Count; - } - else if (targetObject is System.Data.DataTable) - { - size = ((System.Data.DataTable)targetObject).Rows.Count; - } - else if (targetObject is int) - { - size = (int)targetObject; - } - else - { - throw new Exception("target object is strange data."); - } - rowEndIndex = rowStartIndex + size - 1; - } - } - else - { - rowEndIndex = rowEndValue.ConvertToUserVariableAsInteger("End Row", engine); - } - - if (rowStartIndex > rowEndIndex) - { - int t = rowStartIndex; - rowStartIndex = rowEndIndex; - rowEndIndex = t; - } - - CheckCorrectRCRange(rowStartIndex, columnIndex, rowEndIndex, columnIndex, excelSheet); - - return (columnIndex, rowStartIndex, rowEndIndex, valueType); - } - - public static (int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) GetRangeIndeiesRowDirection(string rowValueName, string columnTypeName, string columnStartName, string columnEndName, string valueTypeName, Automation.Engine.AutomationEngineInstance engine, Worksheet excelSheet, ScriptCommand command, object targetObject = null) - { - int rowIndex = command.ConvertToUserVariableAsInteger(rowValueName, "Row Index", engine); - - string valueType = command.GetUISelectionValue(valueTypeName, "Value Type", engine); - - int columnStartIndex = 0; - int columnEndIndex = 0; - - string columnStartValue = command.GetRawPropertyString(columnStartName, "Start Column"); - string columnEndValue = command.GetRawPropertyString(columnEndName, "End Column"); - - Func getLastRowFromObject = () => - { - int size; - if (targetObject is List) - { - size = ((List)targetObject).Count; - } - else if (targetObject is Dictionary) - { - size = ((Dictionary)targetObject).Count; - } - else if (targetObject is System.Data.DataTable) - { - size = ((System.Data.DataTable)targetObject).Columns.Count; - } - else if (targetObject is int) - { - size = (int)targetObject; - } - else - { - throw new Exception("target object is strange data."); - } - return columnStartIndex + size - 1; - }; - - string columnType = command.GetUISelectionValue(columnTypeName, "Column Type", engine); - switch (columnType) - { - case "range": - if (String.IsNullOrEmpty(columnStartValue)) - { - columnStartValue = "A"; - } - columnStartIndex = ExcelControls.GetColumnIndex(excelSheet, columnStartValue.ConvertToUserVariable(engine)); - - - if (String.IsNullOrEmpty(columnEndValue)) - { - if (targetObject == null) - { - columnEndIndex = ExcelControls.GetLastColumnIndex(excelSheet, rowIndex, columnStartIndex, valueType); - } - else - { - columnEndIndex = getLastRowFromObject(); - } - } - else - { - columnEndIndex = ExcelControls.GetColumnIndex(excelSheet, columnEndValue.ConvertToUserVariable(engine)); - - } - break; - - case "rc": - if (String.IsNullOrEmpty(columnStartValue)) - { - columnStartValue = "1"; - } - columnStartIndex = columnStartValue.ConvertToUserVariableAsInteger("Start Column", engine); - - if (String.IsNullOrEmpty(columnEndValue)) - { - if (targetObject == null) - { - columnEndIndex = ExcelControls.GetLastColumnIndex(excelSheet, rowIndex, columnStartIndex, valueType); - } - else - { - columnEndIndex = getLastRowFromObject(); - } - } - else - { - columnEndIndex = columnEndValue.ConvertToUserVariableAsInteger("Column End", engine); - } - - break; - } - - if (columnStartIndex > columnEndIndex) - { - int t = columnStartIndex; - columnStartIndex = columnEndIndex; - columnEndIndex = t; - } - - CheckCorrectRCRange(rowIndex, columnStartIndex, rowIndex, columnEndIndex, excelSheet); - - return (rowIndex, columnStartIndex, columnEndIndex, valueType); - } + #region cell-range methods + + //public static int GetColumnIndex(Worksheet sheet, string columnName) + //{ + // if (CheckCorrectColumnName(columnName, sheet)) + // { + // return ((Range)sheet.Columns[columnName]).Column; + // } + // else + // { + // throw new Exception("Strange Column Name '" + columnName + "'"); + // } + //} + + //public static string GetColumnName(Worksheet sheet, int columnIndex) + //{ + // if (columnIndex < 1) + // { + // return ""; + // } + // else + // { + // return ((Range)sheet.Cells[1, columnIndex]).Address.Split('$')[1]; + // } + //} + + //public static string GetAddress(Worksheet sheet, int row, int column) + //{ + // if (CheckCorrectRC(row, column, sheet)) + // { + // return ((Range)sheet.Cells[row, column]).Address.Replace("$", ""); + // } + // else + // { + // throw new Exception("Strange Excel Location. Row: " + row + ", Column: " + column); + // } + //} + + //public static int GetLastRowIndex(Worksheet sheet, string column, int startRow, string targetType) + //{ + // return GetLastRowIndex(sheet, GetColumnIndex(sheet, column), startRow, targetType); + //} + + //public static int GetLastRowIndex(Worksheet sheet, int column, int startRow, string targetType) + //{ + // int lastRow = startRow; + // switch (targetType.ToLower()) + // { + // case "formula": + // while ((string)(((Range)sheet.Cells[lastRow, column]).Formula) != "") + // { + // lastRow++; + // } + // break; + + // default: + // while((string)(((Range)sheet.Cells[lastRow, column]).Text) != "") + // { + // lastRow++; + // } + // break; + // } + // return --lastRow; + //} + + //public static int GetLastColumnIndex(Worksheet sheet, int row, string startColum, string targetType) + //{ + // return GetLastColumnIndex(sheet, row, GetColumnIndex(sheet, startColum), targetType); + //} + + //public static int GetLastColumnIndex(Worksheet sheet, int row, int startColum, string targetType) + //{ + // int lastColumn = startColum; + // switch (targetType.ToLower()) + // { + // case "formula": + // while ((string)(((Range)sheet.Cells[row, lastColumn]).Formula) != "") + // { + // lastColumn++; + // } + // break; + + // default: + // while ((string)(((Range)sheet.Cells[row, lastColumn]).Text) != "") + // { + // lastColumn++; + // } + // break; + // } + // return --lastColumn; + //} + + //public static (int columnIndex, int rowStartIndex, int rowEndIndex, string valueType) GetRangeIndeiesColumnDirection(string columnValueName, string columnTypeName, string rowStartName, string rowEndName, string valueTypeName, Automation.Engine.AutomationEngineInstance engine, Worksheet excelSheet, ScriptCommand command, object targetObject = null) + //{ + // string columnType = command.ExpandValueOrUserVariableAsSelectionItem(columnTypeName, "Column Type", engine); + + // int columnIndex = 0; + // switch (columnType) + // { + // case "range": + // string col = command.ExpandValueOrUserVariable(columnValueName, "Column", engine); + // columnIndex = GetColumnIndex(excelSheet, col); + // break; + // case "rc": + // columnIndex = command.ExpandValueOrUserVariableAsInteger(columnValueName, "Column", engine); + // break; + // } + + // string valueType = command.ExpandValueOrUserVariableAsSelectionItem(valueTypeName, "Value Type", engine); + + // int rowStartIndex = command.ExpandValueOrUserVariableAsInteger(rowStartName, "Start Row", engine); + // string rowEndValue = command.GetRawPropertyValueAsString(rowEndName, "End Row"); + // int rowEndIndex; + // if (String.IsNullOrEmpty(rowEndValue)) + // { + // if (targetObject == null) + // { + // rowEndIndex = GetLastRowIndex(excelSheet, columnIndex, rowStartIndex, valueType); + // } + // else + // { + // int size; + // if (targetObject is List) + // { + // size = ((List)targetObject).Count; + // } + // else if (targetObject is Dictionary) + // { + // size = ((Dictionary)targetObject).Count; + // } + // else if (targetObject is System.Data.DataTable) + // { + // size = ((System.Data.DataTable)targetObject).Rows.Count; + // } + // else if (targetObject is int) + // { + // size = (int)targetObject; + // } + // else + // { + // throw new Exception("target object is strange data."); + // } + // rowEndIndex = rowStartIndex + size - 1; + // } + // } + // else + // { + // rowEndIndex = rowEndValue.ExpandValueOrUserVariableAsInteger("End Row", engine); + // } + + // if (rowStartIndex > rowEndIndex) + // { + // int t = rowStartIndex; + // rowStartIndex = rowEndIndex; + // rowEndIndex = t; + // } + + // CheckCorrectRCRange(rowStartIndex, columnIndex, rowEndIndex, columnIndex, excelSheet); + + // return (columnIndex, rowStartIndex, rowEndIndex, valueType); + //} + + //public static (int rowIndex, int columnStartIndex, int columnEndIndex, string valueType) GetRangeIndeiesRowDirection(string rowValueName, string columnTypeName, string columnStartName, string columnEndName, string valueTypeName, Automation.Engine.AutomationEngineInstance engine, Worksheet excelSheet, ScriptCommand command, object targetObject = null) + //{ + // int rowIndex = command.ExpandValueOrUserVariableAsInteger(rowValueName, "Row Index", engine); + + // string valueType = command.ExpandValueOrUserVariableAsSelectionItem(valueTypeName, "Value Type", engine); + + // int columnStartIndex = 0; + // int columnEndIndex = 0; + + // string columnStartValue = command.GetRawPropertyValueAsString(columnStartName, "Start Column"); + // string columnEndValue = command.GetRawPropertyValueAsString(columnEndName, "End Column"); + + // Func getLastRowFromObject = () => + // { + // int size; + // if (targetObject is List) + // { + // size = ((List)targetObject).Count; + // } + // else if (targetObject is Dictionary) + // { + // size = ((Dictionary)targetObject).Count; + // } + // else if (targetObject is System.Data.DataTable) + // { + // size = ((System.Data.DataTable)targetObject).Columns.Count; + // } + // else if (targetObject is int) + // { + // size = (int)targetObject; + // } + // else + // { + // throw new Exception("target object is strange data."); + // } + // return columnStartIndex + size - 1; + // }; + + // string columnType = command.ExpandValueOrUserVariableAsSelectionItem(columnTypeName, "Column Type", engine); + // switch (columnType) + // { + // case "range": + // if (String.IsNullOrEmpty(columnStartValue)) + // { + // columnStartValue = "A"; + // } + // columnStartIndex = ExcelControls.GetColumnIndex(excelSheet, columnStartValue.ExpandValueOrUserVariable(engine)); + + + // if (String.IsNullOrEmpty(columnEndValue)) + // { + // if (targetObject == null) + // { + // columnEndIndex = ExcelControls.GetLastColumnIndex(excelSheet, rowIndex, columnStartIndex, valueType); + // } + // else + // { + // columnEndIndex = getLastRowFromObject(); + // } + // } + // else + // { + // columnEndIndex = ExcelControls.GetColumnIndex(excelSheet, columnEndValue.ExpandValueOrUserVariable(engine)); + + // } + // break; + + // case "rc": + // if (String.IsNullOrEmpty(columnStartValue)) + // { + // columnStartValue = "1"; + // } + // columnStartIndex = columnStartValue.ExpandValueOrUserVariableAsInteger("Start Column", engine); + + // if (String.IsNullOrEmpty(columnEndValue)) + // { + // if (targetObject == null) + // { + // columnEndIndex = ExcelControls.GetLastColumnIndex(excelSheet, rowIndex, columnStartIndex, valueType); + // } + // else + // { + // columnEndIndex = getLastRowFromObject(); + // } + // } + // else + // { + // columnEndIndex = columnEndValue.ExpandValueOrUserVariableAsInteger("Column End", engine); + // } + + // break; + // } + + // if (columnStartIndex > columnEndIndex) + // { + // int t = columnStartIndex; + // columnStartIndex = columnEndIndex; + // columnEndIndex = t; + // } + + // CheckCorrectRCRange(rowIndex, columnStartIndex, rowIndex, columnEndIndex, excelSheet); + + // return (rowIndex, columnStartIndex, columnEndIndex, valueType); + //} + #endregion #region convert methods - public static string GetoExcelRangeLocation(this string value, Automation.Engine.AutomationEngineInstance engine, Application excelInstance) - { - var location = value.ConvertToUserVariable(engine); - if (CheckCorrectRange(location, excelInstance)) - { - return location; - } - else - { - throw new Exception("Location '" + value + "' is not Range. Value: '" + location + "'."); - } - } - - public static (int row, int column) GetExcelRCLocation(this ScriptCommand command, string rowPropertyName, string columnPropertyName, Automation.Engine.AutomationEngineInstance engine, Application excelInstance) - { - int row = command.ConvertToUserVariableAsInteger(rowPropertyName, "Row", engine); - int column = command.ConvertToUserVariableAsInteger(columnPropertyName, "Column", engine); - if (CheckCorrectRC(row, column, excelInstance)) - { - return (row, column); - } - else - { - throw new Exception("Invalid Location. Row: " + row + ", Column: " + column); - } - } - - public static Range GetExcelRange(this string location, Automation.Engine.AutomationEngineInstance engine, Application excelInstance, Worksheet excelSheet, ScriptCommand command) - { - string pos = location.GetoExcelRangeLocation(engine, excelInstance); - return excelSheet.Range[pos]; - } - - public static Range GetExcelRange(this ScriptCommand command, string rowPropertyName, string columnPropertyName, Automation.Engine.AutomationEngineInstance engine, Application excelInstance, Worksheet excelSheet) - { - var rc = command.GetExcelRCLocation(rowPropertyName, columnPropertyName, engine, excelInstance); - return excelSheet.Cells[rc.row, rc.column]; - } + //public static string GetoExcelRangeLocation(this string value, Automation.Engine.AutomationEngineInstance engine, Application excelInstance) + //{ + // var location = value.ExpandValueOrUserVariable(engine); + // if (CheckCorrectRange(location, excelInstance)) + // { + // return location; + // } + // else + // { + // throw new Exception("Location '" + value + "' is not Range. Value: '" + location + "'."); + // } + //} + + //public static (int row, int column) GetExcelRCLocation(this ScriptCommand command, string rowPropertyName, string columnPropertyName, Automation.Engine.AutomationEngineInstance engine, Application excelInstance) + //{ + // int row = command.ExpandValueOrUserVariableAsInteger(rowPropertyName, "Row", engine); + // int column = command.ExpandValueOrUserVariableAsInteger(columnPropertyName, "Column", engine); + // if (CheckCorrectRC(row, column, excelInstance)) + // { + // return (row, column); + // } + // else + // { + // throw new Exception("Invalid Location. Row: " + row + ", Column: " + column); + // } + //} + + //public static Range GetExcelRange(this string location, Automation.Engine.AutomationEngineInstance engine, Application excelInstance, Worksheet excelSheet, ScriptCommand command) + //{ + // string pos = location.GetoExcelRangeLocation(engine, excelInstance); + // return excelSheet.Range[pos]; + //} + + //public static Range GetExcelRange(this ScriptCommand command, string rowPropertyName, string columnPropertyName, Automation.Engine.AutomationEngineInstance engine, Application excelInstance, Worksheet excelSheet) + //{ + // var rc = command.GetExcelRCLocation(rowPropertyName, columnPropertyName, engine, excelInstance); + // return excelSheet.Cells[rc.row, rc.column]; + //} #endregion #region check methods - public static bool CheckCorrectColumnName(string columnName, Worksheet excelSheet) - { - return CheckCorrectRange(columnName + "1", excelSheet); - } - - public static bool CheckCorrectColumnIndex(int columnIndex, Worksheet excelSheet) - { - return CheckCorrectRC(1, columnIndex, excelSheet); - } - - public static bool CheckCorrectRange(string range, Worksheet excelSheet) - { - try - { - var rg = excelSheet.Range[range]; - return true; - } - catch - { - return false; - } - } - - public static bool CheckCorrectRC(int row, int column, Worksheet excelSheet) - { - try - { - var rc = excelSheet.Cells[row, column]; - return true; - } - catch - { - return false; - } - } - - public static bool CheckCorrectColumnName(string columnName, Application excelInstance) - { - return CheckCorrectRange(columnName + "1", excelInstance); - } - - public static bool CheckCorrectRowIndex(int rowIndex, Application excelInstance) - { - return CheckCorrectRC(rowIndex, 1, excelInstance); - } - - public static bool CheckCorrectColumnIndex(int columnIndex, Application excelInstance) - { - return CheckCorrectRC(1, columnIndex, excelInstance); - } - - public static bool CheckCorrectRange(this string range, Application excelInstance) - { - try - { - var rg = excelInstance.Range[range]; - return true; - } - catch - { - return false; - } - } - - public static bool CheckCorrectRC(int row, int column, Application excelInstance) - { - try - { - var rc = excelInstance.Cells[row, column]; - return true; - } - catch - { - return false; - } - } - - public static bool CheckCorrectRCRange(int startRow, int startColumn, int endRow, int endColumn, Application excelInstance, bool throwExceptionWhenInvalidRange = true) - { - if (!CheckCorrectRC(startRow, startColumn, excelInstance)) - { - if (throwExceptionWhenInvalidRange) - { - throw new Exception("Invalid Start Location. Row: " + startRow + ", Column: " + startColumn); - } - else - { - return false; - } - } - if (!CheckCorrectRC(endRow, endColumn, excelInstance)) - { - if (throwExceptionWhenInvalidRange) - { - throw new Exception("Invalid End Location. Row: " + endRow + ", Column: " + endColumn); - } - else - { - return false; - } - } - return true; - } - public static bool CheckCorrectRCRange(int startRow, int startColumn, int endRow, int endColumn, Worksheet excelSheet, bool throwExceptionWhenInvalidRange = true) - { - if (!CheckCorrectRC(startRow, startColumn, excelSheet)) - { - if (throwExceptionWhenInvalidRange) - { - throw new Exception("Invalid Start Location. Row: " + startRow + ", Column: " + startColumn); - } - else - { - return false; - } - } - if (!CheckCorrectRC(endRow, endColumn, excelSheet)) - { - if (throwExceptionWhenInvalidRange) - { - throw new Exception("Invalid End Location. Row: " + endRow + ", Column: " + endColumn); - } - else - { - return false; - } - } - return true; - } + //public static bool CheckCorrectColumnName(string columnName, Worksheet excelSheet) + //{ + // return CheckCorrectRange(columnName + "1", excelSheet); + //} + + //public static bool CheckCorrectColumnIndex(int columnIndex, Worksheet excelSheet) + //{ + // return CheckCorrectRC(1, columnIndex, excelSheet); + //} + + //public static bool CheckCorrectRange(string range, Worksheet excelSheet) + //{ + // try + // { + // var rg = excelSheet.Range[range]; + // return true; + // } + // catch + // { + // return false; + // } + //} + + //public static bool CheckCorrectRC(int row, int column, Worksheet excelSheet) + //{ + // try + // { + // var rc = excelSheet.Cells[row, column]; + // return true; + // } + // catch + // { + // return false; + // } + //} + + //public static bool CheckCorrectColumnName(string columnName, Application excelInstance) + //{ + // return CheckCorrectRange(columnName + "1", excelInstance); + //} + + //public static bool CheckCorrectRowIndex(int rowIndex, Application excelInstance) + //{ + // return CheckCorrectRC(rowIndex, 1, excelInstance); + //} + + //public static bool CheckCorrectColumnIndex(int columnIndex, Application excelInstance) + //{ + // return CheckCorrectRC(1, columnIndex, excelInstance); + //} + + //public static bool CheckCorrectRange(this string range, Application excelInstance) + //{ + // try + // { + // var rg = excelInstance.Range[range]; + // return true; + // } + // catch + // { + // return false; + // } + //} + + //public static bool CheckCorrectRC(int row, int column, Application excelInstance) + //{ + // try + // { + // var rc = excelInstance.Cells[row, column]; + // return true; + // } + // catch + // { + // return false; + // } + //} + + //public static bool CheckCorrectRCRange(int startRow, int startColumn, int endRow, int endColumn, Application excelInstance, bool throwExceptionWhenInvalidRange = true) + //{ + // if (!CheckCorrectRC(startRow, startColumn, excelInstance)) + // { + // if (throwExceptionWhenInvalidRange) + // { + // throw new Exception("Invalid Start Location. Row: " + startRow + ", Column: " + startColumn); + // } + // else + // { + // return false; + // } + // } + // if (!CheckCorrectRC(endRow, endColumn, excelInstance)) + // { + // if (throwExceptionWhenInvalidRange) + // { + // throw new Exception("Invalid End Location. Row: " + endRow + ", Column: " + endColumn); + // } + // else + // { + // return false; + // } + // } + // return true; + //} + + //public static bool CheckCorrectRCRange(int startRow, int startColumn, int endRow, int endColumn, Worksheet excelSheet, bool throwExceptionWhenInvalidRange = true) + //{ + // if (!CheckCorrectRC(startRow, startColumn, excelSheet)) + // { + // if (throwExceptionWhenInvalidRange) + // { + // throw new Exception("Invalid Start Location. Row: " + startRow + ", Column: " + startColumn); + // } + // else + // { + // return false; + // } + // } + // if (!CheckCorrectRC(endRow, endColumn, excelSheet)) + // { + // if (throwExceptionWhenInvalidRange) + // { + // throw new Exception("Invalid End Location. Row: " + endRow + ", Column: " + endColumn); + // } + // else + // { + // return false; + // } + // } + // return true; + //} #endregion } } diff --git a/taskt/Core/Automation/Commands/File/CheckFileExistsCommand.cs b/taskt/Core/Automation/Commands/File/CheckFileExistsCommand.cs index 2bd354f4d..42760e501 100644 --- a/taskt/Core/Automation/Commands/File/CheckFileExistsCommand.cs +++ b/taskt/Core/Automation/Commands/File/CheckFileExistsCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("File Operation Commands")] + [Attributes.ClassAttributes.Group("File Operation")] [Attributes.ClassAttributes.CommandSettings("Check File Exists")] [Attributes.ClassAttributes.Description("This command returns a existence of file paths from a specified location")] [Attributes.ClassAttributes.UsesDescription("Use this command to return a existence of file paths from a specific location.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CheckFileExistsCommand : ScriptCommand + public sealed class CheckFileExistsCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -42,10 +43,8 @@ public CheckFileExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //try //{ // FilePathControls.WaitForFile(this, nameof(v_TargetFileName), nameof(v_WaitTime), engine); diff --git a/taskt/Core/Automation/Commands/File/CopyFileCommand.cs b/taskt/Core/Automation/Commands/File/CopyFileCommand.cs index 04a5cde8b..f3871471e 100644 --- a/taskt/Core/Automation/Commands/File/CopyFileCommand.cs +++ b/taskt/Core/Automation/Commands/File/CopyFileCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("File Operation Commands")] + [Attributes.ClassAttributes.Group("File Operation")] [Attributes.ClassAttributes.CommandSettings("Copy File")] [Attributes.ClassAttributes.Description("This command copies a file to a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to copy a file to a new destination.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CopyFileCommand : ScriptCommand + public sealed class CopyFileCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -62,10 +63,8 @@ public CopyFileCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //var sourceFile = FilePathControls.WaitForFile(this, nameof(v_SourceFilePath), nameof(v_WaitTime), engine); //var destinationFolder = v_DestinationDirectory.ConvertToUserVariableAsFolderPath(engine); @@ -101,11 +100,11 @@ public override void RunCommand(object sender) FilePathControls.FileAction(this, engine, new Action(path => { - var destinationFolder = v_DestinationDirectory.ConvertToUserVariableAsFolderPath(engine); + var destinationFolder = v_DestinationDirectory.ExpandValueOrUserVariableAsFolderPath(engine); if (!Directory.Exists(destinationFolder)) { - if (this.GetYesNoSelectionValue(nameof(v_CreateDirectory), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_CreateDirectory), engine)) { Directory.CreateDirectory(destinationFolder); } @@ -124,7 +123,7 @@ public override void RunCommand(object sender) // todo: check folder is same //delete if it already exists per user - if (this.GetYesNoSelectionValue(nameof(v_DeleteExisting), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_DeleteExisting), engine)) { File.Delete(destinationPath); } diff --git a/taskt/Core/Automation/Commands/File/DeleteFileCommand.cs b/taskt/Core/Automation/Commands/File/DeleteFileCommand.cs index 678c14580..2b292b76c 100644 --- a/taskt/Core/Automation/Commands/File/DeleteFileCommand.cs +++ b/taskt/Core/Automation/Commands/File/DeleteFileCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("File Operation Commands")] + [Attributes.ClassAttributes.Group("File Operation")] [Attributes.ClassAttributes.CommandSettings("Delete File")] [Attributes.ClassAttributes.Description("This command deletes a file from a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to detete a file from a specific location.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class DeleteFileCommand : ScriptCommand + public sealed class DeleteFileCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -24,7 +25,7 @@ public class DeleteFileCommand : ScriptCommand public string v_WhenFileDoesNotExists { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("File Move to the Recycle Bin")] [PropertyIsOptional(true, "No")] public string v_MoveToRecycleBin { get; set; } @@ -45,10 +46,8 @@ public DeleteFileCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //try //{ // var targetFile = FilePathControls.WaitForFile(this, nameof(v_SourceFilePath), nameof(v_WaitTime), engine); @@ -73,7 +72,7 @@ public override void RunCommand(object sender) FilePathControls.FileAction(this, engine, new Action(path => { - if (this.GetYesNoSelectionValue(nameof(v_MoveToRecycleBin), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_MoveToRecycleBin), engine)) { Shell32.MoveToRecycleBin(path); } @@ -84,7 +83,7 @@ public override void RunCommand(object sender) }), new Action(ex => { - if (this.GetUISelectionValue(nameof(v_WhenFileDoesNotExists), engine) == "error") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenFileDoesNotExists), engine) == "error") { throw new Exception("File does Not Exists. File Path: '" + v_SourceFilePath + "'"); } diff --git a/taskt/Core/Automation/Commands/File/ExtractZipFileCommand.cs b/taskt/Core/Automation/Commands/File/ExtractZipFileCommand.cs index c384cbd96..d2a2b60bc 100644 --- a/taskt/Core/Automation/Commands/File/ExtractZipFileCommand.cs +++ b/taskt/Core/Automation/Commands/File/ExtractZipFileCommand.cs @@ -10,14 +10,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("File Operation Commands")] + [Attributes.ClassAttributes.Group("File Operation")] [Attributes.ClassAttributes.CommandSettings("Extract Zip File")] [Attributes.ClassAttributes.Description("This command extracts files from a compressed file")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExtractZipFileCommand : ScriptCommand + public sealed class ExtractZipFileCommand : ScriptCommand, ICanHandleList { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -40,7 +41,7 @@ public class ExtractZipFileCommand : ScriptCommand [XmlAttribute] //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Create Folder When Destination Does not Exist")] //[PropertyUISelectionOption("Yes")] //[PropertyUISelectionOption("No")] @@ -78,12 +79,10 @@ public ExtractZipFileCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //get absolute variable path or URL to source file - var vSourceFile = this.ConvertToUserVariableAsFilePath(nameof(v_FilePathOrigin), engine); + var vSourceFile = this.ExpandValueOrUserVariableAsFilePath(nameof(v_FilePathOrigin), engine); //track local file location string vLocalSourceFile = vSourceFile; @@ -94,7 +93,8 @@ public override void RunCommand(object sender) if (FilePathControls.IsURL(vSourceFile)) { //create temp directory - var tempDir = Folders.GetFolder(Folders.FolderType.TempFolder); + //var tempDir = Folders.GetFolder(Folders.FolderType.TempFolder); + var tempDir = Folders.GetTempFolderPath(); var tempFile = Path.Combine(tempDir, $"{ Guid.NewGuid()}." + vFileType); //check if directory does not exist then create directory @@ -121,7 +121,7 @@ public override void RunCommand(object sender) //get file path to destination files //var vExtractionFolder = v_PathDestination.ConvertToUserVariable(engine); - var vExtractionFolder = v_PathDestination.ConvertToUserVariableAsFolderPath(engine); + var vExtractionFolder = v_PathDestination.ExpandValueOrUserVariableAsFolderPath(engine); // If the directory doesn't exist, create it. if (!Directory.Exists(vExtractionFolder)) @@ -132,7 +132,7 @@ public override void RunCommand(object sender) //{ // Directory.CreateDirectory(vExtractionFolder); //} - if (this.GetYesNoSelectionValue(nameof(v_CreateDirectory), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_CreateDirectory), engine)) { Directory.CreateDirectory(vExtractionFolder); } @@ -148,7 +148,7 @@ public override void RunCommand(object sender) IReader reader; //get optional password - var vPassword = v_Password.ConvertToUserVariable(engine); + var vPassword = v_Password.ExpandValueOrUserVariable(engine); //check if password is needed if (string.IsNullOrEmpty(vPassword)) @@ -175,7 +175,8 @@ public override void RunCommand(object sender) if (!string.IsNullOrEmpty(v_applyToVariableName)) { - fileList.StoreInUserVariable(engine, v_applyToVariableName); + //fileList.StoreInUserVariable(engine, v_applyToVariableName); + this.StoreListInUserVariable(fileList, nameof(v_applyToVariableName), engine); } } catch (Exception ex) diff --git a/taskt/Core/Automation/Commands/File/ExtractionFilePathCommand.cs b/taskt/Core/Automation/Commands/File/ExtractionFilePathCommand.cs index d2617a923..a1ed09a0f 100644 --- a/taskt/Core/Automation/Commands/File/ExtractionFilePathCommand.cs +++ b/taskt/Core/Automation/Commands/File/ExtractionFilePathCommand.cs @@ -8,14 +8,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("File Operation Commands")] + [Attributes.ClassAttributes.Group("File Operation")] [Attributes.ClassAttributes.CommandSettings("Extraction File Path")] [Attributes.ClassAttributes.Description("This command allows you to extract from file path.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to extract from file path.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExtractionFilePathCommand : ScriptCommand + public sealed class ExtractionFilePathCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -47,12 +48,10 @@ public ExtractionFilePathCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var filePath = this.ConvertToUserVariableAsFilePath(nameof(v_SourceFilePath), engine); - string format = v_Format.ConvertToUserVariable(engine); + var filePath = this.ExpandValueOrUserVariableAsFilePath(nameof(v_SourceFilePath), engine); + string format = v_Format.ExpandValueOrUserVariable(engine); string result = FilePathControls.FormatFileFolderPath(filePath, format); result.StoreInUserVariable(engine, v_Result); @@ -61,7 +60,7 @@ public override void RunCommand(object sender) private void lnkFormatChecker_Click(object sender, EventArgs e) { ComboBox cmb = (ComboBox)((CommandItemControl)sender).Tag; - UI.Forms.Supplement_Forms.frmFormatChecker.ShowFormatCheckerFormLinkClicked(cmb, "File Folder"); + UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmFormatChecker.ShowFormatCheckerFormLinkClicked(cmb, "File Folder"); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/File/GetFileInfoCommand.cs b/taskt/Core/Automation/Commands/File/GetFileInfoCommand.cs index f56d0f6a7..2fc0f4260 100644 --- a/taskt/Core/Automation/Commands/File/GetFileInfoCommand.cs +++ b/taskt/Core/Automation/Commands/File/GetFileInfoCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("File Operation Commands")] + [Attributes.ClassAttributes.Group("File Operation")] [Attributes.ClassAttributes.CommandSettings("Get File Info")] [Attributes.ClassAttributes.Description("This command returns a list of file paths from a specified location")] [Attributes.ClassAttributes.UsesDescription("Use this command to return a list of file paths from a specific location.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetFileInfoCommand : ScriptCommand + public sealed class GetFileInfoCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -54,10 +55,8 @@ public GetFileInfoCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //var targetFile = FilePathControls.WaitForFile(this, nameof(v_TargetFileName), nameof(v_WaitTime), engine); //var fileInfo = new System.IO.FileInfo(targetFile); @@ -94,7 +93,7 @@ public override void RunCommand(object sender) { var fileInfo = new System.IO.FileInfo(path); - var infoType = this.GetUISelectionValue(nameof(v_InfoType), engine); + var infoType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_InfoType), engine); string ret = ""; switch (infoType) { diff --git a/taskt/Core/Automation/Commands/File/GetFilesCommand.cs b/taskt/Core/Automation/Commands/File/GetFilesCommand.cs index cf571ae03..1c6d7900b 100644 --- a/taskt/Core/Automation/Commands/File/GetFilesCommand.cs +++ b/taskt/Core/Automation/Commands/File/GetFilesCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("File Operation Commands")] + [Attributes.ClassAttributes.Group("File Operation")] [Attributes.ClassAttributes.CommandSettings("Get Files")] [Attributes.ClassAttributes.Description("This command returns a list of file paths from a specified location")] [Attributes.ClassAttributes.UsesDescription("Use this command to return a list of file paths from a specific location.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetFilesCommand : ScriptCommand + public sealed class GetFilesCommand : ScriptCommand, ICanHandleList { [XmlAttribute] //[PropertyDescription("Path to the Source Folder")] @@ -80,24 +81,22 @@ public GetFilesCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //apply variable logic var sourceFolder = FolderPathControls.WaitForFolder(this, nameof(v_SourceFolderPath), nameof(v_WaitForFolder), engine); - var searchFile = v_SearchFileName.ConvertToUserVariableAsFileName(engine); + var searchFile = v_SearchFileName.ExpandValueOrUserVariableAsFileName(engine); - var ext = v_SearchExtension.ConvertToUserVariable(engine).ToLower(); + var ext = v_SearchExtension.ExpandValueOrUserVariable(engine).ToLower(); // get all files List filesList; filesList = System.IO.Directory.GetFiles(sourceFolder).ToList(); - if (!String.IsNullOrEmpty(searchFile)) + if (!string.IsNullOrEmpty(searchFile)) { - var searchMethod = this.GetUISelectionValue(nameof(v_SearchMethod), engine); + var searchMethod = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_SearchMethod), engine); switch (searchMethod) { case "contains": @@ -115,13 +114,14 @@ public override void RunCommand(object sender) } } - if (!String.IsNullOrEmpty(ext)) + if (!string.IsNullOrEmpty(ext)) { ext = "." + ext; filesList = filesList.Where(t => System.IO.Path.GetExtension(t).ToLower() == ext).ToList(); } - filesList.StoreInUserVariable(engine, v_UserVariableName); + //filesList.StoreInUserVariable(engine, v_UserVariableName); + this.StoreListInUserVariable(filesList, nameof(v_UserVariableName), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/File/MoveFileCommand.cs b/taskt/Core/Automation/Commands/File/MoveFileCommand.cs index 4111f479a..c8d6108d3 100644 --- a/taskt/Core/Automation/Commands/File/MoveFileCommand.cs +++ b/taskt/Core/Automation/Commands/File/MoveFileCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("File Operation Commands")] + [Attributes.ClassAttributes.Group("File Operation")] [Attributes.ClassAttributes.CommandSettings("Move File")] [Attributes.ClassAttributes.Description("This command moves a file to a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to move a file to a new destination.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] // TODO: change to file action command - public class MoveFileCommand : ScriptCommand + public sealed class MoveFileCommand : ScriptCommand { //[XmlAttribute] //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -77,10 +78,8 @@ public MoveFileCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - // var sourceFile = FilePathControls.WaitForFile(this, nameof(v_SourceFilePath), nameof(v_WaitTime), engine); // var destinationFolder = v_DestinationDirectory.ConvertToUserVariableAsFolderPath(engine); @@ -128,11 +127,11 @@ public override void RunCommand(object sender) FilePathControls.FileAction(this, engine, new Action(path => { - var destinationFolder = v_DestinationDirectory.ConvertToUserVariableAsFolderPath(engine); + var destinationFolder = v_DestinationDirectory.ExpandValueOrUserVariableAsFolderPath(engine); if (!Directory.Exists(destinationFolder)) { - if (this.GetYesNoSelectionValue(nameof(v_CreateDirectory), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_CreateDirectory), engine)) { Directory.CreateDirectory(destinationFolder); } @@ -151,7 +150,7 @@ public override void RunCommand(object sender) // todo: check folder is same //delete if it already exists per user - if (this.GetYesNoSelectionValue(nameof(v_DeleteExisting), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_DeleteExisting), engine)) { File.Delete(destinationPath); } diff --git a/taskt/Core/Automation/Commands/File/RenameFileCommand.cs b/taskt/Core/Automation/Commands/File/RenameFileCommand.cs index 1bcf27cb1..b651ef39c 100644 --- a/taskt/Core/Automation/Commands/File/RenameFileCommand.cs +++ b/taskt/Core/Automation/Commands/File/RenameFileCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("File Operation Commands")] + [Attributes.ClassAttributes.Group("File Operation")] [Attributes.ClassAttributes.CommandSettings("Rename File")] [Attributes.ClassAttributes.Description("This command renames a file at a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to rename an existing file.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RenameFileCommand : ScriptCommand + public sealed class RenameFileCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -92,10 +93,8 @@ public RenameFileCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - ////apply variable logic //var sourceFile = FilePathControls.WaitForFile(this, nameof(v_SourceFilePath), nameof(v_WaitTime), engine); @@ -128,15 +127,15 @@ public override void RunCommand(object sender) new Action(sourceFile => { var currentFileName = Path.GetFileName(sourceFile); - var newFileName = v_NewName.ConvertToUserVariableAsFileName(engine); + var newFileName = v_NewName.ExpandValueOrUserVariableAsFileName(engine); - var newExtension = v_NewExtention.ConvertToUserVariable(engine); + var newExtension = v_NewExtention.ExpandValueOrUserVariable(engine); if (!newExtension.StartsWith(".")) { newExtension = "." + newExtension; } - var newFileOption = this.GetUISelectionValue(nameof(v_ExtentionOption), engine); + var newFileOption = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ExtentionOption), engine); switch (newFileOption) { case "auto": @@ -169,7 +168,7 @@ public override void RunCommand(object sender) //create destination var destinationPath = Path.Combine(sourceFileInfo.DirectoryName, newFileName); - var whenSame = this.GetUISelectionValue(nameof(v_IfFileNameSame), engine); + var whenSame = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfFileNameSame), engine); if (currentFileName == newFileName) { switch (whenSame) diff --git a/taskt/Core/Automation/Commands/File/WaitForFileToExistCommand.cs b/taskt/Core/Automation/Commands/File/WaitForFileToExistCommand.cs index baf799f86..6e92135da 100644 --- a/taskt/Core/Automation/Commands/File/WaitForFileToExistCommand.cs +++ b/taskt/Core/Automation/Commands/File/WaitForFileToExistCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("File Operation Commands")] + [Attributes.ClassAttributes.Group("File Operation")] [Attributes.ClassAttributes.CommandSettings("Wait For File To Exists")] [Attributes.ClassAttributes.Description("This command waits for a file to exist at a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to wait for a file to exist before proceeding.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WaitForFileToExistCommand : ScriptCommand + public sealed class WaitForFileToExistCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -37,10 +38,8 @@ public WaitForFileToExistCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - ////convert items to variables //var fileName = v_FileName.ConvertToUserVariable(sender); diff --git a/taskt/Core/Automation/Commands/FilePathControls.cs b/taskt/Core/Automation/Commands/FilePathControls.cs index dd7ee09dc..a2ad5a71b 100644 --- a/taskt/Core/Automation/Commands/FilePathControls.cs +++ b/taskt/Core/Automation/Commands/FilePathControls.cs @@ -27,6 +27,7 @@ internal static class FilePathControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("File Path", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "File")] + [PropertyParameterOrder(5000)] public static string v_FilePath { get; } /// @@ -42,6 +43,7 @@ internal static class FilePathControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("File Path", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "File")] + [PropertyParameterOrder(5000)] public static string v_NoSample_FilePath { get; } /// @@ -58,6 +60,7 @@ internal static class FilePathControls [PropertyIsOptional(true, "Error")] [PropertyDisplayText(false, "")] [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] + [PropertyParameterOrder(5000)] public static string v_WhenFileDoesNotExists { get; } /// @@ -74,6 +77,7 @@ internal static class FilePathControls [PropertyIsOptional(true, "10")] [PropertyFirstValue("10")] [PropertyDisplayText(true, "Wait", "s")] + [PropertyParameterOrder(5000)] public static string v_WaitTime { get; } /// @@ -91,6 +95,7 @@ internal static class FilePathControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("File Path Result", PropertyValidationRule.ValidationRuleFlags.None)] [PropertyDisplayText(false, "")] + [PropertyParameterOrder(5000)] public static string v_FilePathResult { get; } #endregion @@ -189,26 +194,26 @@ private static (string beforeCounter, string counterVariable, string afterCounte } /// - /// convert to FilePath support FileCounter + /// expand value or user variable as FilePath support FileCounter /// /// /// /// /// /// - private static string ConvertToUserVariableAsFilePath_SupportFileCounter(string parameterValue, PropertyFilePathSetting setting, Engine.AutomationEngineInstance engine) + private static string ExpandValueOrUserVariableAsFilePath_SupportFileCounter(string parameterValue, PropertyFilePathSetting setting, Engine.AutomationEngineInstance engine) { // check contains FileCounter if (!ContainsFileCounter(parameterValue, engine)) { // don't contains FileCounter - return ConvertToUserVariableAsFilePath_NoSupportFileCounter(parameterValue, setting, engine); + return ExpandValueOrUserVariableAsFilePath_NoSupportFileCounter(parameterValue, setting, engine); } (var beforeVariable, var wrappedCounterVariableName, var afterVariable) = ParseFileCounter(parameterValue, engine); - beforeVariable = beforeVariable.ConvertToUserVariable(engine); - afterVariable = afterVariable.ConvertToUserVariable(engine); + beforeVariable = beforeVariable.ExpandValueOrUserVariable(engine); + afterVariable = afterVariable.ExpandValueOrUserVariable(engine); var counterVariableName = VariableNameControls.GetVariableName(wrappedCounterVariableName, engine); // URL Check @@ -295,16 +300,16 @@ private static string ConvertToUserVariableAsFilePath_SupportFileCounter(string } /// - /// convert to FilePath not support FileCounter + /// expand value or User variable as FilePath not support FileCounter /// /// /// /// /// /// - private static string ConvertToUserVariableAsFilePath_NoSupportFileCounter(string parameterValue, PropertyFilePathSetting setting, Engine.AutomationEngineInstance engine) + private static string ExpandValueOrUserVariableAsFilePath_NoSupportFileCounter(string parameterValue, PropertyFilePathSetting setting, Engine.AutomationEngineInstance engine) { - var path = parameterValue.ConvertToUserVariable(engine); + var path = parameterValue.ExpandValueOrUserVariable(engine); if (IsURL(path)) { @@ -374,23 +379,23 @@ private static string ConvertToUserVariableAsFilePath_NoSupportFileCounter(strin } /// - /// convert to FilePath. this method use the specified PropertyFilePathSetting + /// expand value or user variable as FilePath. this method use the specified PropertyFilePathSetting /// /// /// /// /// - public static string ConvertToUserVariableAsFilePath(this string parameterValue, PropertyFilePathSetting setting, Engine.AutomationEngineInstance engine) + public static string ExpandValueOrUserVariableAsFilePath(this string parameterValue, PropertyFilePathSetting setting, Engine.AutomationEngineInstance engine) { string p; if ((setting.supportFileCounter != PropertyFilePathSetting.FileCounterBehavior.NoSupport) && (setting.supportExtension != PropertyFilePathSetting.ExtensionBehavior.RequiredExtensionAndExists)) { - p = ConvertToUserVariableAsFilePath_SupportFileCounter(parameterValue, setting, engine); + p = ExpandValueOrUserVariableAsFilePath_SupportFileCounter(parameterValue, setting, engine); } else { - p = ConvertToUserVariableAsFilePath_NoSupportFileCounter(parameterValue, setting, engine); + p = ExpandValueOrUserVariableAsFilePath_NoSupportFileCounter(parameterValue, setting, engine); } var invs = Path.GetInvalidPathChars(); @@ -405,13 +410,13 @@ public static string ConvertToUserVariableAsFilePath(this string parameterValue, } /// - /// convert to FilePath. this method use PropertyFilePathSetting + /// expand value or user variable to FilePath. this method use PropertyFilePathSetting /// /// /// /// /// - public static string ConvertToUserVariableAsFilePath(this ScriptCommand command, string parameterName, Engine.AutomationEngineInstance engine) + public static string ExpandValueOrUserVariableAsFilePath(this ScriptCommand command, string parameterName, Engine.AutomationEngineInstance engine) { var prop = command.GetProperty(parameterName); var vProp = prop.GetVirtualProperty(); @@ -419,19 +424,19 @@ public static string ConvertToUserVariableAsFilePath(this ScriptCommand command, var pathSetting = PropertyControls.GetCustomAttributeWithVirtual(prop, vProp) ?? new PropertyFilePathSetting(); - return ConvertToUserVariableAsFilePath(parameterValue, pathSetting, engine); + return ExpandValueOrUserVariableAsFilePath(parameterValue, pathSetting, engine); } /// - /// convert to File Name + /// expand value or user variable as File Name /// /// /// /// - /// - public static string ConvertToUserVariableAsFileName(this string fileName, Engine.AutomationEngineInstance engine) + /// value is not file name + public static string ExpandValueOrUserVariableAsFileName(this string fileName, Engine.AutomationEngineInstance engine) { - var fn = fileName.ConvertToUserVariable(engine); + var fn = fileName.ExpandValueOrUserVariable(engine); var invs = Path.GetInvalidFileNameChars(); if (fn.IndexOfAny(invs) < 0) { @@ -534,14 +539,14 @@ public static string WaitForFile(string path, int waitTime, Engine.AutomationEng /// public static string WaitForFile(string pathValue, string waitTimeValue, Engine.AutomationEngineInstance engine) { - var path = pathValue.ConvertToUserVariable(engine); + var path = pathValue.ExpandValueOrUserVariable(engine); var invs = Path.GetInvalidPathChars(); if (path.IndexOfAny(invs) >= 0) { throw new Exception("File Path contains Invalid chars. Path: '" + path + "'"); } - var waitTime = waitTimeValue.ConvertToUserVariableAsInteger("Wait Time", engine); + var waitTime = waitTimeValue.ExpandValueOrUserVariableAsInteger("Wait Time", engine); return WaitForFile(path, waitTime, engine); } @@ -555,8 +560,8 @@ public static string WaitForFile(string pathValue, string waitTimeValue, Engine. /// public static string WaitForFile(ScriptCommand command, string pathName, string waitTimeName, Engine.AutomationEngineInstance engine) { - var path = command.ConvertToUserVariableAsFilePath(pathName, engine); - var waitTime = command.ConvertToUserVariableAsInteger(waitTimeName, "Wait Time", engine); + var path = command.ExpandValueOrUserVariableAsFilePath(pathName, engine); + var waitTime = command.ExpandValueOrUserVariableAsInteger(waitTimeName, "Wait Time", engine); return WaitForFile(path, waitTime, engine); } @@ -580,7 +585,7 @@ private static void FileAction(ScriptCommand command, string pathName, string wa if (!string.IsNullOrEmpty(pathResultName)) { - var pathResult = command.GetRawPropertyString(pathResultName, "Path Result"); + var pathResult = command.GetRawPropertyValueAsString(pathResultName, "Path Result"); if (!string.IsNullOrEmpty(pathResult)) { path.StoreInUserVariable(engine, pathResult); diff --git a/taskt/Core/Automation/Commands/Folder/CheckFolderExistsCommand.cs b/taskt/Core/Automation/Commands/Folder/CheckFolderExistsCommand.cs index 27dfdf1f9..2570e2811 100644 --- a/taskt/Core/Automation/Commands/Folder/CheckFolderExistsCommand.cs +++ b/taskt/Core/Automation/Commands/Folder/CheckFolderExistsCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Folder Operation Commands")] + [Attributes.ClassAttributes.Group("Folder Operation")] [Attributes.ClassAttributes.CommandSettings("Check Folder Exists")] [Attributes.ClassAttributes.Description("This command returns existence of folder paths from a specified location")] [Attributes.ClassAttributes.UsesDescription("Use this command to return a existence of file paths from a specific location.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CheckFolderExistsCommand : ScriptCommand + public sealed class CheckFolderExistsCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FolderPathControls), nameof(FolderPathControls.v_FolderPath))] @@ -42,9 +43,8 @@ public CheckFolderExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; //try //{ // FolderPathControls.WaitForFolder(this, nameof(v_TargetFolderName), nameof(v_WaitForFolder), engine); diff --git a/taskt/Core/Automation/Commands/Folder/CopyFolderCommand.cs b/taskt/Core/Automation/Commands/Folder/CopyFolderCommand.cs index 8608b51f0..b8f68e5f2 100644 --- a/taskt/Core/Automation/Commands/Folder/CopyFolderCommand.cs +++ b/taskt/Core/Automation/Commands/Folder/CopyFolderCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Folder Operation Commands")] + [Attributes.ClassAttributes.Group("Folder Operation")] [Attributes.ClassAttributes.CommandSettings("Copy Folder")] [Attributes.ClassAttributes.Description("This command copies a folder to a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to copy a folder to a new destination.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CopyFolderCommand : ScriptCommand + public sealed class CopyFolderCommand : ScriptCommand { //[XmlAttribute] //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -39,13 +40,13 @@ public class CopyFolderCommand : ScriptCommand public string v_DestinationDirectory { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Create Folder when the Destination Folder does not Exists")] [PropertyIsOptional(true, "No")] public string v_CreateDirectory { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Delete Folder when it already Exists")] [PropertyIsOptional(true, "No")] public string v_DeleteExisting { get; set; } @@ -74,10 +75,8 @@ public CopyFolderCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - ////apply variable logic //var sourceFolder = FolderPathControls.WaitForFolder(this, nameof(v_SourceFolderPath), nameof(v_WaitForTargetFolder), engine); @@ -116,11 +115,11 @@ public override void RunCommand(object sender) FolderPathControls.FolderAction(this, engine, new Action(path => { - var destinationFolder = v_DestinationDirectory.ConvertToUserVariableAsFolderPath(engine); + var destinationFolder = v_DestinationDirectory.ExpandValueOrUserVariableAsFolderPath(engine); if (!Directory.Exists(destinationFolder)) { - if (this.GetYesNoSelectionValue(nameof(v_CreateDirectory), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_CreateDirectory), engine)) { Directory.CreateDirectory(destinationFolder); } @@ -135,7 +134,7 @@ public override void RunCommand(object sender) //delete if it already exists per user if (Directory.Exists(finalPath)) { - if (this.GetYesNoSelectionValue(nameof(v_DeleteExisting), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_DeleteExisting), engine)) { Directory.Delete(finalPath, true); } diff --git a/taskt/Core/Automation/Commands/Folder/CreateFolderCommand.cs b/taskt/Core/Automation/Commands/Folder/CreateFolderCommand.cs index 0833b569d..9c81b8e4e 100644 --- a/taskt/Core/Automation/Commands/Folder/CreateFolderCommand.cs +++ b/taskt/Core/Automation/Commands/Folder/CreateFolderCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Folder Operation Commands")] + [Attributes.ClassAttributes.Group("Folder Operation")] [Attributes.ClassAttributes.CommandSettings("Create Folder")] [Attributes.ClassAttributes.Description("This command creates a folder in a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to create a folder in a specific location.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateFolderCommand : ScriptCommand + public sealed class CreateFolderCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -31,7 +32,7 @@ public class CreateFolderCommand : ScriptCommand public string v_DestinationDirectory { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Delete Folder When it already Exists")] [PropertyIsOptional(true, "No")] public string v_DeleteExisting { get; set; } @@ -56,10 +57,8 @@ public CreateFolderCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - ////apply variable logic //var destinationDirectory = FolderPathControls.WaitForFolder(this, nameof(v_DestinationDirectory), nameof(v_WaitForFolder), engine); @@ -83,12 +82,12 @@ public override void RunCommand(object sender) FolderPathControls.FolderAction(this, engine, new Action(path => { - var newFolder = v_NewFolderName.ConvertToUserVariableAsFolderName(engine); + var newFolder = v_NewFolderName.ExpandValueOrUserVariableAsFolderName(engine); var finalPath = System.IO.Path.Combine(path, newFolder); if (System.IO.Directory.Exists(finalPath)) { } { - if (this.GetYesNoSelectionValue(nameof(v_DeleteExisting), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_DeleteExisting), engine)) { System.IO.Directory.Delete(finalPath, true); } diff --git a/taskt/Core/Automation/Commands/Folder/DeleteFolderCommand.cs b/taskt/Core/Automation/Commands/Folder/DeleteFolderCommand.cs index 0390874ff..6ea27635b 100644 --- a/taskt/Core/Automation/Commands/Folder/DeleteFolderCommand.cs +++ b/taskt/Core/Automation/Commands/Folder/DeleteFolderCommand.cs @@ -6,21 +6,22 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Folder Operation Commands")] + [Attributes.ClassAttributes.Group("Folder Operation")] [Attributes.ClassAttributes.CommandSettings("Delete Folder")] [Attributes.ClassAttributes.Description("This command deletes a folder from a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to delete a folder from a specific location.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class DeleteFolderCommand : ScriptCommand + public sealed class DeleteFolderCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FolderPathControls), nameof(FolderPathControls.v_FolderPath))] public string v_SourceFolderPath { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Folder Move to the Recycle Bin")] [PropertyIsOptional(true, "No")] public string v_MoveToRecycleBin { get; set; } @@ -41,10 +42,8 @@ public DeleteFolderCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - ////apply variable logic //var sourceFolder = FolderPathControls.WaitForFolder(this, nameof(v_SourceFolderPath), nameof(v_WaitForFolder), engine); @@ -62,7 +61,7 @@ public override void RunCommand(object sender) new Action(path => { //delete folder - if (this.GetYesNoSelectionValue(nameof(v_MoveToRecycleBin), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_MoveToRecycleBin), engine)) { Shell32.MoveToRecycleBin(path); } diff --git a/taskt/Core/Automation/Commands/Folder/ExtractionFolderPathCommand.cs b/taskt/Core/Automation/Commands/Folder/ExtractionFolderPathCommand.cs index 1fe1c6668..38a2f66af 100644 --- a/taskt/Core/Automation/Commands/Folder/ExtractionFolderPathCommand.cs +++ b/taskt/Core/Automation/Commands/Folder/ExtractionFolderPathCommand.cs @@ -8,14 +8,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Folder Operation Commands")] + [Attributes.ClassAttributes.Group("Folder Operation")] [Attributes.ClassAttributes.CommandSettings("Extraction Folder Path")] [Attributes.ClassAttributes.Description("This command allows you to extract from folder path.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to extract from folder path.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExtractionFolderPathCommand : ScriptCommand + public sealed class ExtractionFolderPathCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FolderPathControls), nameof(FolderPathControls.v_FolderPath))] @@ -43,13 +44,11 @@ public ExtractionFolderPathCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (taskt.Core.Automation.Engine.AutomationEngineInstance)sender; + string folderPath = v_SourceFolderPath.ExpandValueOrUserVariableAsFolderPath(engine); - string folderPath = v_SourceFolderPath.ConvertToUserVariableAsFolderPath(engine); - - string format = v_Format.ConvertToUserVariable(engine); + string format = v_Format.ExpandValueOrUserVariable(engine); string result = FilePathControls.FormatFileFolderPath(folderPath, format); result.StoreInUserVariable(engine, v_Result); @@ -58,7 +57,7 @@ public override void RunCommand(object sender) private void lnkFormatChecker_Click(object sender, EventArgs e) { ComboBox cmb = (ComboBox)((CommandItemControl)sender).Tag; - UI.Forms.Supplement_Forms.frmFormatChecker.ShowFormatCheckerFormLinkClicked(cmb, "File Folder"); + UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmFormatChecker.ShowFormatCheckerFormLinkClicked(cmb, "File Folder"); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Folder/GetFoldersCommand.cs b/taskt/Core/Automation/Commands/Folder/GetFoldersCommand.cs index ea82a4c2b..5c479ccb0 100644 --- a/taskt/Core/Automation/Commands/Folder/GetFoldersCommand.cs +++ b/taskt/Core/Automation/Commands/Folder/GetFoldersCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Folder Operation Commands")] + [Attributes.ClassAttributes.Group("Folder Operation")] [Attributes.ClassAttributes.CommandSettings("Get Folders")] [Attributes.ClassAttributes.Description("This command returns a list of folder directories from a specified location")] [Attributes.ClassAttributes.UsesDescription("Use this command to return a list of folder directories from a specific location.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetFoldersCommand : ScriptCommand + public sealed class GetFoldersCommand : ScriptCommand, ICanHandleList { [XmlAttribute] [PropertyVirtualProperty(nameof(FolderPathControls), nameof(FolderPathControls.v_FolderPath))] @@ -58,20 +59,18 @@ public GetFoldersCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //apply variable logic var sourceFolder = FolderPathControls.WaitForFolder(this, nameof(v_SourceFolderPath), nameof(v_WaitForFolder), engine); //delete folder var directoriesList = System.IO.Directory.GetDirectories(sourceFolder).ToList(); - var searchFolder = v_SearchFolderName.ConvertToUserVariableAsFolderName(engine); + var searchFolder = v_SearchFolderName.ExpandValueOrUserVariableAsFolderName(engine); if (!String.IsNullOrEmpty(searchFolder)) { - switch (this.GetUISelectionValue(nameof(v_SearchMethod), engine)) + switch (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_SearchMethod), engine)) { case "contains": directoriesList = directoriesList.Where(t => System.IO.Path.GetFileName(t).Contains(searchFolder)).ToList(); @@ -88,7 +87,8 @@ public override void RunCommand(object sender) } } - directoriesList.StoreInUserVariable(engine, v_UserVariableName); + //directoriesList.StoreInUserVariable(engine, v_UserVariableName); + this.StoreListInUserVariable(directoriesList, nameof(v_UserVariableName), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Folder/MoveFolderCommand.cs b/taskt/Core/Automation/Commands/Folder/MoveFolderCommand.cs index c2b8170a5..65a040a5b 100644 --- a/taskt/Core/Automation/Commands/Folder/MoveFolderCommand.cs +++ b/taskt/Core/Automation/Commands/Folder/MoveFolderCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Folder Operation Commands")] + [Attributes.ClassAttributes.Group("Folder Operation")] [Attributes.ClassAttributes.CommandSettings("Move Folder")] [Attributes.ClassAttributes.Description("This command moves a folder to a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to move a folder to a new destination.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MoveFolderCommand : ScriptCommand + public sealed class MoveFolderCommand : ScriptCommand { //[XmlAttribute] //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -39,13 +40,13 @@ public class MoveFolderCommand : ScriptCommand public string v_DestinationDirectory { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Create Folder when the Destination Folder does not Exists")] [PropertyIsOptional(true, "No")] public string v_CreateDirectory { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Delete Folder when it already Exists")] [PropertyIsOptional(true, "No")] public string v_DeleteExisting { get; set; } @@ -74,10 +75,8 @@ public MoveFolderCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - ////apply variable logic //var sourceFolder = FolderPathControls.WaitForFolder(this, nameof(v_SourceFolderPath), nameof(v_WaitForTargetFolder), engine); @@ -116,11 +115,11 @@ public override void RunCommand(object sender) FolderPathControls.FolderAction(this, engine, new Action(path => { - var destinationFolder = v_DestinationDirectory.ConvertToUserVariableAsFolderPath(engine); + var destinationFolder = v_DestinationDirectory.ExpandValueOrUserVariableAsFolderPath(engine); if (!Directory.Exists(destinationFolder)) { - if (this.GetYesNoSelectionValue(nameof(v_CreateDirectory), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_CreateDirectory), engine)) { Directory.CreateDirectory(destinationFolder); } @@ -135,7 +134,7 @@ public override void RunCommand(object sender) //delete if it already exists per user if (Directory.Exists(finalPath)) { - if (this.GetYesNoSelectionValue(nameof(v_DeleteExisting), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_DeleteExisting), engine)) { Directory.Delete(finalPath, true); } diff --git a/taskt/Core/Automation/Commands/Folder/RenameFolderCommand.cs b/taskt/Core/Automation/Commands/Folder/RenameFolderCommand.cs index 389586d2c..5fe03d33a 100644 --- a/taskt/Core/Automation/Commands/Folder/RenameFolderCommand.cs +++ b/taskt/Core/Automation/Commands/Folder/RenameFolderCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Folder Operation Commands")] + [Attributes.ClassAttributes.Group("Folder Operation")] [Attributes.ClassAttributes.CommandSettings("Rename Folder")] [Attributes.ClassAttributes.Description("This command renames a folder at a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to rename an existing folder.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RenameFolderCommand : ScriptCommand + public sealed class RenameFolderCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FolderPathControls), nameof(FolderPathControls.v_FolderPath))] @@ -65,10 +66,8 @@ public RenameFolderCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - ////apply variable logic //var sourceFolder = FolderPathControls.WaitForFolder(this, nameof(v_SourceFolderPath), nameof(v_WaitForFolder), engine); //var currentFolderName = Path.GetFileName(sourceFolder); @@ -102,7 +101,7 @@ public override void RunCommand(object sender) { var currentFolderName = Path.GetFileName(path); - var newFolderName = v_NewName.ConvertToUserVariableAsFolderName(engine); + var newFolderName = v_NewName.ExpandValueOrUserVariableAsFolderName(engine); //get source folder name and info DirectoryInfo sourceFolderInfo = new DirectoryInfo(path); @@ -110,7 +109,7 @@ public override void RunCommand(object sender) //create destination var destinationPath = Path.Combine(sourceFolderInfo.Parent.FullName, newFolderName); - var whenSame = this.GetUISelectionValue(nameof(v_IfFolderNameSame), engine); + var whenSame = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfFolderNameSame), engine); if (currentFolderName == newFolderName) { switch (whenSame) diff --git a/taskt/Core/Automation/Commands/Folder/WaitForFolderToExistCommand.cs b/taskt/Core/Automation/Commands/Folder/WaitForFolderToExistCommand.cs index f3da4ac3d..85763581b 100644 --- a/taskt/Core/Automation/Commands/Folder/WaitForFolderToExistCommand.cs +++ b/taskt/Core/Automation/Commands/Folder/WaitForFolderToExistCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Folder Operation Commands")] + [Attributes.ClassAttributes.Group("Folder Operation")] [Attributes.ClassAttributes.CommandSettings("Wait For Folder To Exists")] [Attributes.ClassAttributes.Description("This command waits for a folder to exist at a specified destination")] [Attributes.ClassAttributes.UsesDescription("Use this command to wait for a folder to exist before proceeding.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WaitForFolderToExistCommand : ScriptCommand + public sealed class WaitForFolderToExistCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FolderPathControls), nameof(FolderPathControls.v_FolderPath))] @@ -37,10 +38,8 @@ public WaitForFolderToExistCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //try //{ // FolderPathControls.WaitForFolder(this, nameof(v_FolderName), nameof(v_WaitTime), engine); diff --git a/taskt/Core/Automation/Commands/FolderPathControls.cs b/taskt/Core/Automation/Commands/FolderPathControls.cs index 1ce21103b..b0c39b9f1 100644 --- a/taskt/Core/Automation/Commands/FolderPathControls.cs +++ b/taskt/Core/Automation/Commands/FolderPathControls.cs @@ -9,6 +9,7 @@ namespace taskt.Core.Automation.Commands /// internal static class FolderPathControls { + #region Virtual Property /// /// folder path /// @@ -24,6 +25,7 @@ internal static class FolderPathControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("Folder Path", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Folder")] + [PropertyParameterOrder(5000)] public static string v_FolderPath { get; } /// @@ -40,6 +42,7 @@ internal static class FolderPathControls [PropertyIsOptional(true, "10")] [PropertyFirstValue("10")] [PropertyDisplayText(true, "Wait", "s")] + [PropertyParameterOrder(5000)] public static string v_WaitTime { get; } /// @@ -57,7 +60,9 @@ internal static class FolderPathControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("Folder Path Result", PropertyValidationRule.ValidationRuleFlags.None)] [PropertyDisplayText(false, "")] + [PropertyParameterOrder(5000)] public static string v_FolderPathResult { get; } + #endregion /// /// Wait For Folder @@ -100,8 +105,8 @@ public static string WaitForFolder(string path, int waitTime, Engine.AutomationE /// public static string WaitForFolder(string pathValue, string waitTimeValue, Engine.AutomationEngineInstance engine) { - var path = pathValue.ConvertToUserVariableAsFolderPath(engine); - var waitTime = waitTimeValue.ConvertToUserVariableAsInteger("Wait Time", engine); + var path = pathValue.ExpandValueOrUserVariableAsFolderPath(engine); + var waitTime = waitTimeValue.ExpandValueOrUserVariableAsInteger("Wait Time", engine); return WaitForFolder(path, waitTime, engine); } @@ -115,8 +120,8 @@ public static string WaitForFolder(string pathValue, string waitTimeValue, Engin /// public static string WaitForFolder(ScriptCommand command, string pathName, string waitTimeName, Engine.AutomationEngineInstance engine) { - var path = command.ConvertToUserVariableAsFolderPath(pathName, engine); - var waitTime = command.ConvertToUserVariableAsInteger(waitTimeName, "Wait Time", engine); + var path = command.ExpandValueOrUserVariableAsFolderPath(pathName, engine); + var waitTime = command.ExpandValueOrUserVariableAsInteger(waitTimeName, "Wait Time", engine); return WaitForFolder(path, waitTime, engine); } @@ -139,7 +144,7 @@ public static void FolderAction(ScriptCommand command, string pathName, string w if (!string.IsNullOrEmpty(pathResultName)) { - var pathResult = command.GetRawPropertyString(pathResultName, "Folder Path Result"); + var pathResult = command.GetRawPropertyValueAsString(pathResultName, "Folder Path Result"); if (!string.IsNullOrEmpty(pathResult)) { path.StoreInUserVariable(engine, pathResult); @@ -196,14 +201,15 @@ private static string ConvertToFullPath(string path, Engine.AutomationEngineInst } /// - /// convert to Folder Path + /// expand value or User variable as Folder Path /// /// /// /// - public static string ConvertToUserVariableAsFolderPath(this string value, Engine.AutomationEngineInstance engine) + /// value is not Folder Path + public static string ExpandValueOrUserVariableAsFolderPath(this string value, Engine.AutomationEngineInstance engine) { - var p = ConvertToFullPath(value.ConvertToUserVariable(engine), engine); + var p = ConvertToFullPath(value.ExpandValueOrUserVariable(engine), engine); var invs = Path.GetInvalidPathChars(); if (p.IndexOfAny(invs) < 0) { @@ -216,27 +222,27 @@ public static string ConvertToUserVariableAsFolderPath(this string value, Engine } /// - /// convert to Folder Path + /// Expand value or user variable as Folder Path /// /// /// /// /// - public static string ConvertToUserVariableAsFolderPath(this ScriptCommand command, string parameterValue, Engine.AutomationEngineInstance engine) + public static string ExpandValueOrUserVariableAsFolderPath(this ScriptCommand command, string parameterValue, Engine.AutomationEngineInstance engine) { - return command.ConvertToUserVariable(parameterValue, "Folder Path", engine).ConvertToUserVariableAsFolderPath(engine); + return command.ExpandValueOrUserVariable(parameterValue, "Folder Path", engine).ExpandValueOrUserVariableAsFolderPath(engine); } /// - /// convert to folder name + /// expand value or User variable as Folder Name /// /// /// /// - /// - public static string ConvertToUserVariableAsFolderName(this string folderName, Engine.AutomationEngineInstance engine) + /// value is not folder name + public static string ExpandValueOrUserVariableAsFolderName(this string folderName, Engine.AutomationEngineInstance engine) { - var fn = folderName.ConvertToUserVariable(engine); + var fn = folderName.ExpandValueOrUserVariable(engine); var invs = Path.GetInvalidFileNameChars(); if (fn.IndexOfAny(invs) < 0) { diff --git a/taskt/Core/Automation/Commands/FormUIControls.cs b/taskt/Core/Automation/Commands/FormUIControls.cs new file mode 100644 index 000000000..4a0c5918a --- /dev/null +++ b/taskt/Core/Automation/Commands/FormUIControls.cs @@ -0,0 +1,212 @@ +using System; +using System.Collections.Generic; +using System.Windows.Forms; +using static taskt.UI.CustomControls.CommandControls; + +namespace taskt.Core.Automation.Commands +{ + public static class FormUIControls + { + #region control search method + + /// + /// get parameter group controls + /// + /// + /// + /// + /// + public static List GetControlGroup(this List ctrls, string parameterName, string nextParameterName = "") + { + List ret = new List(); + + int index; + index = ctrls.FindIndex(t => (t.Name == GROUP_PREFIX + parameterName)); + if (index >= 0) + { + ret.Add(ctrls[index]); + } + else + { + index = ctrls.FindIndex(t => (t.Name == LABEL_PREFIX + parameterName)); + int last = (nextParameterName == "") ? ctrls.Count : ctrls.FindIndex(t => (t.Name == LABEL_PREFIX + nextParameterName)); + + for (int i = index; i < last; i++) + { + ret.Add(ctrls[i]); + } + } + + return ret; + } + + /// + /// get paramter body control + /// + /// + /// + /// + /// + /// + public static T GetPropertyControl(this Dictionary controls, string parameterName) where T : Control + { + if (controls.ContainsKey(parameterName)) + { + return (T)controls[parameterName]; + } + else + { + throw new Exception("Control '" + parameterName + "' does not exists."); + } + } + + /// + /// get paramter label + /// + /// + /// + /// + /// + public static Label GetPropertyControlLabel(this Dictionary controls, string parameterName) + { + if (controls.ContainsKey(LABEL_PREFIX + parameterName)) + { + return (Label)controls[LABEL_PREFIX + parameterName]; + } + else + { + throw new Exception("Label '" + LABEL_PREFIX + parameterName + "' does not exists."); + } + } + + /// + /// get parameter 2nd label + /// + /// + /// + /// + /// + public static Label GetPropertyControl2ndLabel(this Dictionary controls, string parameterName) + { + if (controls.ContainsKey(LABEL_2ND_PREFIX + parameterName)) + { + return (Label)controls[LABEL_2ND_PREFIX + parameterName]; + } + else + { + throw new Exception("2nd Label '" + LABEL_2ND_PREFIX + parameterName + "' does not exists."); + } + } + + /// + /// get all paramter controls + /// + /// + /// + /// + /// + /// + /// + public static (T body, Label label, Label label2nd) GetAllPropertyControl(this Dictionary controls, string parameterName, bool throwWhenLabelNotExists = true, bool throwWhen2ndLabelNotExists = false) where T : Control + { + T body = controls.GetPropertyControl(parameterName); + + Label label; + try + { + label = controls.GetPropertyControlLabel(parameterName); + } + catch (Exception ex) + { + if (throwWhenLabelNotExists) + { + throw ex; + } + else + { + label = null; + } + } + Label label2nd; + try + { + label2nd = controls.GetPropertyControl2ndLabel(parameterName); + } + catch (Exception ex) + { + if (throwWhen2ndLabelNotExists) + { + throw ex; + } + else + { + label2nd = null; + } + } + return (body, label, label2nd); + } + + /// + /// get 2nd label text + /// + /// + /// + /// + public static Dictionary Get2ndLabelText(this Dictionary controls, string parameterName) + { + return controls.GetPropertyControlLabel(parameterName).Get2ndLabelTexts(); + } + + /// + /// get 2nd label text + /// + /// + /// + /// + public static Dictionary Get2ndLabelTexts(this Label lbl) + { + if (lbl.Tag is Dictionary dic) + { + return dic; + } + else + { + throw new Exception(lbl.Name + " does not has Dictionary item for 2nd-Label"); + } + } + + /// + /// create 2nd label text + /// + /// + /// + /// + /// + public static void SecondLabelProcess(this Dictionary controls, string labelTextName, string label2ndName, string key) + { + var dic = controls.Get2ndLabelText(labelTextName); + var lbl = controls.GetPropertyControl2ndLabel(label2ndName); + + lbl.Text = dic.ContainsKey(key) ? dic[key] : ""; + } + + + /// + /// show/hide Command parameter groups + /// + /// + /// + /// + public static void SetVisibleParameterControlGroup(Dictionary controlsList, string parameterName, bool visible) + { + foreach (var ctrl in controlsList) + { + if (ctrl.Key.Contains(parameterName)) + { + ctrl.Value.Visible = visible; + } + } + } + #endregion + } +} diff --git a/taskt/Core/Automation/Commands/GeneralPropertyControls.cs b/taskt/Core/Automation/Commands/GeneralPropertyControls.cs index a387ccbe8..b4d257abf 100644 --- a/taskt/Core/Automation/Commands/GeneralPropertyControls.cs +++ b/taskt/Core/Automation/Commands/GeneralPropertyControls.cs @@ -9,6 +9,7 @@ namespace taskt.Core.Automation.Commands /// internal static class GeneralPropertyControls { + #region Virtual Property /// /// specify variable name to store result property /// @@ -23,6 +24,7 @@ internal static class GeneralPropertyControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("Result", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Result")] + [PropertyParameterOrder(5000)] public static string v_Result { get; } /// @@ -35,6 +37,7 @@ internal static class GeneralPropertyControls [PropertyShowSampleUsageInDescription(true)] [PropertyTextBoxSetting(1, false)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(5000)] public static string v_DisallowNewLine_OneLineTextBox { get; } /// @@ -46,6 +49,7 @@ internal static class GeneralPropertyControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.TextBox)] [PropertyShowSampleUsageInDescription(true)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(5000)] public static string v_OneLineTextBox { get; } /// @@ -57,6 +61,7 @@ internal static class GeneralPropertyControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.MultiLineTextBox)] [PropertyShowSampleUsageInDescription(true)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(5000)] public static string v_MultiLinesTextBox { get; } /// @@ -67,23 +72,8 @@ internal static class GeneralPropertyControls [Remarks("")] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(5000)] public static string v_ComboBox { get; } - - /// - /// show/hide Command parameter groups - /// - /// - /// - /// - public static void SetVisibleParameterControlGroup(Dictionary controlsList, string parameterName, bool visible) - { - foreach (var ctrl in controlsList) - { - if (ctrl.Key.Contains(parameterName)) - { - ctrl.Value.Visible = visible; - } - } - } + #endregion } } diff --git a/taskt/Core/Automation/Commands/IE/IEBrowserCloseCommand.cs b/taskt/Core/Automation/Commands/IE/IEBrowserCloseCommand.cs index 17f3324d4..c905de448 100644 --- a/taskt/Core/Automation/Commands/IE/IEBrowserCloseCommand.cs +++ b/taskt/Core/Automation/Commands/IE/IEBrowserCloseCommand.cs @@ -4,15 +4,15 @@ using System.Xml.Serialization; using System.Linq; using taskt.UI.CustomControls; -using taskt.UI.Forms; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("IE Browser Commands")] + [Attributes.ClassAttributes.Group("IE Browser")] [Attributes.ClassAttributes.Description("This command allows you to close the associated IE web browser")] [Attributes.ClassAttributes.ImplementationDescription("This command implements the 'InternetExplorer' application object from SHDocVw.dll to achieve automation.")] - public class IEBrowserCloseCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] + public sealed class IEBrowserCloseCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Enter the instance name")] @@ -29,11 +29,9 @@ public IEBrowserCloseCommand() this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - - var vInstance = v_InstanceName.ConvertToUserVariable(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); var browserObject = engine.GetAppInstance(vInstance); @@ -44,7 +42,7 @@ public override void RunCommand(object sender) engine.RemoveAppInstance(vInstance); } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -53,7 +51,7 @@ public override List Render(frmCommandEditor editor) RenderedControls.AddRange(instanceCtrls); //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultBrowserInstanceName; } diff --git a/taskt/Core/Automation/Commands/IE/IEBrowserCreateCommand.cs b/taskt/Core/Automation/Commands/IE/IEBrowserCreateCommand.cs index 84426dde5..5e460ba19 100644 --- a/taskt/Core/Automation/Commands/IE/IEBrowserCreateCommand.cs +++ b/taskt/Core/Automation/Commands/IE/IEBrowserCreateCommand.cs @@ -4,15 +4,15 @@ using System.Xml.Serialization; using System.Linq; using taskt.UI.CustomControls; -using taskt.UI.Forms; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("IE Browser Commands")] + [Attributes.ClassAttributes.Group("IE Browser")] [Attributes.ClassAttributes.Description("This command allows you to create a new IE web browser session.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements the 'InternetExplorer' application object from SHDocVw.dll to achieve automation.")] - public class IEBrowserCreateCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] + public sealed class IEBrowserCreateCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Enter the instance name")] @@ -44,16 +44,14 @@ public IEBrowserCreateCommand() this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - - var instanceName = v_InstanceName.ConvertToUserVariable(sender); + var instanceName = v_InstanceName.ExpandValueOrUserVariable(engine); SHDocVw.InternetExplorer newBrowserSession = new SHDocVw.InternetExplorer(); try { - newBrowserSession.Navigate(v_URL.ConvertToUserVariable(sender)); + newBrowserSession.Navigate(v_URL.ExpandValueOrUserVariable(engine)); WaitForReadyState(newBrowserSession); newBrowserSession.Visible = true; } @@ -90,7 +88,7 @@ public static void WaitForReadyState(SHDocVw.InternetExplorer ieInstance) } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -100,7 +98,7 @@ public override List Render(frmCommandEditor editor) //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_URL", this, editor)); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultBrowserInstanceName; } diff --git a/taskt/Core/Automation/Commands/IE/IEBrowserElementActionCommand.cs b/taskt/Core/Automation/Commands/IE/IEBrowserElementActionCommand.cs index b79f401e8..fef847f10 100644 --- a/taskt/Core/Automation/Commands/IE/IEBrowserElementActionCommand.cs +++ b/taskt/Core/Automation/Commands/IE/IEBrowserElementActionCommand.cs @@ -1,25 +1,21 @@ -using System; +using MSHTML; +using SHDocVw; +using System; using System.Collections.Generic; using System.Data; -using System.Drawing; using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; -using Newtonsoft.Json; -using OpenQA.Selenium; using taskt.UI.CustomControls; -using taskt.UI.Forms; -using SHDocVw; -using MSHTML; -using taskt.Core.Automation.User32; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("IE Browser Commands")] + [Attributes.ClassAttributes.Group("IE Browser")] [Attributes.ClassAttributes.Description("This command allows you to manipulate (get or set) elements within the HTML document of the associated IE web browser. Features an assisting element capture form")] [Attributes.ClassAttributes.ImplementationDescription("This command implements the 'InternetExplorer' application object from SHDocVw.dll and MSHTML.dll to achieve automation.")] - public class IEBrowserElementActionCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] + public sealed class IEBrowserElementActionCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Enter the instance name")] @@ -142,19 +138,18 @@ private Boolean InspectFrame(IHTMLElementCollection elementCollection, Enumerabl } [STAThread] - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { object browserObject = null; - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - - var vInstance = v_InstanceName.ConvertToUserVariable(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); browserObject = engine.GetAppInstance(vInstance); var browserInstance = (SHDocVw.InternetExplorer)browserObject; - DataTable searchTable = Core.Common.Clone(v_WebSearchParameter); + //DataTable searchTable = Core.Common.Clone(v_WebSearchParameter); + DataTable searchTable = v_WebSearchParameter.Copy(); DataColumn matchFoundColumn = new DataColumn(); matchFoundColumn.ColumnName = "Match Found"; @@ -167,7 +162,7 @@ where rws.Field("Enabled").ToString() == "True" foreach (DataRow seachCriteria in elementSearchProperties) { string searchPropertyValue = seachCriteria.Field("Property Value"); - searchPropertyValue = searchPropertyValue.ConvertToUserVariable(engine); + searchPropertyValue = searchPropertyValue.ExpandValueOrUserVariable(engine); seachCriteria.SetField("Property Value", searchPropertyValue); } @@ -177,11 +172,11 @@ where rws.Field("Enabled").ToString() == "True" if (doc == lastDocFound) { - qualifyingElementFound = InspectFrame(lastElementCollectionFound, elementSearchProperties, sender, browserInstance); + qualifyingElementFound = InspectFrame(lastElementCollectionFound, elementSearchProperties, engine, browserInstance); } if (!qualifyingElementFound) { - qualifyingElementFound = InspectFrame(doc.all, elementSearchProperties, sender, browserInstance); + qualifyingElementFound = InspectFrame(doc.all, elementSearchProperties, engine, browserInstance); } if (qualifyingElementFound) { @@ -279,6 +274,8 @@ private bool FindQualifyingElement(EnumerableRowCollection elementSearc private void RunCommandActions(IHTMLElement element, object sender, InternetExplorer browserInstance) { + var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; + if (v_WebAction == "Fire onmousedown event") { ((IHTMLElement3)element).FireEvent("onmousedown"); @@ -308,14 +305,14 @@ where rw.Field("Parameter Name") == "Y Adjustment" select rw.Field("Parameter Value")).FirstOrDefault()); //var ieClientLocation = User32Functions.GetWindowPosition(new IntPtr(browserInstance.HWND)); - var ieClientLocation = WindowNameControls.GetWindowPosition(new IntPtr(browserInstance.HWND)); + var ieClientLocation = WindowControls.GetWindowRect(new IntPtr(browserInstance.HWND)); MoveMouseCommand newMouseMove = new MoveMouseCommand(); newMouseMove.v_XMousePosition = ((elementXposition + ieClientLocation.left + 10) + userXAdjust).ToString(); // + 10 gives extra padding newMouseMove.v_YMousePosition = ((elementYposition + ieClientLocation.top + 90 + System.Windows.Forms.SystemInformation.CaptionHeight) + userYAdjust).ToString(); // +90 accounts for title bar height newMouseMove.v_MouseClick = v_WebAction; - newMouseMove.RunCommand(sender); + newMouseMove.RunCommand(engine); } else if (v_WebAction == "Set Attribute") { @@ -327,7 +324,7 @@ where rw.Field("Parameter Name") == "Attribute Name" where rw.Field("Parameter Name") == "Value To Set" select rw.Field("Parameter Value")).FirstOrDefault(); - valueToSet = valueToSet.ConvertToUserVariable(sender); + valueToSet = valueToSet.ExpandValueOrUserVariable(engine); element.setAttribute(attributeName, valueToSet); } @@ -339,7 +336,7 @@ where rw.Field("Parameter Name") == "Value To Set" where rw.Field("Parameter Name") == "Text To Set" select rw.Field("Parameter Value")).FirstOrDefault(); - textToSet = textToSet.ConvertToUserVariable(sender); + textToSet = textToSet.ExpandValueOrUserVariable(engine); element.setAttribute(attributeName, textToSet); } @@ -355,7 +352,7 @@ where rw.Field("Parameter Name") == "Variable Name" string convertedAttribute = Convert.ToString(element.getAttribute(attributeName)); - convertedAttribute.StoreInUserVariable(sender, variableName); + convertedAttribute.StoreInUserVariable(engine, variableName); } } @@ -389,7 +386,7 @@ public int FindElementYPosition(MSHTML.IHTMLElement obj) return curtop; } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -436,7 +433,7 @@ public override List Render(frmCommandEditor editor) ElementParameterControls.Add(ElementsGridViewHelper); RenderedControls.AddRange(ElementParameterControls); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultBrowserInstanceName; } diff --git a/taskt/Core/Automation/Commands/IE/IEBrowserFindBrowserCommand.cs b/taskt/Core/Automation/Commands/IE/IEBrowserFindBrowserCommand.cs index 1f0a8f524..9b180a197 100644 --- a/taskt/Core/Automation/Commands/IE/IEBrowserFindBrowserCommand.cs +++ b/taskt/Core/Automation/Commands/IE/IEBrowserFindBrowserCommand.cs @@ -5,15 +5,15 @@ using System.Xml.Serialization; using System.Linq; using taskt.UI.CustomControls; -using taskt.UI.Forms; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("IE Browser Commands")] + [Attributes.ClassAttributes.Group("IE Browser")] [Attributes.ClassAttributes.Description("This command allows you to find and attach to an existing IE web browser session.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements the 'InternetExplorer' application object from SHDocVw.dll to achieve automation.")] - public class IEBrowserFindBrowserCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] + public sealed class IEBrowserFindBrowserCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Enter the instance name")] @@ -37,11 +37,9 @@ public IEBrowserFindBrowserCommand() this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - - var instanceName = v_InstanceName.ConvertToUserVariable(sender); + var instanceName = v_InstanceName.ExpandValueOrUserVariable(engine); bool browserFound = false; var shellWindows = new ShellWindows(); @@ -75,7 +73,7 @@ public override void RunCommand(object sender) } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -103,7 +101,7 @@ public override List Render(frmCommandEditor editor) //RenderedControls.AddRange(ElementParameterControls); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultBrowserInstanceName; } diff --git a/taskt/Core/Automation/Commands/IE/IEBrowserNavigateURLCommand.cs b/taskt/Core/Automation/Commands/IE/IEBrowserNavigateURLCommand.cs index 6ffd4584b..f8b302f4b 100644 --- a/taskt/Core/Automation/Commands/IE/IEBrowserNavigateURLCommand.cs +++ b/taskt/Core/Automation/Commands/IE/IEBrowserNavigateURLCommand.cs @@ -4,17 +4,17 @@ using System.Xml.Serialization; using System.Linq; using taskt.UI.CustomControls; -using taskt.UI.Forms; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("IE Browser Commands")] + [Attributes.ClassAttributes.Group("IE Browser")] [Attributes.ClassAttributes.Description("This command allows you to navigate a IE web browser session to a given URL or resource.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to navigate an existing IE instance to a known URL or web resource")] [Attributes.ClassAttributes.ImplementationDescription("This command implements the 'InternetExplorer' application object from SHDocVw.dll to achieve automation.")] - public class IEBrowserNavigateURLCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] + public sealed class IEBrowserNavigateURLCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Enter the instance name")] @@ -42,24 +42,22 @@ public IEBrowserNavigateURLCommand() this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { object browserObject = null; - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - - var vInstance = v_InstanceName.ConvertToUserVariable(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); browserObject = engine.GetAppInstance(vInstance); var browserInstance = (SHDocVw.InternetExplorer)browserObject; - browserInstance.Navigate(v_URL.ConvertToUserVariable(sender)); + browserInstance.Navigate(v_URL.ExpandValueOrUserVariable(engine)); IEBrowserCreateCommand.WaitForReadyState(browserInstance); } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -70,7 +68,7 @@ public override List Render(frmCommandEditor editor) RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_URL", this, editor)); - if (editor.creationMode == frmCommandEditor.CreationMode.Add) + if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) { this.v_InstanceName = editor.appSettings.ClientSettings.DefaultBrowserInstanceName; } diff --git a/taskt/Core/Automation/Commands/If/BeginIfCommand.cs b/taskt/Core/Automation/Commands/If/BeginIfCommand.cs index 779b8e66a..207d492ff 100644 --- a/taskt/Core/Automation/Commands/If/BeginIfCommand.cs +++ b/taskt/Core/Automation/Commands/If/BeginIfCommand.cs @@ -2,22 +2,19 @@ using System.Linq; using System.Xml.Serialization; using System.Data; -using taskt.Core.Automation.User32; using System.Collections.Generic; using System.Windows.Forms; -using taskt.UI.Forms; using taskt.UI.CustomControls; -using System.Drawing; -using System.Text; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("If Commands")] + [Attributes.ClassAttributes.Group("If")] [Attributes.ClassAttributes.Description("This command allows you to evaluate a logical statement to determine if the statement is true.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check if a statement is 'true' or 'false' and subsequently take an action based on either condition. Any 'BeginIf' command must have a following 'EndIf' command.")] [Attributes.ClassAttributes.ImplementationDescription("This command evaluates supplied arguments and if evaluated to true runs sub elements")] - public class BeginIfCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_begin_if))] + public sealed class BeginIfCommand : ScriptCommand, IHaveDataTableElements, IHaveIfAdditionalCommands { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please select type of If Command")] @@ -88,7 +85,7 @@ public BeginIfCommand() this.CustomRendering = true; //define parameter table - this.v_IfActionParameterTable = new System.Data.DataTable + this.v_IfActionParameterTable = new DataTable { TableName = DateTime.Now.ToString("IfActionParamTable" + DateTime.Now.ToString("MMddyy.hhmmss")) }; @@ -96,21 +93,19 @@ public BeginIfCommand() this.v_IfActionParameterTable.Columns.Add("Parameter Value"); } - private void IfGridViewHelper_MouseEnter(object sender, EventArgs e, frmCommandEditor editor) + private void IfGridViewHelper_MouseEnter(object sender, EventArgs e, UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { ifAction_SelectionChangeCommitted(null, null, editor); } - public override void RunCommand(object sender, Core.Script.ScriptAction parentCommand) + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) { - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - bool ifResult = ConditionControls.DetermineStatementTruth(v_IfActionType, v_IfActionParameterTable, engine); int startIndex, endIndex, elseIndex; - if (parentCommand.AdditionalScriptCommands.Any(item => item.ScriptCommand is Core.Automation.Commands.ElseCommand)) + if (parentCommand.AdditionalScriptCommands.Any(item => item.ScriptCommand is ElseCommand)) { - elseIndex = parentCommand.AdditionalScriptCommands.FindIndex(a => a.ScriptCommand is Core.Automation.Commands.ElseCommand); + elseIndex = parentCommand.AdditionalScriptCommands.FindIndex(a => a.ScriptCommand is ElseCommand); if (ifResult) { @@ -140,701 +135,9 @@ public override void RunCommand(object sender, Core.Script.ScriptAction parentCo engine.ExecuteCommand(parentCommand.AdditionalScriptCommands[i]); } - } - //public bool DetermineStatementTruth(object sender) - //{ - // var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - - // bool ifResult = false; - - // string actionType = v_IfActionType.ConvertToUserVariable(engine); - - // switch (actionType.ToLower()) - // { - // case "value": - // ifResult = DetermineStatementTruth_Value(engine); - // break; - - // case "date compare": - // ifResult = DetermineStatementTruth_DateCompare(engine); - // break; - - // case "variable compare": - // ifResult = DetermineStatementTruth_VariableCompare(engine); - // break; - - // case "variable has value": - // ifResult = DetermineStatementTruth_VariableHasValue(engine); - // break; - - // case "variable is numeric": - // ifResult = DetermineStatementTruth_VariableIsNumeric(engine); - // break; - - // case "error occured": - // ifResult = DetermineStatementTruth_ErrorOccur(engine, false); - // break; - - // case "error did not occur": - // ifResult = DetermineStatementTruth_ErrorOccur(engine, true); - // break; - - // case "window name exists": - // ifResult = DetermineStatementTruth_WindowNameExists(engine); - // break; - - // case "active window name is": - // ifResult = DetermineStatementTruth_ActiveWindow(engine); - // break; - - // case "file exists": - // ifResult = DetermineStatementTruth_File(engine); - // break; - - // case "folder exists": - // ifResult = DetermineStatementTruth_Folder(engine); - // break; - - // case "web element exists": - // ifResult = DetermineStatementTruth_WebElement(engine); - // break; - - // case "gui element exists": - // ifResult = DetermineStatementTruth_GUIElement(engine); - // break; - - // case "boolean": - // ifResult = DetermineStatementTruth_Boolean(engine); - // break; - - // default: - // throw new Exception("If type not recognized!"); - // break; - // } - - // //if (v_IfActionType == "Value") - // //{ - // // ifResult = DetermineStatementTruth_Value(engine); - // //} - // //else if (v_IfActionType == "Date Compare") - // //{ - // // ifResult = DetermineStatementTruth_DateCompare(engine); - // //} - // //else if (v_IfActionType == "Variable Compare") - // //{ - // // ifResult = DetermineStatementTruth_VariableCompare(engine); - // //} - // //else if (v_IfActionType == "Variable Has Value") - // //{ - // // ifResult = DetermineStatementTruth_VariableHasValue(engine); - // //} - // //else if (v_IfActionType == "Variable Is Numeric") - // //{ - // // ifResult = DetermineStatementTruth_VariableIsNumeric(engine); - // //} - // //else if (v_IfActionType == "Error Occured") - // //{ - // // ////get line number - // // //string userLineNumber = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // // where rw.Field("Parameter Name") == "Line Number" - // // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // // ////convert to variable - // // //string variableLineNumber = userLineNumber.ConvertToUserVariable(sender); - - // // ////convert to int - // // //int lineNumber = int.Parse(variableLineNumber); - - // // ////determine if error happened - // // //if (engine.ErrorsOccured.Where(f => f.LineNumber == lineNumber).Count() > 0) - // // //{ - - // // // var error = engine.ErrorsOccured.Where(f => f.LineNumber == lineNumber).FirstOrDefault(); - // // // error.ErrorMessage.StoreInUserVariable(sender, "Error.Message"); - // // // error.LineNumber.ToString().StoreInUserVariable(sender, "Error.Line"); - // // // error.StackTrace.StoreInUserVariable(sender, "Error.StackTrace"); - - // // // ifResult = true; - // // //} - // // //else - // // //{ - // // // ifResult = false; - // // //} - // // ifResult = DetermineStatementTruth_ErrorDidOccur(engine, false); - // //} - // //else if (v_IfActionType == "Error Did Not Occur") - // //{ - // // ifResult = DetermineStatementTruth_ErrorDidOccur(engine, true); - // //} - // //else if (v_IfActionType == "Window Name Exists") - // //{ - // // ifResult = DetermineStatementTruth_WindowNameExists(engine); - // //} - // //else if (v_IfActionType == "Active Window Name Is") - // //{ - // // ifResult = DetermineStatementTruth_ActiveWindow(engine); - // //} - // //else if (v_IfActionType == "File Exists") - // //{ - // // ifResult = DetermineStatementTruth_File(engine); - // //} - // //else if (v_IfActionType == "Folder Exists") - // //{ - // // ifResult = DetermineStatementTruth_Folder(engine); - // //} - // //else if (v_IfActionType == "Web Element Exists") - // //{ - // // ifResult = DetermineStatementTruth_WebElement(engine); - // //} - // //else if (v_IfActionType == "GUI Element Exists") - // //{ - // // ifResult = DetermineStatementTruth_GUIElement(engine); - // //} - // //else if (v_IfActionType == "Boolean") - // //{ - // // ifResult = DetermineStatementTruth_Boolean(engine); - // //} - // //else - // //{ - // // throw new Exception("If type not recognized!"); - // //} - - // return ifResult; - //} - - //private bool DetermineStatementTruth_Value(Engine.AutomationEngineInstance engine) - //{ - // //string value1 = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Value1" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - // //string operand = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Operand" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - // //string value2 = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Value2" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //value1 = value1.ConvertToUserVariable(sender); - // //value2 = value2.ConvertToUserVariable(sender); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value"); - - // string operand = param["Operand"].ConvertToUserVariable(engine); - - // bool isBoolCompare = false; - // decimal value1 = 0; - // decimal value2 = 0; - // switch (operand.ToLower()) - // { - // case "is equal to": - // case "is not equal to": - // bool tempBool; - // isBoolCompare = bool.TryParse(param["Value1"], out tempBool) && bool.TryParse(param["Value2"], out tempBool); - // break; - // default: - // value1 = param["Value1"].ConvertToUserVariableAsDecimal("Value1", engine); - // value2 = param["Value2"].ConvertToUserVariableAsDecimal("Value2", engine); - // break; - // } - - // //bool tempBool; - // //bool isBoolCompare = (bool.TryParse(value1, out tempBool) && bool.TryParse(value2, out tempBool)); - // //decimal cdecValue1, cdecValue2; - - // bool ifResult; - // switch (operand.ToLower()) - // { - // case "is equal to": - // if (isBoolCompare) - // { - // ifResult = (bool.Parse(param["Value1"]) == bool.Parse(param["Value2"])); - // } - // else - // { - // ifResult = (param["Value1"] == param["Value2"]); - // } - // break; - - // case "is not equal to": - // if (isBoolCompare) - // { - // ifResult = (bool.Parse(param["Value1"]) != bool.Parse(param["Value2"])); - // } - // else - // { - // ifResult = (param["Value1"] != param["Value2"]); - // } - // break; - - // case "is greater than": - // //cdecValue1 = Convert.ToDecimal(value1); - // //cdecValue2 = Convert.ToDecimal(value2); - // //ifResult = (cdecValue1 > cdecValue2); - // ifResult = value1 > value2; - // break; - - // case "is greater than or equal to": - // //cdecValue1 = Convert.ToDecimal(value1); - // //cdecValue2 = Convert.ToDecimal(value2); - // //ifResult = (cdecValue1 >= cdecValue2); - // ifResult = value1 >= value2; - // break; - - // case "is less than": - // //cdecValue1 = Convert.ToDecimal(value1); - // //cdecValue2 = Convert.ToDecimal(value2); - // //ifResult = (cdecValue1 < cdecValue2); - // ifResult = value1 < value2; - // break; - - // case "is less than or equal to": - // //cdecValue1 = Convert.ToDecimal(value1); - // //cdecValue2 = Convert.ToDecimal(value2); - // //ifResult = (cdecValue1 <= cdecValue2); - // ifResult = value1 <= value2; - // break; - // default: - // throw new Exception("Strange Operand " + param["Operand"]); - // break; - // } - // return ifResult; - //} - - //private bool DetermineStatementTruth_DateCompare(Engine.AutomationEngineInstance engine) - //{ - // //string value1 = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Value1" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - // //string operand = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Operand" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - // //string value2 = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Value2" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //value1 = value1.ConvertToUserVariable(sender); - // //value2 = value2.ConvertToUserVariable(sender); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value"); - - // string operand = param["Operand"].ConvertToUserVariable(engine); - - // DateTime dt1 = param["Value1"].ConvertToUserVariableAsDate("Value1", engine); - // DateTime dt2 = param["Value2"].ConvertToUserVariableAsDate("Value2", engine); - - // //DateTime dt1, dt2; - // //dt1 = DateTime.Parse(value1); - // //dt2 = DateTime.Parse(value2); - - // bool ifResult; - // switch (operand.ToLower()) - // { - // case "is equal to": - // ifResult = (dt1 == dt2); - // break; - - // case "is not equal to": - // ifResult = (dt1 != dt2); - // break; - - // case "is greater than": - // ifResult = (dt1 > dt2); - // break; - - // case "is greater than or equal to": - // ifResult = (dt1 >= dt2); - // break; - - // case "is less than": - // ifResult = (dt1 < dt2); - // break; - - // case "is less than or equal to": - // ifResult = (dt1 <= dt2); - // break; - - // default: - // throw new Exception("Strange Operand " + param["Operand"]); - // break; - // } - // return ifResult; - //} - - //private bool DetermineStatementTruth_VariableCompare(Engine.AutomationEngineInstance engine) - //{ - // //string value1 = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Value1" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - // //string operand = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Operand" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - // //string value2 = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Value2" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string caseSensitive = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Case Sensitive" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //value1 = value1.ConvertToUserVariable(sender); - // //value2 = value2.ConvertToUserVariable(sender); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value", engine); - - // //if (caseSensitive == "No") - // //{ - // // value1 = value1.ToUpper(); - // // value2 = value2.ToUpper(); - // //} - - // string value1 = param["Value1"]; - // string value2 = param["Value2"]; - // if (param["Case Sensitive"].ToLower() == "no") - // { - // value1 = value1.ToLower(); - // value2 = value2.ToLower(); - // } - - // bool ifResult; - // switch (param["Operand"].ToLower()) - // { - // case "contains": - // ifResult = (value1.Contains(value2)); - // break; - - // case "does not contain": - // ifResult = (!value1.Contains(value2)); - // break; - - // case "is equal to": - // ifResult = (value1 == value2); - // break; - - // case "is not equal to": - // ifResult = (value1 != value2); - // break; - - // default: - // throw new Exception("Strange Operand " + param["Operand"]); - // break; - // } - // return ifResult; - //} - - //private bool DetermineStatementTruth_VariableHasValue(Engine.AutomationEngineInstance engine) - //{ - // //string variableName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Variable Name" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //var actualVariable = variableName.ConvertToUserVariable(sender).Trim(); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value", engine); - - // string actualVariable = param["Variable Name"].Trim(); - - // //if (!string.IsNullOrEmpty(actualVariable)) - // //{ - // // ifResult = true; - // //} - // //else - // //{ - // // ifResult = false; - // //} - - // return (!string.IsNullOrEmpty(actualVariable)); - //} - - //private bool DetermineStatementTruth_VariableIsNumeric(Engine.AutomationEngineInstance engine) - //{ - // //string variableName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Variable Name" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //var actualVariable = variableName.ConvertToUserVariable(sender).Trim(); - - // var dic = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value", engine); - - // var numericTest = decimal.TryParse(dic["Variable Name"], out decimal parsedResult); - - // //if (numericTest) - // //{ - // // ifResult = true; - // //} - // //else - // //{ - // // ifResult = false; - // //} - // return numericTest; - //} - - //private bool DetermineStatementTruth_ErrorOccur(Engine.AutomationEngineInstance engine, bool inverseResult = false) - //{ - // ////get line number - // //string userLineNumber = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Line Number" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // ////convert to variable - // //string variableLineNumber = userLineNumber.ConvertToUserVariable(sender); - - // ////convert to int - // //int lineNumber = int.Parse(variableLineNumber); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value"); - // int lineNumber = param["Line Number"].ConvertToUserVariableAsInteger("Line Number", engine); - - // bool result; - - // ////determine if error happened - // //if (engine.ErrorsOccured.Where(f => f.LineNumber == lineNumber).Count() == 0) - // //{ - // // result = true; - // //} - // //else - // //{ - // // var error = engine.ErrorsOccured.Where(f => f.LineNumber == lineNumber).FirstOrDefault(); - // // error.ErrorMessage.StoreInUserVariable(engine, "Error.Message"); - // // error.LineNumber.ToString().StoreInUserVariable(engine, "Error.Line"); - // // error.StackTrace.StoreInUserVariable(engine, "Error.StackTrace"); - - // // result = false; - // //} - - // //determine if error happened - // if (engine.ErrorsOccured.Where(f => f.LineNumber == lineNumber).Count() > 0) - // { - - // var error = engine.ErrorsOccured.Where(f => f.LineNumber == lineNumber).FirstOrDefault(); - // error.ErrorMessage.StoreInUserVariable(engine, "Error.Message"); - // error.LineNumber.ToString().StoreInUserVariable(engine, "Error.Line"); - // error.StackTrace.StoreInUserVariable(engine, "Error.StackTrace"); - - // result = true; - // } - // else - // { - // result = false; - // } - - // return inverseResult ? !result : result; - //} - //private bool DetermineStatementTruth_WindowNameExists(Engine.AutomationEngineInstance engine) - //{ - // ////get user supplied name - // //string windowName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Window Name" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - // ////variable translation - // //string variablizedWindowName = windowName.ConvertToUserVariable(sender); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value", engine); - - // //search for window - // IntPtr windowPtr = User32Functions.FindWindow(param["Window Name"]); - - // ////conditional - // //if (windowPtr != IntPtr.Zero) - // //{ - // // ifResult = true; - // //} - // return (windowPtr != IntPtr.Zero); - //} - //private bool DetermineStatementTruth_ActiveWindow(Engine.AutomationEngineInstance engine) - //{ - // //string windowName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Window Name" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string variablizedWindowName = windowName.ConvertToUserVariable(sender); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value", engine); - - // var currentWindowTitle = User32Functions.GetActiveWindowTitle(); - - // //if (currentWindowTitle == variablizedWindowName) - // //{ - // // ifResult = true; - // //} - // return (currentWindowTitle == param["Window Name"]); - //} - //private bool DetermineStatementTruth_File(Engine.AutomationEngineInstance engine) - //{ - // //string fileName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "File Path" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string trueWhenFileExists = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "True When" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value", engine); - - // //var userFileSelected = fileName.ConvertToUserVariable(sender); - - // //bool existCheck = false; - // //if (trueWhenFileExists == "It Does Exist") - // //{ - // // existCheck = true; - // //} - - - // //if (System.IO.File.Exists(userFileSelected) == existCheck) - // //{ - // // ifResult = true; - // //} - - // bool existCheck = System.IO.File.Exists(param["File Path"]); - // switch (param["True When"].ToLower()) - // { - // case "it does exist": - // return existCheck; - // break; - - // case "it does not exist": - // return !existCheck; - // break; - - // default: - // throw new Exception("True When is strange value " + param["True When"]); - // break; - // } - //} - //private bool DetermineStatementTruth_Folder(Engine.AutomationEngineInstance engine) - //{ - // //string folderName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Folder Path" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string trueWhenFileExists = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "True When" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value", engine); - - // //var userFolderSelected = folderName.ConvertToUserVariable(sender); - - // //bool existCheck = false; - // //if (trueWhenFileExists == "It Does Exist") - // //{ - // // existCheck = true; - // //} - - - // //if (System.IO.Directory.Exists(folderName) == existCheck) - // //{ - // // ifResult = true; - // //} - - // bool existCheck = System.IO.Directory.Exists(param["Folder Path"]); - // switch(param["True When"].ToLower()) - // { - // case "it does exist": - // return existCheck; - // break; - - // case "it does not exist": - // return !existCheck; - // break; - - // default: - // throw new Exception("True When is strange value " + param["True When"]); - // break; - // } - //} - - //private bool DetermineStatementTruth_WebElement(Engine.AutomationEngineInstance engine) - //{ - // //string instanceName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Selenium Instance Name" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string parameterName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Element Search Parameter" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string searchMethod = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Element Search Method" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value", engine); - - // SeleniumBrowserElementActionCommand newElementActionCommand = new SeleniumBrowserElementActionCommand(); - // newElementActionCommand.v_SeleniumSearchType = param["Element Search Method"]; - // newElementActionCommand.v_InstanceName = param["Selenium Instance Name"]; - // bool elementExists = newElementActionCommand.ElementExists(engine, param["Element Search Method"], param["Element Search Parameter"]); - // return elementExists; - //} - - //private bool DetermineStatementTruth_GUIElement(Engine.AutomationEngineInstance engine) - //{ - // //string windowName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Window Name" - // // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender)); - - // //string elementSearchParam = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Element Search Parameter" - // // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender)); - - // //string elementSearchMethod = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Element Search Method" - // // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender)); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value", engine); - // string windowName = param["Window Name"]; - - // if (windowName == engine.engineSettings.CurrentWindowKeyword) - // { - // windowName = User32Functions.GetActiveWindowTitle(); - // } - - // UIAutomationCommand newUIACommand = new UIAutomationCommand(); - // newUIACommand.v_WindowName = windowName; - // newUIACommand.v_UIASearchParameters.Rows.Add(true, param["Element Search Method"], param["Element Search Parameter"]); - // var handle = newUIACommand.SearchForGUIElement(engine, windowName); - - // //if (handle is null) - // //{ - // // ifResult = false; - // //} - // //else - // //{ - // // ifResult = true; - // //} - // return !(handle is null); - //} - //private bool DetermineStatementTruth_Boolean(Engine.AutomationEngineInstance engine) - //{ - // //string value = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Variable Name" - // // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender)); - - // //string compare = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Value Is" - // // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender)); - - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value"); - - // bool value = param["Variable Name"].ConvertToUserVariableAsBool("Variable Name", engine); - // string compare = param["Value Is"].ConvertToUserVariable(engine); - - // switch (compare.ToLower()) - // { - // case "true": - // return value; - // break; - // case "false": - // return !value; - // break; - // default: - // throw new Exception("Value Is " + param["Value Is"] + " is not support."); - // break; - // } - //} - - - public override List Render(frmCommandEditor editor) + + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -906,11 +209,11 @@ public override List Render(frmCommandEditor editor) return RenderedControls; } - private void linkWebBrowserInstanceSelector_Click(object sender, EventArgs e, frmCommandEditor editor) + private void linkWebBrowserInstanceSelector_Click(object sender, EventArgs e, UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var instances = editor.instanceList.getInstanceClone(Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.WebBrowser); - using (var frm = new UI.Forms.Supplemental.frmItemSelector(instances.Keys.ToList())) + using (var frm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmItemSelector(instances.Keys.ToList())) { if (frm.ShowDialog() == DialogResult.OK) { @@ -923,24 +226,26 @@ private void linkWebBrowserInstanceSelector_Click(object sender, EventArgs e, fr } } - private void linkWindowNameSelector_Click(object sender, EventArgs e, frmCommandEditor editor) + private void linkWindowNameSelector_Click(object sender, EventArgs e, UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - List windowNames = new List(); - - windowNames.Add(editor.appSettings.EngineSettings.CurrentWindowKeyword); + List windowNames = new List + { + //editor.appSettings.EngineSettings.CurrentWindowKeyword + VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Window_CurrentWindowName.VariableName, editor.appSettings), + }; System.Diagnostics.Process[] processlist = System.Diagnostics.Process.GetProcesses(); //pull the main window title for each foreach (var process in processlist) { - if (!String.IsNullOrEmpty(process.MainWindowTitle)) + if (!string.IsNullOrEmpty(process.MainWindowTitle)) { //add to the control list of available windows windowNames.Add(process.MainWindowTitle); } } - using (var frm = new UI.Forms.Supplemental.frmItemSelector(windowNames)) + using (var frm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmItemSelector(windowNames)) { if (frm.ShowDialog() == DialogResult.OK) { @@ -953,11 +258,11 @@ private void linkWindowNameSelector_Click(object sender, EventArgs e, frmCommand } } - private void linkBooleanInstanceSelector_Click(object sender, EventArgs e, frmCommandEditor editor) + private void linkBooleanInstanceSelector_Click(object sender, EventArgs e, UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var instances = editor.instanceList.getInstanceClone(Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Boolean); - using (var frm = new UI.Forms.Supplemental.frmItemSelector(instances.Keys.ToList())) + using (var frm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmItemSelector(instances.Keys.ToList())) { if (frm.ShowDialog() == DialogResult.OK) { @@ -985,12 +290,12 @@ private void linkBooleanInstanceSelector_Click(object sender, EventArgs e, frmCo } } - private void ifAction_SelectionChangeCommitted(object sender, EventArgs e, frmCommandEditor editor) + private void ifAction_SelectionChangeCommitted(object sender, EventArgs e, UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { ComboBox ifAction = (ComboBox)ActionDropdown; DataGridView ifActionParameterBox = (DataGridView)IfGridViewHelper; - Core.Automation.Commands.BeginIfCommand cmd = (Core.Automation.Commands.BeginIfCommand)this; + BeginIfCommand cmd = (BeginIfCommand)this; DataTable actionParameters = cmd.v_IfActionParameterTable; //sender is null when command is updating @@ -999,17 +304,6 @@ private void ifAction_SelectionChangeCommitted(object sender, EventArgs e, frmCo actionParameters.Rows.Clear(); } - //DataGridViewComboBoxCell comparisonComboBox = new DataGridViewComboBoxCell(); - - //recorder control - //Control recorderControl = (Control)RecorderControl; - - //remove if exists - //if (RecorderControl.Visible) - //{ - // RecorderControl.Hide(); - //} - lnkBrowserInstanceSelector.Hide(); lnkWindowNameSelector.Hide(); lnkBooleanSelector.Hide(); @@ -1089,433 +383,12 @@ private void ifAction_SelectionChangeCommitted(object sender, EventArgs e, frmCo } } - //private void RenderValueCompare(object sender, DataGridView ifActionParameterBox, DataTable actionParameters) - //{ - // ifActionParameterBox.Visible = true; - - // if (sender != null) - // { - // actionParameters.Rows.Add("Value1", ""); - // actionParameters.Rows.Add("Operand", ""); - // actionParameters.Rows.Add("Value2", ""); - // ifActionParameterBox.DataSource = actionParameters; - // } - - // //combobox cell for Variable Name - // DataGridViewComboBoxCell comparisonComboBox = new DataGridViewComboBoxCell(); - // comparisonComboBox.Items.Add("is equal to"); - // comparisonComboBox.Items.Add("is greater than"); - // comparisonComboBox.Items.Add("is greater than or equal to"); - // comparisonComboBox.Items.Add("is less than"); - // comparisonComboBox.Items.Add("is less than or equal to"); - // comparisonComboBox.Items.Add("is not equal to"); - - // //assign cell as a combobox - // ifActionParameterBox.Rows[1].Cells[1] = comparisonComboBox; - //} - - //private void RenderVariableCompare(object sender, DataGridView ifActionParameterBox, DataTable actionParameters) - //{ - // ifActionParameterBox.Visible = true; - - // if (sender != null) - // { - // actionParameters.Rows.Add("Value1", ""); - // actionParameters.Rows.Add("Operand", ""); - // actionParameters.Rows.Add("Value2", ""); - // actionParameters.Rows.Add("Case Sensitive", "No"); - // ifActionParameterBox.DataSource = actionParameters; - // } - - // //combobox cell for Variable Name - // DataGridViewComboBoxCell comparisonComboBox = new DataGridViewComboBoxCell(); - // comparisonComboBox.Items.Add("contains"); - // comparisonComboBox.Items.Add("does not contain"); - // comparisonComboBox.Items.Add("is equal to"); - // comparisonComboBox.Items.Add("is not equal to"); - - // //assign cell as a combobox - // ifActionParameterBox.Rows[1].Cells[1] = comparisonComboBox; - - // DataGridViewComboBoxCell caseSensitiveComboBox = new DataGridViewComboBoxCell(); - // caseSensitiveComboBox.Items.Add("Yes"); - // caseSensitiveComboBox.Items.Add("No"); - - // //assign cell as a combobox - // ifActionParameterBox.Rows[3].Cells[1] = caseSensitiveComboBox; - //} - - //private void RenderVariableIsHas(object sender, DataGridView ifActionParameterBox, DataTable actionParameters) - //{ - // ifActionParameterBox.Visible = true; - // if (sender != null) - // { - // actionParameters.Rows.Add("Variable Name", ""); - // ifActionParameterBox.DataSource = actionParameters; - // } - //} - - //private void RenderErrorOccur(object sender, DataGridView ifActionParameterBox, DataTable actionParameters) - //{ - // ifActionParameterBox.Visible = true; - // if (sender != null) - // { - // actionParameters.Rows.Add("Line Number", ""); - // ifActionParameterBox.DataSource = actionParameters; - // } - //} - - //private void RenderWindowName(object sender, DataGridView ifActionParameterBox, DataTable actionParameters) - //{ - // ifActionParameterBox.Visible = true; - // if (sender != null) - // { - // actionParameters.Rows.Add("Window Name", ""); - // ifActionParameterBox.DataSource = actionParameters; - // } - //} - - //private void RenderFileExists(object sender, DataGridView ifActionParameterBox, DataTable actionParameters) - //{ - // ifActionParameterBox.Visible = true; - // if (sender != null) - // { - // actionParameters.Rows.Add("File Path", ""); - // actionParameters.Rows.Add("True When", "It Does Exist"); - // ifActionParameterBox.DataSource = actionParameters; - // } - - // //combobox cell for Variable Name - // DataGridViewComboBoxCell comparisonComboBox = new DataGridViewComboBoxCell(); - // comparisonComboBox.Items.Add("It Does Exist"); - // comparisonComboBox.Items.Add("It Does Not Exist"); - - // //assign cell as a combobox - // ifActionParameterBox.Rows[1].Cells[1] = comparisonComboBox; - //} - - //private void RenderFolderExists(object sender, DataGridView ifActionParameterBox, DataTable actionParameters) - //{ - // ifActionParameterBox.Visible = true; - - // if (sender != null) - // { - // actionParameters.Rows.Add("Folder Path", ""); - // actionParameters.Rows.Add("True When", "It Does Exist"); - // ifActionParameterBox.DataSource = actionParameters; - // } - - // //combobox cell for Variable Name - // DataGridViewComboBoxCell comparisonComboBox = new DataGridViewComboBoxCell(); - // comparisonComboBox.Items.Add("It Does Exist"); - // comparisonComboBox.Items.Add("It Does Not Exist"); - - // //assign cell as a combobox - // ifActionParameterBox.Rows[1].Cells[1] = comparisonComboBox; - //} - - //private void RenderWebElement(object sender, DataGridView ifActionParameterBox, DataTable actionParameters, frmCommandEditor editor) - //{ - // ifActionParameterBox.Visible = true; - - // if (sender != null) - // { - // actionParameters.Rows.Add("Selenium Instance Name", editor.appSettings.ClientSettings.DefaultBrowserInstanceName); - // actionParameters.Rows.Add("Element Search Method", ""); - // actionParameters.Rows.Add("Element Search Parameter", ""); - // ifActionParameterBox.DataSource = actionParameters; - // } - - // DataGridViewComboBoxCell comparisonComboBox = new DataGridViewComboBoxCell(); - // comparisonComboBox.Items.Add("Find Element By XPath"); - // comparisonComboBox.Items.Add("Find Element By ID"); - // comparisonComboBox.Items.Add("Find Element By Name"); - // comparisonComboBox.Items.Add("Find Element By Tag Name"); - // comparisonComboBox.Items.Add("Find Element By Class Name"); - // comparisonComboBox.Items.Add("Find Element By CSS Selector"); - - // //assign cell as a combobox - // ifActionParameterBox.Rows[1].Cells[1] = comparisonComboBox; - //} - - //private void RenderGUIElement(object sender, DataGridView ifActionParameterBox, DataTable actionParameters, frmCommandEditor editor) - //{ - // ifActionParameterBox.Visible = true; - // if (sender != null) - // { - // actionParameters.Rows.Add("Window Name", editor.appSettings.EngineSettings.CurrentWindowKeyword); - // actionParameters.Rows.Add("Element Search Method", ""); - // actionParameters.Rows.Add("Element Search Parameter", ""); - // ifActionParameterBox.DataSource = actionParameters; - // } - - // var parameterName = new DataGridViewComboBoxCell(); - // parameterName.Items.Add("AcceleratorKey"); - // parameterName.Items.Add("AccessKey"); - // parameterName.Items.Add("AutomationId"); - // parameterName.Items.Add("ClassName"); - // parameterName.Items.Add("FrameworkId"); - // parameterName.Items.Add("HasKeyboardFocus"); - // parameterName.Items.Add("HelpText"); - // parameterName.Items.Add("IsContentElement"); - // parameterName.Items.Add("IsControlElement"); - // parameterName.Items.Add("IsEnabled"); - // parameterName.Items.Add("IsKeyboardFocusable"); - // parameterName.Items.Add("IsOffscreen"); - // parameterName.Items.Add("IsPassword"); - // parameterName.Items.Add("IsRequiredForForm"); - // parameterName.Items.Add("ItemStatus"); - // parameterName.Items.Add("ItemType"); - // parameterName.Items.Add("LocalizedControlType"); - // parameterName.Items.Add("Name"); - // parameterName.Items.Add("NativeWindowHandle"); - // parameterName.Items.Add("ProcessID"); - - // //assign cell as a combobox - // ifActionParameterBox.Rows[1].Cells[1] = parameterName; - - // //RecorderControl.Show(); - //} - - //private void RenderBoolean(object sender, DataGridView ifActionParameterBox, DataTable actionParameters) - //{ - // ifActionParameterBox.Visible = true; - // if (sender != null) - // { - // actionParameters.Rows.Add("Variable Name", ""); - // actionParameters.Rows.Add("Value Is", "True"); - // ifActionParameterBox.DataSource = actionParameters; - // } - // //assign cell as a combobox - // DataGridViewComboBoxCell booleanParam = new DataGridViewComboBoxCell(); - // booleanParam.Items.Add("True"); - // booleanParam.Items.Add("False"); - // ifActionParameterBox.Rows[1].Cells[1] = booleanParam; - - // //RecorderControl.Show(); - //} - - //private void ShowIfElementRecorder(object sender, EventArgs e) - //{ - // //get command reference - // Core.Automation.Commands.UIAutomationCommand cmd = new Core.Automation.Commands.UIAutomationCommand(); - - // //create recorder - // UI.Forms.Supplemental.frmThickAppElementRecorder newElementRecorder = new UI.Forms.Supplemental.frmThickAppElementRecorder(); - // newElementRecorder.searchParameters = cmd.v_UIASearchParameters; - - // //show form - // newElementRecorder.ShowDialog(); - - - // var sb = new StringBuilder(); - // sb.AppendLine("Element Properties Found!"); - // sb.AppendLine(Environment.NewLine); - // sb.AppendLine("Element Search Method - Element Search Parameter"); - // foreach (DataRow rw in cmd.v_UIASearchParameters.Rows) - // { - // if (rw.ItemArray[2].ToString().Trim() == string.Empty) - // continue; - - // sb.AppendLine(rw.ItemArray[1].ToString() + " - " + rw.ItemArray[2].ToString()); - // } - - // DataGridView ifActionBox = IfGridViewHelper; - // ifActionBox.Rows[0].Cells[1].Value = newElementRecorder.cboWindowTitle.Text; - - // MessageBox.Show(sb.ToString()); - //} public override string GetDisplayValue() { - //var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value"); - - //switch (v_IfActionType) - //{ - // //case "Value": - // case "Numeric Compare": - // case "Date Compare": - // //case "Variable Compare": - // case "Text Compare": - // case "Boolean Compare": - // //string value1 = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Value1" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - // //string operand = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Operand" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - // //string value2 = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Value2" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //return "If ([" + v_IfActionType + "] " + value1 + " " + operand + " " + value2 + ")"; - // return "If ([" + v_IfActionType + "] " + param["Value1"] + " " + param["Operand"] + " " + param["Value2"] + ")"; - // break; - - // case "Variable Has Value": - // //string variableName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Variable Name" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //return "If (Variable " + variableName + " Has Value)"; - // return "If (Variable " + param["Variable Name"] + " Has Value)"; - // break; - - // case "Variable Is Numeric": - // //string varName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Variable Name" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //return "If (Variable " + varName + " Is Numeric)"; - // return "If (Variable " + param["Variable Name"] + " Is Numeric)"; - // break; - - // case "Error Occured": - // //string lineNumber = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Line Number" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //return "If (Error Occured on Line Number " + lineNumber + ")"; - // return "If (Error Occured on Line Number " + param["Line Number"] + ")"; - // break; - - - // case "Error Did Not Occur": - // //string lineNum = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Line Number" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //return "If (Error Did Not Occur on Line Number " + lineNum + ")"; - // return "If (Error Did Not Occur on Line Number " + param["Line Number"] + ")"; - // break; - - // case "Window Name Exists": - // case "Active Window Name Is": - // //string windowName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Window Name" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //return "If " + v_IfActionType + " [Name: " + windowName + "]"; - // return "If " + v_IfActionType + " [Name: " + param["Window Name"] + "]"; - // break; - - // case "File Exists": - // //string filePath = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "File Path" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string fileCompareType = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "True When" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - - // //return "If " + v_IfActionType + " [File: " + filePath + "]"; - // return "If " + v_IfActionType + " [File: " + param["File Path"] + "]"; - // break; - - - // case "Folder Exists": - // //string folderPath = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Folder Path" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string folderCompareType = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "True When" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - - // //return "If " + v_IfActionType + " [Folder: " + folderPath + "]"; - // return "If " + v_IfActionType + " [Folder: " + param["Folder Path"] + "]"; - // break; - - - // case "Web Element Exists": - // //string parameterName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Element Search Parameter" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string searchMethod = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Element Search Method" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //return "If Web Element Exists [" + searchMethod + ": " + parameterName + "]"; - // return "If Web Element Exists [" + param["Element Search Method"] + ": " + param["Element Search Parameter"] + "]"; - // break; - - // case "GUI Element Exists": - // //string guiWindowName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Window Name" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string guiSearch = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Element Search Parameter" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //return "If GUI Element Exists [Find " + guiSearch + " Element In " + guiWindowName + "]"; - // return "If GUI Element Exists [Find " + param["Element Search Parameter"] + " Element In " + param["Window Name"] + "]"; - // break; - - // case "Boolean": - // //string booleanVariable = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Variable Name" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //string compareTo = ((from rw in v_IfActionParameterTable.AsEnumerable() - // // where rw.Field("Parameter Name") == "Value Is" - // // select rw.Field("Parameter Value")).FirstOrDefault()); - // //return "If [Boolean] " + booleanVariable + " is " + compareTo; - // return "If [Boolean] " + param["Variable Name"] + " is " + param["Value Is"]; - // break; - - // case "List Compare": - // //var paramList = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value"); - // return "If [List Compare] '" + param["List1"] + "' and '" + param["List2"] + "'"; - - // case "Dictionary Compare": - // //var paramDic = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value"); - // return "If [Dictionary Compare] '" + param["Dictionary1"] + "' and '" + param["Dictionary2"] + "'"; - - // case "DataTable Compare": - // //var paramDT = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value"); - // return "If [DataTable Compare] '" + param["DataTable1"] + "' and '" + param["DataTable2"] + "'"; - - // default: - // return "If .... "; - //} - return ConditionControls.GetDisplayValue("If", v_IfActionType, v_IfActionParameterTable); } - //private void IfGridViewHelper_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) - //{ - // if (e.ColumnIndex == 0) - // { - // e.Cancel = true; - // } - //} - //private void IfGridViewHelper_CellClick(object sender, DataGridViewCellEventArgs e) - //{ - // if (e.ColumnIndex >= 0) - // { - // if (e.ColumnIndex == 1) - // { - // var targetCell = IfGridViewHelper.Rows[e.RowIndex].Cells[1]; - // if (targetCell is DataGridViewTextBoxCell) - // { - // IfGridViewHelper.BeginEdit(false); - // } - // else if (targetCell is DataGridViewComboBoxCell && targetCell.Value.ToString() == "") - // { - // SendKeys.Send("{F4}"); - // } - // } - // } - // else - // { - // IfGridViewHelper.EndEdit(); - // } - //} - - public override bool IsValidate(frmCommandEditor editor) + public override bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.IsValidate(editor); @@ -1605,188 +478,7 @@ public override bool IsValidate(frmCommandEditor editor) return this.IsValid; } - //private void ValueValidate() - //{ - // string operand = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Operand" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // if (String.IsNullOrEmpty(operand)) - // { - // this.validationResult += "Operand is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void VariableValidate() - //{ - // string v = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Variable Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // if (String.IsNullOrEmpty(v)) - // { - // this.validationResult += "Variable Name is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void WindowValidate() - //{ - // string windowName = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Window Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // if (String.IsNullOrEmpty(windowName)) - // { - // this.validationResult += "Window Name is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void FileValidate() - //{ - // string fp = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "File Path" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // if (String.IsNullOrEmpty(fp)) - // { - // this.validationResult += "File Path is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void FoloderValidate() - //{ - // string fp = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Folder Path" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // if (String.IsNullOrEmpty(fp)) - // { - // this.validationResult += "Folder Path is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void WebValidate() - //{ - // string instance = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Selenium Instance Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string method = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Method" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string param = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Parameter" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // if (String.IsNullOrEmpty(instance)) - // { - // this.validationResult += "Browser Instance Name (Selenium Insntance) is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(method)) - // { - // this.validationResult += "Search Method is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(param)) - // { - // this.validationResult += "Search Parameter is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void GUIValidate() - //{ - // string window = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Window Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string method = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Method" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string param = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Parameter" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // if (String.IsNullOrEmpty(window)) - // { - // this.validationResult += "Window Name is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(method)) - // { - // this.validationResult += "Search Method is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(param)) - // { - // this.validationResult += "Search Parameter is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void ErrorValidate() - //{ - // string line = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Line Number" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // if (String.IsNullOrEmpty(line)) - // { - // this.validationResult += "Line Number is empty.\n"; - // this.IsValid = false; - // } - // else - // { - // int vLine; - // if (int.TryParse(line, out vLine)) - // { - // if (vLine < 1) - // { - // this.validationResult += "Specify 1 or more to Line Number.\n"; - // this.IsValid = false; - // } - // } - // } - //} - - //private void BooleanValidate() - //{ - // string variable = ((from rw in v_IfActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Variable Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // if (String.IsNullOrEmpty(variable)) - // { - // this.validationResult += "Variable is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void BooleanCompareValidate() - //{ - // var param = DataTableControls.GetFieldValues(v_IfActionParameterTable, "Parameter Name", "Parameter Value"); - - // if (String.IsNullOrEmpty(param["Value1"])) - // { - // this.validationResult += "Value1 is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(param["Value2"])) - // { - // this.validationResult += "Value2 is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(param["Operand"])) - // { - // this.validationResult += "Operand is empty.\n"; - // this.IsValid = false; - // } - //} - - public override void ConvertToIntermediate(EngineSettings settings, List variables) + public override void ConvertToIntermediate(EngineSettings settings, List variables) { if (this.v_IfActionType == "GUI Element Exists") { @@ -1813,5 +505,13 @@ public override void ConvertToRaw(EngineSettings settings) base.ConvertToRaw(settings); } } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + //var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_IfActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(IfGridViewHelper, v_IfActionParameterTable); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/If/BeginMutliIfCommand.cs b/taskt/Core/Automation/Commands/If/BeginMutliIfCommand.cs index a065acae0..4d1a5cb6f 100644 --- a/taskt/Core/Automation/Commands/If/BeginMutliIfCommand.cs +++ b/taskt/Core/Automation/Commands/If/BeginMutliIfCommand.cs @@ -4,17 +4,17 @@ using System.Data; using System.Collections.Generic; using System.Windows.Forms; -using taskt.UI.Forms; using taskt.UI.CustomControls; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("If Commands")] + [Attributes.ClassAttributes.Group("If")] [Attributes.ClassAttributes.Description("This command allows you to evaluate a logical statement to determine if the statement is true.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check if a statement is 'true' or 'false' and subsequently take an action based on either condition. Any 'BeginIf' command must have a following 'EndIf' command.")] [Attributes.ClassAttributes.ImplementationDescription("This command evaluates supplied arguments and if evaluated to true runs sub elements")] - public class BeginMultiIfCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_begin_multi_if))] + public sealed class BeginMultiIfCommand : ScriptCommand, IHaveDataTableElements, IHaveIfAdditionalCommands { [XmlElement] [Attributes.PropertyAttributes.PropertyDescription("Multiple If Conditions - All Must Be True")] @@ -50,10 +50,8 @@ public BeginMultiIfCommand() } - public override void RunCommand(object sender, Core.Script.ScriptAction parentCommand) + public override void RunCommand(Engine.AutomationEngineInstance engine, Core.Script.ScriptAction parentCommand) { - var engine = (Engine.AutomationEngineInstance)sender; - bool isTrueStatement = true; foreach (DataRow rw in v_IfConditionsTable.Rows) { @@ -115,7 +113,7 @@ public override void RunCommand(object sender, Core.Script.ScriptAction parentCo } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -169,12 +167,12 @@ private void IfConditionHelper_CellContentClick(object sender, DataGridViewCellE var ifCommand = Newtonsoft.Json.JsonConvert.DeserializeObject(commandData); - var automationCommands = taskt.UI.CustomControls.CommandControls.GenerateCommandsandControls().Where(f => f.Command is BeginIfCommand).ToList(); - frmCommandEditor editor = new frmCommandEditor(automationCommands, null); + var automationCommands = taskt.UI.CustomControls.CommandControls.GenerateCommandsAndControls().Where(f => f.Command is BeginIfCommand).ToList(); + var editor = new UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor(automationCommands, null); editor.selectedCommand = ifCommand; editor.editingCommand = ifCommand; editor.originalCommand = ifCommand; - editor.creationMode = frmCommandEditor.CreationMode.Edit; + editor.creationMode = UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Edit; editor.scriptVariables = ScriptVariables; editor.appSettings = this.appSetting; @@ -202,9 +200,9 @@ private void IfConditionHelper_CellContentClick(object sender, DataGridViewCellE private void CreateIfCondition(object sender, EventArgs e) { - var automationCommands = taskt.UI.CustomControls.CommandControls.GenerateCommandsandControls().Where(f => f.Command is BeginIfCommand).ToList(); + var automationCommands = taskt.UI.CustomControls.CommandControls.GenerateCommandsAndControls().Where(f => f.Command is BeginIfCommand).ToList(); - frmCommandEditor editor = new frmCommandEditor(automationCommands, null); + var editor = new UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor(automationCommands, null); editor.selectedCommand = new BeginIfCommand(); editor.appSettings = this.appSetting; var res = editor.ShowDialog(); diff --git a/taskt/Core/Automation/Commands/If/ElseCommand.cs b/taskt/Core/Automation/Commands/If/ElseCommand.cs index db27de06c..b5743d730 100644 --- a/taskt/Core/Automation/Commands/If/ElseCommand.cs +++ b/taskt/Core/Automation/Commands/If/ElseCommand.cs @@ -2,16 +2,16 @@ using System.Collections.Generic; using System.Windows.Forms; using taskt.UI.CustomControls; -using taskt.UI.Forms; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("If Commands")] + [Attributes.ClassAttributes.Group("If")] [Attributes.ClassAttributes.Description("This command declares the seperation between the actions based on the 'true' or 'false' condition.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to signify the exit point of your if scenario")] [Attributes.ClassAttributes.ImplementationDescription("TBD")] - public class ElseCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_else))] + public sealed class ElseCommand : ScriptCommand, IDelimitersOfStructuredCommands { public ElseCommand() { @@ -21,7 +21,7 @@ public ElseCommand() this.CommandEnabled = true; this.CustomRendering = true; } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); diff --git a/taskt/Core/Automation/Commands/If/EndIfCommand.cs b/taskt/Core/Automation/Commands/If/EndIfCommand.cs index 44858fb73..759c8782b 100644 --- a/taskt/Core/Automation/Commands/If/EndIfCommand.cs +++ b/taskt/Core/Automation/Commands/If/EndIfCommand.cs @@ -7,11 +7,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("If Commands")] + [Attributes.ClassAttributes.Group("If")] [Attributes.ClassAttributes.Description("This command signifies the exit point of If actions. Required for all Begin Ifs.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to signify the exit point of your if scenario")] [Attributes.ClassAttributes.ImplementationDescription("This command is used by the serializer to signify the end point of an if.")] - public class EndIfCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_end_if))] + public sealed class EndIfCommand : ScriptCommand, IEndOfStacturedCommand { public EndIfCommand() { @@ -21,7 +22,7 @@ public EndIfCommand() this.CommandEnabled = true; this.CustomRendering = true; } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); diff --git a/taskt/Core/Automation/Commands/If/IHaveIfAdditionalCommands.cs b/taskt/Core/Automation/Commands/If/IHaveIfAdditionalCommands.cs new file mode 100644 index 000000000..e215755b5 --- /dev/null +++ b/taskt/Core/Automation/Commands/If/IHaveIfAdditionalCommands.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// this command has Additional Commands for If (Condition) + /// + public interface IHaveIfAdditionalCommands : IHaveAdditionalCommands + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/Image/ExecuteOCRCommand.cs b/taskt/Core/Automation/Commands/Image/ExecuteOCRCommand.cs index bcfceae96..a7b08bc16 100644 --- a/taskt/Core/Automation/Commands/Image/ExecuteOCRCommand.cs +++ b/taskt/Core/Automation/Commands/Image/ExecuteOCRCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Image Commands")] + [Attributes.ClassAttributes.Group("Image")] [Attributes.ClassAttributes.CommandSettings("Execute OCR")] [Attributes.ClassAttributes.Description("This command allows you to covert an image file into text for parsing.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert an image into text. You can then use additional commands to parse the data.")] [Attributes.ClassAttributes.ImplementationDescription("This command has a dependency on and implements OneNote OCR to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_camera))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExecuteOCRCommand : ScriptCommand + public sealed class ExecuteOCRCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -41,10 +42,8 @@ public ExecuteOCRCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var filePath = FilePathControls.WaitForFile(this, nameof(v_FilePath), nameof(v_WaitForFile), engine); try diff --git a/taskt/Core/ImageRecognition.cs b/taskt/Core/Automation/Commands/Image/ImageRecognition.cs similarity index 74% rename from taskt/Core/ImageRecognition.cs rename to taskt/Core/Automation/Commands/Image/ImageRecognition.cs index dc738506f..0e7618428 100644 --- a/taskt/Core/ImageRecognition.cs +++ b/taskt/Core/Automation/Commands/Image/ImageRecognition.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Drawing; namespace taskt.Core { @@ -18,5 +13,4 @@ public class ImageRecognitionFingerPrint public int yLocation { get; set; } bool matchFound { get; set; } } - } diff --git a/taskt/Core/Automation/Commands/Image/ImageRecognitionCommand.cs b/taskt/Core/Automation/Commands/Image/ImageRecognitionCommand.cs index ae4e5824b..b66875c7f 100644 --- a/taskt/Core/Automation/Commands/Image/ImageRecognitionCommand.cs +++ b/taskt/Core/Automation/Commands/Image/ImageRecognitionCommand.cs @@ -1,23 +1,25 @@ using System; using System.Collections.Generic; -using System.Linq; -using System.Xml.Serialization; using System.Drawing; +using System.IO; +using System.Linq; using System.Windows.Forms; -using taskt.UI.Forms; -using taskt.UI.CustomControls; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.UI.CustomControls; +using taskt.UI.Forms.ScriptBuilder.CommandEditor; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Image Commands")] + [Attributes.ClassAttributes.Group("Image")] [Attributes.ClassAttributes.CommandSettings("Image Recognition")] [Attributes.ClassAttributes.Description("This command attempts to find an existing image on screen.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to attempt to locate an image on screen. You can subsequently take actions such as move the mouse to the location or perform a click. This command generates a fingerprint from the comparison image and searches for it in on the desktop.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_camera))] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ImageRecognitionCommand : ScriptCommand + public sealed class ImageRecognitionCommand : ScriptCommand { [XmlAttribute] [PropertyDescription("Please Specify the Search Image")] @@ -106,14 +108,12 @@ public ImageRecognitionCommand() //v_TimeoutSeconds = "30"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - bool testMode = TestMode; //user image to bitmap - Bitmap userImage = new Bitmap(Common.Base64ToImage(v_ImageCapture)); + Bitmap userImage = new Bitmap(ConvertBase64ToImage(v_ImageCapture)); //take screenshot Size shotSize = Screen.PrimaryScreen.Bounds.Size; @@ -167,7 +167,7 @@ public override void RunCommand(object sender) } //begin search - double timeoutSeconds = this.ConvertToUserVariableAsInteger(nameof(v_TimeoutSeconds), engine); + double timeoutSeconds = this.ExpandValueOrUserVariableAsInteger(nameof(v_TimeoutSeconds), engine); DateTime timeoutDue = DateTime.Now.AddSeconds(timeoutSeconds); bool imageFound = false; @@ -247,9 +247,9 @@ public override void RunCommand(object sender) screenShotUpdate.FillRectangle(brush, Rectangle); } - var xOffset = this.ConvertToUserVariableAsInteger(nameof(v_xOffsetAdjustment), engine); - var yOffset = this.ConvertToUserVariableAsInteger(nameof(v_YOffsetAdjustment), engine); - var mouseClick = this.GetUISelectionValue(nameof(v_MouseClick), engine); + var xOffset = this.ExpandValueOrUserVariableAsInteger(nameof(v_xOffsetAdjustment), engine); + var yOffset = this.ExpandValueOrUserVariableAsInteger(nameof(v_YOffsetAdjustment), engine); + var mouseClick = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_MouseClick), engine); //move mouse to position var mouseMove = new MoveMouseCommand @@ -289,7 +289,7 @@ public override void RunCommand(object sender) //screenShotUpdate.DrawImage(sampleOut, desktopOutput.Width - sampleOut.Width, 0); - UI.Forms.Supplement_Forms.frmImageCapture captureOutput = new UI.Forms.Supplement_Forms.frmImageCapture(); + var captureOutput = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmImageCapture(); captureOutput.pbTaggedImage.Image = sampleOut; captureOutput.pbSearchResult.Image = desktopOutput; captureOutput.Show(); @@ -319,18 +319,18 @@ private void ShowImageCapture(object sender, EventArgs e) HideAllForms(); //var userAcceptance = MessageBox.Show("The image capture process will now begin and display a screenshot of the current desktop in a custom full-screen window. You may stop the capture process at any time by pressing the 'ESC' key, or selecting 'Close' at the top left. Simply create the image by clicking once to start the rectangle and clicking again to finish. The image will be cropped to the boundary within the red rectangle. Shall we proceed?", "Image Capture", MessageBoxButtons.YesNo); - using (var fm = new UI.Forms.Supplemental.frmDialog("The image capture process will now begin and display a screenshot of the current desktop in a custom full-screen window.\nYou may stop the capture process at any time by pressing the 'ESC' key, or selecting 'Close' at the top left. Simply create the image by clicking once to start the rectangle and clicking again to finish.\nThe image will be cropped to the boundary within the red rectangle. Shall we proceed?", "Image Capture", UI.Forms.Supplemental.frmDialog.DialogType.YesNo, 0)) + using (var fm = new UI.Forms.General.frmDialog("The image capture process will now begin and display a screenshot of the current desktop in a custom full-screen window.\nYou may stop the capture process at any time by pressing the 'ESC' key, or selecting 'Close' at the top left. Simply create the image by clicking once to start the rectangle and clicking again to finish.\nThe image will be cropped to the boundary within the red rectangle. Shall we proceed?", "Image Capture", UI.Forms.General.frmDialog.DialogType.YesNo, 0)) { if (fm.ShowDialog() == DialogResult.OK) { - using (UI.Forms.Supplement_Forms.frmImageCapture imageCaptureForm = new UI.Forms.Supplement_Forms.frmImageCapture()) + using (var imageCaptureForm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmImageCapture()) { if (imageCaptureForm.ShowDialog() == DialogResult.OK) { var targetPictureBox = (UIPictureBox)((CommandItemControl)sender).Tag; targetPictureBox.Image = imageCaptureForm.userSelectedBitmap; - var convertedImage = Common.ImageToBase64(imageCaptureForm.userSelectedBitmap); + var convertedImage = ConvertImageToBase64(imageCaptureForm.userSelectedBitmap); var convertedLength = convertedImage.Length; targetPictureBox.EncodedImage = convertedImage; @@ -365,7 +365,7 @@ private void RunImageCapture(object sender, EventArgs e) // image is empty if (string.IsNullOrEmpty(imageSource)) { - using (var fm = new UI.Forms.Supplemental.frmDialog("Please capture an image before attempting to test!", "Image Recognition", UI.Forms.Supplemental.frmDialog.DialogType.OkOnly, 0)) + using (var fm = new UI.Forms.General.frmDialog("Please capture an image before attempting to test!", "Image Recognition", UI.Forms.General.frmDialog.DialogType.OkOnly, 0)) { fm.ShowDialog(); return; @@ -387,7 +387,7 @@ private void RunImageCapture(object sender, EventArgs e) } catch (Exception ex) { - using (var fm = new UI.Forms.Supplemental.frmDialog("Error: " + ex.Message, "Image Recognition", UI.Forms.Supplemental.frmDialog.DialogType.OkOnly, 0)) + using (var fm = new UI.Forms.General.frmDialog("Error: " + ex.Message, "Image Recognition", UI.Forms.General.frmDialog.DialogType.OkOnly, 0)) { fm.ShowDialog(); } @@ -411,7 +411,7 @@ private static void HideAllForms() } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -433,5 +433,42 @@ public override List Render(frmCommandEditor editor) return RenderedControls; } + + public override void AfterShown(frmCommandEditor editor) + { + if (!string.IsNullOrEmpty(v_ImageCapture)) + { + //var pic = ControlsList.GetPropertyControl(nameof(v_ImageCapture)); + //pic.Image = Common.Base64ToImage(v_ImageCapture); + var ctrls = editor.flw_InputVariables.Controls; + foreach(var c in ctrls) + { + if (c is UIPictureBox pic) + { + pic.Image = ConvertBase64ToImage(v_ImageCapture); + } + } + } + } + + private static string ConvertImageToBase64(Image image) + { + using (MemoryStream m = new MemoryStream()) + { + image.Save(m, System.Drawing.Imaging.ImageFormat.Bmp); + byte[] imageBytes = m.ToArray(); + var base64String = Convert.ToBase64String(imageBytes); + return base64String; + } + } + + private static Image ConvertBase64ToImage(string base64String) + { + byte[] imageBytes = Convert.FromBase64String(base64String); + MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); + ms.Write(imageBytes, 0, imageBytes.Length); + Image image = Image.FromStream(ms, true); + return image; + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Image/TakeScreenshotCommand.cs b/taskt/Core/Automation/Commands/Image/TakeScreenshotCommand.cs index 05d0f2c34..599fcca26 100644 --- a/taskt/Core/Automation/Commands/Image/TakeScreenshotCommand.cs +++ b/taskt/Core/Automation/Commands/Image/TakeScreenshotCommand.cs @@ -1,26 +1,27 @@ using System; using System.Windows.Forms; using System.Xml.Serialization; -using taskt.UI.Forms; +using System.Collections.Generic; using taskt.UI.CustomControls; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Image Commands")] + [Attributes.ClassAttributes.Group("Image")] [Attributes.ClassAttributes.CommandSettings("Take Screenshot")] [Attributes.ClassAttributes.Description("This command takes a screenshot and saves it to a location")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to take and save a screenshot.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements User32 CaptureWindow to achieve automation")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_camera))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class TakeScreenshotCommand : ScriptCommand + public sealed class TakeScreenshotCommand : ScriptCommand { [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowName))] [PropertyIsWindowNamesList(true, true, false, true)] - public string v_ScreenshotWindowName { get; set; } + public string v_WindowName { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_FilePath))] @@ -33,21 +34,45 @@ public class TakeScreenshotCommand : ScriptCommand public string v_FilePath { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Activate Window Before Capture")] + [PropertyIsOptional(true, "No")] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + public string v_ActivateWindowBeforeCapture { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Wait Time before Capture")] + [PropertyIsOptional(true, "500")] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] + [PropertyFirstValue("500")] + public string v_WaitTimeBeforeCapture { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_CompareMethod))] + public string v_CompareMethod { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] public string v_MatchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_TargetWindowIndex))] public string v_TargetWindowIndex { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitForWindow { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + public string v_WaitTimeForWindow { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowNameResult))] + public string v_NameResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_HandleResult { get; set; } public TakeScreenshotCommand() { @@ -57,39 +82,59 @@ public TakeScreenshotCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //string targetWindowName; + //if (v_WindowName == "Desktop") + //{ + // targetWindowName = "Desktop"; + //} + //else + //{ + // var wins = WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitForWindow), engine); + // targetWindowName = wins[0].Item2; + //} + + ////var image = User32Functions.CaptureWindow(targetWindowName); + //var image = WindowNameControls.CaptureWindow(targetWindowName, engine); + + //var outputFile = this.ExpandValueOrUserVariableAsFilePath(nameof(v_FilePath), engine); + + //image.Save(outputFile); - string targetWindowName; - if (v_ScreenshotWindowName == "Desktop") - { - targetWindowName = "Desktop"; - } - else - { - var wins = WindowNameControls.FindWindows(this, nameof(v_ScreenshotWindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitForWindow), engine); - targetWindowName = wins[0].Item2; - } + WindowControls.WindowAction(this, engine, + new Action>(wins => + { + var whnd = wins[0].Item1; - //var image = User32Functions.CaptureWindow(targetWindowName); - var image = WindowNameControls.CaptureWindow(targetWindowName, engine); + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ActivateWindowBeforeCapture), engine)) + { + WindowControls.ActivateWindow(whnd); + } - var outputFile = this.ConvertToUserVariableAsFilePath(nameof(v_FilePath), engine); + // wait time + var waitTime = this.ExpandValueOrUserVariableAsInteger(nameof(v_WaitTimeBeforeCapture), engine); + System.Threading.Thread.Sleep(waitTime); + + var image = WindowControls.CaptureWindow(whnd); + var outputFile = this.ExpandValueOrUserVariableAsFilePath(nameof(v_FilePath), engine); + + image.Save(outputFile); + }) + ); - image.Save(outputFile); } + private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + WindowControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); } - public override void Refresh(frmCommandEditor editor) + public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - base.Refresh(); //ComboBox cmb = (ComboBox)ControlsList[nameof(v_ScreenshotWindowName)]; //cmb.AddWindowNames(); - ControlsList.GetPropertyControl(nameof(v_ScreenshotWindowName)).AddWindowNames(); + ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/IntermediateControls.cs b/taskt/Core/Automation/Commands/IntermediateControls.cs index 91fcdaa30..a6e40dfbf 100644 --- a/taskt/Core/Automation/Commands/IntermediateControls.cs +++ b/taskt/Core/Automation/Commands/IntermediateControls.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Reflection; -using static taskt.Core.Automation.Commands.PropertyControls; namespace taskt.Core.Automation.Commands { @@ -10,6 +9,27 @@ namespace taskt.Core.Automation.Commands /// internal static class IntermediateControls { + #region fields + /// + /// intermediate start variable marker + /// + public const string INTERMEDIATE_VALIABLE_START_MARKER = "\u2983"; // like { + /// + /// intermediate end variable marker + /// + public const string INTERMEDIATE_VALIABLE_END_MARKER = "\u2984"; // like } + + // TODO: To be discontinued eventually + /// + /// intermediate start keyword marker + /// + public const string INTERMEDIATE_KEYWORD_START_MARKER = "\U0001D542"; // like k + /// + /// intermediate end keywrod marker + /// + public const string INTERMEDIATE_KEYWORD_END_MARKER = "\U0001D54E"; // like w + #endregion + /// /// proprety value convert to intermediate. this method use default convert method. /// @@ -226,5 +246,58 @@ public static void ConvertToRaw(ScriptCommand command, EngineSettings settings, } } + /// + /// check value is wrapped intermediate keyword marker + /// + /// + /// + private static bool IsWrappedIntermediateKeywordMarker(string value) + { + return (value.StartsWith(INTERMEDIATE_KEYWORD_END_MARKER) && value.EndsWith(INTERMEDIATE_KEYWORD_END_MARKER)); + } + + /// + /// get wrapped intermediate keyword + /// + /// + /// + public static string GetWrappedIntermediateKeyword(string keyword) + { + if (IsWrappedIntermediateKeywordMarker(keyword)) + { + return keyword; + } + else + { + return string.Concat(INTERMEDIATE_KEYWORD_START_MARKER, keyword, INTERMEDIATE_KEYWORD_END_MARKER); + } + } + + /// + /// check value is wrapped intermediate variable marker + /// + /// + /// + private static bool IsWrappedIntermediateVariableMarker(string value) + { + return (value.StartsWith(INTERMEDIATE_VALIABLE_START_MARKER) && value.EndsWith(INTERMEDIATE_VALIABLE_END_MARKER)); + } + + /// + /// get wrapped intermediate variable marker + /// + /// + /// + public static string GetWrappedIntermediateVariable(string variableName) + { + if (IsWrappedIntermediateVariableMarker(variableName)) + { + return variableName; + } + else + { + return string.Concat(INTERMEDIATE_VALIABLE_START_MARKER, variableName, INTERMEDIATE_VALIABLE_END_MARKER); + } + } } } diff --git a/taskt/Core/Automation/Commands/InternalKeywordsControls.cs b/taskt/Core/Automation/Commands/InternalKeywordsControls.cs new file mode 100644 index 000000000..79bd4d6bf --- /dev/null +++ b/taskt/Core/Automation/Commands/InternalKeywordsControls.cs @@ -0,0 +1,75 @@ +namespace taskt.Core.Automation.Commands +{ + public static class InternalKeywordsControls + { + /// + /// default webbrowser instance keyword + /// + public const string INTERNAL_DEFAULT_WEBBROWSER_INSTANCE_NAME_KEYWORD = "%kwd_default_browser_instance%"; + /// + /// default stopwatch instance keyword + /// + public const string INTERNAL_DEFAULT_STOPWATCH_INSTANCE_NAME_KEYWORD = "%kwd_default_stopwatch_instance%"; + /// + /// default excel instance keyword + /// + public const string INTERNAL_DEFAULT_EXCEL_INSTANCE_NAME_KEYWORD = "%kwd_default_excel_instance%"; + /// + /// default word instance keyword + /// + public const string INTERNAL_DEFAULT_WORD_INSTANCE_NAME_KEYWORD = "%kwd_default_word_instance%"; + /// + /// default db instance keyword + /// + public const string INTERNAL_DEFAULT_DB_INSTANCE_NAME_KEYWORD = "%kwd_default_db_instance%"; + /// + /// default nlg instance keyword + /// + public const string INTERNAL_DEFAULT_NLG_INSTANCE_NAME_KEYWORD = "%kwd_default_nlg_instance%"; + + /// + /// replace keyword to default instance name + /// + /// + /// + /// + public static string ReplaceKeywordsToInstanceName(string txt, ApplicationSettings settings) + { + return txt.Replace(INTERNAL_DEFAULT_WEBBROWSER_INSTANCE_NAME_KEYWORD, settings.ClientSettings.DefaultBrowserInstanceName) + .Replace(INTERNAL_DEFAULT_STOPWATCH_INSTANCE_NAME_KEYWORD, settings.ClientSettings.DefaultStopWatchInstanceName) + .Replace(INTERNAL_DEFAULT_EXCEL_INSTANCE_NAME_KEYWORD, settings.ClientSettings.DefaultExcelInstanceName) + .Replace(INTERNAL_DEFAULT_WORD_INSTANCE_NAME_KEYWORD, settings.ClientSettings.DefaultWordInstanceName) + .Replace(INTERNAL_DEFAULT_DB_INSTANCE_NAME_KEYWORD, settings.ClientSettings.DefaultDBInstanceName) + .Replace(INTERNAL_DEFAULT_NLG_INSTANCE_NAME_KEYWORD, settings.ClientSettings.DefaultNLGInstanceName); + } + + /// + /// Replace Internal Keywords to SystemVariable Names (not support Variable Marker) + /// + /// + /// + /// + public static string ReplaceKeywordsToSystemVariable(string txt, Engine.AutomationEngineInstance engine) + { + txt = VariableNameControls.ReplaceKeywordsToSystemVariable(txt, engine); + txt = WindowControls.ReplaceKeywordsToSystemVariable(txt, engine); + txt = ExcelControls.ReplaceKeywordsToSystemVariable(txt, engine); + return txt; + } + + /// + /// Replace Internal Keywords to SystemVariable Names & Instance Name + /// + /// + /// + /// + public static string ReplaceKeywordsToSystemVariableAndInstanceName(string txt, ApplicationSettings settings) + { + txt = ReplaceKeywordsToInstanceName(txt, settings); + txt = VariableNameControls.ReplaceKeywordsToSystemVariable(txt, settings); + txt = WindowControls.ReplaceKeywordsToSystemVariable(txt, settings); + txt = ExcelControls.ReplaceKeywordsToSystemVariable(txt, settings); + return txt; + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/AJSONAddInsertSetJContainerCommands.cs b/taskt/Core/Automation/Commands/JSON/AJSONAddInsertSetJContainerCommands.cs new file mode 100644 index 000000000..45d9dbd62 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/AJSONAddInsertSetJContainerCommands.cs @@ -0,0 +1,21 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Add/Insert/Set something to JContainer commands + /// + public abstract class AJSONAddInsertSetJContainerCommands : AJSONJSONPathCommands, IJSONValueActionProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] + [PropertyParameterOrder(10000)] + public virtual string v_Value { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] + [PropertyParameterOrder(11000)] + public virtual string v_ValueType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/AJSONGetFromJContainerCommands.cs b/taskt/Core/Automation/Commands/JSON/AJSONGetFromJContainerCommands.cs new file mode 100644 index 000000000..37b76fe47 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/AJSONGetFromJContainerCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Get From JContainer(Object or Array) commands + /// + public abstract class AJSONGetFromJContainerCommands : AJSONGetFromJSONCommands, IJSONInputJContainer, IJSONJSONPathProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] + [PropertyParameterOrder(6000)] + public virtual string v_JsonExtractor { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/AJSONGetFromJSONCommands.cs b/taskt/Core/Automation/Commands/JSON/AJSONGetFromJSONCommands.cs new file mode 100644 index 000000000..1a09e1930 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/AJSONGetFromJSONCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Get something from JSON commands + /// + public abstract class AJSONGetFromJSONCommands : AJSONInputJSONCommands, ILResultProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(10000)] + public abstract string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/AJSONInputJSONCommands.cs b/taskt/Core/Automation/Commands/JSON/AJSONInputJSONCommands.cs new file mode 100644 index 000000000..d5683d809 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/AJSONInputJSONCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Input JSON commands + /// + public abstract class AJSONInputJSONCommands : ScriptCommand, ILJSONInputJSONProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_InputJSONName))] + [PropertyParameterOrder(5000)] + public virtual string v_Json { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/AJSONInsertValueToJContainerCommands.cs b/taskt/Core/Automation/Commands/JSON/AJSONInsertValueToJContainerCommands.cs new file mode 100644 index 000000000..235e11335 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/AJSONInsertValueToJContainerCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// Insert Value to JContainer commands + /// + public abstract class AJSONInsertValueToJContainerCommands : AJSONAddInsertSetJContainerCommands + { + [XmlAttribute] + [PropertyDescription("Value to Insert")] + public override string v_Value { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/AJSONJSONPathCommands.cs b/taskt/Core/Automation/Commands/JSON/AJSONJSONPathCommands.cs new file mode 100644 index 000000000..b0f520955 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/AJSONJSONPathCommands.cs @@ -0,0 +1,20 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for JSON and JSONPath commands + /// + public abstract class AJSONJSONPathCommands : AJSONInputJSONCommands, IJSONJSONPathProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] + public override string v_Json { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] + [PropertyParameterOrder(6000)] + public virtual string v_JsonExtractor { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/AJSONSetValueOfJContainerCommands.cs b/taskt/Core/Automation/Commands/JSON/AJSONSetValueOfJContainerCommands.cs new file mode 100644 index 000000000..45c0cfc16 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/AJSONSetValueOfJContainerCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// Set Value of JContainer commands + /// + public abstract class AJSONSetValueOfJContainerCommands : AJSONAddInsertSetJContainerCommands + { + [XmlAttribute] + [PropertyDescription("Value to Set")] + public override string v_Value { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/AJSONValueActionCommands.cs b/taskt/Core/Automation/Commands/JSON/AJSONValueActionCommands.cs new file mode 100644 index 000000000..4d1a2d36e --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/AJSONValueActionCommands.cs @@ -0,0 +1,21 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for JSON Value Action commands + /// + public abstract class AJSONValueActionCommands : AJSONInputJSONCommands, IJSONValueActionProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] + [PropertyParameterOrder(10000)] + public virtual string v_Value { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] + [PropertyParameterOrder(11000)] + public virtual string v_ValueType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/AddJSONArrayItemCommand.cs b/taskt/Core/Automation/Commands/JSON/AddJSONArrayItemCommand.cs index b6e44d5bc..27230975e 100644 --- a/taskt/Core/Automation/Commands/JSON/AddJSONArrayItemCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/AddJSONArrayItemCommand.cs @@ -6,32 +6,33 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Add JSON Array Item")] [Attributes.ClassAttributes.Description("This command allows you to add item to JSON Array.")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class AddJSONArrayItemCommand : ScriptCommand + public sealed class AddJSONArrayItemCommand : AJSONAddInsertSetJContainerCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] - [PropertyDescription("JSON Array Variable Name")] - public string v_InputValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] + //[PropertyDescription("JSON Array Variable Name")] + //public string v_Json { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] - public string v_JsonExtractor { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] + //public string v_JsonExtractor { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] - public string v_ArrayItem { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] + //public string v_Value { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] + //public string v_ValueType { get; set; } public AddJSONArrayItemCommand() { @@ -41,22 +42,33 @@ public AddJSONArrayItemCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //Action addItemFunc = new Action((searchResult) => + //{ + // if (!(searchResult is JArray)) + // { + // throw new Exception("Extraction Result is not JSON Array and can not Add Item. Value: '" + searchResult.ToString() + "'"); + // } + // JArray ary = (JArray)searchResult; - Action addItemFunc = new Action((searchResult) => + // var addItem = this.GetJSONValue(nameof(v_Value), nameof(v_ValueType), "Add", engine); + // ary.Add(addItem); + //}); + //this.JSONModifyByJSONPath(nameof(v_Json), nameof(v_JsonExtractor), addItemFunc, addItemFunc, engine); + + (var root, var json, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + if (json is JArray ary) + { + var v = this.ExpandValueOrVariableValueAsJSONSupportedValueInJSONValue(engine); + ary.Add(v); + //root.ToString().StoreInUserVariable(engine, v_Json); + this.StoreJSONInUserVariable(root, engine); + } + else { - if (!(searchResult is JArray)) - { - throw new Exception("Extraction Result is not JSON Array and can not Add Item. Value: '" + searchResult.ToString() + "'"); - } - JArray ary = (JArray)searchResult; - - var addItem = this.GetJSONValue(nameof(v_ArrayItem), nameof(v_ValueType), "Add", engine); - ary.Add(addItem); - }); - this.JSONModifyByJSONPath(nameof(v_InputValue), nameof(v_JsonExtractor), addItemFunc, addItemFunc, engine); + throw new Exception($"Extraction Result is NOT JSON Array. Result: '{json}', JSONPath: '{v_JsonExtractor}'"); + } } } -} \ No newline at end of file +} diff --git a/taskt/Core/Automation/Commands/JSON/AddJSONObjectPropertyCommand.cs b/taskt/Core/Automation/Commands/JSON/AddJSONObjectPropertyCommand.cs index 00a33bf9c..3235c82b4 100644 --- a/taskt/Core/Automation/Commands/JSON/AddJSONObjectPropertyCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/AddJSONObjectPropertyCommand.cs @@ -6,46 +6,38 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Add JSON Object Property")] [Attributes.ClassAttributes.Description("This command allows you to add property to JSON Object.")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class AddJSONObjectPropertyCommand : ScriptCommand + public sealed class AddJSONObjectPropertyCommand : AJSONAddInsertSetJContainerCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] - [PropertyDescription("JSON Object Variable Name")] - public string v_InputValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] + //[PropertyDescription("JSON Object Variable Name")] + //public string v_Json { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] - public string v_JsonExtractor { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] + //public string v_JsonExtractor { get; set; } [XmlAttribute] - //[PropertyDescription("Property Name to Add")] - //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - //[InputSpecification("")] - //[PropertyDetailSampleUsage("**Name**", PropertyDetailSampleUsage.ValueType.Value, "Property Name")] - //[PropertyDetailSampleUsage("**{{{vName}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Property Name")] - //[Remarks("")] - //[PropertyTextBoxSetting(1, false)] - //[PropertyShowSampleUsageInDescription(true)] - //[PropertyValidationRule("Property Name", PropertyValidationRule.ValidationRuleFlags.Empty)] - //[PropertyDisplayText(true, "Property Name")] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_PropertyName))] + [PropertyParameterOrder(7000)] public string v_PropertyName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] - public string v_PropertyValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] + //public string v_Value { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] + //public string v_ValueType { get; set; } public AddJSONObjectPropertyCommand() { @@ -55,23 +47,35 @@ public AddJSONObjectPropertyCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //Action addPropertyFunc = new Action((searchResult) => + //{ + // if (!(searchResult is JObject)) + // { + // throw new Exception("Extraction Result is not JSON Object and can not Add JSON Property. Value: '" + searchResult.ToString() + "'"); + // } + // JObject obj = (JObject)searchResult; - Action addPropertyFunc = new Action((searchResult) => - { - if (!(searchResult is JObject)) - { - throw new Exception("Extraction Result is not JSON Object and can not Add JSON Property. Value: '" + searchResult.ToString() + "'"); - } - JObject obj = (JObject)searchResult; + // var propertyValue = this.GetJSONValue(nameof(v_Value), nameof(v_ValueType), "Add", engine); + // var propertyName = v_PropertyName.ExpandValueOrUserVariable(engine); + // obj.Add(new JProperty(propertyName, propertyValue)); + //}); + //this.JSONModifyByJSONPath(nameof(v_Json), nameof(v_JsonExtractor), addPropertyFunc, addPropertyFunc, engine); - var propertyValue = this.GetJSONValue(nameof(v_PropertyValue), nameof(v_ValueType), "Add", engine); - var propertyName = v_PropertyName.ConvertToUserVariable(engine); - obj.Add(new JProperty(propertyName, propertyValue)); - }); - this.JSONModifyByJSONPath(nameof(v_InputValue), nameof(v_JsonExtractor), addPropertyFunc, addPropertyFunc, engine); + (var root, var json, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + if (json is JObject obj) + { + var v = this.ExpandValueOrVariableValueAsJSONSupportedValueInJSONValue(engine); + var key = this.ExpandValueOrUserVariable(nameof(v_PropertyName), "Property", engine); + obj.Add(new JProperty(key, v)); + //root.ToString().StoreInUserVariable(engine, v_Json); + this.StoreJSONInUserVariable(root, engine); + } + else + { + throw new Exception($"Extraction Result is NOT JSON Object. Result: '{json}', JSONPath: '{v_JsonExtractor}'"); + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/ConvertJSONToDataTableCommand.cs b/taskt/Core/Automation/Commands/JSON/ConvertJSONToDataTableCommand.cs index 2b3833e05..cd60a25f3 100644 --- a/taskt/Core/Automation/Commands/JSON/ConvertJSONToDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/ConvertJSONToDataTableCommand.cs @@ -1,29 +1,33 @@ -using System; -using System.Xml.Serialization; +using Newtonsoft.Json.Linq; +using System; using System.Data; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; -using Newtonsoft.Json.Linq; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Convert")] [Attributes.ClassAttributes.CommandSettings("Convert JSON To DataTable")] [Attributes.ClassAttributes.Description("This command allows you to convert JSON to DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert JSON to DataTable")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertJSONToDataTableCommand : ScriptCommand + public sealed class ConvertJSONToDataTableCommand : AJSONGetFromJContainerCommands, IDataTableResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_InputJSONName))] - public string v_InputValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_InputJSONName))] + //public string v_Json { get; set; } + + //[XmlAttribute] + //public string v_JsonExtractor { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] - public string v_applyToVariableName { get; set; } + public override string v_Result { get; set; } public ConvertJSONToDataTableCommand() { @@ -33,40 +37,71 @@ public ConvertJSONToDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //Action objFunc = new Action((obj) => + //{ + // var resultDT = new DataTable(); - Action objFunc = new Action((obj) => - { - DataTable resultDT = new DataTable(); + // resultDT.Rows.Add(); + // int i = 0; + // foreach (var result in obj) + // { + // resultDT.Columns.Add(result.Key); + // resultDT.Rows[0][i] = result.Value.ToString(); + // i++; + // } + // //resultDT.StoreInUserVariable(engine, v_applyToVariableName); + // this.StoreDataTableInUserVariable(resultDT, nameof(v_Result), engine); + //}); + //Action aryFunc = new Action((ary) => + //{ + // var resultDT = new DataTable(); + // //parseJSONArrayAsDataTable(ary, resultDT).StoreInUserVariable(engine, v_applyToVariableName); + // this.StoreDataTableInUserVariable(parseJSONArrayAsDataTable(ary, resultDT), nameof(v_Result), engine); + //}); + //this.JSONProcess(nameof(v_Json), objFunc, aryFunc, engine); + + //(_, var jCon, _) = this.ExpandValueOrUserVariableAsJSON(engine); + (_, var jCon, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); - resultDT.Rows.Add(); + var res = this.CreateEmptyDataTable(); + if (jCon is JObject obj) + { + res.Rows.Add(); int i = 0; - foreach (var result in obj) + foreach(var item in obj) { - resultDT.Columns.Add(result.Key); - resultDT.Rows[0][i] = result.Value.ToString(); + res.Columns.Add(item.Key); + res.Rows[0][i] = item.Value.ToString(); i++; } - resultDT.StoreInUserVariable(engine, v_applyToVariableName); - }); - Action aryFunc = new Action((ary) => + } + else if (jCon is JArray ary) { - DataTable resultDT = new DataTable(); - parseJSONArrayAsDataTable(ary, resultDT).StoreInUserVariable(engine, v_applyToVariableName); - }); - this.JSONProcess(nameof(v_InputValue), objFunc, aryFunc, engine); + ParseJSONArrayAsDataTable(ary, res); + } + else if (jCon is JValue va) + { + res.Columns.Add("column0"); + res.Rows.Add(); + res.Rows[0][0] = va.ToString(); + } + else + { + throw new Exception($"Extraction Result is NOT Supported Type. Result: '{jCon}', JSONPath: '{v_JsonExtractor}'"); + } + this.StoreDataTableInUserVariable(res, engine); } - private static DataTable parseJSONArrayAsDataTable(JArray arr, DataTable DT) + private static DataTable ParseJSONArrayAsDataTable(JArray arr, DataTable DT) { var arr0 = arr[0].ToString(); if (arr0.StartsWith("{") && arr0.EndsWith("}")) { // Object JObject col = JObject.Parse(arr[0].ToString()); - int colSize = col.Count; + //int colSize = col.Count; DT.Rows.Add(); foreach (var co in col) { @@ -113,7 +148,7 @@ private static DataTable parseJSONArrayAsDataTable(JArray arr, DataTable DT) DT.Rows.Add(); for (int i = 0; i < arr.Count; i++) { - DT.Columns.Add("column" + i.ToString()); + DT.Columns.Add($"column{i}"); DT.Rows[0][i] = arr[i].ToString(); } } diff --git a/taskt/Core/Automation/Commands/JSON/ConvertJSONToDictionaryCommand.cs b/taskt/Core/Automation/Commands/JSON/ConvertJSONToDictionaryCommand.cs index 96447384b..3426e4de6 100644 --- a/taskt/Core/Automation/Commands/JSON/ConvertJSONToDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/ConvertJSONToDictionaryCommand.cs @@ -1,61 +1,90 @@ using Newtonsoft.Json.Linq; using System; -using System.Collections.Generic; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Convert")] [Attributes.ClassAttributes.CommandSettings("Convert JSON To Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to convert JSON to Dictionary.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert JSON to Dictionary")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertJSONToDictionaryCommand : ScriptCommand + public sealed class ConvertJSONToDictionaryCommand : AJSONGetFromJContainerCommands, IDictionaryResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_InputJSONName))] - public string v_InputValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_InputJSONName))] + //public string v_Json { get; set; } + + //[XmlAttribute] + //public string v_JsonExtractor { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_OutputDictionaryName))] - public string v_applyToVariableName { get; set; } + public override string v_Result { get; set; } public ConvertJSONToDictionaryCommand() { - //this.CommandName = "ConvertJSONToDictionaryCommand"; - //this.SelectionName = "Convert JSON To Dictionary"; - //this.CommandEnabled = true; - //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //Action objFunc = new Action((obj) => + //{ + // var resultDic = new Dictionary(); + // foreach (var result in obj) + // { + // resultDic.Add(result.Key, result.Value.ToString()); + // } + // //resultDic.StoreInUserVariable(engine, v_applyToVariableName); + // this.StoreDictionaryInUserVariable(resultDic, nameof(v_Result), engine); + //}); + //Action aryFunc = new Action((ary) => + //{ + // var resultDic = new Dictionary(); + // for (int i = 0; i < ary.Count; i++) + // { + // resultDic.Add("key" + i.ToString(), ary[i].ToString()); + // } + // //resultDic.StoreInUserVariable(engine, v_applyToVariableName); + // this.StoreDictionaryInUserVariable(resultDic, nameof(v_Result), engine); + //}); + //this.JSONProcess(nameof(v_Json), objFunc, aryFunc, engine); + + //(_, var jCon, _) = this.ExpandValueOrUserVariableAsJSON(nameof(v_Json), engine); + //(_, var jCon, _) = this.ExpandValueOrUserVariableAsJSON(engine); + (_, var jCon, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); - Action objFunc = new Action((obj) => + var res = this.CreateEmptyDictionary(); + if (jCon is JObject obj) { - Dictionary resultDic = new Dictionary(); - foreach (var result in obj) + foreach(var item in obj) { - resultDic.Add(result.Key, result.Value.ToString()); + res.Add(item.Key, item.Value.ToString()); } - resultDic.StoreInUserVariable(engine, v_applyToVariableName); - }); - Action aryFunc = new Action((ary) => + } + else if (jCon is JArray ary) { - Dictionary resultDic = new Dictionary(); - for (int i = 0; i < ary.Count; i++) + int i = 0; + foreach (var item in ary) { - resultDic.Add("key" + i.ToString(), ary[i].ToString()); + res.Add($"key{i}", item.ToString()); } - resultDic.StoreInUserVariable(engine, v_applyToVariableName); - }); - this.JSONProcess(nameof(v_InputValue), objFunc, aryFunc, engine); + } + else if (jCon is JValue va) + { + res.Add("key0", va.ToString()); + } + else + { + throw new Exception($"Extraction Result is NOT Supported Type. Result: '{jCon}', JSONPath: '{v_JsonExtractor}'"); + } + this.StoreDictionaryInUserVariable(res, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/ConvertJSONToListCommand.cs b/taskt/Core/Automation/Commands/JSON/ConvertJSONToListCommand.cs index c421aa626..a0e26e1fb 100644 --- a/taskt/Core/Automation/Commands/JSON/ConvertJSONToListCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/ConvertJSONToListCommand.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Xml.Serialization; using Newtonsoft.Json.Linq; using taskt.Core.Automation.Attributes.PropertyAttributes; @@ -7,55 +6,84 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Convert")] [Attributes.ClassAttributes.CommandSettings("Convert JSON To List")] - [Attributes.ClassAttributes.Description("This command allows you to convert JSON Array into a List.")] + [Attributes.ClassAttributes.Description("This command allows you to convert JSON to List.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to convert JSON Array into a List")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertJSONToListCommand : ScriptCommand + public sealed class ConvertJSONToListCommand : AJSONGetFromJContainerCommands, IListResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_InputJSONName))] - public string v_InputValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_InputJSONName))] + //public string v_Json { get; set; } + + //[XmlAttribute] + //public string v_JsonExtractor { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] - public string v_applyToVariableName { get; set; } + public override string v_Result { get; set; } public ConvertJSONToListCommand() { - //this.CommandName = "ConvertJSONToListCommand"; - //this.SelectionName = "Convert JSON To List"; - //this.CommandEnabled = true; - //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //Action objFunc = new Action((obj) => + //{ + // List resultList = new List(); + // foreach (var result in obj) + // { + // resultList.Add(result.Value.ToString()); + // } + // //resultList.StoreInUserVariable(engine, v_applyToVariableName); + // this.StoreListInUserVariable(resultList, nameof(v_Result), engine); + //}); + //Action aryFunc = new Action((ary) => + //{ + // List resultList = new List(); + // foreach (var result in ary) + // { + // resultList.Add(result.ToString()); + // } + // //resultList.StoreInUserVariable(engine, v_applyToVariableName); + // this.StoreListInUserVariable(resultList, nameof(v_Result), engine); + //}); + //this.JSONProcess(nameof(v_Json), objFunc, aryFunc, engine); + + //(_, var jCon, _) = this.ExpandValueOrUserVariableAsJSON(nameof(v_Json), engine); + //(_, var jCon, _) = this.ExpandValueOrUserVariableAsJSON(engine); + (_, var jCon, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); - Action objFunc = new Action((obj) => + var res = this.CreateEmptyList(); + if (jCon is JObject obj) { - List resultList = new List(); - foreach (var result in obj) + foreach(var item in obj) { - resultList.Add(result.Value.ToString()); + res.Add(item.Value.ToString()); } - resultList.StoreInUserVariable(engine, v_applyToVariableName); - }); - Action aryFunc = new Action((ary) => + } + else if (jCon is JArray ary) { - List resultList = new List(); - foreach (var result in ary) + foreach(var item in ary) { - resultList.Add(result.ToString()); + res.Add(item.ToString()); } - resultList.StoreInUserVariable(engine, v_applyToVariableName); - }); - this.JSONProcess(nameof(v_InputValue), objFunc, aryFunc, engine); + } + else if (jCon is JValue v) + { + res.Add(v.ToString()); + } + else + { + throw new Exception($"Extraction Result is NOT Supported Type. Result: '{jCon}', JSONPath: '{v_JsonExtractor}'"); + } + this.StoreListInUserVariable(res, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/CreateJSONVariableCommand.cs b/taskt/Core/Automation/Commands/JSON/CreateJSONVariableCommand.cs index 8cad9ce77..3e286e3e5 100644 --- a/taskt/Core/Automation/Commands/JSON/CreateJSONVariableCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/CreateJSONVariableCommand.cs @@ -5,32 +5,41 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Create JSON Variable")] [Attributes.ClassAttributes.Description("This command allows you to create JSON Variable.")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateJSONVariableCommand : ScriptCommand + public sealed class CreateJSONVariableCommand : AJSONValueActionCommands { [XmlAttribute] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_OutputJSONName))] - public string v_JsonVariable { get; set; } + public override string v_Json { get; set; } [XmlAttribute] + //[PropertyDescription("JSON Value")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("")] + //[PropertyDetailSampleUsage("**{ \"id\": 1, \"name\": \"John\" }**", "Specify JSON Object")] + //[PropertyDetailSampleUsage("**[ 1, 2, \"Hello\" ]**", "Specify JSON Array")] + //[PropertyDetailSampleUsage("**{{{vJSONValue}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "JSON Value")] + //[Remarks("")] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.MultiLineTextBox)] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyDisplayText(true, "JSON Value")] [PropertyDescription("JSON Value")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("")] - [PropertyDetailSampleUsage("**{ \"id\": 1, \"name\": \"John\" }**", "Specify JSON Object")] - [PropertyDetailSampleUsage("**[ 1, 2, \"Hello\" ]**", "Specify JSON Array")] - [PropertyDetailSampleUsage("**{{{vJSONValue}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "JSON Value")] - [Remarks("")] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.MultiLineTextBox)] - [PropertyShowSampleUsageInDescription(true)] [PropertyDisplayText(true, "JSON Value")] - public string v_JsonValue { get; set; } + public override string v_Value { get; set; } + + [XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] + //[PropertyParameterOrder(7000)] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueTypeSimple))] + public override string v_ValueType { get; set; } public CreateJSONVariableCommand() { @@ -40,12 +49,12 @@ public CreateJSONVariableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var jsonText, _) = v_JsonValue.ConvertToUserVariableAsJSON(engine); - jsonText.StoreInUserVariable(engine, v_JsonVariable); + //(var jsonText, _) = v_Value.ExpandValueOrUserVariableAsJSON(engine); + //jsonText.StoreInUserVariable(engine, v_Json); + (var jsonText, _) = this.ExpandValueOrVariableValueAsJSONInJSONValue(engine); + jsonText.StoreInUserVariable(engine, v_Json); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/EM_CanHandleJContainerExtentionMethods.cs b/taskt/Core/Automation/Commands/JSON/EM_CanHandleJContainerExtentionMethods.cs new file mode 100644 index 000000000..6ab7f6b73 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/EM_CanHandleJContainerExtentionMethods.cs @@ -0,0 +1,58 @@ +using System; +using Newtonsoft.Json.Linq; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_CanHandleJContainerExtentionMethods + { + public enum JSONType + { + NotJSON, + Object, + Array + }; + + /// + /// Detect JSON Type + /// + /// + /// (jsonText, JContainer, jsonType) + public static (string, JContainer, JSONType) DetectJSONType(string json, Engine.AutomationEngineInstance engine) + { + if (EM_CanHandleJSONObjectExtensionMethods.IsJSONObject(json, engine, out (string str, JObject json) to)) + { + return (to.str, to.json, JSONType.Object); + } + else if (EM_CanHandleJSONArrayExtentionMethods.IsJSONArray(json, engine, out (string str, JArray json) ta)) + { + return (ta.str, ta.json, JSONType.Array); + } + else + { + return ("", null, JSONType.NotJSON); + } + } + + /// + /// Expand Value or User Variable As JSON + /// + /// + /// + /// + /// (jsonText, JContainer, jsonType) + public static (string, JContainer, string) ExpandValueOrUserVariableAsJSON(this ICanHandleJContainer command, string parameterName, Engine.AutomationEngineInstance engine) + { + var text = ((ScriptCommand)command).ExpandValueOrUserVariable(parameterName, "JSON", engine); + (var jsonText, var jCon, var jsonType) = DetectJSONType(text, engine); + switch (jsonType) + { + case JSONType.Object: + case JSONType.Array: + return (jsonText, jCon, jsonType.ToString().ToLower()); + + default: + throw new Exception($"Specified Value or User Variable is Not JSON."); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/EM_CanHandleJSONArrayExtentionMethods.cs b/taskt/Core/Automation/Commands/JSON/EM_CanHandleJSONArrayExtentionMethods.cs new file mode 100644 index 000000000..07de84234 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/EM_CanHandleJSONArrayExtentionMethods.cs @@ -0,0 +1,114 @@ +using System; +using Newtonsoft.Json.Linq; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_CanHandleJSONArrayExtentionMethods + { + /// + /// Check object is JSONArray + /// + /// + /// + /// + public static bool IsJSONArray(object value, Engine.AutomationEngineInstance engine, out (string str, JArray json) r) + { + r = ("", default); + if (value is string str) + { + str = str.Trim().ExpandValueOrUserVariable(engine); + if (str.StartsWith("[") && str.EndsWith("]")) + { + try + { + r.str = str; + r.json = JArray.Parse(str.Trim()); + return true; + } + catch + { + return false; + } + } + else + { + return false; + } + } + else + { + return false; + } + } + + /// + /// Expand Value or User Variable as JSONArray + /// + /// + /// + /// + public static (string, JArray) ExpandValueOrUserVariableAsJSONArray(ScriptVariable variable, Engine.AutomationEngineInstance engine) + { + if (IsJSONArray(variable.VariableValue, engine, out (string, JArray) r)) + { + return r; + } + else + { + throw new Exception($"Variable '{variable.VariableName}' is not JSONArray."); + } + } + + /// + /// Expand Value or User Variable As JSONArray + /// + /// + /// + /// + /// + public static (string, JArray) ExpandValueOrUserVariableAsJSONArray(this ICanHandleJSONArray command, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "JSON"); + try + { + return ExpandValueOrUserVariableAsJSONArray(variableName.GetRawVariable(engine), engine); + } + catch + { + throw new Exception($"Variable '{variableName}' is not JSON."); + } + } + + /// + /// Store JSONArray in User Variable + /// + /// + /// + /// + /// + public static void StoreJSONArrayInUserVariable(this ICanHandleJSONArray command, JArray json, string parameterName, Engine.AutomationEngineInstance engine) + { + command.StoreJSONArrayInUserVariable(json.ToString(), parameterName, engine); + } + + /// + /// Store JSONArray in User Variable + /// + /// + /// + /// + /// + public static void StoreJSONArrayInUserVariable(this ICanHandleJSONArray command, string json, string parameterName, Engine.AutomationEngineInstance engine) + { + if (IsJSONArray(json.Trim(), engine, out (string str, JArray _) r)) + { + r.str.StoreInUserVariable(engine, parameterName); + } + else + { + throw new Exception($"This value is not JSON Array. Value: '{json}'"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/EM_CanHandleJSONObjectExtensionMethods.cs b/taskt/Core/Automation/Commands/JSON/EM_CanHandleJSONObjectExtensionMethods.cs new file mode 100644 index 000000000..ddf6c6133 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/EM_CanHandleJSONObjectExtensionMethods.cs @@ -0,0 +1,114 @@ +using System; +using Newtonsoft.Json.Linq; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_CanHandleJSONObjectExtensionMethods + { + /// + /// Check object is JSONObject + /// + /// + /// + /// + public static bool IsJSONObject(object value, Engine.AutomationEngineInstance engine, out (string str, JObject json) r) + { + r = ("", default); + if (value is string str) + { + str = str.Trim().ExpandValueOrUserVariable(engine); + if (str.StartsWith("{") && str.EndsWith("}")) + { + try + { + r.json = JObject.Parse(str.Trim()); + r.str = str; + return true; + } + catch + { + return false; + } + } + else + { + return false; + } + } + else + { + return false; + } + } + + /// + /// Expand Value or User Variable as JSONObject + /// + /// + /// + /// + public static (string, JObject) ExpandValueOrUserVariableAsJSONObject(ScriptVariable variable, Engine.AutomationEngineInstance engine) + { + if (IsJSONObject(variable.VariableValue, engine, out (string, JObject) r)) + { + return r; + } + else + { + throw new Exception($"Variable '{variable.VariableName}' is not JSONObject."); + } + } + + /// + /// Expand Value or User Variable As JSONObject + /// + /// + /// + /// + /// + public static (string, JObject) ExpandValueOrUserVariableAsJSONObject(this ICanHandleJSONObject command, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "JSON"); + try + { + return ExpandValueOrUserVariableAsJSONObject(variableName.GetRawVariable(engine), engine); + } + catch + { + throw new Exception($"Variable '{variableName}' is not JSON."); + } + } + + /// + /// Store JSONObject in User Variable + /// + /// + /// + /// + /// + public static void StoreJSONObjectInUserVariable(this ICanHandleJSONObject command, JObject json, string parameterName, Engine.AutomationEngineInstance engine) + { + command.StoreJSONObjectInUserVariable(json.ToString(), parameterName, engine); + } + + /// + /// Store JSONObject in User Variable + /// + /// + /// + /// + /// + public static void StoreJSONObjectInUserVariable(this ICanHandleJSONObject command, string json, string parameterName, Engine.AutomationEngineInstance engine) + { + if (IsJSONObject(json.Trim(), engine, out (string str, JObject _ ) r)) + { + r.str.StoreInUserVariable(engine, parameterName); + } + else + { + throw new Exception($"This value is not JSON Object. Value: '{json}'"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/EM_JSONJSONPathPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/JSON/EM_JSONJSONPathPropertiesExtensionMethods.cs new file mode 100644 index 000000000..cfe7d18b5 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/EM_JSONJSONPathPropertiesExtensionMethods.cs @@ -0,0 +1,95 @@ +using Newtonsoft.Json.Linq; +using System; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_JSONJSONPathPropertiesExtensionMethods + { + /// + /// Expand Value or User Variable as JSON by JSONPath + /// + /// + /// + /// (JContainer(all JSON), JToken, type) + /// + public static (JContainer, JToken, string) ExpandValueOrUserVariableAsJSONByJSONPath(this IJSONJSONPathProperties command, Engine.AutomationEngineInstance engine) + { + (_, var json, _) = command.ExpandValueOrUserVariableAsJSON(engine); + var path = ((ScriptCommand)command).ExpandValueOrUserVariable(nameof(command.v_JsonExtractor), "JSONPath", engine); + + var token = json.SelectToken(path); + if (token is JObject obj) + { + return (json, obj, "object"); + } + else if (token is JArray ary) + { + return (json, ary, "array"); + } + else if (token is JValue v) + { + return (json, v, "value"); + } + else + { + throw new Exception($"Nothing found in JSONPath. Path: '{command.v_JsonExtractor}', ExtractPath: '{path}'"); + } + } + + /// + /// User Variable as JSON by JSONPath + /// + /// + /// + /// (JContainer(all JSON), JToken, type) + /// + public static (JContainer, JToken, string) ExpandUserVariableAsJSONByJSONPath(this IJSONJSONPathProperties command, Engine.AutomationEngineInstance engine) + { + // force wrapped json variable + var jsonVariable = ((ScriptCommand)command).GetRawPropertyValueAsString(nameof(command.v_Json), "JSON"); + if (!VariableNameControls.IsWrappedVariableMarker(jsonVariable, engine)) + { + command.v_Json = VariableNameControls.GetWrappedVariableName(jsonVariable, engine); + } + + (_, var json, _) = command.ExpandValueOrUserVariableAsJSON(engine); + if (string.IsNullOrEmpty(command.v_JsonExtractor)) + { + command.v_JsonExtractor = "$"; + } + var path = ((ScriptCommand)command).ExpandValueOrUserVariable(nameof(command.v_JsonExtractor), "JSONPath", engine); + + var token = json.SelectToken(path); + if (token is JObject obj) + { + return (json, obj, "object"); + } + else if (token is JArray ary) + { + return (json, ary, "array"); + } + else if (token is JValue v) + { + return (json, v, "value"); + } + else if (token is JProperty prop) + { + return (json, prop, "property"); + } + else + { + throw new Exception($"Nothing found in JSONPath. Path: '{command.v_JsonExtractor}', ExtractPath: '{path}'"); + } + } + + /// + /// store JSON in User variable + /// + /// + /// + public static void StoreJSONInUserVariable(this IJSONJSONPathProperties command, JContainer json, Engine.AutomationEngineInstance engine) + { + json.ToString().StoreInUserVariable(engine, command.v_Json); + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/EM_JSONValueActionPropertiesExtentionMethods.cs b/taskt/Core/Automation/Commands/JSON/EM_JSONValueActionPropertiesExtentionMethods.cs new file mode 100644 index 000000000..52ffdf76a --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/EM_JSONValueActionPropertiesExtentionMethods.cs @@ -0,0 +1,146 @@ +using Newtonsoft.Json.Linq; +using System; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_JSONValueActionPropertiesExtentionMethods + { + /// + /// Expand Value or Variable Value As JSON In JSON Value + /// + /// + /// + /// + /// + public static (string, JContainer) ExpandValueOrVariableValueAsJSONInJSONValue(this IJSONValueActionProperties command, Engine.AutomationEngineInstance engine) + { + (var str, var json, _) = command.ExpandValueOrUserVariableAsJSON(nameof(command.v_Value), engine); + var t = ((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), engine); + switch (t) + { + case "auto": + return (str, json); + + case "array": + if (json is JArray) + { + return (str, json); + } + else + { + throw new Exception($"Spceified Value is NOT JSON Array. Value: '{str}'"); + } + + case "object": + if (json is JObject) + { + return (str, json); + } + else + { + throw new Exception($"Spceified Value is NOT JSON Object. Value: '{str}'"); + } + + default: + throw new Exception($"Spceified Value is NOT JSON. Value: '{str}'"); + } + } + + /// + /// Expand Value or User Variable as JSON-Supported value in JSON Value + /// + /// + /// + /// + /// + public static JToken ExpandValueOrVariableValueAsJSONSupportedValueInJSONValue(this IJSONValueActionProperties command, Engine.AutomationEngineInstance engine) + { + string str; + JContainer json = null; + try + { + (str, json, _) = command.ExpandValueOrUserVariableAsJSON(nameof(command.v_Value), engine); + } + catch + { + str = ((ScriptCommand)command).ExpandValueOrUserVariable(nameof(command.v_Value), "Value", engine); + } + + var t = ((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_ValueType), engine); + + if (json is JArray ary) + { + switch (t) + { + case "array": + case "auto": + return ary; + + default: + throw new Exception($"Spceified Value is NOT JSON Array. Value: '{str}'"); + } + } + else if (json is JObject obj) + { + switch (t) + { + case "object": + case "auto": + return obj; + + default: + throw new Exception($"Spceified Value is NOT JSON Object. Value: '{str}'"); + } + + } + else if (decimal.TryParse(str, out decimal num)) + { + switch (t) + { + case "number": + case "auto": + return new JValue(num); + + default: + throw new Exception($"Spceified Value is NOT Number. Value: '{str}'"); + } + } + else if (bool.TryParse(str, out bool tf)) + { + switch (t) + { + case "boolean": + case "auto": + return new JValue(tf); + + default: + throw new Exception($"Spceified Value is NOT Boolean. Value: '{str}'"); + } + } + else if (str.ToLower() == "null") + { + switch (t) + { + case "null": + case "auto": + return null; + + default: + throw new Exception($"Spceified Value is NOT Null. Value: '{str}'"); + } + } + else + { + switch (t) + { + case "text": + case "auto": + return new JValue(str); + + default: + throw new Exception($"Spceified Value is NOT Text. Value: '{str}'"); + } + } + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/EM_JsonInputJContainerExtensionMethods.cs b/taskt/Core/Automation/Commands/JSON/EM_JsonInputJContainerExtensionMethods.cs new file mode 100644 index 000000000..9dfaabdf2 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/EM_JsonInputJContainerExtensionMethods.cs @@ -0,0 +1,18 @@ +using Newtonsoft.Json.Linq; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_JSONInputJContainerExtensionMethods + { + /// + /// Expand Value or User Variable as JSON + /// + /// + /// + /// (jsonText, JContainer, jsonType) + public static (string, JContainer, string) ExpandValueOrUserVariableAsJSON(this IJSONInputJContainer command, Engine.AutomationEngineInstance engine) + { + return command.ExpandValueOrUserVariableAsJSON(nameof(command.v_Json), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/GetJSONValueCommand.cs b/taskt/Core/Automation/Commands/JSON/GetJSONValueCommand.cs new file mode 100644 index 000000000..7ee9b1b48 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/GetJSONValueCommand.cs @@ -0,0 +1,36 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("JSON")] + [Attributes.ClassAttributes.SubGruop("Get/Set")] + [Attributes.ClassAttributes.CommandSettings("Get JSON Value")] + [Attributes.ClassAttributes.Description("This command allows you to Get JSON Value.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get JSON Value")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetJSONValueCommand : AJSONGetFromJContainerCommands + { + //[XmlAttribute] + //public string v_Json { get; set; } + + //[XmlAttribute] + //public string v_JsonExtractor { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + public override string v_Result { get; set; } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + (_, var jCon, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + jCon.ToString().StoreInUserVariable(engine, v_Result); + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/GetJSONValueFromJSONArrayCommand.cs b/taskt/Core/Automation/Commands/JSON/GetJSONValueFromJSONArrayCommand.cs new file mode 100644 index 000000000..1336ea3cf --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/GetJSONValueFromJSONArrayCommand.cs @@ -0,0 +1,62 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("JSON")] + [Attributes.ClassAttributes.SubGruop("Get/Set")] + [Attributes.ClassAttributes.CommandSettings("Get JSON Value From JSON Array")] + [Attributes.ClassAttributes.Description("This command allows you to Get JSON Value From JSON Array")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get JSON Value From JSON Array")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetJSONValueFromJSONArrayCommand : AJSONGetFromJContainerCommands + { + //[XmlAttribute] + //public string v_Json { get; set; } + + //[XmlAttribute] + //public string v_JsonExtractor { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ArrayIndex))] + [PropertyIsOptional(false, "")] + [PropertyValidationRule("Index", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyParameterOrder(7000)] + public string v_ArrayIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + public override string v_Result { get; set; } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + (_, var jCon, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + if (jCon is JArray ary) + { + var index = this.ExpandValueOrUserVariableAsInteger(nameof(v_ArrayIndex), "Index", engine); + if (index < 0) + { + index += ary.Count; + } + if (index >= 0 && index < ary.Count) + { + ary[index].ToString().StoreInUserVariable(engine, v_Result); + } + else + { + throw new Exception($"Array Index is Out of Range. Index; '{v_ArrayIndex}', Expand: '{index}'"); + } + } + else + { + throw new Exception($"Extraction Result is NOT Supported Type. Result: '{jCon}', JSONPath: '{v_JsonExtractor}'"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/GetJSONValueFromJSONObjectCommand.cs b/taskt/Core/Automation/Commands/JSON/GetJSONValueFromJSONObjectCommand.cs new file mode 100644 index 000000000..8a9438fb7 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/GetJSONValueFromJSONObjectCommand.cs @@ -0,0 +1,56 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("JSON")] + [Attributes.ClassAttributes.SubGruop("Get/Set")] + [Attributes.ClassAttributes.CommandSettings("Get JSON Value From JSON Object")] + [Attributes.ClassAttributes.Description("This command allows you to Get JSON Value From JSON Object")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get JSON Value From JSON Object")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetJSONValueFromJSONObjectCommand : AJSONGetFromJContainerCommands + { + //[XmlAttribute] + //public string v_Json { get; set; } + + //[XmlAttribute] + //public string v_JsonExtractor { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_PropertyName))] + [PropertyParameterOrder(7000)] + public string v_PropertyName { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + public override string v_Result { get; set; } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + (_, var jCon, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + if (jCon is JObject obj) + { + var propName = this.ExpandValueOrUserVariable(nameof(v_PropertyName), "Property Name", engine); + if (obj.ContainsKey(propName)) + { + obj[propName].ToString().StoreInUserVariable(engine, v_Result); + } + else + { + throw new Exception($"Specified property does not Exists. Property: '{v_PropertyName}', Expand: '{propName}'"); + } + } + else + { + throw new Exception($"Extraction Result is NOT Supported Type. Result: '{jCon}', JSONPath: '{v_JsonExtractor}'"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/GetJSONValueListCommand.cs b/taskt/Core/Automation/Commands/JSON/GetJSONValueListCommand.cs deleted file mode 100644 index 2df0280eb..000000000 --- a/taskt/Core/Automation/Commands/JSON/GetJSONValueListCommand.cs +++ /dev/null @@ -1,176 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Xml.Serialization; -using System.Windows.Forms; -using taskt.UI.CustomControls; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] - [Attributes.ClassAttributes.SubGruop("Get/Set")] - [Attributes.ClassAttributes.Description("This command allows you to parse a JSON object into a list.")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to extract data from a JSON object")] - [Attributes.ClassAttributes.ImplementationDescription("")] - [Attributes.ClassAttributes.EnableAutomateRender(true)] - [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetJSONValueListCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Supply the JSON text or variable requiring extraction")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Select or provide a variable or text value")] - [SampleUsage("**{\"id\":2}** or **{{{vSomeVariable}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.JSON)] - [PropertyValidationRule("JSON", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "JSON")] - public string v_InputValue { get; set; } - - [XmlAttribute] - [PropertyDescription("Specify a JSON extractor (JSONPath)")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Input a JSON token extractor")] - [SampleUsage("**$.id**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyCustomUIHelper("JSONPath Helper", nameof(lnkJsonPathHelper_Click))] - [PropertyValidationRule("JSON extractor", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "Extractor")] - public string v_JsonExtractor { get; set; } - - [XmlAttribute] - [PropertyDescription("Please select the variable to receive the extracted Result")] - [InputSpecification("Select or provide a variable from the variable list")] - [SampleUsage("**vSomeVariable**")] - [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - [PropertyIsVariablesList(true)] - [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] - [PropertyInstanceType(PropertyInstanceType.InstanceType.List)] - [PropertyValidationRule("Result", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "Result")] - public string v_applyToVariableName { get; set; } - - public GetJSONValueListCommand() - { - this.CommandName = "GetJSONValueListCommand"; - this.SelectionName = "Get JSON Value List"; - this.CommandEnabled = true; - this.CustomRendering = true; - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - var forbiddenMarkers = new List { "[", "]" }; - - if (forbiddenMarkers.Any(f => f == engine.engineSettings.VariableStartMarker) || (forbiddenMarkers.Any(f => f == engine.engineSettings.VariableEndMarker))) - { - throw new Exception("Cannot use Parse JSON command with square bracket variable markers [ ]"); - } - - //get variablized input - var jsonText = v_InputValue.ConvertToUserVariable(sender).Trim(); - - //get variablized token - var jsonSearchToken = v_JsonExtractor.ConvertToUserVariable(sender); - - ////create objects - //Newtonsoft.Json.Linq.JObject o; - //IEnumerable searchResults; - //List resultList = new List(); - - ////parse json - //try - //{ - // o = Newtonsoft.Json.Linq.JObject.Parse(jsonText); - //} - //catch (Exception ex) - //{ - // throw new Exception("Error Occured Parsing Tokens: " + ex.ToString()); - //} - - IEnumerable searchResults; - if (jsonText.StartsWith("{") && jsonText.EndsWith("}")) - { - try - { - var o = Newtonsoft.Json.Linq.JObject.Parse(jsonText); - searchResults = o.SelectTokens(jsonSearchToken); - } - catch (Exception ex) - { - throw new Exception("Fail Parse JSON Object: " + ex.ToString()); - } - } - else if(jsonText.StartsWith("[") && jsonText.EndsWith("]")) - { - try - { - var a = Newtonsoft.Json.Linq.JArray.Parse(jsonText); - searchResults = a.SelectTokens(jsonSearchToken); - } - catch(Exception ex) - { - throw new Exception("Fail Parse JSON Array: " + ex.ToString()); - } - } - else - { - throw new Exception("Strange JSON. First 10 chars '" + jsonText.Substring(0, 10) + "'"); - } - - ////select results - //try - //{ - // searchResults = o.SelectTokens(jsonSearchToken); - //} - //catch (Exception ex) - //{ - // throw new Exception("Error Occured Selecting Tokens: " + ex.ToString()); - //} - - //List sr = searchResults.ToList(); - - //add results to result list since list is supported - List resultList = new List(); - foreach (Newtonsoft.Json.Linq.JToken result in searchResults) - { - resultList.Add(result.ToString()); - } - - ////get variable - //var requiredComplexVariable = engine.VariableList.Where(x => x.VariableName == v_applyToVariableName).FirstOrDefault(); - - ////create if var does not exist - //if (requiredComplexVariable == null) - //{ - // engine.VariableList.Add(new Script.ScriptVariable() { VariableName = v_applyToVariableName, CurrentPosition = 0 }); - // requiredComplexVariable = engine.VariableList.Where(x => x.VariableName == v_applyToVariableName).FirstOrDefault(); - //} - - ////assign value to variable - //requiredComplexVariable.VariableValue = resultList; - - resultList.StoreInUserVariable(engine, v_applyToVariableName); - } - - public void lnkJsonPathHelper_Click(object sender, EventArgs e) - { - using (var fm = new UI.Forms.Supplement_Forms.frmJSONPathHelper()) - { - if (fm.ShowDialog() == DialogResult.OK) - { - //v_JsonExtractor = fm.JSONPath; - ((TextBox)((CommandItemControl)sender).Tag).Text = fm.JSONPath; - } - } - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/GetJSONValuesAsDataTableCommand.cs b/taskt/Core/Automation/Commands/JSON/GetJSONValuesAsDataTableCommand.cs new file mode 100644 index 000000000..334854fbc --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/GetJSONValuesAsDataTableCommand.cs @@ -0,0 +1,51 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("JSON")] + [Attributes.ClassAttributes.SubGruop("Get/Set")] + [Attributes.ClassAttributes.CommandSettings("Get JSON Values As DataTable")] + [Attributes.ClassAttributes.Description("This command allows you to Get JSON Values From JSON and Result Values is DataTable.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get Values From JSON and Result Values is DataTable")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetJSONValuesAsDataTableCommand : AJSONGetFromJContainerCommands, IDataTableResultProperties + { + //[XmlAttribute] + //public string v_Json { get; set; } + + //[XmlAttribute] + //public string v_JsonExtractor { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] + [Remarks("DataTable has JSONPath and Value columns")] + public override string v_Result { get; set; } + + public GetJSONValuesAsDataTableCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + (_, var root, _) = this.ExpandValueOrUserVariableAsJSON(engine); + var jsonPath = v_JsonExtractor.ExpandValueOrUserVariable(engine); + + var elems = root.SelectTokens(jsonPath); + + var tbl = this.CreateEmptyDataTable(); + tbl.Columns.Add("JSONPath"); + tbl.Columns.Add("Value"); + foreach(var e in elems) + { + tbl.Rows.Add(new string[] { e.Path, e.ToString() ?? ""}); + } + this.StoreDataTableInUserVariable(tbl, engine); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/GetJSONValuesAsDictionaryCommand.cs b/taskt/Core/Automation/Commands/JSON/GetJSONValuesAsDictionaryCommand.cs new file mode 100644 index 000000000..d539dcac2 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/GetJSONValuesAsDictionaryCommand.cs @@ -0,0 +1,48 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("JSON")] + [Attributes.ClassAttributes.SubGruop("Get/Set")] + [Attributes.ClassAttributes.CommandSettings("Get JSON Values As Dictionary")] + [Attributes.ClassAttributes.Description("This command allows you to Get JSON Values From JSON and Result Values is Dictionary.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get Values From JSON and Result Values is Dictionary")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetJSONValuesAsDictionaryCommand : AJSONGetFromJContainerCommands, IDictionaryResultProperties + { + //[XmlAttribute] + //public string v_Json { get; set; } + + //[XmlAttribute] + //public string v_JsonExtractor { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_OutputDictionaryName))] + public override string v_Result { get; set; } + + public GetJSONValuesAsDictionaryCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + (_, var root, _) = this.ExpandValueOrUserVariableAsJSON(engine); + var jsonPath = v_JsonExtractor.ExpandValueOrUserVariable(engine); + + var elems = root.SelectTokens(jsonPath); + + var dic = this.CreateEmptyDictionary(); + foreach(var e in elems) + { + dic.Add(e.Path, e.ToString()); + } + this.StoreDictionaryInUserVariable(dic, engine); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/GetJSONValuesAsListCommand.cs b/taskt/Core/Automation/Commands/JSON/GetJSONValuesAsListCommand.cs new file mode 100644 index 000000000..149348472 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/GetJSONValuesAsListCommand.cs @@ -0,0 +1,147 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("JSON")] + [Attributes.ClassAttributes.SubGruop("Get/Set")] + [Attributes.ClassAttributes.CommandSettings("Get JSON Values As List")] + [Attributes.ClassAttributes.Description("This command allows you to Get JSON Values From JSON and Result Values is List.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get Values From JSON and Result Values is List")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetJSONValuesAsListCommand : AJSONGetFromJContainerCommands, IListResultProperties + { + //[XmlAttribute] + //[PropertyDescription("Supply the JSON text or variable requiring extraction")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Select or provide a variable or text value")] + //[SampleUsage("**{\"id\":2}** or **{{{vSomeVariable}}}**")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.JSON)] + //[PropertyValidationRule("JSON", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "JSON")] + //public string v_Json { get; set; } + + //[XmlAttribute] + //[PropertyDescription("Specify a JSON extractor (JSONPath)")] + //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + //[InputSpecification("Input a JSON token extractor")] + //[SampleUsage("**$.id**")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyCustomUIHelper("JSONPath Helper", nameof(lnkJsonPathHelper_Click))] + //[PropertyValidationRule("JSON extractor", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "Extractor")] + //public string v_JsonExtractor { get; set; } + + [XmlAttribute] + //[PropertyDescription("Please select the variable to receive the extracted Result")] + //[InputSpecification("Select or provide a variable from the variable list")] + //[SampleUsage("**vSomeVariable**")] + //[Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] + //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + //[PropertyIsVariablesList(true)] + //[PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] + //[PropertyInstanceType(PropertyInstanceType.InstanceType.List)] + //[PropertyValidationRule("Result", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "Result")] + [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] + public override string v_Result { get; set; } + + public GetJSONValuesAsListCommand() + { + //this.CommandName = "GetJSONValueListCommand"; + //this.SelectionName = "Get JSON Value List"; + //this.CommandEnabled = true; + //this.CustomRendering = true; + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //var forbiddenMarkers = new List { "[", "]" }; + + //if (forbiddenMarkers.Any(f => f == engine.engineSettings.VariableStartMarker) || (forbiddenMarkers.Any(f => f == engine.engineSettings.VariableEndMarker))) + //{ + // throw new Exception("Cannot use Parse JSON command with square bracket variable markers [ ]"); + //} + + ////get variablized input + //var jsonText = v_Json.ExpandValueOrUserVariable(engine).Trim(); + + ////get variablized token + //var jsonSearchToken = v_JsonExtractor.ExpandValueOrUserVariable(engine); + + //IEnumerable searchResults; + //if (jsonText.StartsWith("{") && jsonText.EndsWith("}")) + //{ + // try + // { + // var o = Newtonsoft.Json.Linq.JObject.Parse(jsonText); + // searchResults = o.SelectTokens(jsonSearchToken); + // } + // catch (Exception ex) + // { + // throw new Exception("Fail Parse JSON Object: " + ex.ToString()); + // } + //} + //else if(jsonText.StartsWith("[") && jsonText.EndsWith("]")) + //{ + // try + // { + // var a = Newtonsoft.Json.Linq.JArray.Parse(jsonText); + // searchResults = a.SelectTokens(jsonSearchToken); + // } + // catch(Exception ex) + // { + // throw new Exception("Fail Parse JSON Array: " + ex.ToString()); + // } + //} + //else + //{ + // throw new Exception("Strange JSON. First 10 chars '" + jsonText.Substring(0, 10) + "'"); + //} + + ////add results to result list since list is supported + //List resultList = new List(); + //foreach (Newtonsoft.Json.Linq.JToken result in searchResults) + //{ + // resultList.Add(result.ToString()); + //} + + ////resultList.StoreInUserVariable(engine, v_applyToVariableName); + //this.StoreListInUserVariable(resultList, nameof(v_Result), engine); + + (_, var root, _) = this.ExpandValueOrUserVariableAsJSON(engine); + var jsonPath = v_JsonExtractor.ExpandValueOrUserVariable(engine); + + var elems = root.SelectTokens(jsonPath); + + var list = this.CreateEmptyList(); + foreach(var e in elems) + { + list.Add(e.ToString()); + } + this.StoreListInUserVariable(list, engine); + } + + //public void lnkJsonPathHelper_Click(object sender, EventArgs e) + //{ + // using (var fm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmJSONPathHelper()) + // { + // var item = (CommandItemControl)sender; + // if (fm.ShowDialog(item.FindForm()) == DialogResult.OK) + // { + // //v_JsonExtractor = fm.JSONPath; + // ((TextBox)(item.Tag)).Text = fm.JSONPath; + // } + // } + //} + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/GetMultiJSONValueListCommand.cs b/taskt/Core/Automation/Commands/JSON/GetMultiJSONValueListCommand.cs index 0ad4fbbed..f96b1b1c3 100644 --- a/taskt/Core/Automation/Commands/JSON/GetMultiJSONValueListCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/GetMultiJSONValueListCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Get/Set")] [Attributes.ClassAttributes.Description("This command allows you to parse a JSON object into a list.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to extract data from a JSON object")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetMultiJSONValueListCommand : ScriptCommand + public sealed class GetMultiJSONValueListCommand : ScriptCommand { [XmlAttribute] [PropertyDescription("Please Supply the JSON value or variable")] @@ -27,7 +28,7 @@ public class GetMultiJSONValueListCommand : ScriptCommand [PropertyInstanceType(PropertyInstanceType.InstanceType.JSON)] [PropertyValidationRule("JSON", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "JSON")] - public string v_InputValue { get; set; } + public string v_Json { get; set; } [XmlElement] [PropertyDescription("Please Assign Objects for Parsing.")] @@ -68,10 +69,8 @@ public GetMultiJSONValueListCommand() } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - ////get variablized input //var variableInput = v_InputValue.ConvertToUserVariable(sender); @@ -130,11 +129,18 @@ public override void RunCommand(object sender) var table = DataTableControls.GetFieldValues(v_ParseObjects, "Json Selector", "Output Variable", false); foreach(var row in table) { - new GetJSONValueListCommand + //new GetJSONValueListCommand + //{ + // v_Json = this.v_Json, + // v_JsonExtractor = row.Key, + // v_Result = row.Value + //}.RunCommand(engine); + + new ConvertJSONToListCommand { - v_InputValue = this.v_InputValue, + v_Json = this.v_Json, v_JsonExtractor = row.Key, - v_applyToVariableName = row.Value + v_Result = row.Value }.RunCommand(engine); } } diff --git a/taskt/Core/Automation/Commands/JSON/ICanHandleJContainer.cs b/taskt/Core/Automation/Commands/JSON/ICanHandleJContainer.cs new file mode 100644 index 000000000..d8aa8bad9 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/ICanHandleJContainer.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// both JSONObject and JSONArray + /// + public interface ICanHandleJContainer : ICanHandleJSONArray, ICanHandleJSONObject + { + // nothing + } +} diff --git a/taskt/Core/Automation/Commands/JSON/ICanHandleJSON.cs b/taskt/Core/Automation/Commands/JSON/ICanHandleJSON.cs new file mode 100644 index 000000000..af8aef1df --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/ICanHandleJSON.cs @@ -0,0 +1,7 @@ +namespace taskt.Core.Automation.Commands +{ + public interface ICanHandleJSON : ILExpandableProperties + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/JSON/ICanHandleJSONArray.cs b/taskt/Core/Automation/Commands/JSON/ICanHandleJSONArray.cs new file mode 100644 index 000000000..e01a491cd --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/ICanHandleJSONArray.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// can handle JSON Array + /// + public interface ICanHandleJSONArray : ICanHandleJSON + { + // nothing + } +} diff --git a/taskt/Core/Automation/Commands/JSON/ICanHandleJSONObject.cs b/taskt/Core/Automation/Commands/JSON/ICanHandleJSONObject.cs new file mode 100644 index 000000000..0bddd8031 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/ICanHandleJSONObject.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// can handle JSON Object + /// + public interface ICanHandleJSONObject : ICanHandleJSON + { + // nothing + } +} diff --git a/taskt/Core/Automation/Commands/JSON/IJSONJSONPathProperties.cs b/taskt/Core/Automation/Commands/JSON/IJSONJSONPathProperties.cs new file mode 100644 index 000000000..2621f4cc6 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/IJSONJSONPathProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Input JSON and JSONPath properties + /// + public interface IJSONJSONPathProperties : IJSONInputJContainer + { + /// + /// JSONPath + /// + string v_JsonExtractor { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/IJSONValueActionProperties.cs b/taskt/Core/Automation/Commands/JSON/IJSONValueActionProperties.cs new file mode 100644 index 000000000..47b4a1b05 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/IJSONValueActionProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// JSON Value Action properties + /// + public interface IJSONValueActionProperties : ILJSONInputJSONProperties, ILJSONValueProperties, ICanHandleJContainer + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/JSON/IJsonInputJContainer.cs b/taskt/Core/Automation/Commands/JSON/IJsonInputJContainer.cs new file mode 100644 index 000000000..1e049b43c --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/IJsonInputJContainer.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// JContainer properties + /// + public interface IJSONInputJContainer : ILJSONInputJSONProperties, ICanHandleJContainer + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/JSON/ILJSONInputJSONProperties.cs b/taskt/Core/Automation/Commands/JSON/ILJSONInputJSONProperties.cs new file mode 100644 index 000000000..b9d5343b1 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/ILJSONInputJSONProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Json input properties + /// + public interface ILJSONInputJSONProperties : ICanHandleJSON, ILExpandableProperties + { + /// + /// JSON Value or Variable Name + /// + string v_Json { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/ILJSONValueProperties.cs b/taskt/Core/Automation/Commands/JSON/ILJSONValueProperties.cs new file mode 100644 index 000000000..88b84e979 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/ILJSONValueProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// JSON Value properties + /// + public interface ILJSONValueProperties : ILExpandableProperties + { + /// + /// JSON Value + /// + string v_Value { get; set; } + + /// + /// Type of JSON Value + /// + string v_ValueType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/InsertJSONArrayItemCommand.cs b/taskt/Core/Automation/Commands/JSON/InsertJSONArrayItemCommand.cs index 258c4f788..0911a5ddb 100644 --- a/taskt/Core/Automation/Commands/JSON/InsertJSONArrayItemCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/InsertJSONArrayItemCommand.cs @@ -6,28 +6,30 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Insert JSON Array Item")] [Attributes.ClassAttributes.Description("This command allows you to insert item to JSON Array.")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class InsertJSONArrayItemCommand : ScriptCommand + public sealed class InsertJSONArrayItemCommand : AJSONInsertValueToJContainerCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] - public string v_InputValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] + //public string v_Json { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] - [PropertyDescription("JSON Array Variable Name")] - public string v_JsonExtractor { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] + //[PropertyDescription("JSON Array Variable Name")] + //public string v_JsonExtractor { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ArrayIndex))] [PropertyIsOptional(true, "Last Index")] + [PropertyParameterOrder(8000)] //[PropertyDescription("Index to Insert")] //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] //[InputSpecification("")] @@ -39,15 +41,15 @@ public class InsertJSONArrayItemCommand : ScriptCommand //[PropertyTextBoxSetting(1, false)] //[PropertyShowSampleUsageInDescription(true)] //[PropertyDisplayText(true, "Index")] - public string v_InsertIndex { get; set; } + public string v_Index { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] - public string v_InsertItem { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] + //public string v_Value { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] + //public string v_ValueType { get; set; } public InsertJSONArrayItemCommand() { @@ -57,34 +59,68 @@ public InsertJSONArrayItemCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //Action addItemFunc = new Action((searchResult) => + //{ + // if (!(searchResult is JArray)) + // { + // throw new Exception("Extraction Result is not JSON Array and can not Add Item. Value: '" + searchResult.ToString() + "'"); + // } + // JArray ary = (JArray)searchResult; + + // var insertItem = this.GetJSONValue(nameof(v_Value), nameof(v_ValueType), "Insert", engine); + + // if (String.IsNullOrEmpty(v_Index)) + // { + // v_Index = ary.Count.ToString(); + // } + // var index = this.ExpandValueOrUserVariableAsInteger(nameof(v_Index), engine); + + // if ((index < 0) && (index > ary.Count)) + // { + // throw new Exception("Index is Out of Range. Value: " + index); + // } + + // ary.Insert(index, JToken.FromObject(insertItem)); + //}); + //this.JSONModifyByJSONPath(nameof(v_Json), nameof(v_JsonExtractor), addItemFunc, addItemFunc, engine); - Action addItemFunc = new Action((searchResult) => + (var root, var json, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + if (json is JArray ary) { - if (!(searchResult is JArray)) + if (string.IsNullOrEmpty(v_Index)) { - throw new Exception("Extraction Result is not JSON Array and can not Add Item. Value: '" + searchResult.ToString() + "'"); + v_Index = ary.Count.ToString(); } - JArray ary = (JArray)searchResult; - - var insertItem = this.GetJSONValue(nameof(v_InsertItem), nameof(v_ValueType), "Insert", engine); - - if (String.IsNullOrEmpty(v_InsertIndex)) + var index = this.ExpandValueOrUserVariableAsInteger(nameof(v_Index), engine); + if (index < 0) { - v_InsertIndex = ary.Count.ToString(); + index += ary.Count; } - var index = this.ConvertToUserVariableAsInteger(nameof(v_InsertIndex), engine); - - if ((index < 0) && (index > ary.Count)) + if (index < 0) { - throw new Exception("Index is Out of Range. Value: " + index); + throw new Exception($"Index is Less than zero. Value: '{v_Index}', Expand Value: '{index}'"); } - ary.Insert(index, JToken.FromObject(insertItem)); - }); - this.JSONModifyByJSONPath(nameof(v_InputValue), nameof(v_JsonExtractor), addItemFunc, addItemFunc, engine); + var v = this.ExpandValueOrVariableValueAsJSONSupportedValueInJSONValue(engine); + if (index >= ary.Count) + { + // add + ary.Add(v); + } + else + { + // insert + ary.Insert(index, v); + } + //root.ToString().StoreInUserVariable(engine, v_Json); + this.StoreJSONInUserVariable(root, engine); + } + else + { + throw new Exception($"Extraction Result is NOT JSON Array. Result: '{json}', JSONPath: '{v_JsonExtractor}'"); + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/InsertJSONObjectPropertyCommand.cs b/taskt/Core/Automation/Commands/JSON/InsertJSONObjectPropertyCommand.cs index c0bbda727..b4d62a6af 100644 --- a/taskt/Core/Automation/Commands/JSON/InsertJSONObjectPropertyCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/InsertJSONObjectPropertyCommand.cs @@ -6,24 +6,33 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Insert JSON Object Property")] [Attributes.ClassAttributes.Description("This command allows you to add property to JSON Object.")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class InsertJSONObjectPropertyCommand : ScriptCommand + public sealed class InsertJSONObjectPropertyCommand : AJSONInsertValueToJContainerCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] - [PropertyDescription("JSON Object Variable Name")] - public string v_InputValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] + //[PropertyDescription("JSON Object Variable Name")] + //public string v_Json { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] + //public string v_JsonExtractor { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] - public string v_JsonExtractor { get; set; } + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_PropertyName))] + [PropertyDescription("Property Name of Insert Position")] + [PropertyIsOptional(true, "")] + [PropertyValidationRule("Property Name of Insert Position", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(8000)] + public string v_PropertyNameInsertPosition { get; set; } [XmlAttribute] //[PropertyDescription("Property Name to Insert")] @@ -37,15 +46,16 @@ public class InsertJSONObjectPropertyCommand : ScriptCommand //[PropertyValidationRule("Property Name", PropertyValidationRule.ValidationRuleFlags.Empty)] //[PropertyDisplayText(true, "Property Name")] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_PropertyName))] + [PropertyParameterOrder(8100)] public string v_PropertyName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] - public string v_PropertyValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] + //public string v_Value { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] + //public string v_ValueType { get; set; } public InsertJSONObjectPropertyCommand() { @@ -55,22 +65,59 @@ public InsertJSONObjectPropertyCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //Action addPropertyFunc = new Action((searchResult) => + //{ + // if (!(searchResult.Parent is JProperty)) + // { + // throw new Exception("Extraction Result is not JSON Object and can not Add JSON Property. Value: '" + searchResult.ToString() + "'"); + // } + + // var propertyValue = this.GetJSONValue(nameof(v_Value), nameof(v_ValueType), "Insert", engine); + // var propertyName = v_PropertyName.ExpandValueOrUserVariable(engine); + // searchResult.Parent.AddAfterSelf(new JProperty(propertyName, propertyValue)); + //}); + //this.JSONModifyByJSONPath(nameof(v_Json), nameof(v_JsonExtractor), addPropertyFunc, addPropertyFunc, engine); + (var root, var json, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); - Action addPropertyFunc = new Action((searchResult) => + var propName = this.ExpandValueOrUserVariable(nameof(v_PropertyName), "Property Name", engine); + var v = this.ExpandValueOrVariableValueAsJSONSupportedValueInJSONValue(engine); + + if (json is JObject obj) { - if (!(searchResult.Parent is JProperty)) + // json is JObject -> Add or Insert + + if (string.IsNullOrEmpty(v_PropertyNameInsertPosition)) { - throw new Exception("Extraction Result is not JSON Object and can not Add JSON Property. Value: '" + searchResult.ToString() + "'"); + obj.Add(propName, v); + } + else + { + var insertPos = this.ExpandValueOrUserVariable(nameof(v_PropertyNameInsertPosition), "Insert Position", engine); + if (obj.ContainsKey(insertPos)) + { + obj[insertPos].Parent.AddAfterSelf(new JProperty(propName, v)); + } + else + { + throw new Exception($"Specified property does not Exists. Property: '{v_PropertyNameInsertPosition}', Expand: '{insertPos}'"); + } } - var propertyValue = this.GetJSONValue(nameof(v_PropertyValue), nameof(v_ValueType), "Insert", engine); - var propertyName = v_PropertyName.ConvertToUserVariable(engine); - searchResult.Parent.AddAfterSelf(new JProperty(propertyName, propertyValue)); - }); - this.JSONModifyByJSONPath(nameof(v_InputValue), nameof(v_JsonExtractor), addPropertyFunc, addPropertyFunc, engine); + root.ToString().StoreInUserVariable(engine, v_Json); + } + //else if (json?.Parent is JProperty) + //{ + // // json is JProperty -> insert + // json.Parent.AddAfterSelf(new JProperty(propName, v)); + // //root.ToString().StoreInUserVariable(engine, v_Json); + // this.StoreJSONInUserVariable(root, engine); + //} + else + { + throw new Exception($"Extraction Result is NOT JSON Object or JSON Object Property. Result: '{json}', JSONPath: '{v_JsonExtractor}'"); + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/ParseJSONArray.cs b/taskt/Core/Automation/Commands/JSON/ParseJSONArray.cs deleted file mode 100644 index a213be63a..000000000 --- a/taskt/Core/Automation/Commands/JSON/ParseJSONArray.cs +++ /dev/null @@ -1,80 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Xml.Serialization; -using taskt.Core.Automation.Attributes.PropertyAttributes; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] - [Attributes.ClassAttributes.SubGruop("Convert")] - [Attributes.ClassAttributes.Description("This command allows you to parse a JSON Array into a list.")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to extract data from a JSON object")] - [Attributes.ClassAttributes.ImplementationDescription("")] - [Attributes.ClassAttributes.EnableAutomateRender(true)] - [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ParseJSONArrayCommand : ScriptCommand - { - [XmlAttribute] - [PropertyDescription("Supply the JSON Array or Variable")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Select or provide a variable or json array value")] - [SampleUsage("**[1,2,3]** or **[{obj1},{obj2}]** or **{{{vArrayVariable}}}**")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyValidationRule("JSON", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "JSON")] - public string v_InputValue { get; set; } - - [XmlAttribute] - [PropertyDescription("Please select the variable to receive the List")] - [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [InputSpecification("Select or provide a variable from the variable list")] - [SampleUsage("**vSomeVariable**")] - [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] - [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] - [PropertyIsVariablesList(true)] - [PropertyValidationRule("List", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "List")] - public string v_applyToVariableName { get; set; } - - public ParseJSONArrayCommand() - { - this.CommandName = "ParseJSONArrayCommand"; - this.SelectionName = "Parse JSON Array"; - this.CommandEnabled = true; - this.CustomRendering = true; - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - //get variablized input - var variableInput = v_InputValue.ConvertToUserVariable(sender); - - //create objects - Newtonsoft.Json.Linq.JArray arr; - List resultList = new List(); - - //parse json - try - { - arr = Newtonsoft.Json.Linq.JArray.Parse(variableInput); - } - catch (Exception ex) - { - throw new Exception("Error Occured Selecting Tokens: " + ex.ToString()); - } - - //add results to result list since list is supported - foreach (var result in arr) - { - resultList.Add(result.ToString()); - } - - resultList.StoreInUserVariable(engine, v_applyToVariableName); - - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/ReadJSONFileCommand.cs b/taskt/Core/Automation/Commands/JSON/ReadJSONFileCommand.cs index aeb683755..7673c6875 100644 --- a/taskt/Core/Automation/Commands/JSON/ReadJSONFileCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/ReadJSONFileCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("File")] [Attributes.ClassAttributes.CommandSettings("Read JSON File")] [Attributes.ClassAttributes.Description("This command reads JSON data into a variable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to read data from JSON files.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ReadJSONFileCommand : ScriptCommand + public sealed class ReadJSONFileCommand : ScriptCommand { [XmlAttribute] //[PropertyDescription("Path to the File")] @@ -36,7 +37,7 @@ public class ReadJSONFileCommand : ScriptCommand [XmlAttribute] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_OutputJSONName))] - public string v_userVariableName { get; set; } + public string v_Result { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(FilePathControls), nameof(FilePathControls.v_WaitTime))] @@ -50,10 +51,8 @@ public ReadJSONFileCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //string filePath; //if (!FilePathControls.IsURL(v_FilePath)) //{ @@ -68,9 +67,9 @@ public override void RunCommand(object sender) ScriptCommand readFile = new ReadTextFileCommand { v_FilePath = filePath, - v_userVariableName = this.v_userVariableName + v_userVariableName = this.v_Result }; - readFile.RunCommand(sender); + readFile.RunCommand(engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/RemoveJSONArrayItemCommand.cs b/taskt/Core/Automation/Commands/JSON/RemoveJSONArrayItemCommand.cs index 6e90dc7a7..ef1d8439b 100644 --- a/taskt/Core/Automation/Commands/JSON/RemoveJSONArrayItemCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/RemoveJSONArrayItemCommand.cs @@ -6,24 +6,25 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Remove JSON Array Item")] [Attributes.ClassAttributes.Description("This command allows you to remove item to JSON Array.")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RemoveJSONArrayItemCommand : ScriptCommand + public sealed class RemoveJSONArrayItemCommand : AJSONJSONPathCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] - [PropertyDescription("JSON Array Variable Name")] - public string v_InputValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] + //[PropertyDescription("JSON Array Variable Name")] + //public string v_Json { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] - public string v_JsonExtractor { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] + //public string v_JsonExtractor { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ArrayIndex))] @@ -39,7 +40,8 @@ public class RemoveJSONArrayItemCommand : ScriptCommand //[PropertyShowSampleUsageInDescription(true)] //[PropertyDisplayText(true, "Index")] //[PropertyValidationRule("Index", PropertyValidationRule.ValidationRuleFlags.Empty)] - public string v_RemoveIndex { get; set; } + [PropertyParameterOrder(8000)] + public string v_Index { get; set; } public RemoveJSONArrayItemCommand() { @@ -49,28 +51,53 @@ public RemoveJSONArrayItemCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //Action removeItemFunc = new Action((searchResult) => + //{ + // if (!(searchResult is JArray)) + // { + // throw new Exception("Extraction Result is not JSON Array and can not Add Item. Value: '" + searchResult.ToString() + "'"); + // } + // JArray ary = (JArray)searchResult; + + // var index = this.ExpandValueOrUserVariableAsInteger(nameof(v_Index), engine); + + // if ((index < 0) && (index > ary.Count)) + // { + // throw new Exception("Index is Out of Range. Value: " + index); + // } - Action removeItemFunc = new Action((searchResult) => + // ary.RemoveAt(index); + //}); + //this.JSONModifyByJSONPath(nameof(v_Json), nameof(v_JsonExtractor), removeItemFunc, removeItemFunc, engine); + + (var root, var json, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + if (json is JArray ary) { - if (!(searchResult is JArray)) + if (string.IsNullOrEmpty(v_Index)) { - throw new Exception("Extraction Result is not JSON Array and can not Add Item. Value: '" + searchResult.ToString() + "'"); + v_Index = "-1"; } - JArray ary = (JArray)searchResult; - - var index = this.ConvertToUserVariableAsInteger(nameof(v_RemoveIndex), engine); - - if ((index < 0) && (index > ary.Count)) + var index = this.ExpandValueOrUserVariableAsInteger(nameof(v_Index), "Index", engine); + if (index < 0) { - throw new Exception("Index is Out of Range. Value: " + index); + index += ary.Count; } - - ary.RemoveAt(index); - }); - this.JSONModifyByJSONPath(nameof(v_InputValue), nameof(v_JsonExtractor), removeItemFunc, removeItemFunc, engine); + if (index < 0 || index > ary.Count) + { + throw new Exception($"Index is Out of Range. Value: '{v_Index}', Expand Value: '{index}'"); + } + else + { + ary.RemoveAt(index); + this.StoreJSONInUserVariable(root, engine); + } + } + else + { + throw new Exception($"Extraction Result is NOT JSON Array. Result: '{json}', JSONPath: '{v_JsonExtractor}'"); + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/RemoveJSONObjectPropertyCommand.cs b/taskt/Core/Automation/Commands/JSON/RemoveJSONObjectPropertyCommand.cs new file mode 100644 index 000000000..35707dda6 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/RemoveJSONObjectPropertyCommand.cs @@ -0,0 +1,94 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using Newtonsoft.Json.Linq; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("JSON")] + [Attributes.ClassAttributes.SubGruop("Action")] + [Attributes.ClassAttributes.CommandSettings("Remove JSON Object Property")] + [Attributes.ClassAttributes.Description("This command allows you to remove a property in JSON")] + [Attributes.ClassAttributes.UsesDescription("")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class RemoveJSONObjectPropertyCommand : AJSONJSONPathCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] + //[PropertyDescription("JSON Object Variable Name")] + //public string v_Json { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] + //public string v_JsonExtractor { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_PropertyName))] + [PropertyParameterOrder(7000)] + public string v_PropertyName { get; set; } + + public RemoveJSONObjectPropertyCommand() + { + //this.CommandName = "Remove JSON Property"; + //this.SelectionName = "Remove JSON Property"; + //this.CommandEnabled = true; + //this.CustomRendering = true; + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //Action removeFunc = new Action((searchResult) => + //{ + // var p = searchResult.Parent; + // if (p is JProperty prop) + // { + // prop.Remove(); + // } + // else if (p is JArray ary) + // { + // ary.Remove(searchResult); + // } + // else + // { + // throw new Exception("Strange Search Result. Fail Remove. Value: '" + searchResult.ToString() + "'"); + // } + //}); + //this.JSONModifyByJSONPath(nameof(v_Json), nameof(v_JsonExtractor), removeFunc, removeFunc, engine); + + (var root, var json, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + + //var p = json?.Parent; + //if (p is JProperty prop) + //{ + // prop.Remove(); + // this.StoreJSONInUserVariable(root, engine); + //} + //else if (p is JArray ary) + //{ + // ary.Remove(json); + // this.StoreJSONInUserVariable(root, engine); + //} + if (json is JObject obj) + { + var propName = this.ExpandValueOrUserVariable(nameof(v_PropertyName), "Property Name", engine); + if (obj.ContainsKey(propName)) + { + obj.Remove(propName); + this.StoreJSONInUserVariable(root, engine); + } + else + { + throw new Exception($"Specified property does not Exists. Property: '{v_PropertyName}', Expand: '{propName}'"); + } + } + else + { + throw new Exception($"Search Result is not supported Value. Result: '{json}', JSONPath: '{v_JsonExtractor}'"); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/RemoveJSONPropertyCommand.cs b/taskt/Core/Automation/Commands/JSON/RemoveJSONPropertyCommand.cs deleted file mode 100644 index 594a24a02..000000000 --- a/taskt/Core/Automation/Commands/JSON/RemoveJSONPropertyCommand.cs +++ /dev/null @@ -1,59 +0,0 @@ -using System; -using System.Xml.Serialization; -using taskt.Core.Automation.Attributes.PropertyAttributes; -using Newtonsoft.Json.Linq; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] - [Attributes.ClassAttributes.SubGruop("Action")] - [Attributes.ClassAttributes.CommandSettings("Remove JSON Property")] - [Attributes.ClassAttributes.Description("This command allows you to remove a property in JSON")] - [Attributes.ClassAttributes.UsesDescription("")] - [Attributes.ClassAttributes.ImplementationDescription("")] - [Attributes.ClassAttributes.EnableAutomateRender(true)] - [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RemoveJSONPropertyCommand : ScriptCommand - { - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] - [PropertyDescription("JSON Object Variable Name")] - public string v_InputValue { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] - public string v_JsonExtractor { get; set; } - - public RemoveJSONPropertyCommand() - { - //this.CommandName = "Remove JSON Property"; - //this.SelectionName = "Remove JSON Property"; - //this.CommandEnabled = true; - //this.CustomRendering = true; - } - - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - - Action removeFunc = new Action((searchResult) => - { - var p = searchResult.Parent; - if (p is JProperty prop) - { - prop.Remove(); - } - else if (p is JArray ary) - { - ary.Remove(searchResult); - } - else - { - throw new Exception("Strange Search Result. Fail Remove. Value: '" + searchResult.ToString() + "'"); - } - }); - this.JSONModifyByJSONPath(nameof(v_InputValue), nameof(v_JsonExtractor), removeFunc, removeFunc, engine); - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/JSON/SetJSONValueCommand.cs b/taskt/Core/Automation/Commands/JSON/SetJSONValueCommand.cs index ee8fbb97d..ce58bfa71 100644 --- a/taskt/Core/Automation/Commands/JSON/SetJSONValueCommand.cs +++ b/taskt/Core/Automation/Commands/JSON/SetJSONValueCommand.cs @@ -6,34 +6,35 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("JSON Commands")] + [Attributes.ClassAttributes.Group("JSON")] [Attributes.ClassAttributes.SubGruop("Get/Set")] [Attributes.ClassAttributes.CommandSettings("Set JSON Value")] [Attributes.ClassAttributes.Description("This command allows you to set value in JSON.")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetJSONValueCommand : ScriptCommand + public sealed class SetJSONValueCommand : AJSONAddInsertSetJContainerCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] - public string v_InputValue { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_BothJSONName))] + //public string v_Json { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_JSONPath))] [PropertyDetailSampleUsage("**$.names[0]**", "Specify the First item in the Array of **names** Property")] - public string v_JsonExtractor { get; set; } + public override string v_JsonExtractor { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] - [PropertyDescription("Value to Set")] - public string v_ValueToSet { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueToAdd))] + //[PropertyDescription("Value to Set")] + //public string v_Value { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] - [PropertyDescription("Value Type to Set")] - public string v_ValueType { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ValueType))] + //[PropertyDescription("Value Type to Set")] + //public string v_ValueType { get; set; } public SetJSONValueCommand() { @@ -43,16 +44,27 @@ public SetJSONValueCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //Action setValueFunc = new Action((searchResult) => + //{ + // var valueToSet = this.GetJSONValue(nameof(v_Value), nameof(v_ValueType), "Set", engine); + // searchResult.Replace(JToken.FromObject(valueToSet)); + //}); + //this.JSONModifyByJSONPath(nameof(v_Json), nameof(v_JsonExtractor), setValueFunc, setValueFunc, engine); - Action setValueFunc = new Action((searchResult) => + (var root, var json, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + var v = this.ExpandValueOrVariableValueAsJSONSupportedValueInJSONValue(engine); + + try + { + json.Replace(v); + this.StoreJSONInUserVariable(root, engine); + } + catch { - var valueToSet = this.GetJSONValue(nameof(v_ValueToSet), nameof(v_ValueType), "Set", engine); - searchResult.Replace(JToken.FromObject(valueToSet)); - }); - this.JSONModifyByJSONPath(nameof(v_InputValue), nameof(v_JsonExtractor), setValueFunc, setValueFunc, engine); + throw new Exception($"Extraction Result is NOT Supported Type. Result: '{json}', JSONPath: '{v_JsonExtractor}'"); + } } } -} \ No newline at end of file +} diff --git a/taskt/Core/Automation/Commands/JSON/SetJSONValueOfJSONArrayCommand.cs b/taskt/Core/Automation/Commands/JSON/SetJSONValueOfJSONArrayCommand.cs new file mode 100644 index 000000000..8d887ea79 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/SetJSONValueOfJSONArrayCommand.cs @@ -0,0 +1,60 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("JSON")] + [Attributes.ClassAttributes.SubGruop("Get/Set")] + [Attributes.ClassAttributes.CommandSettings("Set JSON Value Of JSON Array")] + [Attributes.ClassAttributes.Description("This command allows you to Set Value in JSON Array")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Set Value in JSON Array")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class SetJSONValueOfJSONArrayCommand : AJSONSetValueOfJContainerCommands + { + //[XmlAttribute] + //public string v_Json { get; set; } + + //[XmlAttribute] + //public string v_JsonExtractor { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_ArrayIndex))] + [PropertyIsOptional(false, "")] + [PropertyValidationRule("Index", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyParameterOrder(7000)] + public string v_ArrayIndex { get; set; } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + (var root, var jCon, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + if (jCon is JArray ary) + { + var index = this.ExpandValueOrUserVariableAsInteger(nameof(v_ArrayIndex), "Index", engine); + if (index < 0) + { + index += ary.Count; + } + if (index >= 0 && index < ary.Count) + { + var v = this.ExpandValueOrVariableValueAsJSONSupportedValueInJSONValue(engine); + ary[index] = v; + this.StoreJSONInUserVariable(root, engine); + } + else + { + throw new Exception($"Array Index is Out of Range. Index; '{v_ArrayIndex}', Expand: '{index}'"); + } + } + else + { + throw new Exception($"Extraction Result is NOT Supported Type. Result: '{jCon}', JSONPath: '{v_JsonExtractor}'"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/JSON/SetJSONValueOfJSONObjectCommand.cs b/taskt/Core/Automation/Commands/JSON/SetJSONValueOfJSONObjectCommand.cs new file mode 100644 index 000000000..f7a9377c9 --- /dev/null +++ b/taskt/Core/Automation/Commands/JSON/SetJSONValueOfJSONObjectCommand.cs @@ -0,0 +1,54 @@ +using Newtonsoft.Json.Linq; +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("JSON")] + [Attributes.ClassAttributes.SubGruop("Get/Set")] + [Attributes.ClassAttributes.CommandSettings("Set JSON Value Of JSON Object")] + [Attributes.ClassAttributes.Description("This command allows you to Set Value in JSON Object")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Set Value in JSON Object")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class SetJSONValueOfJSONObjectCommand : AJSONSetValueOfJContainerCommands + { + //[XmlAttribute] + //public string v_Json { get; set; } + + //[XmlAttribute] + //public string v_JsonExtractor { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_PropertyName))] + [PropertyParameterOrder(7000)] + public string v_PropertyName { get; set; } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + (var root, var jCon, _) = this.ExpandUserVariableAsJSONByJSONPath(engine); + if (jCon is JObject obj) + { + var propName = this.ExpandValueOrUserVariable(nameof(v_PropertyName), "Property Name", engine); + if (obj.ContainsKey(propName)) + { + var v = this.ExpandValueOrVariableValueAsJSONSupportedValueInJSONValue(engine); + obj[propName] = v; + this.StoreJSONInUserVariable(root, engine); + } + else + { + throw new Exception($"Specified property does not Exists. Property: '{v_PropertyName}', Expand: '{propName}'"); + } + } + else + { + throw new Exception($"Extraction Result is NOT Supported Type. Result: '{jCon}', JSONPath: '{v_JsonExtractor}'"); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/JSONControls.cs b/taskt/Core/Automation/Commands/JSONControls.cs index 0e8780f32..61b27404a 100644 --- a/taskt/Core/Automation/Commands/JSONControls.cs +++ b/taskt/Core/Automation/Commands/JSONControls.cs @@ -1,6 +1,5 @@ using System; using System.Windows.Forms; -using Newtonsoft.Json.Linq; using taskt.Core.Automation.Attributes.PropertyAttributes; using taskt.UI.CustomControls; @@ -8,6 +7,7 @@ namespace taskt.Core.Automation.Commands { static internal class JSONControls { + #region Virtual Property /// /// input JSON Variable or Value /// @@ -23,6 +23,7 @@ static internal class JSONControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("JSON", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "JSON")] + [PropertyParameterOrder(5000)] public static string v_InputJSONName { get; } /// @@ -38,6 +39,7 @@ static internal class JSONControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("JSON", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "JSON")] + [PropertyParameterOrder(5000)] public static string v_InputJSONVariableName { get; } /// @@ -55,6 +57,7 @@ static internal class JSONControls [PropertyInstanceType(PropertyInstanceType.InstanceType.JSON, true)] [PropertyValidationRule("JSON", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "JSON")] + [PropertyParameterOrder(5000)] public static string v_OutputJSONName { get; } /// @@ -72,6 +75,7 @@ static internal class JSONControls [PropertyInstanceType(PropertyInstanceType.InstanceType.JSON, true)] [PropertyValidationRule("JSON", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "JSON")] + [PropertyParameterOrder(5000)] public static string v_BothJSONName { get; } /// @@ -84,9 +88,11 @@ static internal class JSONControls [PropertyDetailSampleUsage("**{{{vPath}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "JSON Extractor")] [Remarks("See this URL for details. https://github.com/json-path/JsonPath")] [PropertyShowSampleUsageInDescription(true)] + [PropertyIsOptional(true, "$")] [PropertyCustomUIHelper("JSONPath Helper", nameof(JSONControls) + "+" + nameof(lnkJsonPathHelper_Click))] - [PropertyValidationRule("JSON Extractor", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyValidationRule("JSON Extractor", PropertyValidationRule.ValidationRuleFlags.None)] [PropertyDisplayText(true, "Extractor")] + [PropertyParameterOrder(5000)] public static string v_JSONPath { get; } /// @@ -111,8 +117,27 @@ static internal class JSONControls [PropertyDetailSampleUsage("**Array**", "Specify Array Object for Value Type")] [PropertyIsOptional(true, "Auto")] [PropertyDisplayText(true, "Value Type")] + [PropertyParameterOrder(5000)] public static string v_ValueType { get; } + /// + /// Value type to Add JSON (only Auto, Object, and Array) + /// + [PropertyDescription("Value Type to Add")] + [InputSpecification("", true)] + [Remarks("")] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyUISelectionOption("Auto")] + [PropertyUISelectionOption("Object")] + [PropertyUISelectionOption("Array")] + [PropertyDetailSampleUsage("**Auto**", "Automatically determines the Value Type")] + [PropertyDetailSampleUsage("**Object**", "Specify JSON Object for Value Type")] + [PropertyDetailSampleUsage("**Array**", "Specify Array Object for Value Type")] + [PropertyIsOptional(true, "Auto")] + [PropertyDisplayText(true, "Value Type")] + [PropertyParameterOrder(5000)] + public static string v_ValueTypeSimple { get; } + /// /// value to add property /// @@ -127,6 +152,7 @@ static internal class JSONControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.MultiLineTextBox)] [PropertyShowSampleUsageInDescription(true)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(5000)] public static string v_ValueToAdd { get; } /// @@ -141,6 +167,7 @@ static internal class JSONControls [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("Property Name", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Property Name")] + [PropertyParameterOrder(5000)] public static string v_PropertyName { get; } /// @@ -156,226 +183,233 @@ static internal class JSONControls [PropertyShowSampleUsageInDescription(true)] [PropertyIsOptional(true, "Last Item")] [PropertyDisplayText(true, "Index")] + [PropertyParameterOrder(5000)] public static string v_ArrayIndex { get; } + #endregion - /// - /// get JSON text from text value or variable contains text. this method returns root type "object" or "array". - /// - /// - /// - /// - /// - public static (string json, string rootType) ConvertToUserVariableAsJSON(this string jsonValue, Core.Automation.Engine.AutomationEngineInstance engine) - { - var jsonText = jsonValue.ConvertToUserVariable(engine).Trim(); - if (jsonText.StartsWith("{") && jsonText.EndsWith("}")) - { - try - { - var _ = JObject.Parse(jsonText); - return (jsonText, "object"); - } - catch (Exception ex) - { - throw new Exception("Fail parse JSON Object. " + ex.ToString()); - } - } - else if (jsonText.StartsWith("[") && jsonText.EndsWith("]")) - { - try - { - var _ = JArray.Parse(jsonText); - return (jsonText, "array"); - } - catch (Exception ex) - { - throw new Exception("Fail parse JSON Object. " + ex.ToString()); - } - } - else - { - throw new Exception("Strange JSON. First 10 chars '" + jsonText.Substring(0, ((jsonText.Length) >= 10 ? 10 : jsonText.Length)) + "'"); - } - } + ///// + ///// expand value or user variable as JSON. this method returns root type "object" or "array". + ///// + ///// + ///// + ///// + ///// + //public static (string json, string rootType) ExpandValueOrUserVariableAsJSON(this string jsonValue, Core.Automation.Engine.AutomationEngineInstance engine) + //{ + // var jsonText = jsonValue.ExpandValueOrUserVariable(engine).Trim(); + // if (jsonText.StartsWith("{") && jsonText.EndsWith("}")) + // { + // try + // { + // var _ = JObject.Parse(jsonText); + // return (jsonText, "object"); + // } + // catch (Exception ex) + // { + // throw new Exception("Fail parse JSON Object. " + ex.ToString()); + // } + // } + // else if (jsonText.StartsWith("[") && jsonText.EndsWith("]")) + // { + // try + // { + // var _ = JArray.Parse(jsonText); + // return (jsonText, "array"); + // } + // catch (Exception ex) + // { + // throw new Exception("Fail parse JSON Object. " + ex.ToString()); + // } + // } + // else + // { + // throw new Exception("Strange JSON. First 10 chars '" + jsonText.Substring(0, ((jsonText.Length) >= 10 ? 10 : jsonText.Length)) + "'"); + // } + //} - /// - /// get JSON root type from string - /// - /// - /// - public static string GetJSONType(string jsonText) - { - jsonText = jsonText.Trim(); - if (jsonText.StartsWith("{") || jsonText.EndsWith("}")) - { - return "Object"; - } - else if (jsonText.StartsWith("[") || jsonText.EndsWith("]")) - { - return "Array"; - } - else if (jsonText.ToLower() == "true" || jsonText.ToLower() == "false") - { - return "bool"; - } - else if (decimal.TryParse(jsonText, out _)) - { - return "Number"; - } - else - { - return "Text"; - } - } + ///// + ///// get JSON root type from string + ///// + ///// + ///// + //public static string GetJSONType(string jsonText) + //{ + // jsonText = jsonText.Trim(); + // if (jsonText.StartsWith("{") || jsonText.EndsWith("}")) + // { + // return "Object"; + // } + // else if (jsonText.StartsWith("[") || jsonText.EndsWith("]")) + // { + // return "Array"; + // } + // else if (jsonText.ToLower() == "true" || jsonText.ToLower() == "false") + // { + // return "bool"; + // } + // else if (decimal.TryParse(jsonText, out _)) + // { + // return "Number"; + // } + // else + // { + // return "Text"; + // } + //} - /// - /// edit JSON by methods passed as arguments, specify a target by JSONPath. JSON specified by Variable Name. - /// - /// - /// - /// - /// - /// - /// - /// - public static void JSONModifyByJSONPath(this ScriptCommand command, string jsonName, string extractorName, Action objectAction, Action arrayAction, Engine.AutomationEngineInstance engine) - { - string jsonVariableName = command.ConvertToUserVariable(jsonName, "JSON", engine); - if (!engine.engineSettings.isWrappedVariableMarker(jsonVariableName)) - { - jsonVariableName = engine.engineSettings.wrapVariableMarker(jsonVariableName); - } - string extractor = command.ConvertToUserVariable(extractorName, "Extractor", engine); - (var jsonText, var rootType) = jsonVariableName.ConvertToUserVariableAsJSON(engine); - switch(rootType) - { - case "object": - var obj = JObject.Parse(jsonText); - var objResult = obj.SelectToken(extractor); - if (objResult == null) - { - throw new Exception("No Property found JSONPath '" + extractor + "'"); - } - objectAction(objResult); - obj.ToString().StoreInUserVariable(engine, jsonVariableName); - break; - case "array": - var ary = JArray.Parse(jsonText); - var aryResult = ary.SelectToken(extractor); - if (aryResult == null) - { - throw new Exception("No Property found JSONPath '" + extractor + "'"); - } - arrayAction(aryResult); - ary.ToString().StoreInUserVariable(engine, jsonVariableName); - break; - } - } + ///// + ///// edit JSON by methods passed as arguments, specify a target by JSONPath. JSON specified by Variable Name. + ///// + ///// + ///// + ///// + ///// + ///// + ///// + ///// + //public static void JSONModifyByJSONPath(this ScriptCommand command, string jsonName, string extractorName, Action objectAction, Action arrayAction, Engine.AutomationEngineInstance engine) + //{ + // string jsonVariableName = command.ExpandValueOrUserVariable(jsonName, "JSON", engine); + // //if (!engine.engineSettings.isWrappedVariableMarker(jsonVariableName)) + // if (!VariableNameControls.IsWrappedVariableMarker(jsonVariableName, engine)) + // { + // //jsonVariableName = engine.engineSettings.wrapVariableMarker(jsonVariableName); + // jsonVariableName = VariableNameControls.GetWrappedVariableName(jsonVariableName, engine); + // } + // string extractor = command.ExpandValueOrUserVariable(extractorName, "Extractor", engine); + // (var jsonText, var rootType) = jsonVariableName.ExpandValueOrUserVariableAsJSON(engine); + // switch(rootType) + // { + // case "object": + // var obj = JObject.Parse(jsonText); + // var objResult = obj.SelectToken(extractor); + // if (objResult == null) + // { + // throw new Exception("No Property found JSONPath '" + extractor + "'"); + // } + // objectAction(objResult); + // obj.ToString().StoreInUserVariable(engine, jsonVariableName); + // break; + // case "array": + // var ary = JArray.Parse(jsonText); + // var aryResult = ary.SelectToken(extractor); + // if (aryResult == null) + // { + // throw new Exception("No Property found JSONPath '" + extractor + "'"); + // } + // arrayAction(aryResult); + // ary.ToString().StoreInUserVariable(engine, jsonVariableName); + // break; + // } + //} - /// - /// do something to JSON (object, array) by methods passed as arguments. by default, JSON is text. - /// - /// - /// - /// - /// - /// - public static void JSONProcess(this ScriptCommand command, string jsonName, Action objectAction, Action arrayAction, Engine.AutomationEngineInstance engine, bool forceJSONVariable = false) - { - string jsonVariableName = command.ConvertToUserVariable(jsonName, "JSON", engine); - if (forceJSONVariable) - { - if (!engine.engineSettings.isWrappedVariableMarker(jsonVariableName)) - { - jsonVariableName = engine.engineSettings.wrapVariableMarker(jsonVariableName); - } - } - (var jsonText, var rootType) = jsonVariableName.ConvertToUserVariableAsJSON(engine); - switch (rootType) - { - case "object": - objectAction(JObject.Parse(jsonText)); - break; - case "array": - arrayAction(JArray.Parse(jsonText)); - break; - } - } + ///// + ///// do something to JSON (object, array) by methods passed as arguments. by default, JSON is text. + ///// + ///// + ///// + ///// + ///// + ///// + //public static void JSONProcess(this ScriptCommand command, string jsonName, Action objectAction, Action arrayAction, Engine.AutomationEngineInstance engine, bool forceJSONVariable = false) + //{ + // string jsonVariableName = command.ExpandValueOrUserVariable(jsonName, "JSON", engine); + // if (forceJSONVariable) + // { + // //if (!engine.engineSettings.isWrappedVariableMarker(jsonVariableName)) + // if (!VariableNameControls.IsWrappedVariableMarker(jsonVariableName, engine)) + // { + // //jsonVariableName = engine.engineSettings.wrapVariableMarker(jsonVariableName); + // jsonVariableName = VariableNameControls.GetWrappedVariableName(jsonVariableName, engine); + // } + // } + // (var jsonText, var rootType) = jsonVariableName.ExpandValueOrUserVariableAsJSON(engine); + // switch (rootType) + // { + // case "object": + // objectAction(JObject.Parse(jsonText)); + // break; + // case "array": + // arrayAction(JArray.Parse(jsonText)); + // break; + // } + //} - /// - /// get JSON value to add, insert, etc. - /// - /// - /// - /// - /// - /// - /// - /// - public static object GetJSONValue(this ScriptCommand command, string jsonValueName, string valueTypeName, string purpose, Engine.AutomationEngineInstance engine) - { - string jsonValue = command.ConvertToUserVariable(jsonValueName, "Value to " + purpose, engine); - string valueType = command.GetUISelectionValue(valueTypeName, "Value Type", engine); - if (valueType == "auto") - { - valueType = GetJSONType(jsonValue).ToLower(); - } + ///// + ///// get JSON value to add, insert, etc. + ///// + ///// + ///// + ///// + ///// + ///// + ///// + ///// + //public static object GetJSONValue(this ScriptCommand command, string jsonValueName, string valueTypeName, string purpose, Engine.AutomationEngineInstance engine) + //{ + // string jsonValue = command.ExpandValueOrUserVariable(jsonValueName, "Value to " + purpose, engine); + // string valueType = command.ExpandValueOrUserVariableAsSelectionItem(valueTypeName, "Value Type", engine); + // if (valueType == "auto") + // { + // valueType = GetJSONType(jsonValue).ToLower(); + // } - object ret = null; - switch (valueType) - { - case "text": - ret = jsonValue; - break; + // object ret = null; + // switch (valueType) + // { + // case "text": + // ret = jsonValue; + // break; - case "number": - ret = new PropertyConvertTag(jsonValue, "Value to " + purpose).ConvertToUserVariableAsDecimal(engine); - break; + // case "number": + // ret = new PropertyConvertTag(jsonValue, "Value to " + purpose).ExpandValueOrUserVariableAsDecimal(engine); + // break; - case "bool": - switch (jsonValue.ToLower()) - { - case "true": - case "false": - ret = bool.Parse(jsonValue); - break; - default: - throw new Exception("Value To Set is NOT bool. Value '" + jsonValue + "'"); - } - break; + // case "bool": + // switch (jsonValue.ToLower()) + // { + // case "true": + // case "false": + // ret = bool.Parse(jsonValue); + // break; + // default: + // throw new Exception("Value To Set is NOT bool. Value '" + jsonValue + "'"); + // } + // break; - case "object": - try - { - ret = JObject.Parse(jsonValue); - } - catch - { - throw new Exception("Value To Set is NOT Object. Value '" + jsonValue + "'"); - } - break; + // case "object": + // try + // { + // ret = JObject.Parse(jsonValue); + // } + // catch + // { + // throw new Exception("Value To Set is NOT Object. Value '" + jsonValue + "'"); + // } + // break; - case "array": - try - { - ret= JArray.Parse(jsonValue); - } - catch - { - throw new Exception("Value To Set is NOT Array. Value '" + jsonValue + "'"); - } - break; - } - return ret; - } + // case "array": + // try + // { + // ret= JArray.Parse(jsonValue); + // } + // catch + // { + // throw new Exception("Value To Set is NOT Array. Value '" + jsonValue + "'"); + // } + // break; + // } + // return ret; + //} public static void lnkJsonPathHelper_Click(object sender, EventArgs e) { - using (var fm = new UI.Forms.Supplement_Forms.frmJSONPathHelper()) + using (var fm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmJSONPathHelper()) { - if (fm.ShowDialog() == DialogResult.OK) + var item = (CommandItemControl)sender; + if (fm.ShowDialog(item.FindForm()) == DialogResult.OK) { - var ctrl = ((CommandItemControl)sender).Tag; + var ctrl = item.Tag; if (ctrl is TextBox txt) { txt.Text = fm.JSONPath; diff --git a/taskt/Core/Automation/Commands/KeyMouse/ClickMouseCommand.cs b/taskt/Core/Automation/Commands/KeyMouse/ClickMouseCommand.cs index 18ad804d5..4b36112cd 100644 --- a/taskt/Core/Automation/Commands/KeyMouse/ClickMouseCommand.cs +++ b/taskt/Core/Automation/Commands/KeyMouse/ClickMouseCommand.cs @@ -6,15 +6,17 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Key/Mouse Commands")] + [Attributes.ClassAttributes.Group("Key/Mouse")] [Attributes.ClassAttributes.SubGruop("Mouse")] + [Attributes.ClassAttributes.CommandSettings("Click Mouse")] [Attributes.ClassAttributes.Description("Simulates mouse clicks.")] [Attributes.ClassAttributes.UsesDescription("Use this command to simulate multiple types of mouse clicks.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'SetCursorPos' function from user32.dll to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_input))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ClickMouseCommand : ScriptCommand + public sealed class ClickMouseCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(KeyMouseControls), nameof(KeyMouseControls.v_MouseClickType))] @@ -24,6 +26,13 @@ public class ClickMouseCommand : ScriptCommand [PropertyVirtualProperty(nameof(KeyMouseControls), nameof(KeyMouseControls.v_WaitTimeAfterMouseClick))] public string v_WaitTimeAfterClick { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Ignore Wait Time When Click Type is 'None'")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + public string v_IgnoreWaitTime { get; set; } + public ClickMouseCommand() { //this.CommandName = "SendMouseClickCommand"; @@ -32,18 +41,20 @@ public ClickMouseCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var clickType = this.GetUISelectionValue(nameof(v_MouseClick), engine); + var clickType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_MouseClick), engine); var mousePosition = Cursor.Position; - //User32Functions.SendMouseClick(clickType, mousePosition.X, mousePosition.Y); KeyMouseControls.SendMouseClick(clickType, mousePosition.X, mousePosition.Y); - var waitTime = this.ConvertToUserVariableAsInteger(nameof(v_WaitTimeAfterClick), engine); - System.Threading.Thread.Sleep(waitTime); + var isIgnore = this.ExpandValueOrUserVariableAsYesNo(nameof(v_IgnoreWaitTime), engine); + + if ((clickType != "none") && isIgnore) + { + var waitTime = this.ExpandValueOrUserVariableAsInteger(nameof(v_WaitTimeAfterClick), engine); + System.Threading.Thread.Sleep(waitTime); + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/KeyMouse/EnterKeysCommand.cs b/taskt/Core/Automation/Commands/KeyMouse/EnterKeysCommand.cs index 20019bc00..c904fe59c 100644 --- a/taskt/Core/Automation/Commands/KeyMouse/EnterKeysCommand.cs +++ b/taskt/Core/Automation/Commands/KeyMouse/EnterKeysCommand.cs @@ -1,24 +1,25 @@ using System; using System.Windows.Forms; +using System.Collections.Generic; using System.Xml.Serialization; -using taskt.Core.Automation.User32; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Key/Mouse Commands")] + [Attributes.ClassAttributes.Group("Key/Mouse")] [Attributes.ClassAttributes.SubGruop("Key")] [Attributes.ClassAttributes.CommandSettings("Enter Keys")] [Attributes.ClassAttributes.Description("Sends keystrokes to a targeted window")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to send keystroke inputs to a window.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Windows.Forms.SendKeys' method to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_input))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class EnterKeysCommand : ScriptCommand + public sealed class EnterKeysCommand : ScriptCommand { [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowName))] public string v_WindowName { get; set; } [XmlAttribute] @@ -26,7 +27,6 @@ public class EnterKeysCommand : ScriptCommand [PropertyCustomUIHelper("Keys Builder", nameof(lnkKeysBulider_Click))] [PropertyCustomUIHelper("Encrypt Text", nameof(lnkEncryptText_Click))] [InputSpecification("Text to Send", true)] - //[SampleUsage("**Hello, World!** or **^s** or **{{{vEntryText}}}** or **{WIN_KEY}** or **{WIN_KEY+R}**")] [PropertyDetailSampleUsage("**Hello, World!**", PropertyDetailSampleUsage.ValueType.Value, "Text")] [PropertyDetailSampleUsage("**{{{vText}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Text")] [PropertyDetailSampleUsage("**^s**", "Specify **Ctrl+S** for Enter Keys")] @@ -47,26 +47,47 @@ public class EnterKeysCommand : ScriptCommand public string v_EncryptionOption { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Use Paste from Clipboard")] + [PropertyIsOptional(true, "No")] + [Remarks("When entering keys in combination with the Ctrl key, etc., It will NOT work correctly.")] + public string v_UseClipBoard { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_CompareMethod))] + public string v_CompareMethod { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] public string v_MatchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_TargetWindowIndex))] public string v_TargetWindowIndex { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitForWindow { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + public string v_WaitTimeForWindow { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(KeyMouseControls), nameof(KeyMouseControls.v_WaitTimeAfterKeyEnter))] public string v_WaitTime { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Try Activate Window, when Specifiy Current Window Variable")] + [PropertyIsOptional(true, "No")] + public string v_ActivateCurrentWindow { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowNameResult))] + public string v_NameResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_HandleResult { get; set; } + public EnterKeysCommand() { //this.CommandName = "SendKeysCommand"; @@ -76,102 +97,177 @@ public EnterKeysCommand() //this.v_EncryptionOption = "Not Encrypted"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //var targetWindow = v_WindowName.ExpandValueOrUserVariable(engine); + //if (targetWindow != engine.engineSettings.CurrentWindowKeyword) + //{ + // var activateWindow = new ActivateWindowCommand + // { + // v_WindowName = v_WindowName, + // v_SearchMethod = v_SearchMethod, + // v_MatchMethod= v_MatchMethod, + // v_TargetWindowIndex = v_TargetWindowIndex, + // v_WaitTime = v_WaitForWindow + // }; + // activateWindow.RunCommand(engine); + //} - var targetWindow = v_WindowName.ConvertToUserVariable(engine); - if (targetWindow != engine.engineSettings.CurrentWindowKeyword) - { - var activateWindow = new ActivateWindowCommand - { - v_WindowName = v_WindowName, - v_SearchMethod = v_SearchMethod, - v_MatchMethod= v_MatchMethod, - v_TargetWindowIndex = v_TargetWindowIndex, - v_WaitTime = v_WaitForWindow - }; - activateWindow.RunCommand(engine); - } + //var textToSend = v_TextToSend.ExpandValueOrUserVariable(engine); - var textToSend = v_TextToSend.ConvertToUserVariable(engine); + //var encryptOption = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_EncryptionOption), engine); + //if (encryptOption == "encrypted") + //{ + // textToSend = EncryptionServices.DecryptString(textToSend, "TASKT"); + //} - var encryptOption = this.GetUISelectionValue(nameof(v_EncryptionOption), engine); - if (encryptOption == "encrypted") - { - textToSend = EncryptionServices.DecryptString(textToSend, "TASKT"); - } + //if (textToSend == "{WIN_KEY}") + //{ + // KeyMouseControls.KeyDown(Keys.LWin); + // KeyMouseControls.KeyUp(Keys.LWin); + //} + //else if (textToSend.StartsWith("{WIN_KEY+") && textToSend.EndsWith("}")) + //{ + // KeyMouseControls.KeyDown(Keys.LWin); + // var remainingText = textToSend.Replace("{WIN_KEY+", "").Replace("}",""); - if (textToSend == "{WIN_KEY}") - { - //User32Functions.KeyDown(Keys.LWin); - //User32Functions.KeyUp(Keys.LWin); - KeyMouseControls.KeyDown(Keys.LWin); - KeyMouseControls.KeyUp(Keys.LWin); - } - else if (textToSend.StartsWith("{WIN_KEY+") && textToSend.EndsWith("}")) - { - //User32Functions.KeyDown(Keys.LWin); - KeyMouseControls.KeyDown(Keys.LWin); - var remainingText = textToSend.Replace("{WIN_KEY+", "").Replace("}",""); + // foreach (var c in remainingText) + // { + // Keys key = (Keys)Enum.Parse(typeof(Keys), c.ToString()); + // KeyMouseControls.KeyDown(key); + // } - foreach (var c in remainingText) - { - Keys key = (Keys)Enum.Parse(typeof(Keys), c.ToString()); - //User32Functions.KeyDown(key); - KeyMouseControls.KeyDown(key); - } + // KeyMouseControls.KeyUp(Keys.LWin); + + // foreach (var c in remainingText) + // { + // Keys key = (Keys)Enum.Parse(typeof(Keys), c.ToString()); + // KeyMouseControls.KeyUp(key); + // } + //} + //else + //{ + // SendKeys.SendWait(textToSend); + //} - //User32Functions.KeyUp(Keys.LWin); - KeyMouseControls.KeyUp(Keys.LWin); + //var waitTime = this.ExpandValueOrUserVariableAsInteger(nameof(v_WaitTime), engine); + //System.Threading.Thread.Sleep(waitTime); - foreach (var c in remainingText) + WindowControls.WindowAction(this, engine, + new Action>(wins => { - Keys key = (Keys)Enum.Parse(typeof(Keys), c.ToString()); - //User32Functions.KeyUp(key); - KeyMouseControls.KeyUp(key); - } - } - else - { - SendKeys.SendWait(textToSend); - } + //if (WindowControls.GetActiveWindowHandle() != wins[0].Item1) + //{ + // // DBG + // Console.WriteLine($"#### strange win-handle. cur: {WindowControls.GetActiveWindowHandle()}, arg: {wins[0].Item1}"); + // WindowControls.ActivateWindow(wins[0].Item1); + //} + //else + //{ + // // DBG + // Console.WriteLine($"#### same win-handle. key: {v_TextToSend}"); + //} + //if (VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Window_CurrentWindowName.VariableName, engine) == v_WindowName) + //{ + // // DBG + // Console.WriteLine($"#### same win-handle. key: {v_TextToSend}"); + //} + //else + //{ + // // DBG + // Console.WriteLine($"#### strange win-handle. cur: {WindowControls.GetActiveWindowHandle()}, arg: {wins[0].Item1}"); + // WindowControls.ActivateWindow(wins[0].Item1); + //} + + if (VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Window_CurrentWindowName.VariableName, engine) == v_WindowName) + { + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ActivateCurrentWindow), engine)) + { + WindowControls.ActivateWindow(wins[0].Item1); + } + } + else + { + WindowControls.ActivateWindow(wins[0].Item1); + } + + var textToSend = v_TextToSend.ExpandValueOrUserVariable(engine); + + var encryptOption = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_EncryptionOption), engine); + if (encryptOption == "encrypted") + { + textToSend = EncryptionServices.DecryptString(textToSend, "TASKT"); + } + + if (textToSend == "{WIN_KEY}") + { + KeyMouseControls.KeyDown(Keys.LWin); + KeyMouseControls.KeyUp(Keys.LWin); + } + else if (textToSend.StartsWith("{WIN_KEY+") && textToSend.EndsWith("}")) + { + KeyMouseControls.KeyDown(Keys.LWin); + var remainingText = textToSend.Replace("{WIN_KEY+", "").Replace("}", ""); + + foreach (var c in remainingText) + { + Keys key = (Keys)Enum.Parse(typeof(Keys), c.ToString()); + KeyMouseControls.KeyDown(key); + } + + KeyMouseControls.KeyUp(Keys.LWin); + + foreach (var c in remainingText) + { + Keys key = (Keys)Enum.Parse(typeof(Keys), c.ToString()); + KeyMouseControls.KeyUp(key); + } + } + else + { + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_UseClipBoard), engine)) + { + ClipboardControls.SetClipboardText(textToSend); + textToSend = "^v"; // Ctrl+V + } + SendKeys.SendWait(textToSend); + } - var waitTime = this.ConvertToUserVariableAsInteger(nameof(v_WaitTime), engine); - System.Threading.Thread.Sleep(waitTime); + var waitTime = this.ExpandValueOrUserVariableAsInteger(nameof(v_WaitTime), engine); + System.Threading.Thread.Sleep(waitTime); + }) + ); } private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + WindowControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); } private void lnkEncryptText_Click(object sender, EventArgs e) { - //var InputText = (TextBox)ControlsList[nameof(v_TextToSend)]; - var InputText = ControlsList.GetPropertyControl(nameof(v_TextToSend)); + var inputText = ControlsList.GetPropertyControl(nameof(v_TextToSend)); - if (string.IsNullOrEmpty(InputText.Text)) + if (string.IsNullOrEmpty(inputText.Text)) { MessageBox.Show("Text to send is empty.", "Notice"); return; } - var encrypted = EncryptionServices.EncryptString(InputText.Text, "TASKT"); + var encrypted = EncryptionServices.EncryptString(inputText.Text, "TASKT"); this.v_EncryptionOption = "Encrypted"; - InputText.Text = encrypted; + inputText.Text = encrypted; } private void lnkKeysBulider_Click(object sender, EventArgs e) { - using (var fm = new taskt.UI.Forms.Supplement_Forms.frmKeysBuilder()) + using (var fm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmKeysBuilder()) { - if (fm.ShowDialog() == DialogResult.OK) + if (fm.ShowDialog(((Control)sender).FindForm()) == DialogResult.OK) { - //var InputText = (TextBox)ControlsList[nameof(v_TextToSend)]; - var InputText = ControlsList.GetPropertyControl(nameof(v_TextToSend)); - InputText.Text = fm.Result; + var inputText = ControlsList.GetPropertyControl(nameof(v_TextToSend)); + inputText.Text = fm.Result; } } } diff --git a/taskt/Core/Automation/Commands/KeyMouse/EnterShortcutKeyCommand.cs b/taskt/Core/Automation/Commands/KeyMouse/EnterShortcutKeyCommand.cs index 0ba9ecd6d..d93a65d11 100644 --- a/taskt/Core/Automation/Commands/KeyMouse/EnterShortcutKeyCommand.cs +++ b/taskt/Core/Automation/Commands/KeyMouse/EnterShortcutKeyCommand.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Windows.Forms; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; @@ -7,18 +6,19 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Key/Mouse Commands")] + [Attributes.ClassAttributes.Group("Key/Mouse")] [Attributes.ClassAttributes.SubGruop("Key")] [Attributes.ClassAttributes.CommandSettings("Enter Shortcut Key")] [Attributes.ClassAttributes.Description("Sends keystrokes to a targeted window")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to send keystroke inputs to a window.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Windows.Forms.SendKeys' method to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_input))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class EnterShortcutKeyCommand : ScriptCommand + public sealed class EnterShortcutKeyCommand : ScriptCommand { [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowName))] public string v_WindowName { get; set; } [XmlAttribute] @@ -67,26 +67,34 @@ public class EnterShortcutKeyCommand : ScriptCommand public string v_Hotkey { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_CompareMethod))] + public string v_CompareMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] public string v_MatchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_TargetWindowIndex))] public string v_TargetWindowIndex { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitForWindow { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + public string v_WaitTimeForWindow { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(KeyMouseControls), nameof(KeyMouseControls.v_WaitTimeAfterKeyEnter))] public string v_WaitAfterKeyEnter { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowNameResult))] + public string v_NameResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_HandleResult { get; set; } + public EnterShortcutKeyCommand() { //this.CommandName = "SendHotkeyCommand"; @@ -95,12 +103,10 @@ public EnterShortcutKeyCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - string sendKey = ""; - switch (this.GetUISelectionValue(nameof(v_Hotkey), engine)) + switch (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_Hotkey), engine)) { case "new": sendKey = "^n"; @@ -160,32 +166,28 @@ public override void RunCommand(object sender) var enterKeysCommand = new EnterKeysCommand { - v_WindowName = v_WindowName, - v_SearchMethod = v_SearchMethod, + v_WindowName = this.v_WindowName, + v_CompareMethod = this.v_CompareMethod, v_TextToSend = sendKey, - v_MatchMethod = v_MatchMethod, - v_TargetWindowIndex = v_TargetWindowIndex, - v_WaitForWindow = v_WaitForWindow, - v_WaitTime = v_WaitAfterKeyEnter + v_MatchMethod = this.v_MatchMethod, + v_TargetWindowIndex = this.v_TargetWindowIndex, + v_WaitTimeForWindow = this.v_WaitTimeForWindow, + v_WaitTime = this.v_WaitAfterKeyEnter, + v_NameResult = this.v_NameResult, + v_HandleResult = this.v_HandleResult, }; enterKeysCommand.RunCommand(engine); } private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + WindowControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); } private void cmbHotkey_SelectedIndexChanged(object sender, EventArgs e) { - //var searchedKey = parameterHotkey.Text; var searchedKey = ((ComboBox)sender).SelectedItem?.ToString() ?? ""; - //var dic = (Dictionary)((Label)ControlsList["lbl_" + nameof(v_Hotkey)]).Tag; - - //var hotkey2ndLabel = (Label)ControlsList["lbl2_" + nameof(v_Hotkey)]; - //hotkey2ndLabel.Text = dic.ContainsKey(searchedKey) ? dic[searchedKey] : ""; - ControlsList.SecondLabelProcess(nameof(v_Hotkey), nameof(v_Hotkey), searchedKey); } } diff --git a/taskt/Core/Automation/Commands/KeyMouse/MoveMouseCommand.cs b/taskt/Core/Automation/Commands/KeyMouse/MoveMouseCommand.cs index 259ffa77a..da837d6e6 100644 --- a/taskt/Core/Automation/Commands/KeyMouse/MoveMouseCommand.cs +++ b/taskt/Core/Automation/Commands/KeyMouse/MoveMouseCommand.cs @@ -5,17 +5,17 @@ namespace taskt.Core.Automation.Commands { - [Serializable] - [Attributes.ClassAttributes.Group("Key/Mouse Commands")] + [Attributes.ClassAttributes.Group("Key/Mouse")] [Attributes.ClassAttributes.SubGruop("Mouse")] [Attributes.ClassAttributes.CommandSettings("Move Mouse")] [Attributes.ClassAttributes.Description("Simulates mouse movements")] [Attributes.ClassAttributes.UsesDescription("Use this command to simulate the movement of the mouse, additionally, this command also allows you to perform a click after movement has completed.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'SetCursorPos' function from user32.dll to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_input))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MoveMouseCommand : ScriptCommand + public sealed class MoveMouseCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -51,6 +51,13 @@ public class MoveMouseCommand : ScriptCommand [PropertyVirtualProperty(nameof(KeyMouseControls), nameof(KeyMouseControls.v_WaitTimeAfterMouseClick))] public string v_WaitTimeAfterClick { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Ignore Wait Time When Click Type is 'None'")] + [PropertyIsOptional(true, "Yes")] + [PropertyFirstValue("Yes")] + public string v_IgnoreWaitTime { get; set; } + public MoveMouseCommand() { //this.CommandName = "SendMouseMoveCommand"; @@ -59,28 +66,25 @@ public MoveMouseCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var mouseX = this.ConvertToUserVariableAsInteger(nameof(v_XMousePosition), engine); - var mouseY = this.ConvertToUserVariableAsInteger(nameof(v_YMousePosition), engine); + var mouseX = this.ExpandValueOrUserVariableAsInteger(nameof(v_XMousePosition), engine); + var mouseY = this.ExpandValueOrUserVariableAsInteger(nameof(v_YMousePosition), engine); try { - //var xLocation = Convert.ToInt32(Math.Floor(Convert.ToDouble(mouseX))); - //var yLocation = Convert.ToInt32(Math.Floor(Convert.ToDouble(mouseY))); - - //User32Functions.SetCursorPosition(xLocation, yLocation); - //User32Functions.SetCursorPosition(mouseX, mouseY); KeyMouseControls.SetCursorPosition(mouseX, mouseY); if (!String.IsNullOrEmpty(v_MouseClick)) { + // because default value is different from Click Mouse + var ignoreWaitTime = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IgnoreWaitTime), engine); + var clickCommand = new ClickMouseCommand { v_MouseClick = v_MouseClick, - v_WaitTimeAfterClick = v_WaitTimeAfterClick + v_WaitTimeAfterClick = v_WaitTimeAfterClick, + v_IgnoreWaitTime = ignoreWaitTime, }; clickCommand.RunCommand(engine); } @@ -93,7 +97,7 @@ public override void RunCommand(object sender) private void lnkMouseCapture_Clicked(object sender, EventArgs e) { - using (UI.Forms.Supplemental.frmShowCursorPosition frmShowCursorPos = new UI.Forms.Supplemental.frmShowCursorPosition()) + using (var frmShowCursorPos = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmShowCursorPosition()) { if (frmShowCursorPos.ShowDialog() == DialogResult.OK) { diff --git a/taskt/Core/Automation/Commands/KeyMouse/SendAdvancedKeyStrokesCommand.cs b/taskt/Core/Automation/Commands/KeyMouse/SendAdvancedKeyStrokesCommand.cs index b210e5c2e..cdab32211 100644 --- a/taskt/Core/Automation/Commands/KeyMouse/SendAdvancedKeyStrokesCommand.cs +++ b/taskt/Core/Automation/Commands/KeyMouse/SendAdvancedKeyStrokesCommand.cs @@ -2,29 +2,28 @@ using System.Collections.Generic; using System.Xml.Serialization; using System.Data; -using taskt.Core.Automation.User32; -using taskt.UI.Forms; using System.Windows.Forms; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { - [Serializable] - [Attributes.ClassAttributes.Group("Key/Mouse Commands")] + [Attributes.ClassAttributes.Group("Key/Mouse")] [Attributes.ClassAttributes.SubGruop("Key")] [Attributes.ClassAttributes.CommandSettings("Send Advanced Keystrokes")] [Attributes.ClassAttributes.Description("Sends advanced keystrokes to a targeted window")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to send advanced keystroke inputs to a window.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'User32' method to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_input))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SendAdvancedKeyStrokesCommand : ScriptCommand + public sealed class SendAdvancedKeyStrokesCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowName))] public string v_WindowName { get; set; } + [XmlElement] [PropertyDescription("Keys and Action Type")] [InputSpecification("")] [SampleUsage("")] @@ -36,32 +35,46 @@ public class SendAdvancedKeyStrokesCommand : ScriptCommand [PropertyDataGridViewCellEditEvent(nameof(DataTableControls) + "+" + nameof(DataTableControls.AllEditableDataGridView_CellClick), PropertyDataGridViewCellEditEvent.DataGridViewCellEvent.CellClick)] public DataTable v_KeyActions { get; set; } - [XmlElement] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Return all keys to 'UP' position after execution")] - [PropertyIsOptional(true, "No")] + [PropertyIsOptional(true, "Yes")] public string v_KeyUpDefault { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_CompareMethod))] + public string v_CompareMethod { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(KeyMouseControls), nameof(KeyMouseControls.v_WaitTimeAfterKeyEnter))] + public string v_WaitAfterKeyEnter { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] public string v_MatchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_TargetWindowIndex))] public string v_TargetWindowIndex { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitForWindow { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + public string v_WaitTimeForWindow { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(KeyMouseControls), nameof(KeyMouseControls.v_WaitTimeAfterKeyEnter))] - public string v_WaitAfterKeyEnter { get; set; } + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Try Activate Window, when Specifiy Current Window Variable")] + [PropertyIsOptional(true, "No")] + public string v_ActivateCurrentWindow { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowNameResult))] + public string v_NameResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_HandleResult { get; set; } public SendAdvancedKeyStrokesCommand() { @@ -71,116 +84,195 @@ public SendAdvancedKeyStrokesCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetWindow = v_WindowName.ConvertToUserVariable(sender); - - if (targetWindow != engine.engineSettings.CurrentWindowKeyword) - { - var activateWindow = new ActivateWindowCommand + WindowControls.WindowAction(this, engine, + new Action>(wins => { - v_WindowName = v_WindowName, - v_SearchMethod = v_SearchMethod, - v_MatchMethod = v_MatchMethod, - v_TargetWindowIndex = v_TargetWindowIndex, - v_WaitTime = v_WaitForWindow - }; - activateWindow.RunCommand(engine); - } + //var whnd = wins[0].Item1; + //WindowControls.ActivateWindow(whnd); + if (VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Window_CurrentWindowName.VariableName, engine) == v_WindowName) + { + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ActivateCurrentWindow), engine)) + { + WindowControls.ActivateWindow(wins[0].Item1); + } + } + else + { + WindowControls.ActivateWindow(wins[0].Item1); + } - //track all keys down - var keysDown = new List(); + //track all keys down + var keysDown = new List(); - //run each selected item - foreach (DataRow rw in v_KeyActions.Rows) - { - //get key name - var keyName = rw.Field("Key"); + //run each selected item + foreach (DataRow rw in v_KeyActions.Rows) + { + //get key name + var keyName = rw.Field("Key"); - //get key action - var action = rw.Field("Action"); + //get key action + var action = rw.Field("Action"); - //parse OEM key name - string oemKeyString = keyName.Split('[', ']')[1]; + //parse OEM key name + string oemKeyString = keyName.Split('[', ']')[1]; - var oemKeyName = (Keys)Enum.Parse(typeof(Keys), oemKeyString); + var oemKeyName = (Keys)Enum.Parse(typeof(Keys), oemKeyString); - - //"Key Press (Down + Up)", "Key Down", "Key Up" - switch (action) - { - case "Key Press (Down + Up)": - //simulate press - //User32Functions.KeyDown(oemKeyName); - //User32Functions.KeyUp(oemKeyName); - KeyMouseControls.KeyDown(oemKeyName); - KeyMouseControls.KeyUp(oemKeyName); - - //key returned to UP position so remove if we added it to the keys down list - if (keysDown.Contains(oemKeyName)) - { - keysDown.Remove(oemKeyName); - } - break; - case "Key Down": - //simulate down - //User32Functions.KeyDown(oemKeyName); - KeyMouseControls.KeyDown(oemKeyName); - - //track via keys down list - if (!keysDown.Contains(oemKeyName)) + + //"Key Press (Down + Up)", "Key Down", "Key Up" + switch (action) { - keysDown.Add(oemKeyName); + case "Key Press (Down + Up)": + //simulate press + KeyMouseControls.KeyDown(oemKeyName); + KeyMouseControls.KeyUp(oemKeyName); + + //key returned to UP position so remove if we added it to the keys down list + if (keysDown.Contains(oemKeyName)) + { + keysDown.Remove(oemKeyName); + } + break; + + case "Key Down": + //simulate down + KeyMouseControls.KeyDown(oemKeyName); + + //track via keys down list + if (!keysDown.Contains(oemKeyName)) + { + keysDown.Add(oemKeyName); + } + break; + + case "Key Up": + //simulate up + KeyMouseControls.KeyUp(oemKeyName); + + //remove from key down + if (keysDown.Contains(oemKeyName)) + { + keysDown.Remove(oemKeyName); + } + break; + + default: + break; } - - break; - case "Key Up": - //simulate up - //User32Functions.KeyUp(oemKeyName); - KeyMouseControls.KeyUp(oemKeyName); - - //remove from key down - if (keysDown.Contains(oemKeyName)) + } + + //return key to up position if requested + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_KeyUpDefault), engine)) + { + foreach (var key in keysDown) { - keysDown.Remove(oemKeyName); + KeyMouseControls.KeyUp(key); } + } + }) + ); - break; + //var targetWindow = v_WindowName.ExpandValueOrUserVariable(engine); - default: - break; - } + //if (targetWindow != engine.engineSettings.CurrentWindowKeyword) + //{ + // var activateWindow = new ActivateWindowCommand + // { + // v_WindowName = v_WindowName, + // v_SearchMethod = v_SearchMethod, + // v_MatchMethod = v_MatchMethod, + // v_TargetWindowIndex = v_TargetWindowIndex, + // v_WaitTime = v_WaitForWindow + // }; + // activateWindow.RunCommand(engine); + //} - } + ////track all keys down + //var keysDown = new List(); - //return key to up position if requested - if (this.GetYesNoSelectionValue(nameof(v_KeyUpDefault), engine)) - { - foreach (var key in keysDown) - { - //User32Functions.KeyUp(key); - KeyMouseControls.KeyUp(key); - } - } + ////run each selected item + //foreach (DataRow rw in v_KeyActions.Rows) + //{ + // //get key name + // var keyName = rw.Field("Key"); + + // //get key action + // var action = rw.Field("Action"); + + // //parse OEM key name + // string oemKeyString = keyName.Split('[', ']')[1]; + + // var oemKeyName = (Keys)Enum.Parse(typeof(Keys), oemKeyString); + + + // //"Key Press (Down + Up)", "Key Down", "Key Up" + // switch (action) + // { + // case "Key Press (Down + Up)": + // //simulate press + // KeyMouseControls.KeyDown(oemKeyName); + // KeyMouseControls.KeyUp(oemKeyName); + + // //key returned to UP position so remove if we added it to the keys down list + // if (keysDown.Contains(oemKeyName)) + // { + // keysDown.Remove(oemKeyName); + // } + // break; + + // case "Key Down": + // //simulate down + // KeyMouseControls.KeyDown(oemKeyName); + + // //track via keys down list + // if (!keysDown.Contains(oemKeyName)) + // { + // keysDown.Add(oemKeyName); + // } + // break; + + // case "Key Up": + // //simulate up + // KeyMouseControls.KeyUp(oemKeyName); + + // //remove from key down + // if (keysDown.Contains(oemKeyName)) + // { + // keysDown.Remove(oemKeyName); + // } + // break; + + // default: + // break; + // } + //} + + ////return key to up position if requested + //if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_KeyUpDefault), engine)) + //{ + // foreach (var key in keysDown) + // { + // KeyMouseControls.KeyUp(key); + // } + //} } private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + WindowControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - //var dgv = (DataGridView)ControlsList[nameof(v_KeyActions)]; var dgv = ControlsList.GetPropertyControl(nameof(v_KeyActions)); var column = (DataGridViewComboBoxColumn)dgv.Columns[0]; - column.DataSource = Common.GetAvailableKeys(); + column.DataSource = KeyMouseControls.KeysList; } - public override bool IsValidate(frmCommandEditor editor) + public override bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.IsValidate(editor); @@ -201,5 +293,13 @@ public override bool IsValidate(frmCommandEditor editor) return this.IsValid; } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_KeyActions)); + DataTableControls.BeforeValidate(dgv, v_KeyActions); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/KeyMouseControls.cs b/taskt/Core/Automation/Commands/KeyMouseControls.cs index 78195619b..c54acf6cb 100644 --- a/taskt/Core/Automation/Commands/KeyMouseControls.cs +++ b/taskt/Core/Automation/Commands/KeyMouseControls.cs @@ -1,5 +1,4 @@ using System; -using System.Data; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Windows.Forms; @@ -7,7 +6,7 @@ namespace taskt.Core.Automation.Commands { - static internal class KeyMouseControls + static public class KeyMouseControls { #region VirtualProperty /// @@ -23,6 +22,7 @@ static internal class KeyMouseControls [PropertyFirstValue("500")] [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Wait Time", PropertyValidationRule.ValidationRuleFlags.LessThanZero | PropertyValidationRule.ValidationRuleFlags.EqualsZero)] + [PropertyParameterOrder(5000)] public static string v_WaitTimeAfterKeyEnter { get; } /// @@ -46,6 +46,7 @@ static internal class KeyMouseControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyValidationRule("Mouse Click", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Mouse Click")] + [PropertyParameterOrder(5000)] public static string v_MouseClickType { get; } /// @@ -61,6 +62,7 @@ static internal class KeyMouseControls [PropertyFirstValue("500")] [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Wait Time", PropertyValidationRule.ValidationRuleFlags.LessThanZero | PropertyValidationRule.ValidationRuleFlags.EqualsZero)] + [PropertyParameterOrder(5000)] public static string v_WaitTimeAfterMouseClick { get; } /// @@ -77,6 +79,7 @@ static internal class KeyMouseControls [PropertyIsOptional(true, "0")] [PropertyFirstValue("0")] [PropertyDisplayText(true, "Offset X")] + [PropertyParameterOrder(5000)] public static string v_XOffsetAdjustment { get; } /// @@ -93,10 +96,11 @@ static internal class KeyMouseControls [PropertyIsOptional(true, "0")] [PropertyFirstValue("0")] [PropertyDisplayText(true, "Offset Y")] + [PropertyParameterOrder(5000)] public static string v_YOffsetAdjustment { get; } #endregion - #region enum, struct, const + #region enum, struct, const, field, property private enum MouseEvents { MOUSEEVENTF_LEFTDOWN = 0x02, @@ -110,6 +114,35 @@ private enum MouseEvents private const int KEYEVENTF_EXTENDEDKEY = 0x1; private const int KEYEVENTF_KEYUP = 0x2; + private static Dictionary _keysDescription = new Dictionary(); + + public static Dictionary KeysDescription + { + get + { + if (_keysDescription.Count == 0) + { + CreateKeysDescription(); + } + + return _keysDescription; + } + } + + private static List _keysList = new List(); + + public static List KeysList + { + get + { + if (_keysList.Count == 0) + { + CreateKeysList(); + } + return _keysList; + } + } + #endregion #region api @@ -221,6 +254,428 @@ public static void KeyUp(Keys vKey) { keybd_event((byte)vKey, 0, KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP, 0); } + + private static void CreateKeysDescription() + { + _keysDescription.Clear(); + foreach(Keys k in Enum.GetValues(typeof(Keys))) + { + if (_keysDescription.ContainsKey(k.ToString())) + { + continue; + } + + switch (k) + { + //letters + case Keys.A: + case Keys.B: + case Keys.C: + case Keys.D: + case Keys.E: + case Keys.F: + case Keys.G: + case Keys.H: + case Keys.I: + case Keys.J: + case Keys.K: + case Keys.L: + case Keys.M: + case Keys.N: + case Keys.O: + case Keys.P: + case Keys.Q: + case Keys.R: + case Keys.S: + case Keys.T: + case Keys.U: + case Keys.V: + case Keys.W: + case Keys.X: + case Keys.Y: + case Keys.Z: + _keysDescription.Add(k.ToString(), k.ToString()); + break; + + //digits + case Keys.D0: + _keysDescription.Add(k.ToString(), "0"); + break; + + case Keys.NumPad0: + _keysDescription.Add(k.ToString(), "Number Pad 0"); + break; + case Keys.D1: + _keysDescription.Add(k.ToString(), "1"); + break; + case Keys.NumPad1: + _keysDescription.Add(k.ToString(), "Number Pad 1"); + break; + case Keys.D2: + _keysDescription.Add(k.ToString(), "2"); + break; + case Keys.NumPad2: + _keysDescription.Add(k.ToString(), "Number Pad 2"); + break; + case Keys.D3: + _keysDescription.Add(k.ToString(), "3"); + break; + case Keys.NumPad3: + _keysDescription.Add(k.ToString(), "Number Pad 3"); + break; + case Keys.D4: + _keysDescription.Add(k.ToString(), "4"); + break; + case Keys.NumPad4: + _keysDescription.Add(k.ToString(), "Number Pad 4"); + break; + case Keys.D5: + _keysDescription.Add(k.ToString(), "5"); + break; + case Keys.NumPad5: + _keysDescription.Add(k.ToString(), "Number Pad 5"); + break; + case Keys.D6: + _keysDescription.Add(k.ToString(), "6"); + break; + case Keys.NumPad6: + _keysDescription.Add(k.ToString(), "Number Pad 6"); + break; + case Keys.D7: + _keysDescription.Add(k.ToString(), "7"); + break; + case Keys.NumPad7: + _keysDescription.Add(k.ToString(), "Number Pad 7"); + break; + case Keys.D8: + _keysDescription.Add(k.ToString(), "8"); + break; + case Keys.NumPad8: + _keysDescription.Add(k.ToString(), "Number Pad 8"); + break; + case Keys.D9: + _keysDescription.Add(k.ToString(), "9"); + break; + case Keys.NumPad9: + _keysDescription.Add(k.ToString(), "Number Pad 9"); + break; + + //punctuation + case Keys.Add: + _keysDescription.Add(k.ToString(), "Number Pad +"); + break; + case Keys.Subtract: + _keysDescription.Add(k.ToString(), "Number Pad -"); + break; + case Keys.Divide: + _keysDescription.Add(k.ToString(), "Number Pad /"); + break; + case Keys.Multiply: + _keysDescription.Add(k.ToString(), "Number Pad *"); + break; + case Keys.Space: + _keysDescription.Add(k.ToString(), "Spacebar"); + break; + case Keys.Decimal: + _keysDescription.Add(k.ToString(), "Number Pad ."); + break; + + //function + case Keys.F1: + case Keys.F2: + case Keys.F3: + case Keys.F4: + case Keys.F5: + case Keys.F6: + case Keys.F7: + case Keys.F8: + case Keys.F9: + case Keys.F10: + case Keys.F11: + case Keys.F12: + case Keys.F13: + case Keys.F14: + case Keys.F15: + case Keys.F16: + case Keys.F17: + case Keys.F18: + case Keys.F19: + case Keys.F20: + case Keys.F21: + case Keys.F22: + case Keys.F23: + case Keys.F24: + _keysDescription.Add(k.ToString(), k.ToString()); + break; + + //navigation + case Keys.Up: + _keysDescription.Add(k.ToString(), "Up Arrow"); + break; + case Keys.Down: + _keysDescription.Add(k.ToString(), "Down Arrow"); + break; + case Keys.Left: + _keysDescription.Add(k.ToString(), "Left Arrow"); + break; + case Keys.Right: + _keysDescription.Add(k.ToString(), "Right Arrow"); + break; + case Keys.Prior: + _keysDescription.Add(k.ToString(), "Page Up"); + break; + case Keys.Next: + _keysDescription.Add(k.ToString(), "Page Down"); + break; + case Keys.Home: + _keysDescription.Add(k.ToString(), "Home"); + break; + case Keys.End: + _keysDescription.Add(k.ToString(), "End"); + break; + + //control keys + case Keys.Back: + _keysDescription.Add(k.ToString(), "Backspace"); + break; + case Keys.Tab: + _keysDescription.Add(k.ToString(), "Tab"); + break; + case Keys.Escape: + _keysDescription.Add(k.ToString(), "Escape"); + break; + case Keys.Enter: + _keysDescription.Add(k.ToString(), "Enter"); + break; + case Keys.Shift: + case Keys.ShiftKey: + _keysDescription.Add(k.ToString(), "Shift"); + break; + case Keys.LShiftKey: + _keysDescription.Add(k.ToString(), "Shift (Left)"); + break; + case Keys.RShiftKey: + _keysDescription.Add(k.ToString(), "Shift (Right)"); + break; + case Keys.Control: + case Keys.ControlKey: + _keysDescription.Add(k.ToString(), "Control"); + break; + case Keys.LControlKey: + _keysDescription.Add(k.ToString(), "Control (Left)"); + break; + case Keys.RControlKey: + _keysDescription.Add(k.ToString(), "Control (Right)"); + break; + case Keys.Menu: + case Keys.Alt: + _keysDescription.Add(k.ToString(), "Alt"); + break; + case Keys.LMenu: + _keysDescription.Add(k.ToString(), "Alt (Left)"); + break; + case Keys.RMenu: + _keysDescription.Add(k.ToString(), "Alt (Right)"); + break; + case Keys.Pause: + _keysDescription.Add(k.ToString(), "Pause"); + break; + case Keys.CapsLock: + _keysDescription.Add(k.ToString(), "Caps Lock"); + break; + case Keys.NumLock: + _keysDescription.Add(k.ToString(), "Num Lock"); + break; + case Keys.Scroll: + _keysDescription.Add(k.ToString(), "Scroll Lock"); + break; + case Keys.PrintScreen: + _keysDescription.Add(k.ToString(), "Print Screen"); + break; + case Keys.Insert: + _keysDescription.Add(k.ToString(), "Insert"); + break; + case Keys.Delete: + _keysDescription.Add(k.ToString(), "Delete"); + break; + case Keys.Help: + _keysDescription.Add(k.ToString(), "Help"); + break; + case Keys.LWin: + _keysDescription.Add(k.ToString(), "Windows (Left)"); + break; + case Keys.RWin: + _keysDescription.Add(k.ToString(), "Windows (Right)"); + break; + case Keys.Apps: + _keysDescription.Add(k.ToString(), "Context Menu"); + break; + + //browser keys + case Keys.BrowserBack: + _keysDescription.Add(k.ToString(), "Browser Back"); + break; + case Keys.BrowserFavorites: + _keysDescription.Add(k.ToString(), "Browser Favorites"); + break; + case Keys.BrowserForward: + _keysDescription.Add(k.ToString(), "Browser Forward"); + break; + case Keys.BrowserHome: + _keysDescription.Add(k.ToString(), "Browser Home"); + break; + case Keys.BrowserRefresh: + _keysDescription.Add(k.ToString(), "Browser Refresh"); + break; + case Keys.BrowserSearch: + _keysDescription.Add(k.ToString(), "Browser Search"); + break; + case Keys.BrowserStop: + _keysDescription.Add(k.ToString(), "Browser Stop"); + break; + + //media keys + case Keys.VolumeDown: + _keysDescription.Add(k.ToString(), "Volume Down"); + break; + case Keys.VolumeMute: + _keysDescription.Add(k.ToString(), "Volume Mute"); + break; + case Keys.VolumeUp: + _keysDescription.Add(k.ToString(), "Volume Up"); + break; + case Keys.MediaNextTrack: + _keysDescription.Add(k.ToString(), "Next Track"); + break; + case Keys.Play: + case Keys.MediaPlayPause: + _keysDescription.Add(k.ToString(), "Play"); + break; + case Keys.MediaPreviousTrack: + _keysDescription.Add(k.ToString(), "Previous Track"); + break; + case Keys.MediaStop: + _keysDescription.Add(k.ToString(), "Stop"); + break; + case Keys.SelectMedia: + _keysDescription.Add(k.ToString(), "Select Media"); + break; + + //special keys + case Keys.LaunchMail: + _keysDescription.Add(k.ToString(), "Launch Mail"); + break; + case Keys.LaunchApplication1: + _keysDescription.Add(k.ToString(), "Launch Favorite Application 1"); + break; + case Keys.LaunchApplication2: + _keysDescription.Add(k.ToString(), "Launch Favorite Application 2"); + break; + case Keys.Zoom: + _keysDescription.Add(k.ToString(), "Zoom"); + break; + + //oem keys + case Keys.OemSemicolon: //oem1 + _keysDescription.Add(k.ToString(), ");"); + break; + case Keys.OemQuestion: //oem2 + _keysDescription.Add(k.ToString(), "?"); + break; + case Keys.Oemtilde: //oem3 + _keysDescription.Add(k.ToString(), "~"); + break; + case Keys.OemOpenBrackets: //oem4 + _keysDescription.Add(k.ToString(), "["); + break; + case Keys.OemPipe: //oem5 + _keysDescription.Add(k.ToString(), "|"); + break; + case Keys.OemCloseBrackets: //oem6 + _keysDescription.Add(k.ToString(), "]"); + break; + case Keys.OemQuotes: //oem7 + _keysDescription.Add(k.ToString(), "'"); + break; + case Keys.OemBackslash: //oem102 + _keysDescription.Add(k.ToString(), "/"); + break; + case Keys.Oemplus: + _keysDescription.Add(k.ToString(), "+"); + break; + case Keys.OemMinus: + _keysDescription.Add(k.ToString(), "-"); + break; + case Keys.Oemcomma: + _keysDescription.Add(k.ToString(), ","); + break; + case Keys.OemPeriod: + _keysDescription.Add(k.ToString(), "."); + break; + + //unsupported oem keys + case Keys.Oem8: + case Keys.OemClear: + break; + + + //IME keys (not support SendKeys) + case Keys.HanjaMode: + case Keys.JunjaMode: + case Keys.HangulMode: + case Keys.FinalMode: //duplicate values: Hanguel, Kana, Kanji + case Keys.IMEAccept: + case Keys.IMEConvert: //duplicate: IMEAceept + case Keys.IMEModeChange: + case Keys.IMENonconvert: + break; + + //unsupported other keys + case Keys.None: + case Keys.LButton: + case Keys.RButton: + case Keys.MButton: + case Keys.XButton1: + case Keys.XButton2: + case Keys.Clear: + case Keys.Sleep: + case Keys.Cancel: + case Keys.LineFeed: + case Keys.Select: + case Keys.Print: + case Keys.Execute: + case Keys.Separator: + case Keys.ProcessKey: + case Keys.Packet: + case Keys.Attn: + case Keys.Crsel: + case Keys.Exsel: + case Keys.EraseEof: + case Keys.NoName: + case Keys.Pa1: + case Keys.KeyCode: + case Keys.Modifiers: + default: + break; + } + } + } + + public static void CreateKeysList() + { + if (_keysDescription.Count == 0) + { + CreateKeysDescription(); + } + + if (_keysList.Count == 0) + { + foreach(var kv in _keysDescription) + { + _keysList.Add(string.Concat(kv.Value, " [", kv.Key, "]")); + } + } + } #endregion } } diff --git a/taskt/Core/Automation/Commands/List/AListBothListCommands.cs b/taskt/Core/Automation/Commands/List/AListBothListCommands.cs new file mode 100644 index 000000000..dfe5732a6 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/AListBothListCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Both List Commands + /// + public abstract class AListBothListCommands : AListInputListCommands + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_BothListName))] + public override string v_List { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/AListCreateFromListCommands.cs b/taskt/Core/Automation/Commands/List/AListCreateFromListCommands.cs new file mode 100644 index 000000000..dfa5a8732 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/AListCreateFromListCommands.cs @@ -0,0 +1,21 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Create List From List commands + /// + public abstract class AListCreateFromListCommands : ScriptCommand, ILListCreateFromListProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + [PropertyParameterOrder(5000)] + public virtual string v_TargetList { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_NewOutputListName))] + [PropertyParameterOrder(10000)] + public virtual string v_NewList { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/AListGetFromListCommands.cs b/taskt/Core/Automation/Commands/List/AListGetFromListCommands.cs new file mode 100644 index 000000000..0b88b461c --- /dev/null +++ b/taskt/Core/Automation/Commands/List/AListGetFromListCommands.cs @@ -0,0 +1,15 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Get something From List commands + /// + public abstract class AListGetFromListCommands : AListInputListCommands, IListGetFromListProperties + { + [XmlAttribute] + [PropertyParameterOrder(10000)] + public abstract string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/AListGetFromValueCommands.cs b/taskt/Core/Automation/Commands/List/AListGetFromValueCommands.cs new file mode 100644 index 000000000..5afdac571 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/AListGetFromValueCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Get List something from List Value commands + /// + public abstract class AListGetFromValueCommands : AListGetFromListCommands, IListGetFromValueProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_SearchValue))] + [PropertyParameterOrder(7000)] + public string v_Value { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/AListGetMathResultFromListCommands.cs b/taskt/Core/Automation/Commands/List/AListGetMathResultFromListCommands.cs new file mode 100644 index 000000000..6402fb597 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/AListGetMathResultFromListCommands.cs @@ -0,0 +1,20 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for Get Math Result from List commands + /// + public abstract class AListGetMathResultFromListCommands : AListGetFromListCommands, IListGetMathResultFromListProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] + [PropertyParameterOrder(11000)] + public virtual string v_WhenValueIsNotNumeric { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/AListIndexCommands.cs b/taskt/Core/Automation/Commands/List/AListIndexCommands.cs new file mode 100644 index 000000000..75c34b469 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/AListIndexCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for List Index specified commands + /// + public abstract class AListIndexCommands : AListInputListCommands, IListIndexProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ListIndex))] + [PropertyParameterOrder(6000)] + public virtual string v_Index { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/AListInputListCommands.cs b/taskt/Core/Automation/Commands/List/AListInputListCommands.cs new file mode 100644 index 000000000..16bafc62e --- /dev/null +++ b/taskt/Core/Automation/Commands/List/AListInputListCommands.cs @@ -0,0 +1,16 @@ +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for List Input Commands + /// + public abstract class AListInputListCommands : ScriptCommand, ILListProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + [PropertyParameterOrder(5000)] + public virtual string v_List { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/AddListItemCommand.cs b/taskt/Core/Automation/Commands/List/AddListItemCommand.cs index 060ed1830..2abb134ed 100644 --- a/taskt/Core/Automation/Commands/List/AddListItemCommand.cs +++ b/taskt/Core/Automation/Commands/List/AddListItemCommand.cs @@ -6,19 +6,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Item")] [Attributes.ClassAttributes.CommandSettings("Add List Item")] [Attributes.ClassAttributes.Description("This command allows you to add list item.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add list item. You can even use variables to modify other variables.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class AddListItemCommand : ScriptCommand + public sealed class AddListItemCommand : AListBothListCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_BothListName))] - public string v_ListName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_BothListName))] + //public string v_List { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_OneLineTextBox))] @@ -26,6 +27,7 @@ public class AddListItemCommand : ScriptCommand [PropertyDetailSampleUsage("**Hello**", PropertyDetailSampleUsage.ValueType.Value, "the Value to be added List")] [PropertyDetailSampleUsage("**{{{vValue}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "the Value to be added List")] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(6000)] public string v_Input { get; set; } public AddListItemCommand() @@ -36,14 +38,12 @@ public AddListItemCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - List lst = v_ListName.GetListVariable(engine); + //List lst = v_List.ExpandUserVariableAsList(engine); + var lst = this.ExpandUserVariableAsList(engine); - var variableInput = v_Input.ConvertToUserVariable(sender); + var variableInput = v_Input.ExpandValueOrUserVariable(engine); lst.Add(variableInput); } } diff --git a/taskt/Core/Automation/Commands/List/CheckListItemExistsCommand.cs b/taskt/Core/Automation/Commands/List/CheckListItemExistsCommand.cs index c51d055c6..747df992e 100644 --- a/taskt/Core/Automation/Commands/List/CheckListItemExistsCommand.cs +++ b/taskt/Core/Automation/Commands/List/CheckListItemExistsCommand.cs @@ -6,28 +6,29 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Item")] [Attributes.ClassAttributes.CommandSettings("Check List Item Exists")] [Attributes.ClassAttributes.Description("This command allows you want to check list has a value you specify")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check list has a value you specify")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CheckListItemExistsCommand : ScriptCommand + public sealed class CheckListItemExistsCommand : AListGetFromValueCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_ListName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_SearchValue))] - public string v_SearchItem { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_SearchValue))] + //public string v_Value { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] + //[PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] [Remarks("When the Item Exists, the Result is **True**")] - public string v_Result { get; set; } + public override string v_Result { get; set; } public CheckListItemExistsCommand() { @@ -37,13 +38,12 @@ public CheckListItemExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - List targetList = v_ListName.GetListVariable(engine); + //var targetList = v_List.ExpandUserVariableAsList(engine); + var targetList = this.ExpandUserVariableAsList(engine); - var searchedValue = v_SearchItem.ConvertToUserVariable(sender); + var searchedValue = v_Value.ExpandValueOrUserVariable(engine); targetList.Contains(searchedValue).StoreInUserVariable(engine, v_Result); } diff --git a/taskt/Core/Automation/Commands/List/ConcatenateListsCommand.cs b/taskt/Core/Automation/Commands/List/ConcatenateListsCommand.cs index 834474157..9615e176a 100644 --- a/taskt/Core/Automation/Commands/List/ConcatenateListsCommand.cs +++ b/taskt/Core/Automation/Commands/List/ConcatenateListsCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Actions")] [Attributes.ClassAttributes.CommandSettings("Concatenate Lists")] [Attributes.ClassAttributes.Description("This command allows you to concatenate 2 lists.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to concatenate 2 lists.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConcatenateListsCommand : ScriptCommand + public sealed class ConcatenateListsCommand : ScriptCommand, ICanHandleList { [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] @@ -23,7 +24,7 @@ public class ConcatenateListsCommand : ScriptCommand [PropertyDetailSampleUsage("**vList1**", PropertyDetailSampleUsage.ValueType.VariableName)] [PropertyDetailSampleUsage("**{{{vList1}}}**", PropertyDetailSampleUsage.ValueType.VariableName)] [PropertyDisplayText(true, "List1")] - public string v_InputListA { get; set; } + public string v_ListA { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] @@ -32,12 +33,12 @@ public class ConcatenateListsCommand : ScriptCommand [PropertyDetailSampleUsage("**vList2**", PropertyDetailSampleUsage.ValueType.VariableName)] [PropertyDetailSampleUsage("**{{{vList2}}}**", PropertyDetailSampleUsage.ValueType.VariableName)] [PropertyDisplayText(true, "List2")] - public string v_InputListB { get; set; } + public string v_ListB { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_NewOutputListName))] [Remarks("Concatenate List1, List2 in that order")] - public string v_OutputList { get; set; } + public string v_NewList { get; set; } public ConcatenateListsCommand() { @@ -47,17 +48,20 @@ public ConcatenateListsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //var listA = v_ListA.ExpandUserVariableAsList(engine); + //var listB = v_ListB.ExpandUserVariableAsList(engine); - List listA = v_InputListA.GetListVariable(engine); - List listB = v_InputListB.GetListVariable(engine); + var listA = this.ExpandUserVariableAsList(nameof(v_ListA), engine); + var listB = this.ExpandUserVariableAsList(nameof(v_ListB), engine); - List newList = new List(); + var newList = new List(); newList.AddRange(listA); newList.AddRange(listB); - newList.StoreInUserVariable(engine, v_OutputList); + + //newList.StoreInUserVariable(engine, v_NewList); + this.StoreListInUserVariable(newList, nameof(v_NewList), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/ConvertListToDataTableCommand.cs b/taskt/Core/Automation/Commands/List/ConvertListToDataTableCommand.cs index 0ae7cd177..5be412f4b 100644 --- a/taskt/Core/Automation/Commands/List/ConvertListToDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/List/ConvertListToDataTableCommand.cs @@ -1,26 +1,27 @@ using System; using System.Collections.Generic; -using System.Xml.Serialization; using System.Data; -using taskt.Core.Automation.Attributes.PropertyAttributes; using System.Linq; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Convert")] [Attributes.ClassAttributes.CommandSettings("Convert List To DataTable")] [Attributes.ClassAttributes.Description("This command convert a List to a DataTable.")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertListToDataTableCommand : ScriptCommand + public sealed class ConvertListToDataTableCommand : AListGetFromListCommands, IDataTableResultProperties, ICanHandleList { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_InputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_AType))] @@ -29,6 +30,7 @@ public class ConvertListToDataTableCommand : ScriptCommand [PropertyIsOptional(true, "Column Prefix")] [PropertyDisplayText(true, "DataTable Columns Type")] [PropertyDetailSampleUsage("**col**", "When Select **Column Prefix** and Enter **col**, Column Name is col0, col1, col2, ...")] + [PropertyParameterOrder(6000)] public string v_ColumnType { get; set; } [XmlAttribute] @@ -41,22 +43,25 @@ public class ConvertListToDataTableCommand : ScriptCommand [PropertyIsOptional(true)] [PropertyInstanceType(PropertyInstanceType.InstanceType.List)] [PropertyDisplayText(true, "Columns Name List")] + [PropertyParameterOrder(6001)] public string v_Columns { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ANotEnough))] [PropertyDescription("When the number of items in the List is greater than the number of Columns")] [PropertyUISelectionOption("Try Create Columns")] + [PropertyParameterOrder(6002)] public string v_ColumnsNotEnough { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ListItemNotEnough))] [PropertyDescription("When the number of Columns is greater than the number of items in the List")] + [PropertyParameterOrder(6003)] public string v_ListItemNotEnough { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] - public string v_applyToVariableName { get; set; } + public override string v_Result { get; set; } public ConvertListToDataTableCommand() { @@ -66,26 +71,25 @@ public ConvertListToDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - List targetList = v_InputList.GetListVariable(engine); + //List targetList = v_List.ExpandUserVariableAsList(engine); + var targetList = this.ExpandUserVariableAsList(engine); - DataTable myDT = new DataTable(); + var myDT = new DataTable(); - Action> dtUseColumns = new Action>((targetColumns) => + var dtUseColumns = new Action>((targetColumns) => { - string columnsNotEnough = this.GetUISelectionValue(nameof(v_ColumnsNotEnough), "Columns Not Enough", engine); - string listItemNotEnough = this.GetUISelectionValue(nameof(v_ListItemNotEnough), "List Item Not Enough", engine); + string columnsNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ColumnsNotEnough), "Columns Not Enough", engine); + string listItemNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ListItemNotEnough), "List Item Not Enough", engine); if ((columnsNotEnough == "error") && (targetList.Count > targetColumns.Count)) { - throw new Exception("The number of keys in " + v_Columns + " is not enough"); + throw new Exception($"The number of keys in '{v_Columns}' is not enough"); } if ((listItemNotEnough == "error") && (targetColumns.Count > targetList.Count)) { - throw new Exception("The number of List items in " + v_InputList + " is not enough"); + throw new Exception($"The number of List items in '{v_List}' is not enough"); } if (targetList.Count == targetColumns.Count) @@ -119,7 +123,8 @@ public override void RunCommand(object sender) } for (int i = targetColumns.Count; i < targetList.Count; i++) { - myDT.Columns.Add("column" + i.ToString()); + //myDT.Columns.Add("column" + i.ToString()); + myDT.Columns.Add($"column{i}"); myDT.Rows[0][i] = targetList[i]; } break; @@ -156,39 +161,39 @@ public override void RunCommand(object sender) }); List columnsList; - - string columnsType = this.GetUISelectionValue(nameof(v_ColumnType), "Columns Type", engine); + string columnsType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ColumnType), "Columns Type", engine); switch (columnsType) { case "list": - columnsList = v_Columns.GetListVariable(engine); + //columnsList = v_Columns.ExpandUserVariableAsList(engine); + columnsList = this.ExpandUserVariableAsList(nameof(v_Columns), engine); dtUseColumns(columnsList); break; case "comma separated": - columnsList = v_Columns.ConvertToUserVariable(engine).Split(',').ToList(); + columnsList = v_Columns.ExpandValueOrUserVariable(engine).Split(',').ToList(); dtUseColumns(columnsList); break; case "space separated": - columnsList = v_Columns.ConvertToUserVariable(engine).Split(' ').ToList(); + columnsList = v_Columns.ExpandValueOrUserVariable(engine).Split(' ').ToList(); dtUseColumns(columnsList); break; case "tab separated": - columnsList = v_Columns.ConvertToUserVariable(engine).Split('\t').ToList(); + columnsList = v_Columns.ExpandValueOrUserVariable(engine).Split('\t').ToList(); dtUseColumns(columnsList); break; case "newline separated": - columnsList = v_Columns.ConvertToUserVariable(engine).Replace("\r\n", "\n").Replace("\r", "\n").Split('\n').ToList(); + columnsList = v_Columns.ExpandValueOrUserVariable(engine).Replace("\r\n", "\n").Replace("\r", "\n").Split('\n').ToList(); dtUseColumns(columnsList); break; case "column prefix": string columnPrefix; - if (String.IsNullOrEmpty(v_Columns)) + if (string.IsNullOrEmpty(v_Columns)) { columnPrefix = "column"; } else { - columnPrefix = v_Columns.ConvertToUserVariable(engine); + columnPrefix = v_Columns.ExpandValueOrUserVariable(engine); } myDT.Rows.Add(); @@ -199,7 +204,9 @@ public override void RunCommand(object sender) } break; } - myDT.StoreInUserVariable(engine, v_applyToVariableName); + + //myDT.StoreInUserVariable(engine, v_Result); + this.StoreDataTableInUserVariable(myDT, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/ConvertListToDictionaryCommand.cs b/taskt/Core/Automation/Commands/List/ConvertListToDictionaryCommand.cs index fe707c096..58b9b4ee2 100644 --- a/taskt/Core/Automation/Commands/List/ConvertListToDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/List/ConvertListToDictionaryCommand.cs @@ -7,19 +7,20 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Convert")] [Attributes.ClassAttributes.CommandSettings("Convert List To Dictionary")] [Attributes.ClassAttributes.Description("This command convert a List to Dictionary.")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertListToDictionaryCommand : ScriptCommand + public sealed class ConvertListToDictionaryCommand : AListGetFromListCommands, IDictionaryResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_InputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_AType))] @@ -28,6 +29,7 @@ public class ConvertListToDictionaryCommand : ScriptCommand [PropertyIsOptional(true, "Key Prefix")] [PropertyDisplayText(true, "Dictionary Keys Type")] [PropertyDetailSampleUsage("**item**", "When Select **Key Prefix** and Enter **item**, Key Name is item0, item1, item2, ...")] + [PropertyParameterOrder(6000)] public string v_KeyType { get; set; } [XmlAttribute] @@ -40,22 +42,25 @@ public class ConvertListToDictionaryCommand : ScriptCommand [PropertyIsOptional(true)] [PropertyInstanceType(PropertyInstanceType.InstanceType.List)] [PropertyDisplayText(true, "Dictionary Keys Name List")] + [PropertyParameterOrder(6001)] public string v_Keys { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ANotEnough))] [PropertyDescription("When the number of items in the List is greater than the number of Keys")] [PropertyUISelectionOption("Try Create Keys")] + [PropertyParameterOrder(6002)] public string v_KeysNotEnough { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ListItemNotEnough))] [PropertyDescription("When the number of Keys is greater than the number of items in the List")] + [PropertyParameterOrder(6003)] public string v_ListItemNotEnough { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_OutputDictionaryName))] - public string v_applyToVariableName { get; set; } + public override string v_Result { get; set; } public ConvertListToDictionaryCommand() { @@ -65,28 +70,27 @@ public ConvertListToDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - List targetList = v_InputList.GetListVariable(engine); + //List targetList = v_List.ExpandUserVariableAsList(engine); + var targetList = this.ExpandUserVariableAsList(engine); - var keyType = this.GetUISelectionValue(nameof(v_KeyType), "Key Type", engine); + var keyType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_KeyType), "Key Type", engine); - Dictionary myDic = new Dictionary(); + var myDic = new Dictionary(); - Action> dicUseKeys = new Action>((targetKeys) => + var dicUseKeys = new Action>((targetKeys) => { - string keysNotEnough = this.GetUISelectionValue(nameof(v_KeysNotEnough), "Keys Not Enough", engine); - string listItemNotEnough = this.GetUISelectionValue(nameof(v_ListItemNotEnough), "List Item Not Enough", engine); + string keysNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_KeysNotEnough), "Keys Not Enough", engine); + string listItemNotEnough = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ListItemNotEnough), "List Item Not Enough", engine); if ((keysNotEnough == "error") && (targetList.Count > targetKeys.Count)) { - throw new Exception("The number of keys in " + v_Keys + " is not enough"); + throw new Exception($"The number of keys in '{v_Keys}' is not enough"); } if ((listItemNotEnough == "error") && (targetKeys.Count > targetList.Count)) { - throw new Exception("The number of List items in " + v_InputList + " is not enough"); + throw new Exception($"The number of List items in '{v_List}' is not enough"); } if (targetList.Count == targetKeys.Count) @@ -148,34 +152,35 @@ public override void RunCommand(object sender) switch (keyType) { case "list": - keysList = v_Keys.GetListVariable(engine); + //keysList = v_Keys.ExpandUserVariableAsList(engine); + keysList = this.ExpandUserVariableAsList(nameof(v_Keys), engine); dicUseKeys(keysList); break; case "comma separated": - keysList = v_Keys.ConvertToUserVariable(engine).Split(',').ToList(); + keysList = v_Keys.ExpandValueOrUserVariable(engine).Split(',').ToList(); dicUseKeys(keysList); break; case "space separated": - keysList = v_Keys.ConvertToUserVariable(engine).Split(' ').ToList(); + keysList = v_Keys.ExpandValueOrUserVariable(engine).Split(' ').ToList(); dicUseKeys(keysList); break; case "tab separated": - keysList = v_Keys.ConvertToUserVariable(engine).Split('\t').ToList(); + keysList = v_Keys.ExpandValueOrUserVariable(engine).Split('\t').ToList(); dicUseKeys(keysList); break; case "newline separated": - keysList = v_Keys.ConvertToUserVariable(engine).Replace("\r\n", "\n").Replace("\r", "\n").Split('\n').ToList(); + keysList = v_Keys.ExpandValueOrUserVariable(engine).Replace("\r\n", "\n").Replace("\r", "\n").Split('\n').ToList(); dicUseKeys(keysList); break; case "key prefix": string prefix; - if (String.IsNullOrEmpty(v_Keys)) + if (string.IsNullOrEmpty(v_Keys)) { prefix = "item"; } else { - prefix = v_Keys.ConvertToUserVariable(engine); + prefix = v_Keys.ExpandValueOrUserVariable(engine); } for (int i = 0; i < targetList.Count; i++) { @@ -183,7 +188,9 @@ public override void RunCommand(object sender) } break; } - myDic.StoreInUserVariable(engine, v_applyToVariableName); + + //myDic.StoreInUserVariable(engine, v_Result); + this.StoreDictionaryInUserVariable(myDic, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/ConvertListToJSONCommand.cs b/taskt/Core/Automation/Commands/List/ConvertListToJSONCommand.cs index 8de45bdbd..806cc8aa3 100644 --- a/taskt/Core/Automation/Commands/List/ConvertListToJSONCommand.cs +++ b/taskt/Core/Automation/Commands/List/ConvertListToJSONCommand.cs @@ -1,28 +1,28 @@ using System; -using System.Collections.Generic; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Convert")] [Attributes.ClassAttributes.CommandSettings("Convert List To JSON")] [Attributes.ClassAttributes.Description("This command convert a JSON array to a list.")] [Attributes.ClassAttributes.UsesDescription("")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConvertListToJSONCommand : ScriptCommand + public sealed class ConvertListToJSONCommand : AListGetFromListCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_InputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(JSONControls), nameof(JSONControls.v_OutputJSONName))] - public string v_applyToVariableName { get; set; } + public override string v_Result { get; set; } public ConvertListToJSONCommand() { @@ -32,22 +32,21 @@ public ConvertListToJSONCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - List targetList = v_InputList.GetListVariable(engine); + //List targetList = v_List.ExpandUserVariableAsList(engine); + var targetList = this.ExpandUserVariableAsList(engine); // convert json try { - string convertedList = Newtonsoft.Json.JsonConvert.SerializeObject(targetList); - convertedList.StoreInUserVariable(sender, v_applyToVariableName); + var convertedList = Newtonsoft.Json.JsonConvert.SerializeObject(targetList); + convertedList.StoreInUserVariable(engine, v_Result); } catch (Exception ex) { - throw new Exception("Error Occured Selecting Tokens: " + ex.ToString()); + throw new Exception($"Fail Convert to Json. Message: {ex}"); } } } -} \ No newline at end of file +} diff --git a/taskt/Core/Automation/Commands/List/CopyListCommand.cs b/taskt/Core/Automation/Commands/List/CopyListCommand.cs index fd060a37c..d9861275a 100644 --- a/taskt/Core/Automation/Commands/List/CopyListCommand.cs +++ b/taskt/Core/Automation/Commands/List/CopyListCommand.cs @@ -6,24 +6,25 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Actions")] [Attributes.ClassAttributes.CommandSettings("Copy List")] [Attributes.ClassAttributes.Description("This command allows you to list to copy.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to list to copy.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CopyListCommand : ScriptCommand + public sealed class CopyListCommand : AListCreateFromListCommands { [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] [PropertyDescription("List Variable Name to be Copied")] - public string v_InputList { get; set; } + public override string v_TargetList { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_NewOutputListName))] - public string v_OutputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_NewOutputListName))] + //public string v_NewList { get; set; } public CopyListCommand() { @@ -33,13 +34,16 @@ public CopyListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //List targetList = v_TargetList.ExpandUserVariableAsList(engine); + var targetList = this.ExpandUserVariableAsList(engine); + + //List newList = new List(targetList); + var newList = new List(targetList); - List targetList = v_InputList.GetListVariable(engine); - List newList = new List(targetList); - newList.StoreInUserVariable(engine, v_OutputList); + //newList.StoreInUserVariable(engine, v_NewList); + this.StoreListInUserVariable(newList, engine); } } -} \ No newline at end of file +} diff --git a/taskt/Core/Automation/Commands/List/CovnertListToTextCommand.cs b/taskt/Core/Automation/Commands/List/CovnertListToTextCommand.cs new file mode 100644 index 000000000..3da0acc13 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/CovnertListToTextCommand.cs @@ -0,0 +1,96 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("List")] + [Attributes.ClassAttributes.SubGruop("Convert")] + [Attributes.ClassAttributes.CommandSettings("Convert List To Text")] + [Attributes.ClassAttributes.Description("This command allows you to Convert List to Text.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Convert List to Text.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ConvertListToTextCommand : AListGetFromListCommands + { + //[XmlAttribute] + //public string v_List { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(6000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Header")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Header", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7000)] + public string v_ExportHeader { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Index")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7001)] + public string v_ExportIndex { get; set; } + + public ConvertListToTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var list = this.ExpandUserVariableAsList(engine); + + string txt = ""; + + var exportHeader = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportHeader), engine); + var exportIndex = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportIndex), engine); + + if (exportHeader) + { + if (exportIndex) + { + txt = "index,value\r\n"; + } + else + { + txt = "value\r\n"; + } + } + + Func textAction; + if (exportIndex) + { + textAction = new Func((v, i) => + { + return $"{i},{v}\r\n"; + }); + } + else + { + textAction = new Func((v, i) => + { + return $"{v}\r\n"; + }); + } + + for (int i = 0; i < list.Count; i++) + { + txt += textAction(list[i], i); + } + + txt.Trim().StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/CovnertListToVisualizedTextCommand.cs b/taskt/Core/Automation/Commands/List/CovnertListToVisualizedTextCommand.cs new file mode 100644 index 000000000..5fd58bb93 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/CovnertListToVisualizedTextCommand.cs @@ -0,0 +1,78 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("List")] + [Attributes.ClassAttributes.SubGruop("Convert")] + [Attributes.ClassAttributes.CommandSettings("Convert List To Visualized Text")] + [Attributes.ClassAttributes.Description("This command allows you to Convert List to Visualized Text.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Convert List to Visualized Text.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ConvertListToVisualizedTextCommand : AListGetFromListCommands + { + //[XmlAttribute] + //public string v_List { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + public override string v_Result { get; set; } + + public ConvertListToVisualizedTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var list = this.ExpandUserVariableAsList(engine); + + var maxValueLength = 0; + foreach (var item in list) + { + var s = item.Length; + if (maxValueLength < s) + { + maxValueLength = s; + } + } + if (maxValueLength < 5) + { + maxValueLength = 5; // Value + } + + var size = list.Count; + int indexDigits = (int)Math.Log10(size) + 1; + if (indexDigits < 5) + { + indexDigits = 5; // Index + } + + string indexFormat = $"{{0,{indexDigits}}}"; + string valueFormat = $"{{0,-{maxValueLength}}}"; + + string txt = $"{string.Format(indexFormat, "Index")} | {string.Format(valueFormat, "Value")}\r\n"; + for (int i = 0; i < indexDigits; i++) + { + txt += "-"; + } + txt += "-|-"; + for (int i = 0; i < maxValueLength; i++) + { + txt += "-"; + } + txt += "\r\n"; + + for (int i = 0; i < size; i++) + { + txt += $"{string.Format(indexFormat, i)} | {string.Format(valueFormat, list[i])}\r\n"; + } + + txt.StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/CreateListCommand.cs b/taskt/Core/Automation/Commands/List/CreateListCommand.cs index 936fa78b8..c333ffef1 100644 --- a/taskt/Core/Automation/Commands/List/CreateListCommand.cs +++ b/taskt/Core/Automation/Commands/List/CreateListCommand.cs @@ -1,27 +1,28 @@ using System; -using System.Xml.Serialization; +using System.Collections.Generic; using System.Data; +using System.Linq; using System.Windows.Forms; -using System.Collections.Generic; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; -using System.Linq; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Actions")] [Attributes.ClassAttributes.CommandSettings("Create List")] [Attributes.ClassAttributes.Description("This command allows you to create new List")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create new List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateListCommand : ScriptCommand + public sealed class CreateListCommand : AListInputListCommands, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] - public string v_ListName { get; set; } + public override string v_List { get; set; } [XmlElement] [PropertyDescription("List Values")] @@ -36,6 +37,7 @@ public class CreateListCommand : ScriptCommand [PropertyDetailSampleUsage("**1**", "Set **1**")] [PropertyDetailSampleUsage("**ABC**", "Set **ABC**")] [PropertyDetailSampleUsage("**{{{vValue}}}**", "Set Value of Variable **vValue**")] + [PropertyParameterOrder(6000)] public DataTable v_ListValues { get; set; } public CreateListCommand() @@ -46,15 +48,19 @@ public CreateListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - List newList = new List(); + var newList = new List(); - newList.AddRange(v_ListValues.AsEnumerable().Select(r => r["Values"]?.ToString() ?? "").ToArray()); + //newList.AddRange(v_ListValues.AsEnumerable().Select(r => r["Values"]?.ToString() ?? "").ToArray()); + var ary = v_ListValues.AsEnumerable().Select(r => r["Values"]?.ToString() ?? "").ToArray(); + foreach(var v in ary) + { + newList.Add(v.ExpandValueOrUserVariable(engine)); + } - newList.StoreInUserVariable(engine, v_ListName); + //newList.StoreInUserVariable(engine, v_List); + this.StoreListInUserVariable(newList, nameof(v_List), engine); } public override void BeforeValidate() diff --git a/taskt/Core/Automation/Commands/List/EM_CanHandleListExtensionMethods.cs b/taskt/Core/Automation/Commands/List/EM_CanHandleListExtensionMethods.cs new file mode 100644 index 000000000..5d86858f5 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/EM_CanHandleListExtensionMethods.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_CanHandleListExtensionMethods + { + /// + /// check object is List + /// + /// + /// + /// + public static bool IsList(object value, out List list) + { + // TODO: it's ok? + list = default; + if (value is List lst) + { + list = lst; + return true; + } + else + { + return false; + } + } + + /// + /// Create New Empty List + /// + /// + /// + public static List CreateEmptyList(this ICanHandleList command) + { + // todo: is it ok? + return new List(); + } + + /// + /// Expand User Variable As List + /// + /// + /// + /// + /// + public static List ExpandUserVariableAsList(ScriptVariable variable) + { + // TODO; it's OK? + if (IsList(variable.VariableValue, out List list)) + { + return list; + } + else + { + throw new Exception($"Variable '{variable.VariableName}' is not List"); + } + } + + /// + /// expand user varaible as List + /// + /// + /// + /// + /// + /// + public static List ExpandUserVariableAsList(this ICanHandleList command, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "List Variable"); + //var v = variableName.GetRawVariable(engine); + //if (v.VariableValue is List list) + //{ + // return list; + //} + //else + //{ + // throw new Exception($"Variable '{variableName}' is not List"); + //} + try + { + return ExpandUserVariableAsList(variableName.GetRawVariable(engine)); + } + catch + { + throw new Exception($"Variable '{variableName}' is not List"); + } + } + + /// + /// Expand User Variable as Decimal(Numeric) List + /// + /// + /// + /// + /// + /// + /// + public static List ExpandUserVariableAsDecimalList(this ICanHandleList command, string parameterName, bool ignoreNotNumeric, Engine.AutomationEngineInstance engine) + { + var list = command.ExpandUserVariableAsList(parameterName, engine); + + var numList = new List(); + foreach (var value in list) + { + if (decimal.TryParse(value, out decimal v)) + { + numList.Add(v); + } + else if (!ignoreNotNumeric) + { + throw new Exception($"List has Not numeric value. Value: '{value}'"); + } + } + + return numList; + } + + /// + /// store list in User Variable + /// + /// + /// + /// + /// + public static void StoreListInUserVariable(this ICanHandleList command, List list, string parameterName, Engine.AutomationEngineInstance engine) + { + var variableName = ((ScriptCommand)command).GetRawPropertyValueAsString(parameterName, "List Variable"); + ExtensionMethods.StoreInUserVariable(variableName, list, engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/List/EM_ListCreateFromListPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/List/EM_ListCreateFromListPropertiesExtensionMethods.cs new file mode 100644 index 000000000..82c60a1ec --- /dev/null +++ b/taskt/Core/Automation/Commands/List/EM_ListCreateFromListPropertiesExtensionMethods.cs @@ -0,0 +1,29 @@ +using System.Collections.Generic; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ListCreateFromListPropertiesExtensionMethods + { + /// + /// Expand User Variable As List + /// + /// + /// + /// + public static List ExpandUserVariableAsList(this ILListCreateFromListProperties command, Engine.AutomationEngineInstance engine) + { + return command.ExpandUserVariableAsList(nameof(command.v_TargetList), engine); + } + + /// + /// Store List in User Variable + /// + /// + /// + /// + public static void StoreListInUserVariable(this ILListCreateFromListProperties command, List list, Engine.AutomationEngineInstance engine) + { + command.StoreListInUserVariable(list, nameof(command.v_NewList), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/List/EM_ListGetMathResultPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/List/EM_ListGetMathResultPropertiesExtensionMethods.cs new file mode 100644 index 000000000..780dec75b --- /dev/null +++ b/taskt/Core/Automation/Commands/List/EM_ListGetMathResultPropertiesExtensionMethods.cs @@ -0,0 +1,32 @@ +using System; +using System.Collections.Generic; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ListGetMathResultPropertiesExtensionMethods + { + /// + /// Expand User Variable as Decimal (Numeric) List + /// + /// + /// + /// + public static List ExpandUserVariableAsDecimalList(this IListGetMathResultFromListProperties command, Engine.AutomationEngineInstance engine) + { + var notNumeric = ((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_WhenValueIsNotNumeric), "When Not Numeric", engine); + return command.ExpandUserVariableAsDecimalList(nameof(command.v_List), (notNumeric == "ignore"), engine); + } + + /// + /// Decimal (Numeric) List Math Process + /// + /// + /// + /// + /// + public static decimal MathProcess(this IListGetMathResultFromListProperties command, Func, decimal> mathFunc, Engine.AutomationEngineInstance engine) + { + return mathFunc(command.ExpandUserVariableAsDecimalList(engine)); + } + } +} diff --git a/taskt/Core/Automation/Commands/List/EM_ListIndexPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/List/EM_ListIndexPropertiesExtensionMethods.cs new file mode 100644 index 000000000..ed55b0115 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/EM_ListIndexPropertiesExtensionMethods.cs @@ -0,0 +1,46 @@ +using System; +using System.Collections.Generic; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ListIndexPropertiesExtensionMethods + { + /// + /// Expand Value Or User Variable As List Index + /// + /// + /// + /// + /// + /// + public static int ExpandValueOrUserVariableAsListIndex(this IListIndexProperties command, List list, Engine.AutomationEngineInstance engine) + { + var index = ((ScriptCommand)command).ExpandValueOrUserVariableAsInteger(nameof(command.v_Index), engine); + if (index < 0) + { + index += list.Count; + } + if (index >= 0 && index < list.Count) + { + return index; + } + else + { + throw new Exception($"Strange List Index Value. Value: '{command.v_Index}', Expand Value: '{index}'"); + } + } + + /// + /// Expand Value Or User Variable As List and List Index and List Value + /// + /// + /// + /// (list, index, value) + public static (List, int, string) ExpandValueOrUserVariableAsListAndIndexAndValue(this IListIndexProperties command, Engine.AutomationEngineInstance engine) + { + var list = command.ExpandUserVariableAsList(engine); + var index = command.ExpandValueOrUserVariableAsListIndex(list, engine); + return (list, index, list[index]); + } + } +} diff --git a/taskt/Core/Automation/Commands/List/EM_ListPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/List/EM_ListPropertiesExtensionMethods.cs new file mode 100644 index 000000000..245609417 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/EM_ListPropertiesExtensionMethods.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ListPropertiesExtensionMethods + { + /// + /// Expand User Variable as List + /// + /// + /// + /// + public static List ExpandUserVariableAsList(this ILListProperties command, Engine.AutomationEngineInstance engine) + { + return command.ExpandUserVariableAsList(nameof(command.v_List), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/List/EM_ListResultPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/List/EM_ListResultPropertiesExtensionMethods.cs new file mode 100644 index 000000000..6bf7b4d53 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/EM_ListResultPropertiesExtensionMethods.cs @@ -0,0 +1,18 @@ +using System.Collections.Generic; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_ListResultPropertiesExtensionMethods + { + /// + /// Store List in User Variable + /// + /// + /// + /// + public static void StoreListInUserVariable(this IListResultProperties command, List list, Engine.AutomationEngineInstance engine) + { + command.StoreListInUserVariable(list, nameof(command.v_Result), engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/List/ExportListAsTextFileCommand.cs b/taskt/Core/Automation/Commands/List/ExportListAsTextFileCommand.cs new file mode 100644 index 000000000..aa4ed065e --- /dev/null +++ b/taskt/Core/Automation/Commands/List/ExportListAsTextFileCommand.cs @@ -0,0 +1,102 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("List")] + [Attributes.ClassAttributes.SubGruop("File")] + [Attributes.ClassAttributes.CommandSettings("Export List As Text File")] + [Attributes.ClassAttributes.Description("This command allows you to Export List as Text File.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Export List as Text File.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ExportListAsTextFileCommand : AListInputListCommands + { + //[XmlAttribute] + //public string v_List { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_FilePath))] + [PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtension, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "txt")] + [PropertyParameterOrder(6000)] + public string v_FilePath { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Header")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Header", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7000)] + public string v_ExportHeader { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Export Index")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyValidationRule("Export Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(7001)] + public string v_ExportIndex { get; set; } + + public ExportListAsTextFileCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var list = this.ExpandUserVariableAsList(engine); + + string txt = ""; + + var exportHeader = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportHeader), engine); + var exportIndex = this.ExpandValueOrUserVariableAsYesNo(nameof(v_ExportIndex), engine); + + if (exportHeader) + { + if (exportIndex) + { + txt = "index,value\r\n"; + } + else + { + txt = "value\r\n"; + } + } + + Func textAction; + if (exportIndex) + { + textAction = new Func((v, i) => + { + return $"{i},{v}\r\n"; + }); + } + else + { + textAction = new Func((v, i) => + { + return $"{v}\r\n"; + }); + } + + for (int i = 0; i < list.Count; i++) + { + txt += textAction(list[i], i); + } + + var writeText = new WriteTextFileCommand() + { + v_FilePath = this.v_FilePath, + v_TextToWrite = txt.Trim(), + }; + writeText.RunCommand(engine); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/FilterListCommand.cs b/taskt/Core/Automation/Commands/List/FilterListCommand.cs index d593a2595..000a9f6fa 100644 --- a/taskt/Core/Automation/Commands/List/FilterListCommand.cs +++ b/taskt/Core/Automation/Commands/List/FilterListCommand.cs @@ -8,39 +8,43 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Actions")] [Attributes.ClassAttributes.CommandSettings("Filter List")] [Attributes.ClassAttributes.Description("This command allows you to filter List value.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to filter List value.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class FilterListCommand : ScriptCommand + public sealed class FilterListCommand : AListCreateFromListCommands, ILFilterValueProperties, IHaveDataTableElements { [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] [PropertyDescription("List Variable Name to Filter")] [PropertyValidationRule("List to Filter", PropertyValidationRule.ValidationRuleFlags.Empty)] - public string v_InputList { get; set; } + public override string v_TargetList { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_FilterValueType))] [PropertySelectionChangeEvent(nameof(cmbTargetType_SelectionChangeCommited))] - public string v_TargetType { get; set; } + [PropertyParameterOrder(6000)] + public string v_ValueType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_FilterAction))] [PropertySelectionChangeEvent(nameof(cmbFilterAction_SelectionChangeCommited))] + [PropertyParameterOrder(7000)] public string v_FilterAction { get; set; } [XmlElement] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ActionParameterTable))] + [PropertyParameterOrder(8000)] public DataTable v_FilterActionParameterTable { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_NewOutputListName))] - public string v_OutputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_NewOutputListName))] + //public string v_NewList { get; set; } public FilterListCommand() { @@ -50,46 +54,54 @@ public FilterListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - List targetList = v_InputList.GetListVariable(engine); + //List targetList = v_TargetList.ExpandUserVariableAsList(engine); + var targetList = this.ExpandUserVariableAsList(engine); var parameters = DataTableControls.GetFieldValues(v_FilterActionParameterTable, "ParameterName", "ParameterValue", engine); - var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_TargetType), nameof(v_FilterAction), parameters, engine, this); + var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_ValueType), nameof(v_FilterAction), parameters, engine, this); - List res = new List(); + var newList = new List(); foreach(string item in targetList) { if (checkFunc(item, parameters)) { - res.Add(item); + newList.Add(item); } } - res.StoreInUserVariable(engine, v_OutputList); + //res.StoreInUserVariable(engine, v_NewList); + this.StoreListInUserVariable(newList, engine); } private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) { //ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, FilterActionComboboxHelper); - ConditionControls.AddFilterActionItems((ComboBox)ControlsList[nameof(v_TargetType)], (ComboBox)ControlsList[nameof(v_FilterAction)]); + ConditionControls.AddFilterActionItems((ComboBox)ControlsList[nameof(v_ValueType)], (ComboBox)ControlsList[nameof(v_FilterAction)]); } private void cmbFilterAction_SelectionChangeCommited(object sender, EventArgs e) { //ConditionControls.RenderFilter(v_FilterActionParameterTable, FilterParametersGridViewHelper, FilterActionComboboxHelper, TargetTypeComboboxHelper); - ConditionControls.RenderFilter(v_FilterActionParameterTable, (DataGridView)ControlsList[nameof(v_FilterActionParameterTable)], (ComboBox)ControlsList[nameof(v_FilterAction)], (ComboBox)ControlsList[nameof(v_TargetType)]); + ConditionControls.RenderFilter(v_FilterActionParameterTable, (DataGridView)ControlsList[nameof(v_FilterActionParameterTable)], (ComboBox)ControlsList[nameof(v_FilterAction)], (ComboBox)ControlsList[nameof(v_ValueType)]); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { //ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, FilterActionComboboxHelper); - ConditionControls.AddFilterActionItems((ComboBox)ControlsList[nameof(v_TargetType)], (ComboBox)ControlsList[nameof(v_FilterAction)]); + ConditionControls.AddFilterActionItems((ComboBox)ControlsList[nameof(v_ValueType)], (ComboBox)ControlsList[nameof(v_FilterAction)]); //ConditionControls.RenderFilter(v_FilterActionParameterTable, FilterParametersGridViewHelper, FilterActionComboboxHelper, TargetTypeComboboxHelper); - ConditionControls.RenderFilter(v_FilterActionParameterTable, (DataGridView)ControlsList[nameof(v_FilterActionParameterTable)], (ComboBox)ControlsList[nameof(v_FilterAction)], (ComboBox)ControlsList[nameof(v_TargetType)]); + ConditionControls.RenderFilter(v_FilterActionParameterTable, (DataGridView)ControlsList[nameof(v_FilterActionParameterTable)], (ComboBox)ControlsList[nameof(v_FilterAction)], (ComboBox)ControlsList[nameof(v_ValueType)]); + } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_FilterActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_FilterActionParameterTable); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/GetAverageFromListCommand.cs b/taskt/Core/Automation/Commands/List/GetAverageFromListCommand.cs index 343e03e77..2b96a3eb9 100644 --- a/taskt/Core/Automation/Commands/List/GetAverageFromListCommand.cs +++ b/taskt/Core/Automation/Commands/List/GetAverageFromListCommand.cs @@ -7,27 +7,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Math")] [Attributes.ClassAttributes.CommandSettings("Get Average From List")] [Attributes.ClassAttributes.Description("This command allows you to get average value from a list.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get average value from a list.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetAverageFromListCommand : ScriptCommand + public sealed class GetAverageFromListCommand : AListGetMathResultFromListCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_InputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_Result { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + //public string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] - public string v_IfValueIsNotNumeric { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] + //public string v_WhenValueIsNotNumeric { get; set; } public GetAverageFromListCommand() { @@ -37,15 +38,18 @@ public GetAverageFromListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //ListControls.MathProcess(this, nameof(v_WhenValueIsNotNumeric), v_List, engine, + // new Func, decimal>((lst) => + // { + // return lst.Average(); + // }) + //).StoreInUserVariable(engine, v_Result); - ListControls.MathProcess(this, nameof(v_IfValueIsNotNumeric), v_InputList, engine, - new Func, decimal>((lst) => - { - return lst.Average(); - }) + this.MathProcess( + new Func, decimal>(lst => lst.Average()), + engine ).StoreInUserVariable(engine, v_Result); } } diff --git a/taskt/Core/Automation/Commands/List/GetListCountCommand.cs b/taskt/Core/Automation/Commands/List/GetListCountCommand.cs index 96be91919..3888408cf 100644 --- a/taskt/Core/Automation/Commands/List/GetListCountCommand.cs +++ b/taskt/Core/Automation/Commands/List/GetListCountCommand.cs @@ -6,23 +6,24 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Item")] [Attributes.ClassAttributes.CommandSettings("Get List Count")] [Attributes.ClassAttributes.Description("This command allows you to get the item count of a List")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get the item count of a List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetListCountCommand : ScriptCommand + public sealed class GetListCountCommand : AListGetFromListCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_ListName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_UserVariableName { get; set; } + public override string v_Result { get; set; } public GetListCountCommand() { @@ -32,45 +33,46 @@ public GetListCountCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var listVariable = v_ListName.GetRawVariable(engine); - dynamic listToCount; + //var listVariable = v_List.GetRawVariable(engine); + //dynamic listToCount; + + //Type listType = listVariable.VariableValue.GetType(); + //if (listType.IsGenericType && (listType.GetGenericTypeDefinition() == typeof(List<>))) + //{ + // // List + // listToCount = listVariable.VariableValue; + //} + //else + //{ + // if ((listVariable.VariableValue is string) && + // listVariable.VariableValue.ToString().StartsWith("[") && listVariable.VariableValue.ToString().EndsWith("]") && listVariable.VariableValue.ToString().Contains(",")) + // { + // // JSON Array + // Newtonsoft.Json.Linq.JArray jsonArray = Newtonsoft.Json.JsonConvert.DeserializeObject(listVariable.VariableValue.ToString()) as Newtonsoft.Json.Linq.JArray; - Type listType = listVariable.VariableValue.GetType(); - if (listType.IsGenericType && (listType.GetGenericTypeDefinition() == typeof(List<>))) - { - // List - listToCount = listVariable.VariableValue; - } - else - { - if ((listVariable.VariableValue is string) && - listVariable.VariableValue.ToString().StartsWith("[") && listVariable.VariableValue.ToString().EndsWith("]") && listVariable.VariableValue.ToString().Contains(",")) - { - // JSON Array - Newtonsoft.Json.Linq.JArray jsonArray = Newtonsoft.Json.JsonConvert.DeserializeObject(listVariable.VariableValue.ToString()) as Newtonsoft.Json.Linq.JArray; + // var itemList = new List(); + // foreach (var item in jsonArray) + // { + // var value = (Newtonsoft.Json.Linq.JValue)item; + // itemList.Add(value.ToString()); + // } - var itemList = new List(); - foreach (var item in jsonArray) - { - var value = (Newtonsoft.Json.Linq.JValue)item; - itemList.Add(value.ToString()); - } + // listVariable.VariableValue = itemList; + // listToCount = itemList; + // } + // else + // { + // throw new Exception(v_List + " is not List"); + // } + //} - listVariable.VariableValue = itemList; - listToCount = itemList; - } - else - { - throw new Exception(v_ListName + " is not List"); - } - } + //string count = listToCount.Count.ToString(); + //count.StoreInUserVariable(engine, v_Result); - string count = listToCount.Count.ToString(); - count.StoreInUserVariable(sender, v_UserVariableName); + var list = this.ExpandUserVariableAsList(engine); + list.Count.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/GetListIndexCommand.cs b/taskt/Core/Automation/Commands/List/GetListIndexCommand.cs index 301deb0fa..40a8e8b4d 100644 --- a/taskt/Core/Automation/Commands/List/GetListIndexCommand.cs +++ b/taskt/Core/Automation/Commands/List/GetListIndexCommand.cs @@ -6,41 +6,42 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Other")] [Attributes.ClassAttributes.CommandSettings("Get List Index")] [Attributes.ClassAttributes.Description("This command allows you to get List Index.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to ge List Index.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetListIndexCommand : ScriptCommand + public sealed class GetListIndexCommand : AListGetFromListCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_ListName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_Result { get; set; } + public override string v_Result { get; set; } public GetListIndexCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; + // TODO: i want to remove current position - var rawVariable = v_ListName.GetRawVariable(engine); + var rawVariable = v_List.GetRawVariable(engine); if (rawVariable.VariableValue is List) { - rawVariable.CurrentPosition.ToString().StoreInUserVariable(engine, v_Result); + //rawVariable.CurrentPosition.ToString().StoreInUserVariable(engine, v_Result); + rawVariable.CurrentPosition.StoreInUserVariable(engine, v_Result); } else { - throw new Exception("Variable '" + v_ListName + "' is not LIST."); + throw new Exception($"Variable '{v_List}' is not a List. Type: {rawVariable.GetType()}"); } } } diff --git a/taskt/Core/Automation/Commands/List/GetListIndexFromValueCommand.cs b/taskt/Core/Automation/Commands/List/GetListIndexFromValueCommand.cs index dbf663c87..ef03eeaeb 100644 --- a/taskt/Core/Automation/Commands/List/GetListIndexFromValueCommand.cs +++ b/taskt/Core/Automation/Commands/List/GetListIndexFromValueCommand.cs @@ -6,23 +6,24 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Other")] [Attributes.ClassAttributes.CommandSettings("Get List Index From Value")] [Attributes.ClassAttributes.Description("This command allows you want to get list index from value")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get list index from value")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetListIndexFromValueCommand : ScriptCommand + public sealed class GetListIndexFromValueCommand : AListGetFromValueCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_ListName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_SearchValue))] - public string v_SearchItem { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_SearchValue))] + //public string v_Value { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -34,12 +35,13 @@ public class GetListIndexFromValueCommand : ScriptCommand [PropertyUISelectionOption("Last Index")] [PropertyIsOptional(true, "First Index")] [PropertyDisplayText(true, "Search Method")] + [PropertyParameterOrder(8000)] public string v_SearchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] [Remarks("When List does not have value, Result is **-1**")] - public string v_Result { get; set; } + public override string v_Result { get; set; } public GetListIndexFromValueCommand() { @@ -49,16 +51,15 @@ public GetListIndexFromValueCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - List targetList = v_ListName.GetListVariable(engine); + //List targetList = v_List.ExpandUserVariableAsList(engine); + var targetList = this.ExpandUserVariableAsList(engine); - var searchedValue = v_SearchItem.ConvertToUserVariable(sender); + var searchedValue = v_Value.ExpandValueOrUserVariable(engine); //string searchMethod = this.GetUISelectionValue(nameof(v_SearchMethod), "Search Method", engine); - string searchMethod = this.GetUISelectionValue(nameof(v_SearchMethod), engine); + string searchMethod = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_SearchMethod), engine); switch (searchMethod) { diff --git a/taskt/Core/Automation/Commands/List/GetListItemCommand.cs b/taskt/Core/Automation/Commands/List/GetListItemCommand.cs index b5266a87e..89d471610 100644 --- a/taskt/Core/Automation/Commands/List/GetListItemCommand.cs +++ b/taskt/Core/Automation/Commands/List/GetListItemCommand.cs @@ -1,32 +1,33 @@ using System; using System.Xml.Serialization; -using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Item")] [Attributes.ClassAttributes.CommandSettings("Get List Item")] [Attributes.ClassAttributes.Description("This command allows you to get an item from a List")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get an item from a List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetListItemCommand : ScriptCommand + public sealed class GetListItemCommand : AListIndexCommands, ILResultProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_ListName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ListIndex))] - public string v_ItemIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ListIndex))] + //public string v_Index { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_UserVariableName { get; set; } + [PropertyParameterOrder(7000)] + public string v_Result { get; set; } public GetListItemCommand() { @@ -36,10 +37,8 @@ public GetListItemCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //var listVariable = v_ListName.GetRawVariable(engine); //if (listVariable == null) //{ @@ -124,21 +123,24 @@ public override void RunCommand(object sender) // index = this.ConvertToUserVariableAsInteger(nameof(v_ItemIndex), engine); //} - (var list, var index) = this.GetListVariableAndIndex(nameof(v_ListName), nameof(v_ItemIndex), engine); + //(var list, var index) = this.ExpandUserVariablesAsListAndIndex(nameof(v_List), nameof(v_Index), engine); + + //if (index < 0) + //{ + // index += list.Count; + //} - if (index < 0) - { - index += list.Count; - } + //if ((index >= 0) && (index < list.Count)) + //{ + // list[index].StoreInUserVariable(engine, v_Result); + //} + //else + //{ + // throw new Exception("Strange index " + v_Index + ", parsed " + index); + //} - if ((index >= 0) && (index < list.Count)) - { - list[index].StoreInUserVariable(engine, v_UserVariableName); - } - else - { - throw new Exception("Strange index " + v_ItemIndex + ", parsed " + index); - } + (_, _, var value) = this.ExpandValueOrUserVariableAsListAndIndexAndValue(engine); + value.StoreInUserVariable(engine, v_Result); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/GetMaxFromListCommand.cs b/taskt/Core/Automation/Commands/List/GetMaxFromListCommand.cs index 0d0db33c4..b010b7d0d 100644 --- a/taskt/Core/Automation/Commands/List/GetMaxFromListCommand.cs +++ b/taskt/Core/Automation/Commands/List/GetMaxFromListCommand.cs @@ -7,27 +7,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Math")] [Attributes.ClassAttributes.CommandSettings("Get Max From List")] [Attributes.ClassAttributes.Description("This command allows you to get max value from a list.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get max value from a list.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetMaxFromListCommand : ScriptCommand + public sealed class GetMaxFromListCommand : AListGetMathResultFromListCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_InputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_Result { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + //public string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] - public string v_IfValueIsNotNumeric { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] + //public string v_WhenValueIsNotNumeric { get; set; } public GetMaxFromListCommand() { @@ -37,15 +38,18 @@ public GetMaxFromListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //ListControls.MathProcess(this, nameof(v_WhenValueIsNotNumeric), v_List, engine, + // new Func, decimal>((lst) => + // { + // return lst.Max(); + // }) + //).StoreInUserVariable(engine, v_Result); - ListControls.MathProcess(this, nameof(v_IfValueIsNotNumeric), v_InputList, engine, - new Func, decimal>((lst) => - { - return lst.Max(); - }) + this.MathProcess( + new Func, decimal>(lst => lst.Max()), + engine ).StoreInUserVariable(engine, v_Result); } } diff --git a/taskt/Core/Automation/Commands/List/GetMedianFromListCommand.cs b/taskt/Core/Automation/Commands/List/GetMedianFromListCommand.cs index add714e81..79f1c8096 100644 --- a/taskt/Core/Automation/Commands/List/GetMedianFromListCommand.cs +++ b/taskt/Core/Automation/Commands/List/GetMedianFromListCommand.cs @@ -1,32 +1,34 @@ using System; using System.Linq; +using System.Collections.Generic; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Math")] [Attributes.ClassAttributes.CommandSettings("Get Median From List")] [Attributes.ClassAttributes.Description("This command allows you to get median value from a list.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get median value from a list.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetMedianFromListCommand : ScriptCommand + public sealed class GetMedianFromListCommand : AListGetMathResultFromListCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_InputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_Result { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + //public string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] - public string v_IfValueIsNotNumeric { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] + //public string v_WhenValueIsNotNumeric { get; set; } public GetMedianFromListCommand() { @@ -36,12 +38,27 @@ public GetMedianFromListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //ListControls.MathProcess(this, nameof(v_WhenValueIsNotNumeric), v_List, engine, + // new Func, decimal>((lst) => + // { + // decimal med; + // if (lst.Count() % 2 == 0) + // { + // int center = lst.Count() / 2; + // med = (lst[center - 1] + lst[center]) * (decimal)0.5; + // } + // else + // { + // med = lst[lst.Count() / 2]; + // } + // return med; + // }) + //).StoreInUserVariable(engine, v_Result); - ListControls.MathProcess(this, nameof(v_IfValueIsNotNumeric), v_InputList, engine, - new Func, decimal>((lst) => + this.MathProcess( + new Func, decimal>((lst) => { decimal med; if (lst.Count() % 2 == 0) @@ -54,7 +71,8 @@ public override void RunCommand(object sender) med = lst[lst.Count() / 2]; } return med; - }) + }), + engine ).StoreInUserVariable(engine, v_Result); } } diff --git a/taskt/Core/Automation/Commands/List/GetMinFromListCommand.cs b/taskt/Core/Automation/Commands/List/GetMinFromListCommand.cs index 65071dc22..a74003639 100644 --- a/taskt/Core/Automation/Commands/List/GetMinFromListCommand.cs +++ b/taskt/Core/Automation/Commands/List/GetMinFromListCommand.cs @@ -7,27 +7,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Math")] [Attributes.ClassAttributes.CommandSettings("Get Min From List")] [Attributes.ClassAttributes.Description("This command allows you to get min value from a list.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get min value from a list.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetMinFromListCommand : ScriptCommand + public sealed class GetMinFromListCommand : AListGetMathResultFromListCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_InputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_Result { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + //public string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] - public string v_IfValueIsNotNumeric { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] + //public string v_WhenValueIsNotNumeric { get; set; } public GetMinFromListCommand() { @@ -37,15 +38,18 @@ public GetMinFromListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //ListControls.MathProcess(this, nameof(v_WhenValueIsNotNumeric), v_List, engine, + // new Func, decimal>((lst) => + // { + // return lst.Min(); + // }) + //).StoreInUserVariable(engine, v_Result); - ListControls.MathProcess(this, nameof(v_IfValueIsNotNumeric), v_InputList, engine, - new Func, decimal>((lst) => - { - return lst.Min(); - }) + this.MathProcess( + new Func, decimal>(lst => lst.Min()), + engine ).StoreInUserVariable(engine, v_Result); } } diff --git a/taskt/Core/Automation/Commands/List/GetSumFromListCommand.cs b/taskt/Core/Automation/Commands/List/GetSumFromListCommand.cs index 665e2310d..a1cc2d044 100644 --- a/taskt/Core/Automation/Commands/List/GetSumFromListCommand.cs +++ b/taskt/Core/Automation/Commands/List/GetSumFromListCommand.cs @@ -7,27 +7,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Math")] [Attributes.ClassAttributes.CommandSettings("Get Sum From List")] [Attributes.ClassAttributes.Description("This command allows you to get sum value from a list.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get sum value from a list.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetSumFromListCommand : ScriptCommand + public sealed class GetSumFromListCommand : AListGetMathResultFromListCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_InputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_Result { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + //public string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] - public string v_IfValueIsNotNumeric { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] + //public string v_WhenValueIsNotNumeric { get; set; } public GetSumFromListCommand() { @@ -37,15 +38,18 @@ public GetSumFromListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //ListControls.MathProcess(this, nameof(v_WhenValueIsNotNumeric), v_List, engine, + // new Func, decimal>((lst) => + // { + // return lst.Sum(); + // }) + //).StoreInUserVariable(engine, v_Result); - ListControls.MathProcess(this, nameof(v_IfValueIsNotNumeric), v_InputList, engine, - new Func, decimal>((lst) => - { - return lst.Sum(); - }) + this.MathProcess( + new Func, decimal>(lst => lst.Sum()), + engine ).StoreInUserVariable(engine, v_Result); } } diff --git a/taskt/Core/Automation/Commands/List/GetVarianceFromListCommand.cs b/taskt/Core/Automation/Commands/List/GetVarianceFromListCommand.cs index fd8ecbac8..b5c14def7 100644 --- a/taskt/Core/Automation/Commands/List/GetVarianceFromListCommand.cs +++ b/taskt/Core/Automation/Commands/List/GetVarianceFromListCommand.cs @@ -7,27 +7,28 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Math")] [Attributes.ClassAttributes.CommandSettings("Get Variance From List")] [Attributes.ClassAttributes.Description("This command allows you to get variance value from a list.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get variance value from a list.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetVarianceFromListCommand : ScriptCommand + public sealed class GetVarianceFromListCommand : AListGetMathResultFromListCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] - public string v_InputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] - public string v_Result { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + //public string v_Result { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] - public string v_IfValueIsNotNumeric { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_WhenValueIsNotNumeric))] + //public string v_WhenValueIsNotNumeric { get; set; } public GetVarianceFromListCommand() { @@ -37,11 +38,31 @@ public GetVarianceFromListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //ListControls.MathProcess(this, nameof(v_WhenValueIsNotNumeric), v_List, engine, + // new Func, decimal>((lst) => + // { + // if (lst.Count() > 0) + // { + // decimal ave = lst.Average(); - ListControls.MathProcess(this, nameof(v_IfValueIsNotNumeric), v_InputList, engine, + // decimal sum = 0; + // foreach (var v in lst) + // { + // sum += (v - ave) * (v - ave); + // } + + // return (sum / lst.Count()); + // } + // else + // { + // return 0; + // } + // }) + //).StoreInUserVariable(engine, v_Result); + + this.MathProcess( new Func, decimal>((lst) => { if (lst.Count() > 0) @@ -60,7 +81,8 @@ public override void RunCommand(object sender) { return 0; } - }) + }), + engine ).StoreInUserVariable(engine, v_Result); } } diff --git a/taskt/Core/Automation/Commands/List/ICanHandleList.cs b/taskt/Core/Automation/Commands/List/ICanHandleList.cs new file mode 100644 index 000000000..55920064a --- /dev/null +++ b/taskt/Core/Automation/Commands/List/ICanHandleList.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// for handle List + /// + public interface ICanHandleList : ILExpandableProperties + { + // nothing + } +} diff --git a/taskt/Core/Automation/Commands/List/ILListCreateFromListProperties.cs b/taskt/Core/Automation/Commands/List/ILListCreateFromListProperties.cs new file mode 100644 index 000000000..b7d01a50e --- /dev/null +++ b/taskt/Core/Automation/Commands/List/ILListCreateFromListProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Create List from List properties + /// + public interface ILListCreateFromListProperties : ICanHandleList, ILExpandableProperties + { + /// + /// List variable name to Create New List + /// + string v_TargetList { get; set; } + + /// + /// List variable name to Store New List + /// + string v_NewList { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/ILListProperties.cs b/taskt/Core/Automation/Commands/List/ILListProperties.cs new file mode 100644 index 000000000..73e50045d --- /dev/null +++ b/taskt/Core/Automation/Commands/List/ILListProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// List commands properties + /// + public interface ILListProperties : ICanHandleList, ILExpandableProperties + { + /// + /// List variable name + /// + string v_List { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/IListGetFromListProperties.cs b/taskt/Core/Automation/Commands/List/IListGetFromListProperties.cs new file mode 100644 index 000000000..7f125ff6a --- /dev/null +++ b/taskt/Core/Automation/Commands/List/IListGetFromListProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Get From List properties + /// + public interface IListGetFromListProperties : ILListProperties, ILResultProperties + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/List/IListGetFromValueProperties.cs b/taskt/Core/Automation/Commands/List/IListGetFromValueProperties.cs new file mode 100644 index 000000000..092d28e54 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/IListGetFromValueProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Get List something From List Value + /// + public interface IListGetFromValueProperties : IListResultProperties + { + /// + /// List Value + /// + string v_Value { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/IListGetMathResultFromListProperties.cs b/taskt/Core/Automation/Commands/List/IListGetMathResultFromListProperties.cs new file mode 100644 index 000000000..7b719d8d6 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/IListGetMathResultFromListProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Get Math Result From List properties + /// + public interface IListGetMathResultFromListProperties : IListGetFromListProperties + { + /// + /// Behavior when Value is Not Numeric + /// + string v_WhenValueIsNotNumeric { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/IListIndexProperties.cs b/taskt/Core/Automation/Commands/List/IListIndexProperties.cs new file mode 100644 index 000000000..98389fda5 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/IListIndexProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// List Index properties + /// + public interface IListIndexProperties : ILListProperties + { + /// + /// List Index + /// + string v_Index { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/List/IListResultProperties.cs b/taskt/Core/Automation/Commands/List/IListResultProperties.cs new file mode 100644 index 000000000..a2d3749ff --- /dev/null +++ b/taskt/Core/Automation/Commands/List/IListResultProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// List is Result Properties + /// + public interface IListResultProperties : ILResultProperties, ICanHandleList + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/List/JoinListValuesAsTextCommand.cs b/taskt/Core/Automation/Commands/List/JoinListValuesAsTextCommand.cs new file mode 100644 index 000000000..602231306 --- /dev/null +++ b/taskt/Core/Automation/Commands/List/JoinListValuesAsTextCommand.cs @@ -0,0 +1,85 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("List")] + [Attributes.ClassAttributes.SubGruop("Convert")] + [Attributes.ClassAttributes.CommandSettings("Join List Values As Text")] + [Attributes.ClassAttributes.Description("This command allows you to Join List Values. This Result is Text value.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Join List Values. This Result is Text value.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class JoinListValuesAsTextCommand : AListGetFromListCommands + { + //[XmlAttribute] + //public string v_List { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Separator of List Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage(",", PropertyDetailSampleUsage.ValueType.Value, "Separator")] + [PropertyDetailSampleUsage("{{{vSep}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Separator")] + [PropertyValidationRule("Separator", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyDisplayText(true, "Separator")] + [PropertyParameterOrder(6000)] + public string v_Separator { get; set; } + + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyParameterOrder(7000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Text before Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyIsOptional(true)] + [PropertyDetailSampleUsage("\"", PropertyDetailSampleUsage.ValueType.Value, "Text before Values")] + [PropertyDetailSampleUsage("{{{vText}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Text before Values")] + [PropertyValidationRule("Text before Values", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(8000)] + public string v_BeforeText { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Text after Values")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyIsOptional(true)] + [PropertyDetailSampleUsage("\"", PropertyDetailSampleUsage.ValueType.Value, "Text after Values")] + [PropertyDetailSampleUsage("{{{vText}}}", PropertyDetailSampleUsage.ValueType.VariableValue, "Text after Values")] + [PropertyValidationRule("Text after Values", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(8001)] + public string v_AfterText { get; set; } + + public JoinListValuesAsTextCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var list = this.ExpandUserVariableAsList(engine); + + var sep = this.ExpandValueOrUserVariable(nameof(v_Separator), "Separator", engine); + var bef = this.ExpandValueOrUserVariable(nameof(v_BeforeText), "Text before", engine); + var aft = this.ExpandValueOrUserVariable(nameof(v_AfterText), "Text after", engine); + + string txt = ""; + var last = list.Count - 1; + for (int i = 0; i < last; i++) + { + txt += $"{bef}{list[i]}{aft}{sep}"; + } + txt += $"{bef}{list[last]}{aft}"; + txt.StoreInUserVariable(engine, v_Result); + } + } +} diff --git a/taskt/Core/Automation/Commands/List/ReplaceListCommand.cs b/taskt/Core/Automation/Commands/List/ReplaceListCommand.cs index 6e99149a7..aff14935f 100644 --- a/taskt/Core/Automation/Commands/List/ReplaceListCommand.cs +++ b/taskt/Core/Automation/Commands/List/ReplaceListCommand.cs @@ -1,46 +1,50 @@ using System; -using System.Collections.Generic; -using System.Xml.Serialization; using System.Data; using System.Windows.Forms; +using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Actions")] [Attributes.ClassAttributes.CommandSettings("Replace List")] [Attributes.ClassAttributes.Description("This command allows you to relace List value.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to relpace List value.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ReplaceListCommand : ScriptCommand + public sealed class ReplaceListCommand : AListBothListCommands, ILReplaceValueProperties, IHaveDataTableElements { [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_BothListName))] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_BothListName))] [PropertyDescription("List Variable Name to Replace")] [PropertyValidationRule("List to Replace", PropertyValidationRule.ValidationRuleFlags.Empty)] - public string v_TargetList { get; set; } + public override string v_List { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValueType))] [PropertySelectionChangeEvent(nameof(cmbTargetType_SelectionChangeCommited))] - public string v_TargetType { get; set; } + [PropertyParameterOrder(6000)] + public string v_ValueType { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValueType))] [PropertySelectionChangeEvent(nameof(cmbReplaceAction_SelectionChangeCommited))] + [PropertyParameterOrder(6001)] public string v_ReplaceAction { get; set; } [XmlElement] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ActionParameterTable))] + [PropertyParameterOrder(6002)] public DataTable v_ReplaceActionParameterTable { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ConditionControls), nameof(ConditionControls.v_ReplaceValue))] - public string v_ReplaceValue { get; set; } + [PropertyParameterOrder(6003)] + public string v_NewValue { get; set; } public ReplaceListCommand() { @@ -50,16 +54,15 @@ public ReplaceListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - List targetList = v_TargetList.GetListVariable(engine); + //var targetList = v_List.ExpandUserVariableAsList(engine); + var targetList = this.ExpandUserVariableAsList(engine); var parameters = DataTableControls.GetFieldValues(v_ReplaceActionParameterTable, "ParameterName", "ParameterValue", engine); - var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_TargetType), nameof(v_ReplaceAction), parameters, engine, this); + var checkFunc = ConditionControls.GetFilterDeterminStatementTruthFunc(nameof(v_ValueType), nameof(v_ReplaceAction), parameters, engine, this); - string newValue = v_ReplaceValue.ConvertToUserVariable(engine); + string newValue = v_NewValue.ExpandValueOrUserVariable(engine); for (int i = targetList.Count - 1; i >= 0; i--) { @@ -73,21 +76,29 @@ public override void RunCommand(object sender) private void cmbTargetType_SelectionChangeCommited(object sender, EventArgs e) { //ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, ReplaceActionComboboxHelper); - ConditionControls.AddFilterActionItems((ComboBox)ControlsList[nameof(v_TargetType)], (ComboBox)ControlsList[nameof(v_ReplaceAction)]); + ConditionControls.AddFilterActionItems((ComboBox)ControlsList[nameof(v_ValueType)], (ComboBox)ControlsList[nameof(v_ReplaceAction)]); } private void cmbReplaceAction_SelectionChangeCommited(object sender, EventArgs e) { //ConditionControls.RenderFilter(v_ReplaceActionParameterTable, ReplaceParametersGridViewHelper, ReplaceActionComboboxHelper, TargetTypeComboboxHelper); - ConditionControls.RenderFilter(v_ReplaceActionParameterTable, (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)], (ComboBox)ControlsList[nameof(v_ReplaceAction)], (ComboBox)ControlsList[nameof(v_TargetType)]); + ConditionControls.RenderFilter(v_ReplaceActionParameterTable, (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)], (ComboBox)ControlsList[nameof(v_ReplaceAction)], (ComboBox)ControlsList[nameof(v_ValueType)]); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { //ConditionControls.AddFilterActionItems(TargetTypeComboboxHelper, ReplaceActionComboboxHelper); - ConditionControls.AddFilterActionItems((ComboBox)ControlsList[nameof(v_TargetType)], (ComboBox)ControlsList[nameof(v_ReplaceAction)]); + ConditionControls.AddFilterActionItems((ComboBox)ControlsList[nameof(v_ValueType)], (ComboBox)ControlsList[nameof(v_ReplaceAction)]); //ConditionControls.RenderFilter(v_ReplaceActionParameterTable, ReplaceParametersGridViewHelper, ReplaceActionComboboxHelper, TargetTypeComboboxHelper); - ConditionControls.RenderFilter(v_ReplaceActionParameterTable, (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)], (ComboBox)ControlsList[nameof(v_ReplaceAction)], (ComboBox)ControlsList[nameof(v_TargetType)]); + ConditionControls.RenderFilter(v_ReplaceActionParameterTable, (DataGridView)ControlsList[nameof(v_ReplaceActionParameterTable)], (ComboBox)ControlsList[nameof(v_ReplaceAction)], (ComboBox)ControlsList[nameof(v_ValueType)]); + } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_ReplaceActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_ReplaceActionParameterTable); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/ReverseListCommand.cs b/taskt/Core/Automation/Commands/List/ReverseListCommand.cs index 8c0a2c7e3..e7bae4181 100644 --- a/taskt/Core/Automation/Commands/List/ReverseListCommand.cs +++ b/taskt/Core/Automation/Commands/List/ReverseListCommand.cs @@ -6,26 +6,27 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Actions")] [Attributes.ClassAttributes.CommandSettings("Reverse List")] [Attributes.ClassAttributes.Description("This command allows you to reverse list.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to reverse list.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ReverseListCommand : ScriptCommand + public sealed class ReverseListCommand : AListCreateFromListCommands { [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] [PropertyDescription("List Variable Name to Reverse")] [PropertyValidationRule("List to Reverse", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "List to Reverse")] - public string v_InputList { get; set; } + public override string v_TargetList { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_NewOutputListName))] - public string v_OutputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_NewOutputListName))] + //public string v_NewList { get; set; } public ReverseListCommand() { @@ -35,15 +36,17 @@ public ReverseListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + //List targetList = v_TargetList.ExpandUserVariableAsList(engine); + var targetList = this.ExpandUserVariableAsList(engine); - List targetList = v_InputList.GetListVariable(engine); + //List newList = new List(targetList); + var newList = new List(targetList); - List newList = new List(targetList); newList.Reverse(); - newList.StoreInUserVariable(engine, v_OutputList); + //newList.StoreInUserVariable(engine, v_NewList); + this.StoreListInUserVariable(newList, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/SetListIndexCommand.cs b/taskt/Core/Automation/Commands/List/SetListIndexCommand.cs index d26a32d6b..a718ae3c6 100644 --- a/taskt/Core/Automation/Commands/List/SetListIndexCommand.cs +++ b/taskt/Core/Automation/Commands/List/SetListIndexCommand.cs @@ -5,24 +5,25 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("Other")] [Attributes.ClassAttributes.CommandSettings("Set List Index")] [Attributes.ClassAttributes.Description("This command allows you to modify List Index.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to modify List Index. You can even use variables to modify other variables.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetListIndexCommand : ScriptCommand + public sealed class SetListIndexCommand : AListIndexCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_BothListName))] - public string v_ListName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_BothListName))] + //public string v_List { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ListIndex))] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ListIndex))] [PropertyIsOptional(false)] - public string v_Index { get; set; } + public override string v_Index { get; set; } public SetListIndexCommand() { @@ -32,14 +33,14 @@ public SetListIndexCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; + //(var _, var index) = this.ExpandUserVariablesAsListAndIndex(nameof(v_List), nameof(v_Index), engine); - (var _, var index) = this.GetListVariableAndIndex(nameof(v_ListName), nameof(v_Index), engine); + (_, var index, _) = this.ExpandValueOrUserVariableAsListAndIndexAndValue(engine); - var rawVariable = v_ListName.GetRawVariable(engine); + // TODO: i want to be better + var rawVariable = v_List.GetRawVariable(engine); rawVariable.CurrentPosition = index; } } diff --git a/taskt/Core/Automation/Commands/List/SetListItemCommand.cs b/taskt/Core/Automation/Commands/List/SetListItemCommand.cs index 6f7307cbb..25d793ff4 100644 --- a/taskt/Core/Automation/Commands/List/SetListItemCommand.cs +++ b/taskt/Core/Automation/Commands/List/SetListItemCommand.cs @@ -1,28 +1,28 @@ using System; using System.Xml.Serialization; -using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Item")] [Attributes.ClassAttributes.CommandSettings("Set List Item")] [Attributes.ClassAttributes.Description("This command allows you want to set an item in a List")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set an item in a List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetListItemCommand : ScriptCommand + public sealed class SetListItemCommand : AListIndexCommands { [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_BothListName))] - public string v_ListName { get; set; } + public override string v_List { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ListIndex))] - public string v_ItemIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_ListIndex))] + //public string v_Index { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_OneLineTextBox))] @@ -31,6 +31,7 @@ public class SetListItemCommand : ScriptCommand [PropertyDetailSampleUsage("**{{{vValue}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Value to Set")] [PropertyValidationRule("Value", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(7000)] public string v_NewValue { get; set; } public SetListItemCommand() @@ -41,10 +42,8 @@ public SetListItemCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //var listVariable = v_ListName.GetRawVariable(engine); //if (listVariable == null) //{ @@ -76,16 +75,20 @@ public override void RunCommand(object sender) // index = targetList.Count + index; //} - (var list, var index) = this.GetListVariableAndIndex(nameof(v_ListName), nameof(v_ItemIndex), engine); + //(var list, var index) = this.ExpandUserVariablesAsListAndIndex(nameof(v_List), nameof(v_Index), engine); + + //if ((index >= 0) && (index < list.Count)) + //{ + // list[index] = v_NewValue.ExpandValueOrUserVariable(engine); + //} + //else + //{ + // throw new Exception("Strange index " + v_Index + ", parsed " + index); + //} + + (var list, var index, _) = this.ExpandValueOrUserVariableAsListAndIndexAndValue(engine); - if ((index >= 0) && (index < list.Count)) - { - list[index] = v_NewValue.ConvertToUserVariable(engine); - } - else - { - throw new Exception("Strange index " + v_ItemIndex + ", parsed " + index); - } + list[index] = v_NewValue.ExpandValueOrUserVariable(engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/List/SortListCommand.cs b/taskt/Core/Automation/Commands/List/SortListCommand.cs index 2eca683ce..6dda91ef5 100644 --- a/taskt/Core/Automation/Commands/List/SortListCommand.cs +++ b/taskt/Core/Automation/Commands/List/SortListCommand.cs @@ -6,22 +6,23 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("List Commands")] + [Attributes.ClassAttributes.Group("List")] [Attributes.ClassAttributes.SubGruop("List Actions")] [Attributes.ClassAttributes.CommandSettings("Sort List")] [Attributes.ClassAttributes.Description("This command allows you to sort list.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to sort list.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SortListCommand : ScriptCommand + public sealed class SortListCommand : AListCreateFromListCommands { [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] [PropertyDescription("List Variable Name to Sort")] [PropertyValidationRule("List to Sort", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "List to Sort")] - public string v_InputList { get; set; } + public override string v_TargetList { get; set; } [XmlAttribute] [PropertyDescription("Sort Order")] @@ -33,6 +34,7 @@ public class SortListCommand : ScriptCommand [PropertyUISelectionOption("Ascending")] [PropertyUISelectionOption("Descending")] [PropertyDisplayText(true, "Order")] + [PropertyParameterOrder(6000)] public string v_SortOrder { get; set; } [XmlAttribute] @@ -45,11 +47,12 @@ public class SortListCommand : ScriptCommand [PropertyUISelectionOption("Text")] [PropertyUISelectionOption("Number")] [PropertyDisplayText(true, "Type")] + [PropertyParameterOrder(7000)] public string v_TargetType { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_NewOutputListName))] - public string v_OutputList { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_NewOutputListName))] + //public string v_NewList { get; set; } public SortListCommand() { @@ -59,31 +62,32 @@ public SortListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - string sortOrder = this.GetUISelectionValue(nameof(v_SortOrder), "Sort Order", engine); + string sortOrder = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_SortOrder), "Sort Order", engine); - string targetType = this.GetUISelectionValue(nameof(v_TargetType), "Target Type", engine); + string targetType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_TargetType), "Target Type", engine); switch (targetType) { case "text": - List targetList = v_InputList.GetListVariable(engine); - List newList = new List(targetList); + //var targetList = v_TargetList.ExpandUserVariableAsList(engine); + var targetList = this.ExpandUserVariableAsList(engine); + var newList = new List(targetList); newList.Sort(); if (sortOrder == "descending") { newList.Reverse(); } - newList.StoreInUserVariable(engine, v_OutputList); + //newList.StoreInUserVariable(engine, v_NewList); + this.StoreListInUserVariable(newList, engine); break; case "number": - List targetValueList = v_InputList.GetDecimalListVariable(false, engine); - List valueList = new List(targetValueList); + //var targetValueList = v_TargetList.ExpandUserVariableAsDecimalList(false, engine); + var targetValueList = this.ExpandUserVariableAsDecimalList(nameof(v_TargetList), false, engine); + var valueList = new List(targetValueList); valueList.Sort(); if (sortOrder == "descending") @@ -91,12 +95,13 @@ public override void RunCommand(object sender) valueList.Reverse(); } - List newList2 = new List(); + var newValueList = new List(); foreach(var v in valueList) { - newList2.Add(v.ToString()); + newValueList.Add(v.ToString()); } - newList2.StoreInUserVariable(engine, v_OutputList); + //newList2.StoreInUserVariable(engine, v_NewList); + this.StoreListInUserVariable(newValueList, engine); break; } diff --git a/taskt/Core/Automation/Commands/ListControls.cs b/taskt/Core/Automation/Commands/ListControls.cs index f4f7da2d8..a9c523995 100644 --- a/taskt/Core/Automation/Commands/ListControls.cs +++ b/taskt/Core/Automation/Commands/ListControls.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Windows.Automation.Provider; +using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands @@ -11,6 +8,7 @@ namespace taskt.Core.Automation.Commands /// internal static class ListControls { + #region Virtual Property /// /// input List variable property /// @@ -25,6 +23,7 @@ internal static class ListControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("List", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "List")] + [PropertyParameterOrder(5000)] public static string v_InputListName { get; } /// @@ -42,6 +41,7 @@ internal static class ListControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("List", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "List")] + [PropertyParameterOrder(5000)] public static string v_OutputListName { get; } /// @@ -59,6 +59,7 @@ internal static class ListControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("New List", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "New List")] + [PropertyParameterOrder(5000)] public static string v_NewOutputListName { get; } /// @@ -76,6 +77,7 @@ internal static class ListControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Both)] [PropertyValidationRule("List", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "List")] + [PropertyParameterOrder(5000)] public static string v_BothListName { get; } /// @@ -96,6 +98,7 @@ internal static class ListControls [PropertyDetailSampleUsage("**Comman Separated**", "Enter like **A,B,C**")] [PropertyDetailSampleUsage("**Space Separated**", "Enter like **A B C**")] [PropertyDetailSampleUsage("**Tab Separated**", "Enter like **A\tB\tC**")] + [PropertyParameterOrder(5000)] public static string v_AType { get; } @@ -111,6 +114,7 @@ internal static class ListControls [PropertyUISelectionOption("Ignore")] [PropertyUISelectionOption("Error")] [PropertyDisplayText(false, "")] + [PropertyParameterOrder(5000)] public static string v_ANotEnough { get; } /// @@ -126,6 +130,7 @@ internal static class ListControls [PropertyUISelectionOption("Error")] [PropertyUISelectionOption("Insert Empty Value")] [PropertyDisplayText(false, "")] + [PropertyParameterOrder(5000)] public static string v_ListItemNotEnough { get; } /// @@ -140,6 +145,7 @@ internal static class ListControls [PropertyUISelectionOption("Error")] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyIsOptional(true, "Ignore")] + [PropertyParameterOrder(5000)] public static string v_WhenValueIsNotNumeric { get; } /// @@ -154,6 +160,7 @@ internal static class ListControls [PropertyShowSampleUsageInDescription(true)] [PropertyIsOptional(true, "Current Position")] [PropertyDisplayText(true, "Index")] + [PropertyParameterOrder(5000)] public static string v_ListIndex { get; } /// @@ -168,118 +175,120 @@ internal static class ListControls [PropertyShowSampleUsageInDescription(true)] [PropertyIsOptional(true, "Empty")] [PropertyDisplayText(true, "Value to Search")] + [PropertyParameterOrder(5000)] public static string v_SearchValue { get; } + #endregion - /// - /// get List<string> variable from variable name - /// - /// - /// - /// - /// - public static List GetListVariable(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) - { - Script.ScriptVariable v = variableName.GetRawVariable(engine); - if (v.VariableValue is List list) - { - return list; - } - else - { - throw new Exception("Variable " + variableName + " is not supported List"); - } - } + ///// + ///// expand user variable as List<string> + ///// + ///// + ///// + ///// + ///// value is not List + //public static List ExpandUserVariableAsList(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) + //{ + // Script.ScriptVariable v = variableName.GetRawVariable(engine); + // if (v.VariableValue is List list) + // { + // return list; + // } + // else + // { + // throw new Exception("Variable " + variableName + " is not supported List"); + // } + //} - /// - /// get List Variabe and Index value from specified Command parameters name - /// - /// - /// - /// - /// - /// - /// - public static (List, int) GetListVariableAndIndex(this ScriptCommand command, string variableName, string indexName, Engine.AutomationEngineInstance engine) + public static void StoreInUserVariable(this List value, Core.Automation.Engine.AutomationEngineInstance engine, string targetVariable) { - var listVariableName = command.ConvertToUserVariable(variableName, "List Variable Name", engine); + ExtensionMethods.StoreInUserVariable(targetVariable, value, engine, false); + } - var list = listVariableName.GetListVariable(engine); + ///// + ///// expand (value or) user variables as List Variabe and Index + ///// + ///// + ///// + ///// + ///// + ///// + ///// value is not List, or index is out of range + //public static (List, int) ExpandUserVariablesAsListAndIndex(this ScriptCommand command, string variableName, string indexName, Engine.AutomationEngineInstance engine) + //{ + // var listVariableName = command.ExpandValueOrUserVariable(variableName, "List Variable Name", engine); - var indexValue = command.ConvertToUserVariable(indexName, "Index", engine); - int index; - if (String.IsNullOrEmpty(indexValue)) - { - var raw = listVariableName.GetRawVariable(engine); - index = raw.CurrentPosition; - } - else if (!int.TryParse(indexValue, out index)) - { - throw new Exception("Index is not Integer Number. Value: '" + indexValue + "'"); - } + // var list = listVariableName.ExpandUserVariableAsList(engine); - if (index < 0) - { - index += list.Count; - } + // var indexValue = command.ExpandValueOrUserVariable(indexName, "Index", engine); + // int index; + // if (String.IsNullOrEmpty(indexValue)) + // { + // var raw = listVariableName.GetRawVariable(engine); + // index = raw.CurrentPosition; + // } + // else if (!int.TryParse(indexValue, out index)) + // { + // throw new Exception("Index is not Integer Number. Value: '" + indexValue + "'"); + // } - if (list.Count <= index) - { - throw new Exception("Index is out of List index. Index: " + index); - } + // if (index < 0) + // { + // index += list.Count; + // } - return (list, index); - } + // if (list.Count <= index) + // { + // throw new Exception("Index is out of List index. Index: " + index); + // } - public static void StoreInUserVariable(this List value, Core.Automation.Engine.AutomationEngineInstance sender, string targetVariable) - { - ExtensionMethods.StoreInUserVariable(targetVariable, value, sender, false); - } + // return (list, index); + //} - /// - /// get List<string> to List<decimal> from variable name - /// - /// - /// - /// - /// - /// - public static List GetDecimalListVariable(this string listName, bool ignoreNotNumeric, Engine.AutomationEngineInstance engine) - { - var list = listName.GetListVariable(engine); + ///// + ///// expand user variable as List<string> to List<decimal> + ///// + ///// + ///// + ///// + ///// + ///// value is not Decimal List + //public static List ExpandUserVariableAsDecimalList(this string listName, bool ignoreNotNumeric, Engine.AutomationEngineInstance engine) + //{ + // var list = listName.ExpandUserVariableAsList(engine); - List numList = new List(); - foreach(var value in list) - { - if (decimal.TryParse(value, out decimal v)) - { - numList.Add(v); - } - else if (!ignoreNotNumeric) - { - throw new Exception(listName + " has not numeric value."); - } - } + // List numList = new List(); + // foreach(var value in list) + // { + // if (decimal.TryParse(value, out decimal v)) + // { + // numList.Add(v); + // } + // else if (!ignoreNotNumeric) + // { + // throw new Exception(listName + " has not numeric value."); + // } + // } - return numList; - } + // return numList; + //} - /// - /// math calc process to List - /// - /// - /// - /// - /// - /// - /// - /// - public static string MathProcess(ScriptCommand command, string notNumericName, string listName, Engine.AutomationEngineInstance engine, Func, decimal> mathFunc) - { - var notNumeric = command.GetUISelectionValue(notNumericName, "Not Numeric", engine); + ///// + ///// math calc process to List + ///// + ///// + ///// + ///// + ///// + ///// + ///// + ///// + //public static string MathProcess(ScriptCommand command, string notNumericName, string listName, Engine.AutomationEngineInstance engine, Func, decimal> mathFunc) + //{ + // var notNumeric = command.ExpandValueOrUserVariableAsSelectionItem(notNumericName, "Not Numeric", engine); - var list = GetDecimalListVariable(listName, (notNumeric == "ignore"), engine); + // var list = ExpandUserVariableAsDecimalList(listName, (notNumeric == "ignore"), engine); - return mathFunc(list).ToString(); - } + // return mathFunc(list).ToString(); + //} } } diff --git a/taskt/Core/Automation/Commands/Loop/BeginContinousLoopCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginContinousLoopCommand.cs index 9410184c5..e4164514b 100644 --- a/taskt/Core/Automation/Commands/Loop/BeginContinousLoopCommand.cs +++ b/taskt/Core/Automation/Commands/Loop/BeginContinousLoopCommand.cs @@ -1,80 +1,116 @@ using System; -using System.Collections.Generic; -using System.Windows.Forms; -using taskt.UI.CustomControls; -using taskt.UI.Forms; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; namespace taskt.Core.Automation.Commands { - - - [Serializable] - [Attributes.ClassAttributes.Group("Loop Commands")] + [Attributes.ClassAttributes.Group("Loop")] + [Attributes.ClassAttributes.CommandSettings("Loop Continuously")] [Attributes.ClassAttributes.Description("This command allows you to repeat actions continuously. Any 'Begin Loop' command must have a following 'End Loop' command.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to perform a series of commands an endless amount of times.")] [Attributes.ClassAttributes.ImplementationDescription("This command recursively calls the underlying 'BeginLoop' Command to achieve automation.")] - public class BeginContinousLoopCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class BeginContinousLoopCommand : ScriptCommand, IHaveLoopAdditionalCommands { + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store the Number of Loops (First Time Value is 0)")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Number of Loops", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Number of Loops")] + public string v_NumberOfLoops { get; set; } public BeginContinousLoopCommand() { - this.CommandName = "BeginContinousLoopCommand"; - this.SelectionName = "Loop Continuously"; - this.CommandEnabled = true; - this.CustomRendering = true; + //this.CommandName = "BeginContinousLoopCommand"; + //this.SelectionName = "Loop Continuously"; + //this.CommandEnabled = true; + //this.CustomRendering = true; } - public override void RunCommand(object sender, Core.Script.ScriptAction parentCommand) + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) { - Core.Automation.Commands.BeginContinousLoopCommand loopCommand = (Core.Automation.Commands.BeginContinousLoopCommand)parentCommand.ScriptCommand; - - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; + var loopCommand = (BeginContinousLoopCommand)parentCommand.ScriptCommand; + Action loopTimesAction; + if (!string.IsNullOrEmpty(v_NumberOfLoops)) + { + loopTimesAction = new Action(num => + { + num.StoreInUserVariable(engine, v_NumberOfLoops); + SystemVariables.Update_LoopCurrentIndex(num); + }); + } + else + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + }); + } - engine.ReportProgress("Starting Continous Loop From Line " + loopCommand.LineNumber); + engine.ReportProgress($"Starting Continous Loop From Line {loopCommand.LineNumber}"); + decimal count = 0; while (true) { - + //loopTimesAction(count); foreach (var cmd in parentCommand.AdditionalScriptCommands) { if (engine.IsCancellationPending) + { return; + } + + loopTimesAction(count); // update loop count engine.ExecuteCommand(cmd); if (engine.CurrentLoopCancelled) { - engine.ReportProgress("Exiting Loop From Line " + loopCommand.LineNumber); + engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}"); engine.CurrentLoopCancelled = false; return; } if (engine.CurrentLoopContinuing) { - engine.ReportProgress("Continuing Next Loop From Line " + loopCommand.LineNumber); + engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}"); engine.CurrentLoopContinuing = false; break; } } + + try + { + count++; + } + catch + { + count = decimal.MinValue; + } } } - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - RenderedControls.Add(CommandControls.CreateDefaultLabelFor("v_Comment", this)); - RenderedControls.Add(CommandControls.CreateDefaultInputFor("v_Comment", this, 100, 300)); + //public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // base.Render(editor); - return RenderedControls; - } + // RenderedControls.Add(CommandControls.CreateDefaultLabelFor("v_Comment", this)); + // RenderedControls.Add(CommandControls.CreateDefaultInputFor("v_Comment", this, 100, 300)); - public override string GetDisplayValue() - { - return base.GetDisplayValue(); - } + // return RenderedControls; + //} + + //public override string GetDisplayValue() + //{ + // return base.GetDisplayValue(); + //} } -} \ No newline at end of file +} diff --git a/taskt/Core/Automation/Commands/Loop/BeginListLoopCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginListLoopCommand.cs deleted file mode 100644 index 91beffd96..000000000 --- a/taskt/Core/Automation/Commands/Loop/BeginListLoopCommand.cs +++ /dev/null @@ -1,175 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Xml.Serialization; -using System.Data; -using System.Windows.Forms; -using taskt.UI.Forms; -using taskt.UI.CustomControls; - -namespace taskt.Core.Automation.Commands -{ - [Serializable] - [Attributes.ClassAttributes.Group("Loop Commands")] - [Attributes.ClassAttributes.Description("This command allows you to repeat actions several times (loop). Any 'Begin Loop' command must have a following 'End Loop' command.")] - [Attributes.ClassAttributes.UsesDescription("Use this command when you want to iterate over each item in a list, or a series of items.")] - [Attributes.ClassAttributes.ImplementationDescription("This command recursively calls the underlying 'BeginLoop' Command to achieve automation.")] - public class BeginListLoopCommand : ScriptCommand - { - [XmlAttribute] - [Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [Attributes.PropertyAttributes.PropertyDescription("Please input the list variable to be looped (ex. {{{vList}}}, [1,2,3])")] - [Attributes.PropertyAttributes.InputSpecification("Enter a variable which contains a list of items")] - [Attributes.PropertyAttributes.SampleUsage("**{{{vMyList}}}** or **[1,2,3]**")] - [Attributes.PropertyAttributes.Remarks("Use this command to iterate over the results of the Split command.")] - public string v_LoopParameter { get; set; } - - public BeginListLoopCommand() - { - this.CommandName = "BeginListLoopCommand"; - this.SelectionName = "Loop List"; - this.CommandEnabled = true; - this.CustomRendering = true; - } - - public override void RunCommand(object sender, Core.Script.ScriptAction parentCommand) - { - Core.Automation.Commands.BeginListLoopCommand loopCommand = (Core.Automation.Commands.BeginListLoopCommand)parentCommand.ScriptCommand; - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - - Script.ScriptVariable complexVariable = null; - - //get variable by regular name - complexVariable = engine.VariableList.Where(x => x.VariableName == v_LoopParameter).FirstOrDefault(); - - - if (!engine.VariableList.Any(f => f.VariableName == "Loop.CurrentIndex")) - { - engine.VariableList.Add(new Script.ScriptVariable() { VariableName = "Loop.CurrentIndex", VariableValue = "0" }); - } - - //user may potentially include brackets [] - if (complexVariable == null) - { - complexVariable = engine.VariableList.Where(x => x.VariableName.ApplyVariableFormatting(engine) == v_LoopParameter).FirstOrDefault(); - } - - //if still null then throw exception - if (complexVariable == null) - { - throw new System.Exception("Complex Variable '" + v_LoopParameter + "' or '" + v_LoopParameter.ApplyVariableFormatting(engine) + "' not found. Ensure the variable exists before attempting to modify it."); - } - - dynamic listToLoop; - if (complexVariable.VariableValue is List) - { - listToLoop = (List)complexVariable.VariableValue; - } - else if (complexVariable.VariableValue is List) - { - listToLoop = (List)complexVariable.VariableValue; - } - else if (complexVariable.VariableValue is DataTable) - { - listToLoop = ((DataTable)complexVariable.VariableValue).Rows; - } - else if (complexVariable.VariableValue is List) - { - listToLoop = (List)complexVariable.VariableValue; - } - else if (complexVariable.VariableValue is Dictionary) - { - listToLoop = ((Dictionary)complexVariable.VariableValue).Values.ToList(); - } - else if (complexVariable.VariableValue is List) - { - listToLoop = (List)complexVariable.VariableValue; - } - else if ((complexVariable.VariableValue.ToString().StartsWith("[")) && (complexVariable.VariableValue.ToString().EndsWith("]")) && (complexVariable.VariableValue.ToString().Contains(","))) - { - //automatically handle if user has given a json array - Newtonsoft.Json.Linq.JArray jsonArray = Newtonsoft.Json.JsonConvert.DeserializeObject(complexVariable.VariableValue.ToString()) as Newtonsoft.Json.Linq.JArray; - - var itemList = new List(); - foreach (var item in jsonArray) - { - var value = (Newtonsoft.Json.Linq.JValue)item; - itemList.Add(value.ToString()); - } - - complexVariable.VariableValue = itemList; - listToLoop = itemList; - } - else - { - throw new System.Exception("Complex Variable List Type Not Supported"); - } - - int loopTimes = listToLoop.Count; - - for (int i = 0; i < loopTimes; i++) - { - if (complexVariable != null) - { - complexVariable.CurrentPosition = i; - } - - engine.ReportProgress("Starting Loop Number " + (i + 1) + "/" + loopTimes + " From Line " + loopCommand.LineNumber); - - foreach (var cmd in parentCommand.AdditionalScriptCommands) - { - if (engine.IsCancellationPending) - { - return; - } - - (i + 1).ToString().StoreInUserVariable(engine, "Loop.CurrentIndex"); - - engine.ExecuteCommand(cmd); - - if (engine.CurrentLoopCancelled) - { - engine.ReportProgress("Exiting Loop From Line " + loopCommand.LineNumber); - engine.CurrentLoopCancelled = false; - return; - } - - if (engine.CurrentLoopContinuing) - { - engine.ReportProgress("Continuing Next Loop From Line " + loopCommand.LineNumber); - engine.CurrentLoopContinuing = false; - break; - } - } - - engine.ReportProgress("Finished Loop From Line " + loopCommand.LineNumber); - } - } - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_LoopParameter", this, editor)); - - return RenderedControls; - } - - public override string GetDisplayValue() - { - return "Loop List Variable '" + v_LoopParameter + "'"; - } - - public override bool IsValidate(frmCommandEditor editor) - { - base.IsValidate(editor); - - if (String.IsNullOrEmpty(this.v_LoopParameter)) - { - this.validationResult += "List variable is empty.\n"; - this.IsValid = false; - } - - return this.IsValid; - } - } -} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Loop/BeginLoopCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginLoopCommand.cs index fb5edc23a..5679ca673 100644 --- a/taskt/Core/Automation/Commands/Loop/BeginLoopCommand.cs +++ b/taskt/Core/Automation/Commands/Loop/BeginLoopCommand.cs @@ -4,17 +4,17 @@ using System.Data; using System.Collections.Generic; using System.Windows.Forms; -using taskt.UI.Forms; using taskt.UI.CustomControls; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Loop Commands")] + [Attributes.ClassAttributes.Group("Loop")] [Attributes.ClassAttributes.Description("This command allows you to evaluate a logical statement to determine if the statement is true. The following actions will repeat continuously until that statement becomes false")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check if a statement is 'true' or 'false' and subsequently loop actions based on either condition. Any 'BeginLoop' command must have a following 'EndLoop' command.")] [Attributes.ClassAttributes.ImplementationDescription("This command evaluates supplied arguments and if evaluated to true runs sub elements")] - public class BeginLoopCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + public sealed class BeginLoopCommand : ScriptCommand, IHaveDataTableElements, IHaveLoopAdditionalCommands { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please select type of Loop Command")] @@ -92,16 +92,15 @@ public BeginLoopCommand() this.v_LoopActionParameterTable.Columns.Add("Parameter Name"); this.v_LoopActionParameterTable.Columns.Add("Parameter Value"); } - private void LoopGridViewHelper_MouseEnter(object sender, EventArgs e, frmCommandEditor editor) + + private void LoopGridViewHelper_MouseEnter(object sender, EventArgs e, UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { loopAction_SelectionChangeCommitted(null, null, editor); } - public override void RunCommand(object sender, Core.Script.ScriptAction parentCommand) - { - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - //var loopResult = DetermineStatementTruth(sender); - string actionType = v_LoopActionType.ConvertToUserVariable(engine); + public override void RunCommand(Engine.AutomationEngineInstance engine, Core.Script.ScriptAction parentCommand) + { + string actionType = v_LoopActionType.ExpandValueOrUserVariable(engine); bool loopResult = ConditionControls.DetermineStatementTruth(actionType, v_LoopActionParameterTable, engine); engine.ReportProgress("Starting Loop"); @@ -134,450 +133,7 @@ public override void RunCommand(object sender, Core.Script.ScriptAction parentCo } } - //public bool DetermineStatementTruth(object sender) - //{ - // var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - - // bool loopResult = false; - - // if (v_LoopActionType == "Value") - // { - // string value1 = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Value1" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // string operand = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Operand" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // string value2 = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Value2" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // value1 = value1.ConvertToUserVariable(sender); - // value2 = value2.ConvertToUserVariable(sender); - // bool tempBool; - // bool isBoolCompare = (bool.TryParse(value1, out tempBool) && bool.TryParse(value2, out tempBool)); - - // decimal cdecValue1, cdecValue2; - - // switch (operand) - // { - // case "is equal to": - // if (isBoolCompare) - // { - // loopResult = (bool.Parse(value1) == bool.Parse(value2)); - // } - // else - // { - // loopResult = (value1 == value2); - // } - // break; - - // case "is not equal to": - // if (isBoolCompare) - // { - // loopResult = (bool.Parse(value1) != bool.Parse(value2)); - // } - // else - // { - // loopResult = (value1 != value2); - // } - // break; - - // case "is greater than": - // cdecValue1 = Convert.ToDecimal(value1); - // cdecValue2 = Convert.ToDecimal(value2); - // loopResult = (cdecValue1 > cdecValue2); - // break; - - // case "is greater than or equal to": - // cdecValue1 = Convert.ToDecimal(value1); - // cdecValue2 = Convert.ToDecimal(value2); - // loopResult = (cdecValue1 >= cdecValue2); - // break; - - // case "is less than": - // cdecValue1 = Convert.ToDecimal(value1); - // cdecValue2 = Convert.ToDecimal(value2); - // loopResult = (cdecValue1 < cdecValue2); - // break; - - // case "is less than or equal to": - // cdecValue1 = Convert.ToDecimal(value1); - // cdecValue2 = Convert.ToDecimal(value2); - // loopResult = (cdecValue1 <= cdecValue2); - // break; - // } - // } - // else if (v_LoopActionType == "Date Compare") - // { - // string value1 = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Value1" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // string operand = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Operand" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // string value2 = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Value2" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // value1 = value1.ConvertToUserVariable(sender); - // value2 = value2.ConvertToUserVariable(sender); - - - - // DateTime dt1, dt2; - // dt1 = DateTime.Parse(value1); - // dt2 = DateTime.Parse(value2); - // switch (operand) - // { - // case "is equal to": - // loopResult = (dt1 == dt2); - // break; - - // case "is not equal to": - // loopResult = (dt1 != dt2); - // break; - - // case "is greater than": - // loopResult = (dt1 > dt2); - // break; - - // case "is greater than or equal to": - // loopResult = (dt1 >= dt2); - // break; - - // case "is less than": - // loopResult = (dt1 < dt2); - // break; - - // case "is less than or equal to": - // loopResult = (dt1 <= dt2); - // break; - // } - // } - // else if (v_LoopActionType == "Variable Compare") - // { - // string value1 = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Value1" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // string operand = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Operand" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // string value2 = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Value2" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string caseSensitive = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Case Sensitive" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // value1 = value1.ConvertToUserVariable(sender); - // value2 = value2.ConvertToUserVariable(sender); - - // if (caseSensitive == "No") - // { - // value1 = value1.ToUpper(); - // value2 = value2.ToUpper(); - // } - - - - // switch (operand) - // { - // case "contains": - // loopResult = (value1.Contains(value2)); - // break; - - // case "does not contain": - // loopResult = (!value1.Contains(value2)); - // break; - - // case "is equal to": - // loopResult = (value1 == value2); - // break; - - // case "is not equal to": - // loopResult = (value1 != value2); - // break; - // } - // } - // else if (v_LoopActionType == "Variable Has Value") - // { - // string variableName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Variable Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // var actualVariable = variableName.ConvertToUserVariable(sender).Trim(); - - // if (!string.IsNullOrEmpty(actualVariable)) - // { - // loopResult = true; - // } - // else - // { - // loopResult = false; - // } - - // } - // else if (v_LoopActionType == "Variable Is Numeric") - // { - // string variableName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Variable Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // var actualVariable = variableName.ConvertToUserVariable(sender).Trim(); - - // var numericTest = decimal.TryParse(actualVariable, out decimal parsedResult); - - // if (numericTest) - // { - // loopResult = true; - // } - // else - // { - // loopResult = false; - // } - - // } - // else if (v_LoopActionType == "Error Occured") - // { - // //get line number - // string userLineNumber = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Line Number" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //convert to variable - // string variableLineNumber = userLineNumber.ConvertToUserVariable(sender); - - // //convert to int - // int lineNumber = int.Parse(variableLineNumber); - - // //determine if error happened - // if (engine.ErrorsOccured.Where(f => f.LineNumber == lineNumber).Count() > 0) - // { - - // var error = engine.ErrorsOccured.Where(f => f.LineNumber == lineNumber).FirstOrDefault(); - // error.ErrorMessage.StoreInUserVariable(sender, "Error.Message"); - // error.LineNumber.ToString().StoreInUserVariable(sender, "Error.Line"); - // error.StackTrace.StoreInUserVariable(sender, "Error.StackTrace"); - - // loopResult = true; - // } - // else - // { - // loopResult = false; - // } - - // } - // else if (v_LoopActionType == "Error Did Not Occur") - // { - // //get line number - // string userLineNumber = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Line Number" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // //convert to variable - // string variableLineNumber = userLineNumber.ConvertToUserVariable(sender); - - // //convert to int - // int lineNumber = int.Parse(variableLineNumber); - - // //determine if error happened - // if (engine.ErrorsOccured.Where(f => f.LineNumber == lineNumber).Count() == 0) - // { - // loopResult = true; - // } - // else - // { - // var error = engine.ErrorsOccured.Where(f => f.LineNumber == lineNumber).FirstOrDefault(); - // error.ErrorMessage.StoreInUserVariable(sender, "Error.Message"); - // error.LineNumber.ToString().StoreInUserVariable(sender, "Error.Line"); - // error.StackTrace.StoreInUserVariable(sender, "Error.StackTrace"); - - // loopResult = false; - // } - - // } - // else if (v_LoopActionType == "Window Name Exists") - // { - // //get user supplied name - // string windowName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Window Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // //variable translation - // string variablizedWindowName = windowName.ConvertToUserVariable(sender); - - // //search for window - // IntPtr windowPtr = User32Functions.FindWindow(variablizedWindowName); - - // //conditional - // if (windowPtr != IntPtr.Zero) - // { - // loopResult = true; - // } - - - - // } - // else if (v_LoopActionType == "Active Window Name Is") - // { - // string windowName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Window Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string variablizedWindowName = windowName.ConvertToUserVariable(sender); - - // var currentWindowTitle = User32Functions.GetActiveWindowTitle(); - - // if (currentWindowTitle == variablizedWindowName) - // { - // loopResult = true; - // } - - // } - // else if (v_LoopActionType == "File Exists") - // { - - // string fileName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "File Path" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string trueWhenFileExists = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "True When" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // var userFileSelected = fileName.ConvertToUserVariable(sender); - - // bool existCheck = false; - // if (trueWhenFileExists == "It Does Exist") - // { - // existCheck = true; - // } - - - // if (System.IO.File.Exists(userFileSelected) == existCheck) - // { - // loopResult = true; - // } - - - // } - // else if (v_LoopActionType == "Folder Exists") - // { - // string folderName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Folder Path" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string trueWhenFileExists = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "True When" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // var userFolderSelected = folderName.ConvertToUserVariable(sender); - - // bool existCheck = false; - // if (trueWhenFileExists == "It Does Exist") - // { - // existCheck = true; - // } - - - // if (System.IO.Directory.Exists(folderName) == existCheck) - // { - // loopResult = true; - // } - - // } - // else if (v_LoopActionType == "Web Element Exists") - // { - // string instanceName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Selenium Instance Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string parameterName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Parameter" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string searchMethod = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Method" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - - // SeleniumBrowserElementActionCommand newElementActionCommand = new SeleniumBrowserElementActionCommand(); - // newElementActionCommand.v_SeleniumSearchType = searchMethod; - // newElementActionCommand.v_InstanceName = instanceName.ConvertToUserVariable(sender); - // bool elementExists = newElementActionCommand.ElementExists(sender, searchMethod, parameterName); - // loopResult = elementExists; - - // } - // else if (v_LoopActionType == "GUI Element Exists") - // { - // string windowName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Window Name" - // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender)); - - // string elementSearchParam = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Parameter" - // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender)); - - // string elementSearchMethod = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Method" - // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender)); - - - // if (windowName == ((Automation.Engine.AutomationEngineInstance)sender).engineSettings.CurrentWindowKeyword) - // { - // windowName = User32Functions.GetActiveWindowTitle(); - // } - - // UIAutomationCommand newUIACommand = new UIAutomationCommand(); - // newUIACommand.v_WindowName = windowName; - // newUIACommand.v_UIASearchParameters.Rows.Add(true, elementSearchMethod, elementSearchParam); - // var handle = newUIACommand.SearchForGUIElement(sender, windowName); - - // if (handle is null) - // { - // loopResult = false; - // } - // else - // { - // loopResult = true; - // } - - - // } - // else if (v_LoopActionType == "Boolean") - // { - // string value = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Variable Name" - // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender)); - - // string compare = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Value Is" - // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender)); - - // bool vValue = bool.Parse(value); - // switch (compare.ToLower()) - // { - // case "true": - // loopResult = vValue; - // break; - // case "false": - // loopResult = !vValue; - // break; - // default: - // throw new Exception("Value Is " + compare + " is not support."); - // break; - // } - // } - // else - // { - // throw new Exception("Loop type not recognized!"); - // } - - // return loopResult; - //} - - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -648,7 +204,7 @@ public override List Render(frmCommandEditor editor) return RenderedControls; } - private void loopAction_SelectionChangeCommitted(object sender, EventArgs e, frmCommandEditor editor) + private void loopAction_SelectionChangeCommitted(object sender, EventArgs e, UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { ComboBox loopAction = (ComboBox)ActionDropdown; //DataGridView loopActionParameterBox = (DataGridView)LoopGridViewHelper; @@ -662,17 +218,6 @@ private void loopAction_SelectionChangeCommitted(object sender, EventArgs e, frm actionParameters.Rows.Clear(); } - //DataGridViewComboBoxCell comparisonComboBox = new DataGridViewComboBoxCell(); - - ////recorder control - //Control recorderControl = (Control)RecorderControl; - - ////remove if exists - //if (RecorderControl.Visible) - //{ - // RecorderControl.Hide(); - //} - lnkBrowserInstanceSelector.Hide(); lnkWindowNameSelector.Hide(); @@ -681,249 +226,51 @@ private void loopAction_SelectionChangeCommitted(object sender, EventArgs e, frm //case "Value": case "Numeric Compare": case "Date Compare": - //loopActionParameterBox.Visible = true; - - //if (sender != null) - //{ - // actionParameters.Rows.Add("Value1", ""); - // actionParameters.Rows.Add("Operand", ""); - // actionParameters.Rows.Add("Value2", ""); - // loopActionParameterBox.DataSource = actionParameters; - //} - - ////combobox cell for Variable Name - //comparisonComboBox = new DataGridViewComboBoxCell(); - //comparisonComboBox.Items.Add("is equal to"); - //comparisonComboBox.Items.Add("is greater than"); - //comparisonComboBox.Items.Add("is greater than or equal to"); - //comparisonComboBox.Items.Add("is less than"); - //comparisonComboBox.Items.Add("is less than or equal to"); - //comparisonComboBox.Items.Add("is not equal to"); - - ////assign cell as a combobox - //loopActionParameterBox.Rows[1].Cells[1] = comparisonComboBox; - ConditionControls.RenderNumericCompare(sender, LoopGridViewHelper, v_LoopActionParameterTable); break; //case "Variable Compare": case "Text Compare": - //loopActionParameterBox.Visible = true; - - //if (sender != null) - //{ - // actionParameters.Rows.Add("Value1", ""); - // actionParameters.Rows.Add("Operand", ""); - // actionParameters.Rows.Add("Value2", ""); - // actionParameters.Rows.Add("Case Sensitive", "No"); - // loopActionParameterBox.DataSource = actionParameters; - //} - - ////combobox cell for Variable Name - //comparisonComboBox = new DataGridViewComboBoxCell(); - //comparisonComboBox.Items.Add("contains"); - //comparisonComboBox.Items.Add("does not contain"); - //comparisonComboBox.Items.Add("is equal to"); - //comparisonComboBox.Items.Add("is not equal to"); - - ////assign cell as a combobox - //loopActionParameterBox.Rows[1].Cells[1] = comparisonComboBox; - - //comparisonComboBox = new DataGridViewComboBoxCell(); - //comparisonComboBox.Items.Add("Yes"); - //comparisonComboBox.Items.Add("No"); - - ////assign cell as a combobox - //loopActionParameterBox.Rows[3].Cells[1] = comparisonComboBox; - ConditionControls.RenderTextCompare(sender, LoopGridViewHelper, v_LoopActionParameterTable); break; case "Variable Has Value": case "Variable Is Numeric": - //loopActionParameterBox.Visible = true; - //if (sender != null) - //{ - // actionParameters.Rows.Add("Variable Name", ""); - // loopActionParameterBox.DataSource = actionParameters; - //} ConditionControls.RenderVariableIsHas(sender, LoopGridViewHelper, v_LoopActionParameterTable); break; - - //case "Variable Is Numeric": - // //loopActionParameterBox.Visible = true; - // //if (sender != null) - // //{ - // // actionParameters.Rows.Add("Variable Name", ""); - // // loopActionParameterBox.DataSource = actionParameters; - // //} - - // break; - - case "Error Occured": case "Error Did Not Occur": - //loopActionParameterBox.Visible = true; - //if (sender != null) - //{ - // actionParameters.Rows.Add("Line Number", ""); - // loopActionParameterBox.DataSource = actionParameters; - //} ConditionControls.RenderErrorOccur(sender, LoopGridViewHelper, v_LoopActionParameterTable); break; - - //case "Error Did Not Occur": - // //loopActionParameterBox.Visible = true; - - // //if (sender != null) - // //{ - // // actionParameters.Rows.Add("Line Number", ""); - // // loopActionParameterBox.DataSource = actionParameters; - // //} - - // break; - - case "Window Name Exists": case "Active Window Name Is": - //loopActionParameterBox.Visible = true; - //if (sender != null) - //{ - // actionParameters.Rows.Add("Window Name", ""); - // loopActionParameterBox.DataSource = actionParameters; - //} ConditionControls.RenderWindowName(sender, LoopGridViewHelper, v_LoopActionParameterTable); lnkWindowNameSelector.Show(); break; - case "File Exists": - //loopActionParameterBox.Visible = true; - //if (sender != null) - //{ - // actionParameters.Rows.Add("File Path", ""); - // actionParameters.Rows.Add("True When", ""); - // loopActionParameterBox.DataSource = actionParameters; - //} - - ////combobox cell for Variable Name - //comparisonComboBox = new DataGridViewComboBoxCell(); - //comparisonComboBox.Items.Add("It Does Exist"); - //comparisonComboBox.Items.Add("It Does Not Exist"); - - ////assign cell as a combobox - //loopActionParameterBox.Rows[1].Cells[1] = comparisonComboBox; ConditionControls.RenderFileExists(sender, LoopGridViewHelper, v_LoopActionParameterTable); break; - case "Folder Exists": - //loopActionParameterBox.Visible = true; - - //if (sender != null) - //{ - // actionParameters.Rows.Add("Folder Path", ""); - // actionParameters.Rows.Add("True When", ""); - // loopActionParameterBox.DataSource = actionParameters; - //} - - ////combobox cell for Variable Name - //comparisonComboBox = new DataGridViewComboBoxCell(); - //comparisonComboBox.Items.Add("It Does Exist"); - //comparisonComboBox.Items.Add("It Does Not Exist"); - - ////assign cell as a combobox - //loopActionParameterBox.Rows[1].Cells[1] = comparisonComboBox; ConditionControls.RenderFolderExists(sender, LoopGridViewHelper, v_LoopActionParameterTable); break; - case "Web Element Exists": - //loopActionParameterBox.Visible = true; - - //if (sender != null) - //{ - // actionParameters.Rows.Add("Selenium Instance Name", editor.appSettings.ClientSettings.DefaultBrowserInstanceName); - // actionParameters.Rows.Add("Element Search Method", ""); - // actionParameters.Rows.Add("Element Search Parameter", ""); - // loopActionParameterBox.DataSource = actionParameters; - //} - - //comparisonComboBox = new DataGridViewComboBoxCell(); - //comparisonComboBox.Items.Add("Find Element By XPath"); - //comparisonComboBox.Items.Add("Find Element By ID"); - //comparisonComboBox.Items.Add("Find Element By Name"); - //comparisonComboBox.Items.Add("Find Element By Tag Name"); - //comparisonComboBox.Items.Add("Find Element By Class Name"); - //comparisonComboBox.Items.Add("Find Element By CSS Selector"); - - ////assign cell as a combobox - //loopActionParameterBox.Rows[1].Cells[1] = comparisonComboBox; ConditionControls.RenderWebElement(sender, LoopGridViewHelper, v_LoopActionParameterTable, editor.appSettings); lnkBrowserInstanceSelector.Show(); break; - case "GUI Element Exists": - //loopActionParameterBox.Visible = true; - //if (sender != null) - //{ - // actionParameters.Rows.Add("Window Name", editor.appSettings.EngineSettings.CurrentWindowKeyword); - // actionParameters.Rows.Add("Element Search Method", ""); - // actionParameters.Rows.Add("Element Search Parameter", ""); - // loopActionParameterBox.DataSource = actionParameters; - //} - - //var parameterName = new DataGridViewComboBoxCell(); - //parameterName.Items.Add("AcceleratorKey"); - //parameterName.Items.Add("AccessKey"); - //parameterName.Items.Add("AutomationId"); - //parameterName.Items.Add("ClassName"); - //parameterName.Items.Add("FrameworkId"); - //parameterName.Items.Add("HasKeyboardFocus"); - //parameterName.Items.Add("HelpText"); - //parameterName.Items.Add("IsContentElement"); - //parameterName.Items.Add("IsControlElement"); - //parameterName.Items.Add("IsEnabled"); - //parameterName.Items.Add("IsKeyboardFocusable"); - //parameterName.Items.Add("IsOffscreen"); - //parameterName.Items.Add("IsPassword"); - //parameterName.Items.Add("IsRequiredForForm"); - //parameterName.Items.Add("ItemStatus"); - //parameterName.Items.Add("ItemType"); - //parameterName.Items.Add("LocalizedControlType"); - //parameterName.Items.Add("Name"); - //parameterName.Items.Add("NativeWindowHandle"); - //parameterName.Items.Add("ProcessID"); - - ////assign cell as a combobox - //loopActionParameterBox.Rows[1].Cells[1] = parameterName; - - //RecorderControl.Show(); ConditionControls.RenderGUIElement(sender, LoopGridViewHelper, v_LoopActionParameterTable, editor.appSettings); lnkWindowNameSelector.Show(); break; - case "Boolean": - //loopActionParameterBox.Visible = true; - //if (sender != null) - //{ - // actionParameters.Rows.Add("Variable Name", ""); - // actionParameters.Rows.Add("Value Is", "True"); - // loopActionParameterBox.DataSource = actionParameters; - //} - ////assign cell as a combobox - //var booleanParam = new DataGridViewComboBoxCell(); - //booleanParam.Items.Add("True"); - //booleanParam.Items.Add("False"); - //loopActionParameterBox.Rows[1].Cells[1] = booleanParam; - - //RecorderControl.Show(); ConditionControls.RenderBoolean(sender, LoopGridViewHelper, v_LoopActionParameterTable); break; @@ -948,11 +295,11 @@ private void loopAction_SelectionChangeCommitted(object sender, EventArgs e, frm } } - private void linkWebBrowserInstanceSelector_Click(object sender, EventArgs e, frmCommandEditor editor) + private void linkWebBrowserInstanceSelector_Click(object sender, EventArgs e, UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var instances = editor.instanceList.getInstanceClone(Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.WebBrowser); - using (var frm = new UI.Forms.Supplemental.frmItemSelector(instances.Keys.ToList())) + using (var frm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmItemSelector(instances.Keys.ToList())) { if (frm.ShowDialog() == DialogResult.OK) { @@ -965,24 +312,26 @@ private void linkWebBrowserInstanceSelector_Click(object sender, EventArgs e, fr } } - private void linkWindowNameSelector_Click(object sender, EventArgs e, frmCommandEditor editor) + private void linkWindowNameSelector_Click(object sender, EventArgs e, UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - List windowNames = new List(); - - windowNames.Add(editor.appSettings.EngineSettings.CurrentWindowKeyword); + List windowNames = new List + { + //editor.appSettings.EngineSettings.CurrentWindowKeyword + VariableNameControls.GetWrappedVariableName(Engine.SystemVariables.Window_CurrentWindowName.VariableName, editor.appSettings), + }; System.Diagnostics.Process[] processlist = System.Diagnostics.Process.GetProcesses(); //pull the main window title for each foreach (var process in processlist) { - if (!String.IsNullOrEmpty(process.MainWindowTitle)) + if (!string.IsNullOrEmpty(process.MainWindowTitle)) { //add to the control list of available windows windowNames.Add(process.MainWindowTitle); } } - using (var frm = new UI.Forms.Supplemental.frmItemSelector(windowNames)) + using (var frm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmItemSelector(windowNames)) { if (frm.ShowDialog() == DialogResult.OK) { @@ -994,11 +343,12 @@ private void linkWindowNameSelector_Click(object sender, EventArgs e, frmCommand } } } - private void linkBooleanInstanceSelector_Click(object sender, EventArgs e, frmCommandEditor editor) + + private void linkBooleanInstanceSelector_Click(object sender, EventArgs e, UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { var instances = editor.instanceList.getInstanceClone(Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Boolean); - using (var frm = new UI.Forms.Supplemental.frmItemSelector(instances.Keys.ToList())) + using (var frm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmItemSelector(instances.Keys.ToList())) { if (frm.ShowDialog() == DialogResult.OK) { @@ -1026,198 +376,12 @@ private void linkBooleanInstanceSelector_Click(object sender, EventArgs e, frmCo } } - //private void ShowLoopElementRecorder(object sender, EventArgs e) - //{ - // //get command reference - // Core.Automation.Commands.UIAutomationCommand cmd = new Core.Automation.Commands.UIAutomationCommand(); - - // //create recorder - // UI.Forms.Supplemental.frmThickAppElementRecorder newElementRecorder = new UI.Forms.Supplemental.frmThickAppElementRecorder(); - // newElementRecorder.searchParameters = cmd.v_UIASearchParameters; - - // //show form - // newElementRecorder.ShowDialog(); - - // var sb = new StringBuilder(); - // sb.AppendLine("Element Properties Found!"); - // sb.AppendLine(Environment.NewLine); - // sb.AppendLine("Element Search Method - Element Search Parameter"); - // foreach (DataRow rw in cmd.v_UIASearchParameters.Rows) - // { - // if (rw.ItemArray[2].ToString().Trim() == string.Empty) - // continue; - - // sb.AppendLine(rw.ItemArray[1].ToString() + " - " + rw.ItemArray[2].ToString()); - // } - - // DataGridView loopActionBox = LoopGridViewHelper; - // loopActionBox.Rows[0].Cells[1].Value = newElementRecorder.cboWindowTitle.Text; - - // MessageBox.Show(sb.ToString()); - //} - public override string GetDisplayValue() { - //switch (v_LoopActionType) - //{ - // //case "Value": - // case "Numeric Compare": - // case "Date Compare": - // //case "Variable Compare": - // case "Text Compare": - // case "Boolean Compare": - // string value1 = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Value1" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // string operand = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Operand" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // string value2 = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Value2" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // return "Loop While (" + value1 + " " + operand + " " + value2 + ")"; - - // case "Variable Has Value": - // string variableName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Variable Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // return "Loop While (Variable " + variableName + " Has Value)"; - // case "Variable Is Numeric": - // string varName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Variable Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // return "Loop While (Variable " + varName + " Is Numeric)"; - - // case "Error Occured": - - // string lineNumber = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Line Number" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // return "Loop While (Error Occured on Line Number " + lineNumber + ")"; - // case "Error Did Not Occur": - - // string lineNum = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Line Number" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // return "Loop While (Error Did Not Occur on Line Number " + lineNum + ")"; - // case "Window Name Exists": - // case "Active Window Name Is": - - // string windowName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Window Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // return "Loop While " + v_LoopActionType + " [Name: " + windowName + "]"; - // case "File Exists": - - // string filePath = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "File Path" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string fileCompareType = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "True When" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - - // return "Loop While " + v_LoopActionType + " [File: " + filePath + "]"; - - // case "Folder Exists": - - // string folderPath = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Folder Path" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string folderCompareType = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "True When" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - - // return "Loop While " + v_LoopActionType + " [Folder: " + folderPath + "]"; - - // case "Web Element Exists": - - - // string parameterName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Parameter" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string searchMethod = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Method" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - - // return "Loop While Web Element Exists [" + searchMethod + ": " + parameterName + "]"; - - // case "GUI Element Exists": - - - // string guiWindowName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Window Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string guiSearch = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Parameter" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - - - - // return "Loop While GUI Element Exists [Find " + guiSearch + " Element In " + guiWindowName + "]"; - - // case "Boolean": - // string booleanVariable = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Variable Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string compareTo = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Value Is" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // return "Loop While [Boolean] " + booleanVariable + " is " + compareTo; - - // default: - - // return "Loop While .... "; - //} - return ConditionControls.GetDisplayValue("Loop While", v_LoopActionType, v_LoopActionParameterTable); } - //private void LoopGridViewHelper_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) - //{ - // if (e.ColumnIndex == 0) - // { - // e.Cancel = true; - // } - //} - //private void LoopGridViewHelper_CellClick(object sender, DataGridViewCellEventArgs e) - //{ - // if (e.ColumnIndex >= 0) - // { - // if (e.ColumnIndex == 1) - // { - // var targetCell = LoopGridViewHelper.Rows[e.RowIndex].Cells[0]; - // if (targetCell is DataGridViewTextBoxCell) - // { - // LoopGridViewHelper.BeginEdit(false); - // } - // else if ((targetCell is DataGridViewComboBoxCell) && (targetCell.Value.ToString() == "")) - // { - // SendKeys.Send("%{DOWN}"); - // } - // } - // } - // else - // { - // LoopGridViewHelper.EndEdit(); - // } - //} - - public override bool IsValidate(frmCommandEditor editor) + public override bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.IsValidate(editor); @@ -1307,186 +471,6 @@ public override bool IsValidate(frmCommandEditor editor) return this.IsValid; } - //private void ValueValidate() - //{ - // string operand = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Operand" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // if (String.IsNullOrEmpty(operand)) - // { - // this.validationResult += "Operand is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void VariableValidate() - //{ - // string v = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Variable Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // if (String.IsNullOrEmpty(v)) - // { - // this.validationResult += "Variable Name is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void WindowValidate() - //{ - // string windowName = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Window Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // if (String.IsNullOrEmpty(windowName)) - // { - // this.validationResult += "Window Name is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void FileValidate() - //{ - // string fp = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "File Path" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // if (String.IsNullOrEmpty(fp)) - // { - // this.validationResult += "File Path is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void FoloderValidate() - //{ - // string fp = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Folder Path" - // select rw.Field("Parameter Value")).FirstOrDefault()); - // if (String.IsNullOrEmpty(fp)) - // { - // this.validationResult += "Folder Path is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void WebValidate() - //{ - // string instance = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Selenium Instance Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string method = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Method" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string param = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Parameter" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // if (String.IsNullOrEmpty(instance)) - // { - // this.validationResult += "Browser Instance Name (Selenium Insntance) is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(method)) - // { - // this.validationResult += "Search Method is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(param)) - // { - // this.validationResult += "Search Parameter is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void GUIValidate() - //{ - // string window = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Window Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string method = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Method" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // string param = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Element Search Parameter" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // if (String.IsNullOrEmpty(window)) - // { - // this.validationResult += "Window Name is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(method)) - // { - // this.validationResult += "Search Method is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(param)) - // { - // this.validationResult += "Search Parameter is empty.\n"; - // this.IsValid = false; - // } - //} - - //private void ErrorValidate() - //{ - // string line = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Line Number" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // if (String.IsNullOrEmpty(line)) - // { - // this.validationResult += "Line Number is empty.\n"; - // this.IsValid = false; - // } - // else - // { - // int vLine; - // if (int.TryParse(line, out vLine)) - // { - // if (vLine < 1) - // { - // this.validationResult += "Specify 1 or more to Line Number.\n"; - // this.IsValid = false; - // } - // } - // } - //} - - //private void BooleanValidate() - //{ - // string variable = ((from rw in v_LoopActionParameterTable.AsEnumerable() - // where rw.Field("Parameter Name") == "Variable Name" - // select rw.Field("Parameter Value")).FirstOrDefault()); - - // if (String.IsNullOrEmpty(variable)) - // { - // this.validationResult += "Variable is empty.\n"; - // this.IsValid = false; - // } - //} - //private void BooleanCompareValidate() - //{ - // var param = DataTableControls.GetFieldValues(v_LoopActionParameterTable, "Parameter Name", "Parameter Value"); - - // if (String.IsNullOrEmpty(param["Value1"])) - // { - // this.validationResult += "Value1 is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(param["Value2"])) - // { - // this.validationResult += "Value2 is empty.\n"; - // this.IsValid = false; - // } - // if (String.IsNullOrEmpty(param["Operand"])) - // { - // this.validationResult += "Operand is empty.\n"; - // this.IsValid = false; - // } - //} - public override void ConvertToIntermediate(EngineSettings settings, List variables) { if (this.v_LoopActionType == "GUI Element Exists") @@ -1514,5 +498,13 @@ public override void ConvertToRaw(EngineSettings settings) base.ConvertToRaw(settings); } } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + //var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_LoopActionParameterTable)); + DataTableControls.BeforeValidate_NoRowAdding(LoopGridViewHelper, v_LoopActionParameterTable); + } } } diff --git a/taskt/Core/Automation/Commands/Loop/BeginLoopForComplexDataTypesCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginLoopForComplexDataTypesCommand.cs new file mode 100644 index 000000000..19e518c10 --- /dev/null +++ b/taskt/Core/Automation/Commands/Loop/BeginLoopForComplexDataTypesCommand.cs @@ -0,0 +1,185 @@ +using System; +using System.Collections.Generic; +using System.Data; +using System.Linq; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Loop")] + [Attributes.ClassAttributes.CommandSettings("Loop Complex Data Types")] + [Attributes.ClassAttributes.Description("This command allows you to Repeat actions on the values held by List, Dictioanry, and other data. This command must have a following 'End Loop' command.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to iterate over each item in a list, or a series of items.")] + [Attributes.ClassAttributes.ImplementationDescription("This command recursively calls the underlying 'BeginLoop' Command to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class BeginLoopForComplexDataTypesCommand : ScriptCommand, IHaveLoopAdditionalCommands + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] + [PropertyDescription("Variable Name or Value to Loop")] + [InputSpecification("Enter a variable which contains a list of items")] + //[SampleUsage("**{{{vMyList}}}** or **[1,2,3]**")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage("**{{{vList}}}**", PropertyDetailSampleUsage.ValueType.VariableName)] + [PropertyDetailSampleUsage("**[1,2,3]**", PropertyDetailSampleUsage.ValueType.Value)] + [PropertyValidationRule("Loop Target", PropertyValidationRule.ValidationRuleFlags.Empty)] + [Remarks("Use this command to iterate over the results of the Split command.")] + public string v_LoopParameter { get; set; } + + public BeginLoopForComplexDataTypesCommand() + { + //this.CommandName = "BeginListLoopCommand"; + //this.SelectionName = "Loop List"; + //this.CommandEnabled = true; + //this.CustomRendering = true; + } + + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) + { + var loopCommand = (BeginLoopForComplexDataTypesCommand)parentCommand.ScriptCommand; + + //if (!engine.VariableList.Any(f => f.VariableName == "Loop.CurrentIndex")) + //{ + // engine.VariableList.Add(new Script.ScriptVariable() { VariableName = "Loop.CurrentIndex", VariableValue = "0" }); + //} + + //Script.ScriptVariable complexVariable = null; + + ////get variable by regular name + //complexVariable = engine.VariableList.Where(x => x.VariableName == v_LoopParameter).FirstOrDefault(); + + ////user may potentially include brackets [] + //if (complexVariable == null) + //{ + // complexVariable = engine.VariableList.Where(x => x.VariableName.ApplyVariableFormatting(engine) == v_LoopParameter).FirstOrDefault(); + //} + + var complexVariable = v_LoopParameter.GetRawVariable(engine); + + //if still null then throw exception + //if (complexVariable == null) + //{ + // throw new Exception("Complex Variable '" + v_LoopParameter + "' or '" + v_LoopParameter.ApplyVariableFormatting(engine) + "' not found. Ensure the variable exists before attempting to modify it."); + //} + + dynamic listToLoop; + if (complexVariable.VariableValue is List lst) + { + listToLoop = lst; + } + else if (complexVariable.VariableValue is List webElems) + { + listToLoop = webElems; + } + else if (complexVariable.VariableValue is DataTable tbl) + { + listToLoop = tbl.Rows; + } + else if (complexVariable.VariableValue is List outlookMails) + { + listToLoop = outlookMails; + } + else if (complexVariable.VariableValue is Dictionary dic) + { + listToLoop = dic.Values.ToList(); + } + else if (complexVariable.VariableValue is List mailkitMails) + { + listToLoop = mailkitMails; + } + else if ((complexVariable.VariableValue.ToString().StartsWith("[")) && (complexVariable.VariableValue.ToString().EndsWith("]")) && (complexVariable.VariableValue.ToString().Contains(","))) + { + //automatically handle if user has given a json array + var jsonArray = Newtonsoft.Json.JsonConvert.DeserializeObject(complexVariable.VariableValue.ToString()) as Newtonsoft.Json.Linq.JArray; + + var itemList = new List(); + foreach (var item in jsonArray) + { + var value = (Newtonsoft.Json.Linq.JValue)item; + itemList.Add(value.ToString()); + } + + complexVariable.VariableValue = itemList; + listToLoop = itemList; + } + else + { + throw new Exception("Complex Variable List Type Not Supported"); + } + + int loopTimes = listToLoop.Count; + + for (int i = 0; i < loopTimes; i++) + { + if (complexVariable != null) + { + complexVariable.CurrentPosition = i; + } + + engine.ReportProgress($"Starting Loop Number {(i + 1)}/{loopTimes} From Line {loopCommand.LineNumber}"); + + foreach (var cmd in parentCommand.AdditionalScriptCommands) + { + if (engine.IsCancellationPending) + { + return; + } + + //(i + 1).ToString().StoreInUserVariable(engine, "Loop.CurrentIndex"); + SystemVariables.Update_LoopCurrentIndex(i + 1); + + engine.ExecuteCommand(cmd); + + if (engine.CurrentLoopCancelled) + { + engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopCancelled = false; + return; + } + + if (engine.CurrentLoopContinuing) + { + engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopContinuing = false; + break; + } + } + + engine.ReportProgress($"Finished Loop From Line {loopCommand.LineNumber}"); + } + } + + //public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // base.Render(editor); + + // RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_LoopParameter", this, editor)); + + // return RenderedControls; + //} + + //public override string GetDisplayValue() + //{ + // return "Loop List Variable '" + v_LoopParameter + "'"; + //} + + //public override bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // base.IsValidate(editor); + + // if (string.IsNullOrEmpty(this.v_LoopParameter)) + // { + // this.validationResult += "List variable is empty.\n"; + // this.IsValid = false; + // } + + // return this.IsValid; + //} + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableColumnAsDataTableCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableColumnAsDataTableCommand.cs new file mode 100644 index 000000000..a1c7b7e0d --- /dev/null +++ b/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableColumnAsDataTableCommand.cs @@ -0,0 +1,210 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Loop")] + [Attributes.ClassAttributes.CommandSettings("Loop For DataTable Column As DataTable")] + [Attributes.ClassAttributes.Description("This command allows you to Repeat actions on the values held by DataTable. This command must have a following 'End Loop' command.")] + [Attributes.ClassAttributes.UsesDescription("")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class BeginLoopForDataTableColumnAsDataTableCommand : ADataTableGetFromDataTableCommands, IHaveLoopAdditionalCommands + { + //[XmlAttribute] + //public string v_DataTable { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] + [PropertyIsOptional(true)] + [PropertyValidationRule("DataTable Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Column Index")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Column Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Column Index")] + [PropertyParameterOrder(6002)] + public string v_ColumnIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Column Name")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Column Name", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Column Name")] + [PropertyParameterOrder(6003)] + public string v_ColumnName { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Reverse Loop")] + [PropertyIsOptional(true)] + [PropertyFirstValue("No")] + [PropertyDisplayText(false, "")] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6005)] + public string v_ReverseLoop { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Current Loop Times (First Time Value is '1')")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Loop Current Times Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Current Times")] + [PropertyParameterOrder(6007)] + public string v_CurrentTimes { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store the Number of Loops (First Time Value is 0)")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Number of Loops", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Number of Loops")] + [PropertyParameterOrder(6008)] + public string v_NumberOfLoops { get; set; } + + public BeginLoopForDataTableColumnAsDataTableCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) + { + var loopCommand = (BeginLoopForDataTableColumnAsDataTableCommand)parentCommand.ScriptCommand; + + //var rawVariable = v_DataTable.GetRawVariable(engine); + var tableToLoop = this.ExpandUserVariableAsDataTable(engine); + var loopTimes = tableToLoop.Columns.Count; + + Action dataTableVariableAction; + if (string.IsNullOrEmpty(v_Result)) + { + dataTableVariableAction = new Action((column) => { }); // nothing + } + else + { + dataTableVariableAction = new Action((column) => + { + var cnvTbl = new ConvertDataTableColumnToDataTableCommand() + { + v_DataTable = this.v_DataTable, + v_ColumnIndex = column.ToString(), + v_ColumnType = "index", + v_Result = this.v_Result, + }; + cnvTbl.RunCommand(engine); + }); + } + + Action tableColumnIndexAction; + if (string.IsNullOrEmpty(v_ColumnIndex)) + { + tableColumnIndexAction = new Action(idx => { }); // nothing + } + else + { + tableColumnIndexAction = new Action(idx => { idx.StoreInUserVariable(engine, v_ColumnIndex); }); + } + + Action tableColumnNameAction; + if (string.IsNullOrEmpty(v_ColumnIndex)) + { + tableColumnNameAction = new Action(n => { }); // nothing + } + else + { + tableColumnNameAction = new Action(n => { n.StoreInUserVariable(engine, v_ColumnName); }); + } + + Action loopTimesAction; + if (string.IsNullOrEmpty(v_CurrentTimes)) + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + }); + } + else + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + num.StoreInUserVariable(engine, v_CurrentTimes); + }); + } + + Action loopNumAction; + if (string.IsNullOrEmpty(v_NumberOfLoops)) + { + loopNumAction = new Action(num => { }); // nothing + } + else + { + loopNumAction = new Action(num => { num.StoreInUserVariable(engine, v_NumberOfLoops); }); + } + + int count = 0; // loop counter + var loopBodyProcess = new Action((column) => + { + engine.ReportProgress($"Starting Loop Number {(count + 1)}/{loopTimes} From Line {loopCommand.LineNumber}"); + + foreach (var cmd in parentCommand.AdditionalScriptCommands) + { + if (engine.IsCancellationPending) + { + return; + } + + // store variables value + dataTableVariableAction(column); + + tableColumnIndexAction(column); + tableColumnNameAction(tableToLoop.Columns[column].ColumnName); + loopTimesAction(count + 1); + loopNumAction(count); + + engine.ExecuteCommand(cmd); + + if (engine.CurrentLoopCancelled) + { + engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopCancelled = false; + return; + } + + if (engine.CurrentLoopContinuing) + { + engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopContinuing = false; + break; + } + } + + engine.ReportProgress($"Finished Loop From Line {loopCommand.LineNumber}"); + }); + + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ReverseLoop), engine)) + { + for (int i = tableToLoop.Columns.Count - 1; i >= 0; i--) + { + loopBodyProcess(i); + } + } + else + { + for (int i = 0; i < tableToLoop.Columns.Count; i++) + { + loopBodyProcess(i); + } + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableColumnAsListCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableColumnAsListCommand.cs new file mode 100644 index 000000000..8d0affad6 --- /dev/null +++ b/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableColumnAsListCommand.cs @@ -0,0 +1,218 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Loop")] + [Attributes.ClassAttributes.CommandSettings("Loop For DataTable Column As List")] + [Attributes.ClassAttributes.Description("This command allows you to Repeat actions on the values held by DataTable. This command must have a following 'End Loop' command.")] + [Attributes.ClassAttributes.UsesDescription("")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class BeginLoopForDataTableColumnAsListCommand : ADataTableGetFromDataTableCommands, IHaveLoopAdditionalCommands + { + //[XmlAttribute] + //public string v_DataTable { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] + [PropertyIsOptional(true)] + [PropertyValidationRule("List Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Column Index")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Column Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Column Index")] + [PropertyParameterOrder(6002)] + public string v_ColumnIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Column Name")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Column Name", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Column Name")] + [PropertyParameterOrder(6003)] + public string v_ColumnName { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Reverse Loop")] + [PropertyIsOptional(true)] + [PropertyFirstValue("No")] + [PropertyDisplayText(false, "")] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6005)] + public string v_ReverseLoop { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Current Loop Times (First Time Value is '1')")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Loop Current Times Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Current Times")] + [PropertyParameterOrder(6007)] + public string v_CurrentTimes { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store the Number of Loops (First Time Value is 0)")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Number of Loops", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Number of Loops")] + [PropertyParameterOrder(6008)] + public string v_NumberOfLoops { get; set; } + + public BeginLoopForDataTableColumnAsListCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) + { + var loopCommand = (BeginLoopForDataTableColumnAsListCommand)parentCommand.ScriptCommand; + + //var rawVariable = v_DataTable.GetRawVariable(engine); + var tableToLoop = this.ExpandUserVariableAsDataTable(engine); + var loopTimes = tableToLoop.Columns.Count; + + Action listVariableAction; + if (string.IsNullOrEmpty(v_Result)) + { + listVariableAction = new Action((column) => { }); // nothing + } + else + { + listVariableAction = new Action((column) => + { + var cnvList = new ConvertDataTableColumnToListCommand() + { + v_DataTable = this.v_DataTable, + v_ColumnIndex = column.ToString(), + v_ColumnType = "index", + v_Result = this.v_Result, + }; + cnvList.RunCommand(engine); + }); + } + + Action tableColumnIndexAction; + if (string.IsNullOrEmpty(v_ColumnIndex)) + { + tableColumnIndexAction = new Action(idx => { }); // nothing + } + else + { + tableColumnIndexAction = new Action(idx => { idx.StoreInUserVariable(engine, v_ColumnIndex); }); + } + + Action tableColumnNameAction; + if (string.IsNullOrEmpty(v_ColumnIndex)) + { + tableColumnNameAction = new Action(n => { }); // nothing + } + else + { + tableColumnNameAction = new Action(n => { n.StoreInUserVariable(engine, v_ColumnName); }); + } + + Action loopTimesAction; + if (string.IsNullOrEmpty(v_CurrentTimes)) + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + }); + } + else + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + num.StoreInUserVariable(engine, v_CurrentTimes); + }); + } + + Action loopNumAction; + if (string.IsNullOrEmpty(v_NumberOfLoops)) + { + loopNumAction = new Action(num => { }); // nothing + } + else + { + loopNumAction = new Action(num => { num.StoreInUserVariable(engine, v_NumberOfLoops); }); + } + + int count = 0; // loop counter + var loopBodyProcess = new Action((column) => + { + engine.ReportProgress($"Starting Loop Number {(count + 1)}/{loopTimes} From Line {loopCommand.LineNumber}"); + + foreach (var cmd in parentCommand.AdditionalScriptCommands) + { + if (engine.IsCancellationPending) + { + return; + } + + // store variables value + //var convColumnList = new ConvertDataTableColumnToListCommand() + //{ + // v_DataTable = this.v_DataTable, + // v_ColumnIndex = column.ToString(), + // v_ColumnType = "index", + // v_Result = this.v_Result, + //}; + //convColumnList.RunCommand(engine); + listVariableAction(column); + + tableColumnIndexAction(column); + tableColumnNameAction(tableToLoop.Columns[column].ColumnName); + loopTimesAction(count + 1); + loopNumAction(count); + + engine.ExecuteCommand(cmd); + + if (engine.CurrentLoopCancelled) + { + engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopCancelled = false; + return; + } + + if (engine.CurrentLoopContinuing) + { + engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopContinuing = false; + break; + } + } + + engine.ReportProgress($"Finished Loop From Line {loopCommand.LineNumber}"); + }); + + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ReverseLoop), engine)) + { + for (int i = tableToLoop.Columns.Count - 1; i >= 0; i--) + { + loopBodyProcess(i); + } + } + else + { + for (int i = 0; i < tableToLoop.Columns.Count; i++) + { + loopBodyProcess(i); + } + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableCommand.cs new file mode 100644 index 000000000..031a5ff1e --- /dev/null +++ b/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableCommand.cs @@ -0,0 +1,282 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Loop")] + [Attributes.ClassAttributes.CommandSettings("Loop For DataTable")] + [Attributes.ClassAttributes.Description("This command allows you to Repeat actions on the values held by DataTable. This command must have a following 'End Loop' command.")] + [Attributes.ClassAttributes.UsesDescription("")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class BeginLoopForDataTableCommand : ADataTableInputDataTableCommands, IHaveLoopAdditionalCommands + { + //[XmlAttribute] + //public string v_DataTable { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store DataTable Value")] + [PropertyIsOptional(true)] + [PropertyValidationRule("DataTable Value", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "DataTable Value")] + [PropertyParameterOrder(6000)] + public string v_Value { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Row Index")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Row Index")] + [PropertyParameterOrder(6001)] + public string v_RowIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Column Index")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Column Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Column Index")] + [PropertyParameterOrder(6002)] + public string v_ColumnIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Column Name")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Column Name", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Column Name")] + [PropertyParameterOrder(6003)] + public string v_ColumnName { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] + [PropertyDescription("Loop Priority")] + [PropertyUISelectionOption("Row First")] + [PropertyUISelectionOption("Column First")] + [PropertyIsOptional(true, "Row First")] + [PropertyValidationRule("Loop nameof", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Loop Priority")] + [PropertyParameterOrder(6004)] + public string v_LoopDirection { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Row Reverse Loop")] + [PropertyIsOptional(true)] + [PropertyFirstValue("No")] + [PropertyDisplayText(false, "")] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6005)] + public string v_RowReverseLoop { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Column Reverse Loop")] + [PropertyIsOptional(true)] + [PropertyFirstValue("No")] + [PropertyDisplayText(false, "")] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6006)] + public string v_ColumnReverseLoop { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Current Loop Times (First Time Value is '1')")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Loop Current Times Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Current Times")] + [PropertyParameterOrder(6007)] + public string v_CurrentTimes { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store the Number of Loops (First Time Value is 0)")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Number of Loops", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Number of Loops")] + [PropertyParameterOrder(6008)] + public string v_NumberOfLoops { get; set; } + + public BeginLoopForDataTableCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) + { + var loopCommand = (BeginLoopForDataTableCommand)parentCommand.ScriptCommand; + + var rawVariable = v_DataTable.GetRawVariable(engine); + var tableToLoop = this.ExpandUserVariableAsDataTable(engine); + var loopTimes = tableToLoop.Rows.Count * tableToLoop.Columns.Count; + + Action tableValueAction; + if (string.IsNullOrEmpty(v_Value)) + { + tableValueAction = new Action(str => { }); // nothing + } + else + { + tableValueAction = new Action(str => { str.StoreInUserVariable(engine, v_Value); }); + } + + Action tableRowIndexAction; + if (string.IsNullOrEmpty(v_RowIndex)) + { + tableRowIndexAction = new Action(idx => { }); // nothing + } + else + { + tableRowIndexAction = new Action(idx => { idx.StoreInUserVariable(engine, v_RowIndex); }); + } + + Action tableColumnIndexAction; + if (string.IsNullOrEmpty(v_ColumnIndex)) + { + tableColumnIndexAction = new Action(idx => { }); // nothing + } + else + { + tableColumnIndexAction = new Action(idx => { idx.StoreInUserVariable(engine, v_ColumnIndex); }); + } + + Action tableColumnNameAction; + if (string.IsNullOrEmpty(v_ColumnIndex)) + { + tableColumnNameAction = new Action(n => { }); // nothing + } + else + { + tableColumnNameAction = new Action(n => { n.StoreInUserVariable(engine, v_ColumnName); }); + } + + int rowFirstValue, columnFirstValue; + Func rowCondition, columnCondition; + Func rowNextValue, columnNextValue; + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_RowReverseLoop), engine)) + { + rowFirstValue = tableToLoop.Rows.Count - 1; + rowCondition = new Func(row => (row >= 0)); + rowNextValue = new Func(row => (--row)); + } + else + { + rowFirstValue = 0; + rowCondition = new Func(row => (row < tableToLoop.Rows.Count)); + rowNextValue = new Func(row => (++row)); + } + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ColumnReverseLoop), engine)) + { + columnFirstValue = tableToLoop.Columns.Count - 1; + columnCondition = new Func(column => (column >= 0)); + columnNextValue = new Func(column => (--column)); + } + else + { + columnFirstValue = 0; + columnCondition = new Func(column => (column < tableToLoop.Columns.Count)); + columnNextValue = new Func(column => (++column)); + } + + Action loopTimesAction; + if (string.IsNullOrEmpty(v_CurrentTimes)) + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + }); + } + else + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + num.StoreInUserVariable(engine, v_CurrentTimes); + }); + } + + Action loopNumAction; + if (string.IsNullOrEmpty(v_NumberOfLoops)) + { + loopNumAction = new Action(num => { }); // nothing + } + else + { + loopNumAction = new Action(num => { num.StoreInUserVariable(engine, v_NumberOfLoops); }); + } + + int count = 0; // loop counter + var loopBodyProcess = new Action((row, column) => + { + rawVariable.CurrentPosition = row; // TODO: it's no good + + engine.ReportProgress($"Starting Loop Number {(count + 1)}/{loopTimes} From Line {loopCommand.LineNumber}"); + + foreach (var cmd in parentCommand.AdditionalScriptCommands) + { + if (engine.IsCancellationPending) + { + return; + } + + // store variables value + tableValueAction(tableToLoop.Rows[row][column]?.ToString() ?? ""); + tableRowIndexAction(row); + tableColumnIndexAction(column); + tableColumnNameAction(tableToLoop.Columns[column].ColumnName); + loopTimesAction(count + 1); + loopNumAction(count); + + engine.ExecuteCommand(cmd); + + if (engine.CurrentLoopCancelled) + { + engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopCancelled = false; + return; + } + + if (engine.CurrentLoopContinuing) + { + engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopContinuing = false; + break; + } + } + + engine.ReportProgress($"Finished Loop From Line {loopCommand.LineNumber}"); + }); + + switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_LoopDirection), engine)) + { + case "row first": + for (int i = rowFirstValue; rowCondition(i); i = rowNextValue(i)) + { + for (int j = columnFirstValue; columnCondition(j); j = columnNextValue(j)) + { + loopBodyProcess(i, j); + count++; + } + } + break; + case "column first": + for (int j = columnFirstValue; columnCondition(j); j = columnNextValue(j)) + { + for (int i = rowFirstValue; rowCondition(i); i = rowNextValue(i)) + { + + loopBodyProcess(i, j); + count++; + } + } + break; + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableRowAsDataTableCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableRowAsDataTableCommand.cs new file mode 100644 index 000000000..c64408185 --- /dev/null +++ b/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableRowAsDataTableCommand.cs @@ -0,0 +1,190 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Loop")] + [Attributes.ClassAttributes.CommandSettings("Loop For DataTable Row As DataTable")] + [Attributes.ClassAttributes.Description("This command allows you to Repeat actions on the values held by DataTable. This command must have a following 'End Loop' command.")] + [Attributes.ClassAttributes.UsesDescription("")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class BeginLoopForDataTableRowAsDataTableCommand : ADataTableGetFromDataTableCommands, IHaveLoopAdditionalCommands + { + //[XmlAttribute] + //public string v_DataTable { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(DataTableControls), nameof(DataTableControls.v_OutputDataTableName))] + [PropertyIsOptional(true)] + [PropertyValidationRule("DataTable Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Row Index")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Row Index")] + [PropertyParameterOrder(6001)] + public string v_RowIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Reverse Loop")] + [PropertyIsOptional(true)] + [PropertyFirstValue("No")] + [PropertyDisplayText(false, "")] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6002)] + public string v_ReverseLoop { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Current Loop Times (First Time Value is '1')")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Loop Current Times Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Current Times")] + [PropertyParameterOrder(6003)] + public string v_CurrentTimes { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store the Number of Loops (First Time Value is 0)")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Number of Loops", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Number of Loops")] + [PropertyParameterOrder(6004)] + public string v_NumberOfLoops { get; set; } + + public BeginLoopForDataTableRowAsDataTableCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) + { + var loopCommand = (BeginLoopForDataTableRowAsDataTableCommand)parentCommand.ScriptCommand; + + var rawVariable = v_DataTable.GetRawVariable(engine); + var tableToLoop = this.ExpandUserVariableAsDataTable(engine); + var loopTimes = tableToLoop.Rows.Count; + + Action dataTableVariableAction; + if (string.IsNullOrEmpty(v_Result)) + { + dataTableVariableAction = new Action(row => { }); // nothing + } + else + { + dataTableVariableAction = new Action(row => + { + var cnbTbl = new ConvertDataTableRowToDataTableCommand() + { + v_DataTable = this.v_DataTable, + v_RowIndex = row.ToString(), + v_Result = this.v_Result, + }; + cnbTbl.RunCommand(engine); + }); + } + + Action tableRowIndexAction; + if (string.IsNullOrEmpty(v_RowIndex)) + { + tableRowIndexAction = new Action(idx => { }); // nothing + } + else + { + tableRowIndexAction = new Action(idx => { idx.StoreInUserVariable(engine, v_RowIndex); }); + } + + Action loopTimesAction; + if (string.IsNullOrEmpty(v_CurrentTimes)) + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + }); + } + else + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + num.StoreInUserVariable(engine, v_CurrentTimes); + }); + } + + Action loopNumAction; + if (string.IsNullOrEmpty(v_NumberOfLoops)) + { + loopNumAction = new Action(num => { }); // nothing + } + else + { + loopNumAction = new Action(num => { num.StoreInUserVariable(engine, v_NumberOfLoops); }); + } + + int count = 0; // loop counter + var loopBodyProcess = new Action((row) => + { + rawVariable.CurrentPosition = row; // TODO: it's no good + + engine.ReportProgress($"Starting Loop Number {(count + 1)}/{loopTimes} From Line {loopCommand.LineNumber}"); + + foreach (var cmd in parentCommand.AdditionalScriptCommands) + { + if (engine.IsCancellationPending) + { + return; + } + + // store variables value + dataTableVariableAction(row); + tableRowIndexAction(row); + loopTimesAction(count + 1); + loopNumAction(count); + + engine.ExecuteCommand(cmd); + + if (engine.CurrentLoopCancelled) + { + engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopCancelled = false; + return; + } + + if (engine.CurrentLoopContinuing) + { + engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopContinuing = false; + break; + } + } + + engine.ReportProgress($"Finished Loop From Line {loopCommand.LineNumber}"); + }); + + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ReverseLoop), engine)) + { + for (int i = tableToLoop.Rows.Count - 1; i >= 0; i--) + { + loopBodyProcess(i); + } + } + else + { + for (int i = 0; i < tableToLoop.Rows.Count; i++) + { + loopBodyProcess(i); + } + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableRowAsDictionaryCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableRowAsDictionaryCommand.cs new file mode 100644 index 000000000..d85f2464a --- /dev/null +++ b/taskt/Core/Automation/Commands/Loop/BeginLoopForDataTableRowAsDictionaryCommand.cs @@ -0,0 +1,190 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Loop")] + [Attributes.ClassAttributes.CommandSettings("Loop For DataTable Row As Dictionary")] + [Attributes.ClassAttributes.Description("This command allows you to Repeat actions on the values held by DataTable. This command must have a following 'End Loop' command.")] + [Attributes.ClassAttributes.UsesDescription("")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class BeginLoopForDataTableRowAsDictionaryCommand : ADataTableGetFromDataTableCommands, IHaveLoopAdditionalCommands + { + //[XmlAttribute] + //public string v_DataTable { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(DictionaryControls), nameof(DictionaryControls.v_OutputDictionaryName))] + [PropertyIsOptional(true)] + [PropertyValidationRule("Dictionary Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6000)] + public override string v_Result { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Row Index")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Row Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Row Index")] + [PropertyParameterOrder(6001)] + public string v_RowIndex { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Reverse Loop")] + [PropertyIsOptional(true)] + [PropertyFirstValue("No")] + [PropertyDisplayText(false, "")] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6002)] + public string v_ReverseLoop { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Current Loop Times (First Time Value is '1')")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Loop Current Times Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Current Times")] + [PropertyParameterOrder(6003)] + public string v_CurrentTimes { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store the Number of Loops (First Time Value is 0)")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Number of Loops", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Number of Loops")] + [PropertyParameterOrder(6004)] + public string v_NumberOfLoops { get; set; } + + public BeginLoopForDataTableRowAsDictionaryCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) + { + var loopCommand = (BeginLoopForDataTableRowAsDictionaryCommand)parentCommand.ScriptCommand; + + var rawVariable = v_DataTable.GetRawVariable(engine); + var tableToLoop = this.ExpandUserVariableAsDataTable(engine); + var loopTimes = tableToLoop.Rows.Count; + + Action dictionaryVariableAction; + if (string.IsNullOrEmpty(v_Result)) + { + dictionaryVariableAction = new Action(row => { }); // nothing + } + else + { + dictionaryVariableAction = new Action(row => + { + var cnvDic = new ConvertDataTableRowToDictionaryCommand() + { + v_DataTable = this.v_DataTable, + v_RowIndex = row.ToString(), + v_Result = this.v_Result, + }; + cnvDic.RunCommand(engine); + }); + } + + Action tableRowIndexAction; + if (string.IsNullOrEmpty(v_RowIndex)) + { + tableRowIndexAction = new Action(idx => { }); // nothing + } + else + { + tableRowIndexAction = new Action(idx => { idx.StoreInUserVariable(engine, v_RowIndex); }); + } + + Action loopTimesAction; + if (string.IsNullOrEmpty(v_CurrentTimes)) + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + }); + } + else + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + num.StoreInUserVariable(engine, v_CurrentTimes); + }); + } + + Action loopNumAction; + if (string.IsNullOrEmpty(v_NumberOfLoops)) + { + loopNumAction = new Action(num => { }); // nothing + } + else + { + loopNumAction = new Action(num => { num.StoreInUserVariable(engine, v_NumberOfLoops); }); + } + + int count = 0; // loop counter + var loopBodyProcess = new Action((row) => + { + rawVariable.CurrentPosition = row; // TODO: it's no good + + engine.ReportProgress($"Starting Loop Number {(count + 1)}/{loopTimes} From Line {loopCommand.LineNumber}"); + + foreach (var cmd in parentCommand.AdditionalScriptCommands) + { + if (engine.IsCancellationPending) + { + return; + } + + // store variables value + dictionaryVariableAction(row); + tableRowIndexAction(row); + loopTimesAction(count + 1); + loopNumAction(count); + + engine.ExecuteCommand(cmd); + + if (engine.CurrentLoopCancelled) + { + engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopCancelled = false; + return; + } + + if (engine.CurrentLoopContinuing) + { + engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopContinuing = false; + break; + } + } + + engine.ReportProgress($"Finished Loop From Line {loopCommand.LineNumber}"); + }); + + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ReverseLoop), engine)) + { + for (int i = tableToLoop.Rows.Count - 1; i >= 0; i--) + { + loopBodyProcess(i); + } + } + else + { + for (int i = 0; i < tableToLoop.Rows.Count; i++) + { + loopBodyProcess(i); + } + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Loop/BeginLoopForDictionaryCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginLoopForDictionaryCommand.cs new file mode 100644 index 000000000..771b7995a --- /dev/null +++ b/taskt/Core/Automation/Commands/Loop/BeginLoopForDictionaryCommand.cs @@ -0,0 +1,189 @@ +using System; +using System.Linq; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Loop")] + [Attributes.ClassAttributes.CommandSettings("Loop For Dictionary")] + [Attributes.ClassAttributes.Description("This command allows you to Repeat actions on the values held by Dictionary. This command must have a following 'End Loop' command.")] + [Attributes.ClassAttributes.UsesDescription("")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class BeginLoopForDictionaryCommand : ADictionaryInputDictionaryCommands, IHaveLoopAdditionalCommands + { + //[XmlAttribute] + //public string v_Dictionary { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Dictionary Value")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Dictionary Value", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Dictionary Value")] + [PropertyParameterOrder(6000)] + public string v_Value { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Dictionary Key")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Dictionary Key", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Dictionary Key")] + [PropertyParameterOrder(6001)] + public string v_Key { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Reverse Loop")] + [PropertyIsOptional(true)] + [PropertyFirstValue("No")] + [PropertyDisplayText(false, "")] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6003)] + public string v_ReverseLoop { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Current Loop Times (First Time Value is '1')")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Loop Current Times Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Current Times")] + [PropertyParameterOrder(6004)] + public string v_CurrentTimes { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store the Number of Loops (First Time Value is 0)")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Number of Loops", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Number of Loops")] + [PropertyParameterOrder(6005)] + public string v_NumberOfLoops { get; set; } + + public BeginLoopForDictionaryCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) + { + var loopCommand = (BeginLoopForDictionaryCommand)parentCommand.ScriptCommand; + + var rawVariable = v_Dictionary.GetRawVariable(engine); + var dicToLoop = this.ExpandUserVariableAsDictionary(engine); + var keys = dicToLoop.Keys.ToList(); + int loopTimes = keys.Count; + + Action dicValueAction; + if (string.IsNullOrEmpty(v_Value)) + { + dicValueAction = new Action(str => { }); // nothing + } + else + { + dicValueAction = new Action(str => { str.StoreInUserVariable(engine, v_Value); }); + } + + Action dicKeyAction; + if (string.IsNullOrEmpty(v_Key)) + { + dicKeyAction = new Action(idx => { }); // nothing + } + else + { + dicKeyAction = new Action(idx => { idx.StoreInUserVariable(engine, v_Key); }); + } + + Action loopTimesAction; + if (string.IsNullOrEmpty(v_CurrentTimes)) + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + }); + } + else + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + num.StoreInUserVariable(engine, v_CurrentTimes); + }); + } + + Action loopNumAction; + if (string.IsNullOrEmpty(v_NumberOfLoops)) + { + loopNumAction = new Action(num => { }); // nothing + } + else + { + loopNumAction = new Action(num => { num.StoreInUserVariable(engine, v_NumberOfLoops); }); + } + + int count = 0; // loop counter + var loopBodyProcess = new Action(index => + { + rawVariable.CurrentPosition = index; // TODO: it's no good + + engine.ReportProgress($"Starting Loop Number {(count + 1)}/{loopTimes} From Line {loopCommand.LineNumber}"); + + foreach (var cmd in parentCommand.AdditionalScriptCommands) + { + if (engine.IsCancellationPending) + { + return; + } + + var key = keys[index]; + + // store variables value + dicValueAction(dicToLoop[key]); + dicKeyAction(key); + loopTimesAction(count + 1); + loopNumAction(count); + + engine.ExecuteCommand(cmd); + + if (engine.CurrentLoopCancelled) + { + engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopCancelled = false; + return; + } + + if (engine.CurrentLoopContinuing) + { + engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopContinuing = false; + break; + } + } + + engine.ReportProgress($"Finished Loop From Line {loopCommand.LineNumber}"); + }); + + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ReverseLoop), engine)) + { + // reverse loop + for (int i = keys.Count - 1; i >= 0; i--, count++) + { + loopBodyProcess(i); + } + } + else + { + // normal loop + for (int i = 0; i < keys.Count; i++, count++) + { + loopBodyProcess(i); + } + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Loop/BeginLoopForListCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginLoopForListCommand.cs new file mode 100644 index 000000000..688e694da --- /dev/null +++ b/taskt/Core/Automation/Commands/Loop/BeginLoopForListCommand.cs @@ -0,0 +1,191 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Loop")] + [Attributes.ClassAttributes.CommandSettings("Loop For List")] + [Attributes.ClassAttributes.Description("This command allows you to Repeat actions on the values held by List. This command must have a following 'End Loop' command.")] + [Attributes.ClassAttributes.UsesDescription("")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class BeginLoopForListCommand : AListInputListCommands, IHaveLoopAdditionalCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_InputListName))] + //public string v_List { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store List Value")] + [PropertyIsOptional(true)] + [PropertyValidationRule("List Value", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "List Value")] + [PropertyParameterOrder(6000)] + public string v_Value { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store List Index")] + [PropertyIsOptional(true)] + [PropertyValidationRule("List Index", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "List Index")] + [PropertyParameterOrder(6001)] + public string v_Index { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Reverse Loop")] + [PropertyIsOptional(true)] + [PropertyFirstValue("No")] + [PropertyDisplayText(false, "")] + [PropertyValidationRule("", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyParameterOrder(6003)] + public string v_ReverseLoop { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Current Loop Times (First Time Value is '1')")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Loop Current Times Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Current Times")] + [PropertyParameterOrder(6004)] + public string v_CurrentTimes { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store the Number of Loops (First Time Value is 0)")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Number of Loops", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Number of Loops")] + [PropertyParameterOrder(6005)] + public string v_NumberOfLoops { get; set; } + + public BeginLoopForListCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) + { + var loopCommand = (BeginLoopForListCommand)parentCommand.ScriptCommand; + + var rawVariable = v_List.GetRawVariable(engine); + var listToLoop = this.ExpandUserVariableAsList(engine); + int loopTimes = listToLoop.Count; + + Action listValueAction; + if (string.IsNullOrEmpty(v_Value)) + { + listValueAction = new Action(str => { }); // nothing + } + else + { + listValueAction = new Action(str => { str.StoreInUserVariable(engine, v_Value); }); + } + + Action listIndexAction; + if (string.IsNullOrEmpty(v_Index)) + { + listIndexAction = new Action(idx => { }); // nothing + } + else + { + listIndexAction = new Action(idx => { idx.StoreInUserVariable(engine, v_Index); }); + } + + Action loopTimesAction; + if (string.IsNullOrEmpty(v_CurrentTimes)) + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + }); + } + else + { + loopTimesAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + num.StoreInUserVariable(engine, v_CurrentTimes); + }); + } + + Action loopNumAction; + if (string.IsNullOrEmpty(v_NumberOfLoops)) + { + loopNumAction = new Action(num => { }); // nothing + } + else + { + loopNumAction = new Action(num => { num.StoreInUserVariable(engine, v_NumberOfLoops); }); + } + + int count = 0; // loop counter + var loopBodyProcess = new Action(index => + { + rawVariable.CurrentPosition = index; + + engine.ReportProgress($"Starting Loop Number {(count + 1)}/{loopTimes} From Line {loopCommand.LineNumber}"); + + foreach (var cmd in parentCommand.AdditionalScriptCommands) + { + if (engine.IsCancellationPending) + { + return; + } + + // store variables value + listValueAction(listToLoop[index]); + listIndexAction(index); + loopTimesAction(count + 1); + loopNumAction(count); + + engine.ExecuteCommand(cmd); + + if (engine.CurrentLoopCancelled) + { + engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopCancelled = false; + return; + } + + if (engine.CurrentLoopContinuing) + { + engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}"); + engine.CurrentLoopContinuing = false; + break; + } + } + + engine.ReportProgress($"Finished Loop From Line {loopCommand.LineNumber}"); + }); + + //DBG + //var dummyAction = new Action(cnt => { }); + + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ReverseLoop), engine)) + { + // reverse loop + for (int i = listToLoop.Count - 1; i >= 0; i--, count++) + { + loopBodyProcess(i); + } + } + else + { + // normal loop + for (int i = 0; i < listToLoop.Count; i++, count++) + { + loopBodyProcess(i); + //dummyAction(i); + //Console.WriteLine(i); + } + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Loop/BeginMultiLoopCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginMultiLoopCommand.cs index d7ea1d021..88cc9427c 100644 --- a/taskt/Core/Automation/Commands/Loop/BeginMultiLoopCommand.cs +++ b/taskt/Core/Automation/Commands/Loop/BeginMultiLoopCommand.cs @@ -10,11 +10,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Loop Commands")] + [Attributes.ClassAttributes.Group("Loop")] [Attributes.ClassAttributes.Description("This command allows you to evaluate a logical statement to determine if the statement is true. The following actions will repeat continuously until that statement becomes false")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check if a statement is 'true' or 'false' and subsequently loop actions based on either condition. Any 'BeginLoop' command must have a following 'EndLoop' command.")] [Attributes.ClassAttributes.ImplementationDescription("This command evaluates supplied arguments and if evaluated to true runs sub elements")] - public class BeginMultiLoopCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + public sealed class BeginMultiLoopCommand : ScriptCommand, IHaveDataTableElements, IHaveLoopAdditionalCommands { [XmlElement] [Attributes.PropertyAttributes.PropertyDescription("Multiple Loop Conditions - All Must Be True")] @@ -49,11 +50,9 @@ public BeginMultiLoopCommand() v_LoopConditionsTable.Columns.Add("CommandData"); } - public override void RunCommand(object sender, Core.Script.ScriptAction parentCommand) + public override void RunCommand(Engine.AutomationEngineInstance engine, Core.Script.ScriptAction parentCommand) { - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - - bool isTrueStatement = DetermineMultiStatementTruth(sender); + bool isTrueStatement = DetermineMultiStatementTruth(engine); engine.ReportProgress("Starting Loop"); @@ -80,13 +79,12 @@ public override void RunCommand(object sender, Core.Script.ScriptAction parentCo break; } } - isTrueStatement = DetermineMultiStatementTruth(sender); + isTrueStatement = DetermineMultiStatementTruth(engine); } } - private bool DetermineMultiStatementTruth(object sender) + private bool DetermineMultiStatementTruth(Engine.AutomationEngineInstance engine) { - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; bool isTrueStatement = true; foreach (DataRow rw in v_LoopConditionsTable.Rows) { @@ -105,7 +103,7 @@ private bool DetermineMultiStatementTruth(object sender) return isTrueStatement; } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -159,12 +157,12 @@ private void LoopConditionHelper_CellContentClick(object sender, DataGridViewCel var loopCommand = Newtonsoft.Json.JsonConvert.DeserializeObject(commandData); - var automationCommands = taskt.UI.CustomControls.CommandControls.GenerateCommandsandControls().Where(f => f.Command is BeginLoopCommand).ToList(); - frmCommandEditor editor = new frmCommandEditor(automationCommands, null); + var automationCommands = taskt.UI.CustomControls.CommandControls.GenerateCommandsAndControls().Where(f => f.Command is BeginLoopCommand).ToList(); + var editor = new UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor(automationCommands, null); editor.selectedCommand = loopCommand; editor.editingCommand = loopCommand; editor.originalCommand = loopCommand; - editor.creationMode = frmCommandEditor.CreationMode.Edit; + editor.creationMode = UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Edit; editor.scriptVariables = ScriptVariables; editor.appSettings = this.appSettings; @@ -192,9 +190,9 @@ private void LoopConditionHelper_CellContentClick(object sender, DataGridViewCel private void CreateLoopCondition(object sender, EventArgs e) { - var automationCommands = taskt.UI.CustomControls.CommandControls.GenerateCommandsandControls().Where(f => f.Command is BeginLoopCommand).ToList(); + var automationCommands = taskt.UI.CustomControls.CommandControls.GenerateCommandsAndControls().Where(f => f.Command is BeginLoopCommand).ToList(); - frmCommandEditor editor = new frmCommandEditor(automationCommands, null); + var editor = new UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor(automationCommands, null); editor.selectedCommand = new BeginLoopCommand(); editor.appSettings = this.appSettings; var res = editor.ShowDialog(); diff --git a/taskt/Core/Automation/Commands/Loop/BeginNumberOfTimesLoopCommand.cs b/taskt/Core/Automation/Commands/Loop/BeginNumberOfTimesLoopCommand.cs index 21ac72307..bfaaa5d57 100644 --- a/taskt/Core/Automation/Commands/Loop/BeginNumberOfTimesLoopCommand.cs +++ b/taskt/Core/Automation/Commands/Loop/BeginNumberOfTimesLoopCommand.cs @@ -1,157 +1,221 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Windows.Forms; using System.Xml.Serialization; -using taskt.Core; -using taskt.UI.CustomControls; -using taskt.UI.Forms; +using taskt.Core.Automation.Engine; +using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { - [Serializable] - [Attributes.ClassAttributes.Group("Loop Commands")] + [Attributes.ClassAttributes.Group("Loop")] + [Attributes.ClassAttributes.CommandSettings("Loop Number Of Times")] [Attributes.ClassAttributes.Description("This command allows you to repeat actions several times (loop). Any 'Begin Loop' command must have a following 'End Loop' command.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to perform a series of commands a specified amount of times.")] [Attributes.ClassAttributes.ImplementationDescription("This command recursively calls the underlying 'BeginLoop' Command to achieve automation.")] - public class BeginNumberOfTimesLoopCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_startloop))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + + public sealed class BeginNumberOfTimesLoopCommand : ScriptCommand, IHaveLoopAdditionalCommands { [XmlAttribute] - [Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [Attributes.PropertyAttributes.PropertyDescription("Enter how many times to perform the loop (ex. 5, {{{vNum}}})")] - [Attributes.PropertyAttributes.InputSpecification("Enter the amount of times you would like to perform the encased commands.")] - [Attributes.PropertyAttributes.SampleUsage("**5** or **10** or **{{{vNum}}}**")] - [Attributes.PropertyAttributes.Remarks("")] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("How Many Times to perform the Loop")] + [InputSpecification("Enter the amount of times you would like to perform the encased commands.")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage("**5**", PropertyDetailSampleUsage.ValueType.Value, "Loop Times")] + [PropertyDetailSampleUsage("**{{{vNum}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Loop Times")] + //[SampleUsage("**5** or **10** or **{{{vNum}}}**")] + [Remarks("")] + [PropertyValidationRule("Loop Times", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyDisplayText(true, "Loop", "Times")] public string v_LoopParameter { get; set; } [XmlAttribute] - [Attributes.PropertyAttributes.PropertyUIHelper(Attributes.PropertyAttributes.PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] - [Attributes.PropertyAttributes.PropertyDescription("Optional - Define Start Index (Default: 0)")] - [Attributes.PropertyAttributes.InputSpecification("Enter the starting index of the loop.")] - [Attributes.PropertyAttributes.SampleUsage("**0** or **1** or **{{{vStartValue}}}**")] - [Attributes.PropertyAttributes.Remarks("")] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + [PropertyDescription("Define Start Value")] + [InputSpecification("Enter the Starting Value of the loop.")] + //[SampleUsage("**0** or **1** or **{{{vStartValue}}}**")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage("**5**", PropertyDetailSampleUsage.ValueType.Value, "Start Value")] + [PropertyDetailSampleUsage("**{{{vStart}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Start Value")] + [PropertyIsOptional(true, "0")] + [PropertyFirstValue("0")] + [Remarks("If Start Value is **0** and Loop Times is **5**, it Loops **5** times.\nIf Start Value is **1** and Loop Times is **5**, it Loops **4** times.")] + [PropertyDisplayText(true, "Start Value")] public string v_LoopStart { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Current Loop Times (First Time Value is 'Start Value + 1')")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Loop Current Times Variable", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Current Times")] + public string v_CurrentTimes { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store the Number of Loops (First Time Value is 0)")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Number of Loops", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Number of Loops")] + public string v_NumberOfLoops { get; set; } + public BeginNumberOfTimesLoopCommand() { - this.CommandName = "BeginNumberOfTimesLoopCommand"; - this.SelectionName = "Loop Number Of Times"; - this.CommandEnabled = true; - this.CustomRendering = true; - this.v_LoopStart = "0"; + //this.CommandName = "BeginNumberOfTimesLoopCommand"; + //this.SelectionName = "Loop Number Of Times"; + //this.CommandEnabled = true; + //this.CustomRendering = true; + //this.v_LoopStart = "0"; } - public override void RunCommand(object sender, Core.Script.ScriptAction parentCommand) + public override void RunCommand(AutomationEngineInstance engine, Script.ScriptAction parentCommand) { - Core.Automation.Commands.BeginNumberOfTimesLoopCommand loopCommand = (Core.Automation.Commands.BeginNumberOfTimesLoopCommand)parentCommand.ScriptCommand; + var loopCommand = (BeginNumberOfTimesLoopCommand)parentCommand.ScriptCommand; - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; + //if (!engine.VariableList.Any(f => f.VariableName == "Loop.CurrentIndex")) + //{ + // engine.VariableList.Add(new Script.ScriptVariable() { VariableName = "Loop.CurrentIndex", VariableValue = "0" }); + //} - if (!engine.VariableList.Any(f => f.VariableName == "Loop.CurrentIndex")) - { - engine.VariableList.Add(new Script.ScriptVariable() { VariableName = "Loop.CurrentIndex", VariableValue = "0" }); - } + //Script.ScriptVariable complexVarible = null; + //int loopTimes; + //var loopParameter = loopCommand.v_LoopParameter.ExpandValueOrUserVariable(engine); + //loopTimes = int.Parse(loopParameter); - int loopTimes; - Script.ScriptVariable complexVarible = null; + var loopTimes = v_LoopParameter.ExpandValueOrUserVariableAsInteger("Loop Times", engine); - var loopParameter = loopCommand.v_LoopParameter.ConvertToUserVariable(sender); + //int startValue; + //int.TryParse(v_LoopStart.ExpandValueOrUserVariable(engine), out startValue); - loopTimes = int.Parse(loopParameter); - - - int startIndex = 0; - int.TryParse(v_LoopStart.ConvertToUserVariable(sender), out startIndex); + if (string.IsNullOrEmpty(v_LoopStart)) + { + v_LoopStart = "0"; + } + var startValue = v_LoopStart.ExpandValueOrUserVariableAsInteger("Start Value", engine); + Action numbefOfLoopsAction; + if (!string.IsNullOrEmpty(v_NumberOfLoops)) + { + numbefOfLoopsAction = new Action(num => + { + num.StoreInUserVariable(engine, v_NumberOfLoops); + }); + } + else + { + numbefOfLoopsAction = new Action(num => + { + // nothing to to ;-) + }); + } + Action loopCountAction; + if (!string.IsNullOrEmpty(v_CurrentTimes)) + { + loopCountAction = new Action(num => + { + num.StoreInUserVariable(engine, v_CurrentTimes); + SystemVariables.Update_LoopCurrentIndex(num); + }); + } + else + { + loopCountAction = new Action(num => + { + SystemVariables.Update_LoopCurrentIndex(num); + }); + } - for (int i = startIndex; i < loopTimes; i++) + int count = 0; // number of loops + for (int i = startValue; i < loopTimes; i++) { - if (complexVarible != null) - complexVarible.CurrentPosition = i; + //if (complexVarible != null) + //{ + // complexVarible.CurrentPosition = i; + //} - // (i + 1).ToString().StoreInUserVariable(engine, "Loop.CurrentIndex"); + // (i + 1).ToString().StoreInUserVariable(engine, "Loop.CurrentIndex"); - engine.ReportProgress("Starting Loop Number " + (i + 1) + "/" + loopTimes + " From Line " + loopCommand.LineNumber); + engine.ReportProgress($"Starting Loop Number {(i + 1)}/{loopTimes} From Line {loopCommand.LineNumber}"); foreach (var cmd in parentCommand.AdditionalScriptCommands) { if (engine.IsCancellationPending) + { return; + } - (i + 1).ToString().StoreInUserVariable(engine, "Loop.CurrentIndex"); + //(i + 1).ToString().StoreInUserVariable(engine, "Loop.CurrentIndex"); + //SystemVariables.Update_LoopCurrentIndex(i + 1); + numbefOfLoopsAction(count); + loopCountAction(i + 1); engine.ExecuteCommand(cmd); if (engine.CurrentLoopCancelled) { - engine.ReportProgress("Exiting Loop From Line " + loopCommand.LineNumber); + engine.ReportProgress($"Exiting Loop From Line {loopCommand.LineNumber}"); engine.CurrentLoopCancelled = false; return; } if (engine.CurrentLoopContinuing) { - engine.ReportProgress("Continuing Next Loop From Line " + loopCommand.LineNumber); + engine.ReportProgress($"Continuing Next Loop From Line {loopCommand.LineNumber}"); engine.CurrentLoopContinuing = false; break; } - - } - - - engine.ReportProgress("Finished Loop From Line " + loopCommand.LineNumber); - + engine.ReportProgress($"Finished Loop From Line {loopCommand.LineNumber}"); + count++; } } - public override List Render(frmCommandEditor editor) - { - base.Render(editor); - - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_LoopParameter", this, editor)); - RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_LoopStart", this, editor)); - - return RenderedControls; - } - public override string GetDisplayValue() - { - if (v_LoopStart != "0") - { - return "Loop From (" + v_LoopStart + "+1) to " + v_LoopParameter; - - } - else - { - return "Loop " + v_LoopParameter + " Times"; - } - - } - - public override bool IsValidate(frmCommandEditor editor) - { - base.IsValidate(editor); - - if (String.IsNullOrEmpty(this.v_LoopParameter)) - { - this.validationResult += "Times is empty.\n"; - } - else - { - int v; - if (int.TryParse(this.v_LoopParameter, out v)) - { - if (v < 0) - { - this.validationResult += "Specify a value of 0 or more for Times.\n"; - this.IsValid = false; - } - } - } - - return this.IsValid; - } + //public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // base.Render(editor); + + // RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_LoopParameter", this, editor)); + // RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_LoopStart", this, editor)); + + // return RenderedControls; + //} + + //public override string GetDisplayValue() + //{ + // if (v_LoopStart != "0") + // { + // return "Loop From (" + v_LoopStart + "+1) to " + v_LoopParameter; + + // } + // else + // { + // return "Loop " + v_LoopParameter + " Times"; + // } + //} + + //public override bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // base.IsValidate(editor); + + // if (string.IsNullOrEmpty(this.v_LoopParameter)) + // { + // this.validationResult += "Times is empty.\n"; + // } + // else + // { + // if (int.TryParse(this.v_LoopParameter, out int v)) + // { + // if (v < 0) + // { + // this.validationResult += "Specify a value of 0 or more for Times.\n"; + // this.IsValid = false; + // } + // } + // } + + // return this.IsValid; + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Loop/EndLoopCommand.cs b/taskt/Core/Automation/Commands/Loop/EndLoopCommand.cs index 79149c76b..94399314e 100644 --- a/taskt/Core/Automation/Commands/Loop/EndLoopCommand.cs +++ b/taskt/Core/Automation/Commands/Loop/EndLoopCommand.cs @@ -8,11 +8,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Loop Commands")] + [Attributes.ClassAttributes.Group("Loop")] [Attributes.ClassAttributes.Description("This command signifies the exit point of looped (repeated) actions. Required for all loops.")] [Attributes.ClassAttributes.UsesDescription("Use this command to signify the end point of a loop command.")] [Attributes.ClassAttributes.ImplementationDescription("This command is used by the serializer to signify the end point of a loop.")] - public class EndLoopCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_endloop))] + public sealed class EndLoopCommand : ScriptCommand, IEndOfStacturedCommand { public EndLoopCommand() { @@ -22,7 +23,7 @@ public EndLoopCommand() this.CommandEnabled = true; this.CustomRendering = true; } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); diff --git a/taskt/Core/Automation/Commands/Loop/ExitLoopCommand.cs b/taskt/Core/Automation/Commands/Loop/ExitLoopCommand.cs index 068c82d63..78448f058 100644 --- a/taskt/Core/Automation/Commands/Loop/ExitLoopCommand.cs +++ b/taskt/Core/Automation/Commands/Loop/ExitLoopCommand.cs @@ -7,11 +7,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Loop Commands")] + [Attributes.ClassAttributes.Group("Loop")] [Attributes.ClassAttributes.Description("This command signifies the current loop should exit and resume work past the point of the current loop.")] [Attributes.ClassAttributes.UsesDescription("Use this command to signify that looping should end and commands outside the loop should resume execution.")] [Attributes.ClassAttributes.ImplementationDescription("This command is used by the engine to exit a loop")] - public class ExitLoopCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_exitloop))] + public sealed class ExitLoopCommand : ScriptCommand { public ExitLoopCommand() { @@ -22,13 +23,12 @@ public ExitLoopCommand() this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; engine.CurrentLoopCancelled = true; } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); diff --git a/taskt/Core/Automation/Commands/Loop/IHaveLoopAdditionalCommands.cs b/taskt/Core/Automation/Commands/Loop/IHaveLoopAdditionalCommands.cs new file mode 100644 index 000000000..1ad0f0764 --- /dev/null +++ b/taskt/Core/Automation/Commands/Loop/IHaveLoopAdditionalCommands.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// this command has AdditionalCommands for Loop + /// + public interface IHaveLoopAdditionalCommands : IHaveAdditionalCommands + { + // nothing + } +} diff --git a/taskt/Core/Automation/Commands/Loop/NextLoopCommand.cs b/taskt/Core/Automation/Commands/Loop/NextLoopCommand.cs index 2d565e34f..2bb87965a 100644 --- a/taskt/Core/Automation/Commands/Loop/NextLoopCommand.cs +++ b/taskt/Core/Automation/Commands/Loop/NextLoopCommand.cs @@ -7,11 +7,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Loop Commands")] + [Attributes.ClassAttributes.Group("Loop")] [Attributes.ClassAttributes.Description("This command enables user to break and exit from the current loop")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to break from the current loop")] [Attributes.ClassAttributes.ImplementationDescription("")] - public class NextLoopCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_nextloop))] + public sealed class NextLoopCommand : ScriptCommand { public NextLoopCommand() { @@ -22,13 +23,12 @@ public NextLoopCommand() this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; engine.CurrentLoopContinuing = true; } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); diff --git a/taskt/Core/Automation/Commands/Math/AInverseTrignometricCommands.cs b/taskt/Core/Automation/Commands/Math/AInverseTrignometricCommands.cs new file mode 100644 index 000000000..d162748a4 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/AInverseTrignometricCommands.cs @@ -0,0 +1,22 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// abstract class for Inverse Trignometric Commands + /// + [Serializable] + public abstract class AInverseTrignometricCommands : ATrignometricCommands, IInverseTrignometricProperties + { + [XmlAttribute] + [PropertyParameterOrder(7000)] + public override string v_AngleType { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(MathControls), nameof(MathControls.v_WhenValueIsOutOfRange))] + [PropertyParameterOrder(8000)] + public virtual string v_WhenValueIsOutOfRange { get; set; } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/AMathValueResultCommands.cs b/taskt/Core/Automation/Commands/Math/AMathValueResultCommands.cs new file mode 100644 index 000000000..78f66c3bc --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/AMathValueResultCommands.cs @@ -0,0 +1,23 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// abstruct command class for Math commands. only Value, Result parameters + /// + [Serializable] + public abstract class AMathValueResultCommands : ScriptCommand, ILMathValueResultProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + [PropertyParameterOrder(5000)] + public virtual string v_Value { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + [PropertyParameterOrder(6000)] + public virtual string v_Result { get; set; } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/ATrignometricCommands.cs b/taskt/Core/Automation/Commands/Math/ATrignometricCommands.cs new file mode 100644 index 000000000..cf6c0cf15 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/ATrignometricCommands.cs @@ -0,0 +1,18 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// Abstract Class for Trignometric Commands + /// + [Serializable] + public abstract class ATrignometricCommands : AMathValueResultCommands, ITrignometricProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(MathControls), nameof(MathControls.v_AngleType))] + [PropertyParameterOrder(5500)] + public virtual string v_AngleType { get; set; } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/EM_InverseTrignometricPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Math/EM_InverseTrignometricPropertiesExtensionMethods.cs new file mode 100644 index 000000000..8b0c74c19 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/EM_InverseTrignometricPropertiesExtensionMethods.cs @@ -0,0 +1,34 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_InverseTrignometricPropertiesExtensionMethods + { + /// + /// Inverse Trignometic Function Action + /// + /// + /// + /// when out of range, rise a exception + /// + /// + /// + public static void InverseTrignometicFunctionAction(this IInverseTrignometricProperties command, Func actionFunc, Func rangeFunc, Engine.AutomationEngineInstance engine) + { + //var v = (double)command.ExpandValueOrUserVariableAsDecimal(nameof(command.v_Value), engine); + var v = command.ExpandValueOrVariableAsValue(engine); + + if (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_WhenValueIsOutOfRange), engine) == "error") + { + if (!rangeFunc(v)) + { + throw new Exception($"Value is Out of Range. Value: '{command.v_Value}', Expand Value: '{v}'"); + } + } + + //var r = actionFunc(v); + var r = command.ConvertAngleValueToRadian(actionFunc(v), engine); + r.StoreInUserVariable(engine, command.v_Result); + } + } +} diff --git a/taskt/Core/Automation/Commands/Math/EM_MathValueResultPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Math/EM_MathValueResultPropertiesExtensionMethods.cs new file mode 100644 index 000000000..081256260 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/EM_MathValueResultPropertiesExtensionMethods.cs @@ -0,0 +1,18 @@ +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_MathValueResultPropertiesExtensionMethods + { + /// + /// expand value or variable as Value + /// + /// + /// + /// + public static double ExpandValueOrVariableAsValue(this ILMathValueResultProperties command, AutomationEngineInstance engine) + { + return (double)((ScriptCommand)command).ExpandValueOrUserVariableAsDecimal("Value", engine); + } + } +} diff --git a/taskt/Core/Automation/Commands/Math/EM_TrignometricPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Math/EM_TrignometricPropertiesExtensionMethods.cs new file mode 100644 index 000000000..34e089137 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/EM_TrignometricPropertiesExtensionMethods.cs @@ -0,0 +1,54 @@ +using System; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_TrignometricPropertiesExtensionMethods + { + /// + /// convert angle value to radian + /// + /// + /// + /// + /// + public static double ConvertAngleValueToRadian(this ITrignometricProperties command, double value, AutomationEngineInstance engine) + { + if (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_AngleType), engine) != "degree") + { + value = value * Math.PI / 180.0; + } + return value; + } + + /// + /// expand value or variable as Angle Value + /// + /// + /// + /// + public static double ExpandValueOrVariableAsAngleValue(this ITrignometricProperties command, AutomationEngineInstance engine) + { + var v = (double)((ScriptCommand)command).ExpandValueOrUserVariableAsDecimal(nameof(command.v_Value), engine); + //if (command.ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_AngleType), engine) != "degree") + //{ + // v = v * Math.PI / 180.0; + //} + //return v; + return command.ConvertAngleValueToRadian(v, engine); + } + + /// + /// Trignometic Function Action + /// + /// + /// + /// + /// + public static void TrignometicFunctionAction(this ITrignometricProperties command, Func func, Engine.AutomationEngineInstance engine) + { + var r = func(command.ExpandValueOrVariableAsAngleValue(engine)); + r.StoreInUserVariable(engine, command.v_Result); + } + } +} diff --git a/taskt/Core/Automation/Commands/Math/GetAbsoluteCommand.cs b/taskt/Core/Automation/Commands/Math/GetAbsoluteCommand.cs new file mode 100644 index 000000000..7df84dc73 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetAbsoluteCommand.cs @@ -0,0 +1,35 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Absolute")] + [Attributes.ClassAttributes.Description("This command allows you to get abs.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get abs.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetAbsoluteCommand : AMathValueResultCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + //public string v_Value { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + //public string v_Result { get; set; } + + public GetAbsoluteCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var v = (double)this.ExpandValueOrUserVariableAsDecimal(nameof(v_Value), engine); + + Math.Abs(v).StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/GetArccosCommand.cs b/taskt/Core/Automation/Commands/Math/GetArccosCommand.cs new file mode 100644 index 000000000..999072cde --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetArccosCommand.cs @@ -0,0 +1,53 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Arccos")] + [Attributes.ClassAttributes.Description("This command allows you to get arccos.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get arccos.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetArccosCommand : AInverseTrignometricCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + //public string v_Value { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + //public string v_Result { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(MathControls), nameof(MathControls.v_AngleType))] + //public string v_AngleType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(MathControls), nameof(MathControls.v_WhenValueIsOutOfRange))] + //public string v_WhenValueIsOutOfRange { get; set; } + + public GetArccosCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //var r = MathControls.InverseTrignometicFunctionAction(this, nameof(v_Value), nameof(v_AngleType), nameof(v_WhenValueIsOutOfRange), + // Math.Acos, new Func(v => + // { + // return (v >= -1 && v <= 1); + // }), engine); + //var r = MathControls.InverseTrignometicFunctionAction(this, Math.Acos, + // new Func(v => { + // return (v >= -1 && v <= 1); + // }), engine); + //var r = MathControls.InverseTrignometicFunctionAction(this, Math.Acos, MathControls.CheckAcosAsinRange, engine); + //r.StoreInUserVariable(engine, v_Result); + + this.InverseTrignometicFunctionAction(Math.Acos, MathControls.CheckAcosAsinRange, engine); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/GetArcsinCommand.cs b/taskt/Core/Automation/Commands/Math/GetArcsinCommand.cs new file mode 100644 index 000000000..8d281ee45 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetArcsinCommand.cs @@ -0,0 +1,54 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Arcsin")] + [Attributes.ClassAttributes.Description("This command allows you to get arcsin.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get arcsin.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetArcsinCommand : AInverseTrignometricCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + //public string v_Value { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + //public string v_Result { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(MathControls), nameof(MathControls.v_AngleType))] + //public string v_AngleType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(MathControls), nameof(MathControls.v_WhenValueIsOutOfRange))] + //public string v_WhenValueIsOutOfRange { get; set; } + + public GetArcsinCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //var r = MathControls.InverseTrignometicFunctionAction(this, nameof(v_Value), nameof(v_AngleType), nameof(v_WhenValueIsOutOfRange), + // Math.Asin, new Func(v => + // { + // return (v >= -1 && v <= 1); + // }), engine); + //var r = MathControls.InverseTrignometicFunctionAction(this, Math.Asin, + // new Func(v => + // { + // return (v >= -1 && v <= 1); + // }), engine); + //var r = MathControls.InverseTrignometicFunctionAction(this, Math.Asin, MathControls.CheckAcosAsinRange, engine); + //r.StoreInUserVariable(engine, v_Result); + + this.InverseTrignometicFunctionAction(Math.Asin, MathControls.CheckAcosAsinRange, engine); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/GetArctanCommand.cs b/taskt/Core/Automation/Commands/Math/GetArctanCommand.cs new file mode 100644 index 000000000..49c7d05d1 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetArctanCommand.cs @@ -0,0 +1,57 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Arctan")] + [Attributes.ClassAttributes.Description("This command allows you to get arctan.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get arctan.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetArctanCommand : ATrignometricCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + //public string v_Value { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + //public string v_Result { get; set; } + + [XmlAttribute] + //[PropertyVirtualProperty(nameof(MathControls), nameof(MathControls.v_AngleType))] + [PropertyParameterOrder(7000)] + public override string v_AngleType { get; set; } + + public GetArctanCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //var v = (double)this.ExpandValueOrUserVariableAsDecimal(nameof(v_Value), engine); + var v = this.ExpandValueOrVariableAsAngleValue(engine); + + var r = Math.Atan(v); + //switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_AngleType), engine)) + //{ + // case "radian": + // r.StoreInUserVariable(engine, v_Result); + // break; + // case "degree": + // (r * 180.0 / Math.PI).StoreInUserVariable(engine, v_Result); + // break; + //} + //r = MathControls.ConvertAngleValueToRadian(this, r, engine); + + r = this.ConvertAngleValueToRadian(r, engine); + + r.StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/GetCosCommand.cs b/taskt/Core/Automation/Commands/Math/GetCosCommand.cs new file mode 100644 index 000000000..d2437326c --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetCosCommand.cs @@ -0,0 +1,46 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Cos")] + [Attributes.ClassAttributes.Description("This command allows you to get cos.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get cos.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetCosCommand : ATrignometricCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + //public string v_Value { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(MathControls), nameof(MathControls.v_AngleType))] + //public string v_AngleType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + //public string v_Result { get; set; } + + public GetCosCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //var value = MathControls.ConvertAngleValueToRadian(this, nameof(v_Value), nameof(v_AngleType), engine); + + //Math.Cos(value).StoreInUserVariable(engine, v_Result); + + //var r = MathControls.TrignometicFunctionAction(this, nameof(v_Value), nameof(v_AngleType), + // Math.Cos, engine); + //var r = MathControls.TrignometicFunctionAction(this, Math.Cos, engine); + //r.StoreInUserVariable(engine, v_Result); + + this.TrignometicFunctionAction(Math.Cos, engine); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/GetExponentialCommand.cs b/taskt/Core/Automation/Commands/Math/GetExponentialCommand.cs new file mode 100644 index 000000000..be5562ae2 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetExponentialCommand.cs @@ -0,0 +1,39 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Exponential")] + [Attributes.ClassAttributes.Description("This command allows you to get exp.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get exp.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetExponentialCommand : ScriptCommand + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + [PropertyDescription("Power")] + [InputSpecification("Power", true)] + [PropertyDisplayText(true, "Power")] + public string v_Power { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + public string v_Result { get; set; } + + public GetExponentialCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var v = (double)this.ExpandValueOrUserVariableAsDecimal(nameof(v_Power), engine); + Math.Exp(v).StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/GetLogarithmCommand.cs b/taskt/Core/Automation/Commands/Math/GetLogarithmCommand.cs new file mode 100644 index 000000000..d162617b6 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetLogarithmCommand.cs @@ -0,0 +1,50 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Logarithm")] + [Attributes.ClassAttributes.Description("This command allows you to get log.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get log.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetLogarithmCommand : AMathValueResultCommands + { + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + //public string v_Value { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + [PropertyDescription("Base")] + [InputSpecification("Base", true)] + [PropertyDisplayText(true, "Base")] + [PropertyValidationRule("Base", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyIsOptional(true, "10")] + [PropertyFirstValue("10")] + [PropertyParameterOrder(5500)] + public string v_Base { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + //public string v_Result { get; set; } + + public GetLogarithmCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var b = (double)this.ExpandValueOrUserVariableAsDecimal(nameof(v_Base), engine); + var v = (double)this.ExpandValueOrUserVariableAsDecimal(nameof(v_Value), engine); + + Math.Log(v, b).StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/GetPowerCommand.cs b/taskt/Core/Automation/Commands/Math/GetPowerCommand.cs new file mode 100644 index 000000000..d7825d8cf --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetPowerCommand.cs @@ -0,0 +1,48 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Power")] + [Attributes.ClassAttributes.Description("This command allows you to get power.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get power.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetPowerCommand : ScriptCommand + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + [PropertyDescription("Base")] + [InputSpecification("Base", true)] + [PropertyDisplayText(true, "Base")] + public string v_Base { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + [PropertyDescription("Power")] + [InputSpecification("Power", true)] + [PropertyDisplayText(true, "Power")] + public string v_Power { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + public string v_Result { get; set; } + + public GetPowerCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var b = (double)this.ExpandValueOrUserVariableAsDecimal(nameof(v_Base), engine); + var n = (double)this.ExpandValueOrUserVariableAsDecimal(nameof(v_Power), engine); + + Math.Pow(b, n).StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/GetSinCommand.cs b/taskt/Core/Automation/Commands/Math/GetSinCommand.cs new file mode 100644 index 000000000..55215bdea --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetSinCommand.cs @@ -0,0 +1,46 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Sin")] + [Attributes.ClassAttributes.Description("This command allows you to get sin.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get sin.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetSinCommand : ATrignometricCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + //public string v_Value { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(MathControls), nameof(MathControls.v_AngleType))] + //public string v_AngleType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + //public string v_Result { get; set; } + + public GetSinCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //var value = NumberControls.ConvertAngleValueToRadian(this, nameof(v_Value), nameof(v_AngleType), engine); + + //Math.Sin(value).StoreInUserVariable(engine, v_Result); + //var r = MathControls.TrignometicFunctionAction(this, nameof(v_Value), nameof(v_AngleType), + // Math.Sin, engine); + + //var r = MathControls.TrignometicFunctionAction(this, Math.Sin, engine); + //r.StoreInUserVariable(engine, v_Result); + + this.TrignometicFunctionAction(Math.Sin, engine); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/GetSquareRootCommand.cs b/taskt/Core/Automation/Commands/Math/GetSquareRootCommand.cs new file mode 100644 index 000000000..f213c86c3 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetSquareRootCommand.cs @@ -0,0 +1,35 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Square Root")] + [Attributes.ClassAttributes.Description("This command allows you to get Square Root.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Square Root.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetSquareRootCommand : AMathValueResultCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + //public string v_Value { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + //public string v_Result { get; set; } + + public GetSquareRootCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var v = (double)this.ExpandValueOrUserVariableAsDecimal(nameof(v_Value), engine); + + Math.Sqrt(v).StoreInUserVariable(engine, v_Result); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/GetTanCommand.cs b/taskt/Core/Automation/Commands/Math/GetTanCommand.cs new file mode 100644 index 000000000..a94ea7d06 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/GetTanCommand.cs @@ -0,0 +1,46 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Math")] + [Attributes.ClassAttributes.CommandSettings("Get Tan")] + [Attributes.ClassAttributes.Description("This command allows you to get tan.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get tan.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + public sealed class GetTanCommand : ATrignometricCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] + //public string v_Value { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(MathControls), nameof(MathControls.v_AngleType))] + //public string v_AngleType { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] + //public string v_Result { get; set; } + + public GetTanCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + //var value = NumberControls.ConvertAngleValueToRadian(this, nameof(v_Value), nameof(v_AngleType), engine); + + //Math.Tan(value).StoreInUserVariable(engine, v_Result); + //var r = MathControls.TrignometicFunctionAction(this, nameof(v_Value), nameof(v_AngleType), + // Math.Tan, engine); + + //var r = MathControls.TrignometicFunctionAction(this, Math.Tan, engine); + //r.StoreInUserVariable(engine, v_Result); + + this.TrignometicFunctionAction(Math.Tan, engine); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Math/IInverseTrignometricProperties.cs b/taskt/Core/Automation/Commands/Math/IInverseTrignometricProperties.cs new file mode 100644 index 000000000..1518178c2 --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/IInverseTrignometricProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + public interface IInverseTrignometricProperties : ITrignometricProperties + { + /// + /// behavior when value is out of range + /// + string v_WhenValueIsOutOfRange { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Math/ILMathValueResultProperties.cs b/taskt/Core/Automation/Commands/Math/ILMathValueResultProperties.cs new file mode 100644 index 000000000..f4fa2a43a --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/ILMathValueResultProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Math commands value-result + /// + public interface ILMathValueResultProperties : ILExpandableProperties + { + /// + /// value + /// + string v_Value { get; set; } + + /// + /// variable name to store result + /// + string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Math/ITrignometricProperties.cs b/taskt/Core/Automation/Commands/Math/ITrignometricProperties.cs new file mode 100644 index 000000000..72820e35a --- /dev/null +++ b/taskt/Core/Automation/Commands/Math/ITrignometricProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + public interface ITrignometricProperties : ILMathValueResultProperties + { + /// + /// agnle type Radian or Degree + /// + string v_AngleType { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/MathControls.cs b/taskt/Core/Automation/Commands/MathControls.cs new file mode 100644 index 000000000..8c153c117 --- /dev/null +++ b/taskt/Core/Automation/Commands/MathControls.cs @@ -0,0 +1,106 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + internal static class MathControls + { + /// + /// angle type + /// + [PropertyDescription("Angle Value Type")] + [InputSpecification("Angle Value Type", true)] + [Remarks("")] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyUISelectionOption("Radian")] + [PropertyUISelectionOption("Degree")] + [PropertyDisplayText(true, "Angle Value Type")] + [PropertyIsOptional(true, "Radian")] + [PropertyParameterOrder(5000)] + public static string v_AngleType { get; } + + /// + /// when value is out of range + /// + [XmlAttribute] + [PropertyDescription("When Value is Out of Range")] + [InputSpecification("When Value is Out of Range", true)] + [Remarks("")] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyUISelectionOption("Ignore")] + [PropertyUISelectionOption("Error")] + [PropertyDisplayText(false, "")] + [PropertyIsOptional(true, "Ignore")] + [PropertyParameterOrder(5000)] + public static string v_WhenValueIsOutOfRange { get; } + + ///// + ///// convert angle value to radian value + ///// + ///// + ///// + ///// + ///// + //public static double ConvertAngleValueToRadian(ITrignometricProperties command, double value, Engine.AutomationEngineInstance engine) + //{ + // if (((ScriptCommand)command).ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_AngleType), engine) == "degree") + // { + // value = value * Math.PI / 180.0; + // } + // return value; + //} + + ///// + ///// Trignometic Function Action + ///// + ///// + ///// + ///// + ///// + //public static double TrignometicFunctionAction(ATrignometricCommand command, Func func, Engine.AutomationEngineInstance engine) + //{ + // var v = (double)command.ExpandValueOrUserVariableAsDecimal(nameof(command.v_Value), engine); + + // v = ConvertAngleValueToRadian(command, v, engine); + + // return func(v); + //} + + ///// + ///// Inverse Trignometic Function Action + ///// + ///// + ///// + ///// when out of range, rise a exception + ///// + ///// + ///// + //public static double InverseTrignometicFunctionAction(AInverseTrignometricCommand command, Func actionFunc, Func rangeFunc, Engine.AutomationEngineInstance engine) + //{ + // var v = (double)command.ExpandValueOrUserVariableAsDecimal(nameof(command.v_Value), engine); + + // if (command.ExpandValueOrUserVariableAsSelectionItem(nameof(command.v_WhenValueIsOutOfRange), engine) == "error") + // { + // if (!rangeFunc(v)) + // { + // throw new Exception("Value is Out of Range"); + // } + // } + + // var r = actionFunc(v); + // r = ConvertAngleValueToRadian(command, r, engine); + // return r; + //} + + /// + /// Acos, Asin range check + /// + /// + /// + public static bool CheckAcosAsinRange(double v) + { + return (v >= -1 && v <= 1); + } + } +} diff --git a/taskt/Core/Automation/Commands/Misc/ClearClipboardTextCommand.cs b/taskt/Core/Automation/Commands/Misc/ClearClipboardTextCommand.cs index 3fb1f3049..62ddd2418 100644 --- a/taskt/Core/Automation/Commands/Misc/ClearClipboardTextCommand.cs +++ b/taskt/Core/Automation/Commands/Misc/ClearClipboardTextCommand.cs @@ -3,15 +3,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Misc Commands")] + [Attributes.ClassAttributes.Group("Misc")] [Attributes.ClassAttributes.SubGruop("Clipboard")] [Attributes.ClassAttributes.CommandSettings("Clear Clipboard Text")] [Attributes.ClassAttributes.Description("This command allows you to clear text to the clipboard.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to copy the data from the clipboard and apply it to a variable. You can then use the variable to extract the value.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against the VariableList from the scripting engine using System.Windows.Forms.Clipboard.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true, true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ClearClipboardTextCommand : ScriptCommand + public sealed class ClearClipboardTextCommand : ScriptCommand { public ClearClipboardTextCommand() { @@ -21,7 +22,7 @@ public ClearClipboardTextCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //User32Functions.SetClipboardText(""); ClipboardControls.SetClipboardText(""); diff --git a/taskt/Core/Automation/Commands/Misc/CreateShortcutCommand.cs b/taskt/Core/Automation/Commands/Misc/CreateShortcutCommand.cs index ef40086e3..965fc15c4 100644 --- a/taskt/Core/Automation/Commands/Misc/CreateShortcutCommand.cs +++ b/taskt/Core/Automation/Commands/Misc/CreateShortcutCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Misc Commands")] + [Attributes.ClassAttributes.Group("Misc")] [Attributes.ClassAttributes.SubGruop("Other")] [Attributes.ClassAttributes.CommandSettings("Create Shortcut")] [Attributes.ClassAttributes.Description("This command allow to create shortcut file")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create shortcut file")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateShortcutCommand : ScriptCommand + public sealed class CreateShortcutCommand : ScriptCommand { [XmlElement] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -61,11 +62,9 @@ public CreateShortcutCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - string targetPath = v_TargetPath.ConvertToUserVariable(engine); + string targetPath = v_TargetPath.ExpandValueOrUserVariable(engine); //bool isURL = (targetPath.StartsWith("http:") || (targetPath.StartsWith("https:"))); if (!FilePathControls.IsURL(targetPath)) @@ -78,9 +77,9 @@ public override void RunCommand(object sender) //{ // savePath = FilePathControls.FormatFilePath_NoFileCounter(v_SavePath, engine, "lnk"); //} - var savePath = v_SavePath.ConvertToUserVariableAsFilePath(new PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtension, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "lnk"), engine); + var savePath = v_SavePath.ExpandValueOrUserVariableAsFilePath(new PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtension, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "lnk"), engine); - string description = v_Description.ConvertToUserVariable(engine); + string description = v_Description.ExpandValueOrUserVariable(engine); // WshShell Type t = Type.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8")); @@ -104,7 +103,7 @@ public override void RunCommand(object sender) //{ // savePath = FilePathControls.FormatFilePath_NoFileCounter(v_SavePath, engine, "url"); //} - var savePath = v_SavePath.ConvertToUserVariableAsFilePath(new PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtension, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "url"), engine); + var savePath = v_SavePath.ExpandValueOrUserVariableAsFilePath(new PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtension, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "url"), engine); string outputText = "[InternetShortcut]\nURL=" + targetPath; WriteTextFileCommand writeText = new WriteTextFileCommand diff --git a/taskt/Core/Automation/Commands/Misc/GetClipboardTextCommand.cs b/taskt/Core/Automation/Commands/Misc/GetClipboardTextCommand.cs index e8a7e63a2..a945a2ac1 100644 --- a/taskt/Core/Automation/Commands/Misc/GetClipboardTextCommand.cs +++ b/taskt/Core/Automation/Commands/Misc/GetClipboardTextCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Misc Commands")] + [Attributes.ClassAttributes.Group("Misc")] [Attributes.ClassAttributes.SubGruop("Clipboard")] [Attributes.ClassAttributes.CommandSettings("Get Clipboard Text")] [Attributes.ClassAttributes.Description("This command allows you to get text from the clipboard.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to copy the data from the clipboard and apply it to a variable. You can then use the variable to extract the value.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against the VariableList from the scripting engine using System.Windows.Forms.Clipboard.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetClipboardTextCommand : ScriptCommand + public sealed class GetClipboardTextCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] @@ -28,10 +29,10 @@ public GetClipboardTextCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //User32Functions.GetClipboardText().StoreInUserVariable(sender, v_userVariableName); - ClipboardControls.GetClipboardText().StoreInUserVariable(sender, v_userVariableName); + ClipboardControls.GetClipboardText().StoreInUserVariable(engine, v_userVariableName); } } } diff --git a/taskt/Core/Automation/Commands/Misc/PingCommand.cs b/taskt/Core/Automation/Commands/Misc/PingCommand.cs index 77103793a..47bc46217 100644 --- a/taskt/Core/Automation/Commands/Misc/PingCommand.cs +++ b/taskt/Core/Automation/Commands/Misc/PingCommand.cs @@ -7,15 +7,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Misc Commands")] + [Attributes.ClassAttributes.Group("Misc")] [Attributes.ClassAttributes.SubGruop("Network/Internet")] [Attributes.ClassAttributes.CommandSettings("Ping")] [Attributes.ClassAttributes.Description("This command allows you to add an in-line comment to the script.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add code comments or document code. Usage of variables (ex. [vVar]) within the comment block will be parsed and displayed when running the script.")] [Attributes.ClassAttributes.ImplementationDescription("This command is for visual purposes only")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class PingCommand : ScriptCommand + public sealed class PingCommand : ScriptCommand { [XmlAttribute] @@ -44,12 +45,10 @@ public PingCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - Ping ping = new Ping(); - string hstname = v_HostName.ConvertToUserVariable(engine); + string hstname = v_HostName.ExpandValueOrUserVariable(engine); PingReply pingresult = ping.Send(hstname); var pingReply = ConvertObjectToJson(pingresult); diff --git a/taskt/Core/Automation/Commands/Misc/PlaySystemSoundCommand.cs b/taskt/Core/Automation/Commands/Misc/PlaySystemSoundCommand.cs index 19fa0af8e..ec1d67795 100644 --- a/taskt/Core/Automation/Commands/Misc/PlaySystemSoundCommand.cs +++ b/taskt/Core/Automation/Commands/Misc/PlaySystemSoundCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Misc Commands")] + [Attributes.ClassAttributes.Group("Misc")] [Attributes.ClassAttributes.SubGruop("Other")] [Attributes.ClassAttributes.CommandSettings("Play System Sound")] [Attributes.ClassAttributes.Description("This command allows you to Play System Sound.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Play System Sound.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class PlaySystemSoundCommand : ScriptCommand + public sealed class PlaySystemSoundCommand : ScriptCommand { [XmlAttribute] [PropertyDescription("Please select Sound to Play")] @@ -39,10 +40,10 @@ public PlaySystemSoundCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (taskt.Core.Automation.Engine.AutomationEngineInstance)sender; - string sound = v_SoundType.GetUISelectionValue("v_SoundType", this, engine); + //string sound = v_SoundType.ExpandValueOrUserVariableAsSelectionItem("v_SoundType", this, engine); + var sound = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_SoundType), engine); switch (sound) { case "asterisk": diff --git a/taskt/Core/Automation/Commands/Misc/SMTPSendEmailCommand.cs b/taskt/Core/Automation/Commands/Misc/SMTPSendEmailCommand.cs index ec3ee819e..72ee00c03 100644 --- a/taskt/Core/Automation/Commands/Misc/SMTPSendEmailCommand.cs +++ b/taskt/Core/Automation/Commands/Misc/SMTPSendEmailCommand.cs @@ -13,12 +13,13 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Misc Commands")] + [Attributes.ClassAttributes.Group("Misc")] [Attributes.ClassAttributes.SubGruop("Network/Internet")] [Attributes.ClassAttributes.Description("This command allows you to send email using SMTP protocol.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to send an email and have access to SMTP server credentials to generate an email.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements the System.Net Namespace to achieve automation")] - public class SMTPSendEmailCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_smtp))] + public sealed class SMTPSendEmailCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Host Name (ex. mail.example.com, {{{vHost}}})")] @@ -113,10 +114,10 @@ public SMTPSendEmailCommand() this.v_EnableSSL = "Yes"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //bypass ssl validation if requested - if (v_SSLValidation.ConvertToUserVariable(sender) == "Bypass SSL Validation") + if (v_SSLValidation.ExpandValueOrUserVariable(engine) == "Bypass SSL Validation") { ServicePointManager.ServerCertificateValidationCallback = (sndr, certificate, chain, sslPolicyErrors) => true; @@ -124,18 +125,18 @@ public override void RunCommand(object sender) try { - string varSMTPHost = v_SMTPHost.ConvertToUserVariable(sender); - string varSMTPPort = v_SMTPPort.ConvertToUserVariable(sender); - string varSMTPUserName = v_SMTPUserName.ConvertToUserVariable(sender); - string varSMTPPassword = v_SMTPPassword.ConvertToUserVariable(sender); + string varSMTPHost = v_SMTPHost.ExpandValueOrUserVariable(engine); + string varSMTPPort = v_SMTPPort.ExpandValueOrUserVariable(engine); + string varSMTPUserName = v_SMTPUserName.ExpandValueOrUserVariable(engine); + string varSMTPPassword = v_SMTPPassword.ExpandValueOrUserVariable(engine); - string varSMTPFromEmail = v_SMTPFromEmail.ConvertToUserVariable(sender); - string varSMTPToEmail = v_SMTPToEmail.ConvertToUserVariable(sender); - string varSMTPSubject = v_SMTPSubject.ConvertToUserVariable(sender); - string varSMTPBody = v_SMTPBody.ConvertToUserVariable(sender); - string varSMTPFilePath = v_SMTPAttachment.ConvertToUserVariable(sender); + string varSMTPFromEmail = v_SMTPFromEmail.ExpandValueOrUserVariable(engine); + string varSMTPToEmail = v_SMTPToEmail.ExpandValueOrUserVariable(engine); + string varSMTPSubject = v_SMTPSubject.ExpandValueOrUserVariable(engine); + string varSMTPBody = v_SMTPBody.ExpandValueOrUserVariable(engine); + string varSMTPFilePath = v_SMTPAttachment.ExpandValueOrUserVariable(engine); - string varEnableSSL = v_EnableSSL.ConvertToUserVariable(sender).ToUpperInvariant(); + string varEnableSSL = v_EnableSSL.ExpandValueOrUserVariable(engine).ToUpperInvariant(); bool sslPreference = true; if (varEnableSSL == "NO") @@ -168,14 +169,14 @@ public override void RunCommand(object sender) finally { //restore default validation - if (v_SSLValidation.ConvertToUserVariable(sender) == "Bypass SSL Validation") + if (v_SSLValidation.ExpandValueOrUserVariable(engine) == "Bypass SSL Validation") { ServicePointManager.ServerCertificateValidationCallback = null; } } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); @@ -200,7 +201,7 @@ public override string GetDisplayValue() return base.GetDisplayValue() + " [To Address: '" + v_SMTPToEmail + "']"; } - public override bool IsValidate(frmCommandEditor editor) + public override bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.IsValidate(editor); diff --git a/taskt/Core/Automation/Commands/Misc/SetClipboardTextCommand.cs b/taskt/Core/Automation/Commands/Misc/SetClipboardTextCommand.cs index 016410397..175e97069 100644 --- a/taskt/Core/Automation/Commands/Misc/SetClipboardTextCommand.cs +++ b/taskt/Core/Automation/Commands/Misc/SetClipboardTextCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Misc Commands")] + [Attributes.ClassAttributes.Group("Misc")] [Attributes.ClassAttributes.SubGruop("Clipboard")] [Attributes.ClassAttributes.CommandSettings("Set Clipboard Text")] [Attributes.ClassAttributes.Description("This command allows you to set text to the clipboard.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to copy the data from the clipboard and apply it to a variable. You can then use the variable to extract the value.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against the VariableList from the scripting engine using System.Windows.Forms.Clipboard.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetClipboardTextCommand : ScriptCommand + public sealed class SetClipboardTextCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_MultiLinesTextBox))] @@ -31,10 +32,9 @@ public SetClipboardTextCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var input = v_InputValue.ConvertToUserVariable(engine); + var input = v_InputValue.ExpandValueOrUserVariable(engine); //User32Functions.SetClipboardText(input); ClipboardControls.SetClipboardText(input); } diff --git a/taskt/Core/Automation/Commands/NLG/NLGCreateNLGInstanceCommand.cs b/taskt/Core/Automation/Commands/NLG/NLGCreateNLGInstanceCommand.cs index 324c8c23e..a1818fbca 100644 --- a/taskt/Core/Automation/Commands/NLG/NLGCreateNLGInstanceCommand.cs +++ b/taskt/Core/Automation/Commands/NLG/NLGCreateNLGInstanceCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("NLG Commands")] + [Attributes.ClassAttributes.Group("NLG")] [Attributes.ClassAttributes.CommandSettings("Create NLG Instance")] [Attributes.ClassAttributes.Description("This command pauses the script for a set amount of time specified in milliseconds.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to pause your script for a specific amount of time. After the specified time is finished, the script will resume execution.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Thread.Sleep' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_nlg))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class NLGCreateNLGInstanceCommand : ScriptCommand + public sealed class NLGCreateNLGInstanceCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(NLGControls), nameof(NLGControls.v_InstanceName))] @@ -30,15 +31,13 @@ public NLGCreateNLGInstanceCommand() //this.v_InstanceName = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - Lexicon lexicon = Lexicon.getDefaultLexicon(); NLGFactory nlgFactory = new NLGFactory(lexicon); SPhraseSpec p = nlgFactory.createClause(); - var vInstance = v_InstanceName.ConvertToUserVariable(sender); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); engine.AddAppInstance(vInstance, p); } diff --git a/taskt/Core/Automation/Commands/NLG/NLGGenerateNLGPhraseCommand.cs b/taskt/Core/Automation/Commands/NLG/NLGGenerateNLGPhraseCommand.cs index 1d61d1aed..8513331f5 100644 --- a/taskt/Core/Automation/Commands/NLG/NLGGenerateNLGPhraseCommand.cs +++ b/taskt/Core/Automation/Commands/NLG/NLGGenerateNLGPhraseCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("NLG Commands")] + [Attributes.ClassAttributes.Group("NLG")] [Attributes.ClassAttributes.CommandSettings("Generate NLG Phrase")] [Attributes.ClassAttributes.Description("This command pauses the script for a set amount of time specified in milliseconds.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to pause your script for a specific amount of time. After the specified time is finished, the script will resume execution.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Thread.Sleep' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_nlg))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class NLGGenerateNLGPhraseCommand : ScriptCommand + public sealed class NLGGenerateNLGPhraseCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(NLGControls), nameof(NLGControls.v_InstanceName))] @@ -32,17 +33,16 @@ public NLGGenerateNLGPhraseCommand() //this.v_InstanceName = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var vInstance = v_InstanceName.ConvertToUserVariable(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); var p = (SPhraseSpec)engine.GetAppInstance(vInstance); Lexicon lexicon = Lexicon.getDefaultLexicon(); Realiser realiser = new Realiser(lexicon); String phraseOutput = realiser.realiseSentence(p); - phraseOutput.StoreInUserVariable(sender, v_applyToVariableName); + phraseOutput.StoreInUserVariable(engine, v_applyToVariableName); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/NLG/NLGSetNLGParameterCommand.cs b/taskt/Core/Automation/Commands/NLG/NLGSetNLGParameterCommand.cs index 23199be19..0a32d1242 100644 --- a/taskt/Core/Automation/Commands/NLG/NLGSetNLGParameterCommand.cs +++ b/taskt/Core/Automation/Commands/NLG/NLGSetNLGParameterCommand.cs @@ -6,13 +6,14 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("NLG Commands")] + [Attributes.ClassAttributes.Group("NLG")] [Attributes.ClassAttributes.CommandSettings("Set NLG Parameter")] [Attributes.ClassAttributes.Description("This command allows you to define a NLG parameter")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to define NLG parameters")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_nlg))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class NLGSetNLGParameterCommand : ScriptCommand + public sealed class NLGSetNLGParameterCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(NLGControls), nameof(NLGControls.v_InstanceName))] @@ -49,15 +50,14 @@ public NLGSetNLGParameterCommand() //this.v_InstanceName = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var vInstance = v_InstanceName.ConvertToUserVariable(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); var p = (SPhraseSpec)engine.GetAppInstance(vInstance); - var userInput = v_Parameter.ConvertToUserVariable(sender); + var userInput = v_Parameter.ExpandValueOrUserVariable(engine); - switch (this.GetUISelectionValue(nameof(v_ParameterType), engine)) + switch (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ParameterType), engine)) { case "set subject": p.setSubject(userInput); diff --git a/taskt/Core/Automation/Commands/NLGControls.cs b/taskt/Core/Automation/Commands/NLGControls.cs index 91c8a19fa..ee05dd451 100644 --- a/taskt/Core/Automation/Commands/NLGControls.cs +++ b/taskt/Core/Automation/Commands/NLGControls.cs @@ -17,6 +17,7 @@ internal static class NLGControls [PropertyValidationRule("NLG Instance", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Instance")] [PropertyFirstValue("%kwd_default_nlg_instance%")] + [PropertyParameterOrder(5000)] public static string v_InstanceName { get; } } } diff --git a/taskt/Core/Automation/Commands/NumberControls.cs b/taskt/Core/Automation/Commands/NumberControls.cs index 7d73a45dc..a2ffebec2 100644 --- a/taskt/Core/Automation/Commands/NumberControls.cs +++ b/taskt/Core/Automation/Commands/NumberControls.cs @@ -10,6 +10,7 @@ namespace taskt.Core.Automation.Commands /// internal static class NumberControls { + #region Virtual Property /// /// for both numerical variable name /// @@ -24,8 +25,43 @@ internal static class NumberControls [PropertyIsVariablesList(true)] [PropertyValidationRule("Numerical Variable", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Numerical Name")] + [PropertyParameterOrder(5000)] public static string v_BothNumericalVariableName { get; } + /// + /// for both numerical variable name + /// + [PropertyDescription("Numerical Variable Name")] + [InputSpecification("")] + [Remarks("")] + [PropertyDetailSampleUsage("**vNum**", PropertyDetailSampleUsage.ValueType.VariableName)] + [PropertyDetailSampleUsage("**{{{vNum}}}**", PropertyDetailSampleUsage.ValueType.VariableName)] + [PropertyShowSampleUsageInDescription(true)] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] + [PropertyIsVariablesList(true)] + [PropertyValidationRule("Numerical Variable", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyDisplayText(true, "Numerical Name")] + [PropertyParameterOrder(5000)] + public static string v_InputNumericalVariableName { get; } + + /// + /// for output numerical variable name + /// + [PropertyDescription("Numerical Variable Name to Store Result")] + [InputSpecification("")] + [Remarks("")] + [PropertyDetailSampleUsage("**vNum**", PropertyDetailSampleUsage.ValueType.VariableName)] + [PropertyDetailSampleUsage("**{{{vNum}}}**", PropertyDetailSampleUsage.ValueType.VariableName)] + [PropertyShowSampleUsageInDescription(true)] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] + [PropertyIsVariablesList(true)] + [PropertyValidationRule("Result", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyDisplayText(true, "Result")] + [PropertyParameterOrder(5000)] + public static string v_OutputNumericalVariableName { get; } + /// /// for numerical value /// @@ -39,24 +75,82 @@ internal static class NumberControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("Value", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(5000)] public static string v_Value { get; } + #endregion + + ///// + ///// expand value or variable as Integer + ///// + ///// + ///// + ///// + ///// + //public static int ExpandValueOrVariableAsInteger(string value, Engine.AutomationEngineInstance engine) + //{ + // if (int.TryParse(value.ExpandValueOrUserVariable(engine), out int r)) + // { + // return r; + // } + // else + // { + // throw new Exception($"'{value}' is not Integer (Numerical) value."); + // } + //} + + ///// + ///// expand value or variable as Double + ///// + ///// + ///// + ///// + ///// + //public static decimal ExpandValueOrVariableAsDecimal(string value, Engine.AutomationEngineInstance engine) + //{ + // if (decimal.TryParse(value.ExpandValueOrUserVariable(engine), out decimal r)) + // { + // return r; + // } + // else + // { + // throw new Exception($"'{value}' is not Decimal (Numerical) value."); + // } + //} + ///// + ///// expand value or variable as Decimal + ///// + ///// + ///// + ///// + ///// + //public static double ExpandValueOrVariableAsDouble(string value, Engine.AutomationEngineInstance engine) + //{ + // if (double.TryParse(value.ExpandValueOrUserVariable(engine), out double r)) + // { + // return r; + // } + // else + // { + // throw new Exception($"'{value}' is not Double (Numerical) value."); + // } + //} /// - /// Convert property value to integer from property name. This method supports validate, first value. This method may use PropertyValidationRule, PropertyDisplayText, PropertyDescription attributes. + /// expand value or user variable as Integer specified by parameterName. This method supports validate, first value. This method may use PropertyValidationRule, PropertyDisplayText, PropertyDescription attributes. /// /// /// /// /// /// - public static int ConvertToUserVariableAsInteger(this ScriptCommand command, string propertyName, Engine.AutomationEngineInstance engine) + public static int ExpandValueOrUserVariableAsInteger(this ScriptCommand command, string propertyName, Engine.AutomationEngineInstance engine) { - return ConvertToUserVariableAsInteger(command, propertyName, "", engine); + return ExpandValueOrUserVariableAsInteger(command, propertyName, "", engine); } /// - /// Convert property value to integer from property name. This method supports validate, first value. + /// expand value or user variable as integer specified by parameter name. This method supports validate, first value. /// /// /// @@ -64,9 +158,9 @@ public static int ConvertToUserVariableAsInteger(this ScriptCommand command, str /// /// /// - public static int ConvertToUserVariableAsInteger(this ScriptCommand command, string propertyName, string propertyDescription, Engine.AutomationEngineInstance engine) + public static int ExpandValueOrUserVariableAsInteger(this ScriptCommand command, string propertyName, string propertyDescription, Engine.AutomationEngineInstance engine) { - decimal decValue = command.ConvertToUserVariableAsDecimal(propertyName, propertyDescription, engine); + decimal decValue = command.ExpandValueOrUserVariableAsDecimal(propertyName, propertyDescription, engine); try { int value = (int)decValue; @@ -79,20 +173,20 @@ public static int ConvertToUserVariableAsInteger(this ScriptCommand command, str } /// - /// Convert property value to decimal from property name. This method supports validate, first value. This method may use PropertyValidationRule, PropertyDisplayText, PropertyDescription attributes. + /// expand value or user variable as Decimal specified by parameter name. This method supports validate, first value. This method may use PropertyValidationRule, PropertyDisplayText, PropertyDescription attributes. /// /// /// /// /// /// - public static decimal ConvertToUserVariableAsDecimal(this ScriptCommand command, string propertyName, Engine.AutomationEngineInstance engine) + public static decimal ExpandValueOrUserVariableAsDecimal(this ScriptCommand command, string propertyName, Engine.AutomationEngineInstance engine) { - return ConvertToUserVariableAsDecimal(command, propertyName, "", engine); + return ExpandValueOrUserVariableAsDecimal(command, propertyName, "", engine); } /// - /// convert property value to decimal from property name. This method supports validate, first value. + /// expand value or user variable as Decimal specified by parameter name. This method supports validate, first value. /// /// /// @@ -100,24 +194,24 @@ public static decimal ConvertToUserVariableAsDecimal(this ScriptCommand command, /// /// /// - public static decimal ConvertToUserVariableAsDecimal(this ScriptCommand command, string propertyName, string propertyDescription, Engine.AutomationEngineInstance engine) + public static decimal ExpandValueOrUserVariableAsDecimal(this ScriptCommand command, string propertyName, string propertyDescription, Engine.AutomationEngineInstance engine) { var propInfo = command.GetProperty(propertyName); string valueStr = propInfo.GetValue(command)?.ToString() ?? ""; - return new PropertyConvertTag(valueStr, propertyName, propertyDescription).ConvertToUserVariableAsDecimal(propInfo, engine); + return new PropertyConvertTag(valueStr, propertyName, propertyDescription).ExpandValueOrUserVariableAsDecimal(propInfo, engine); } /// - /// convert specified value to int from PropertyConvertTag that specified value, description. + /// expand value or user variable as specified by PropertyConvertTag that specified value, description. /// /// /// /// /// - public static int ConvertToUserVariableAsInteger(this PropertyConvertTag prop, Engine.AutomationEngineInstance engine) + public static int ExpandValueOrUserVariableAsInteger(this PropertyConvertTag prop, Engine.AutomationEngineInstance engine) { - string convertedText = prop.Value.ConvertToUserVariable(engine); + string convertedText = prop.Value.ExpandValueOrUserVariable(engine); if (int.TryParse(convertedText, out int v)) { return v; @@ -129,27 +223,27 @@ public static int ConvertToUserVariableAsInteger(this PropertyConvertTag prop, E } /// - /// convert specified value to integer. + /// expand value or user variable as integer /// /// /// /// /// - public static int ConvertToUserVariableAsInteger(this string propertyValue, string propertyDescription, Engine.AutomationEngineInstance engine) + public static int ExpandValueOrUserVariableAsInteger(this string propertyValue, string propertyDescription, Engine.AutomationEngineInstance engine) { - return new PropertyConvertTag(propertyValue, propertyDescription).ConvertToUserVariableAsInteger(engine); + return new PropertyConvertTag(propertyValue, propertyDescription).ExpandValueOrUserVariableAsInteger(engine); } /// - /// convert specified value to decimal from PropertyConvertTag that specified value, description. + /// expand value or user variable as decimal specified by PropertyConvertTag that specified value, description. /// /// /// /// /// - public static decimal ConvertToUserVariableAsDecimal(this PropertyConvertTag prop, Engine.AutomationEngineInstance engine) + public static decimal ExpandValueOrUserVariableAsDecimal(this PropertyConvertTag prop, Engine.AutomationEngineInstance engine) { - string convertedText = prop.Value.ConvertToUserVariable(engine); + string convertedText = prop.Value.ExpandValueOrUserVariable(engine); if (decimal.TryParse(convertedText, out decimal v)) { return v; @@ -161,14 +255,14 @@ public static decimal ConvertToUserVariableAsDecimal(this PropertyConvertTag pro } /// - /// convert property value to decimal from PropertyConvertTag that specified property name, etc. This method supports validate, first value. This method may use PropertyValidationRule, PropertyDisplayText, PropertyDescription attributes. + /// expand value or user variable as Decimal specified by PropertyConvertTag that specified property name, etc. This method supports validate, first value. This method may use PropertyValidationRule, PropertyDisplayText, PropertyDescription attributes. /// /// /// /// /// /// - public static decimal ConvertToUserVariableAsDecimal(this PropertyConvertTag prop, PropertyInfo propInfo, Engine.AutomationEngineInstance engine) + public static decimal ExpandValueOrUserVariableAsDecimal(this PropertyConvertTag prop, PropertyInfo propInfo, Engine.AutomationEngineInstance engine) { var virtualPropInfo = propInfo.GetVirtualProperty(); @@ -203,7 +297,7 @@ public static decimal ConvertToUserVariableAsDecimal(this PropertyConvertTag pro } } - decimal v = prop.ConvertToUserVariableAsDecimal(engine); + decimal v = prop.ExpandValueOrUserVariableAsDecimal(engine); var validateAttr = GetCustomAttributeWithVirtual(propInfo, virtualPropInfo); var rangeAttr = GetCustomAttributeWithVirtual(propInfo, virtualPropInfo); @@ -293,5 +387,20 @@ private static bool CheckValidate(decimal value, PropertyValidationRule validate } return true; } + + public static void StoreInUserVariable(this int value, Engine.AutomationEngineInstance engine, string targetVariable) + { + ExtensionMethods.StoreInUserVariable(targetVariable, value.ToString(), engine, false); + } + + public static void StoreInUserVariable(this double value, Engine.AutomationEngineInstance engine, string targetVariable) + { + ExtensionMethods.StoreInUserVariable(targetVariable, value.ToString(), engine, false); + } + + public static void StoreInUserVariable(this decimal value, Engine.AutomationEngineInstance engine, string targetVariable) + { + ExtensionMethods.StoreInUserVariable(targetVariable, value.ToString(), engine, false); + } } } diff --git a/taskt/Core/Automation/Commands/Numerical/CreateNumericalVariableCommand.cs b/taskt/Core/Automation/Commands/Numerical/CreateNumericalVariableCommand.cs index e2ab65d07..62c79f2f2 100644 --- a/taskt/Core/Automation/Commands/Numerical/CreateNumericalVariableCommand.cs +++ b/taskt/Core/Automation/Commands/Numerical/CreateNumericalVariableCommand.cs @@ -5,18 +5,18 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Numerical Commands")] + [Attributes.ClassAttributes.Group("Numerical")] [Attributes.ClassAttributes.CommandSettings("Create Numerical Variable")] [Attributes.ClassAttributes.Description("This command allows you to create Number Variable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create Number Variable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] [Attributes.ClassAttributes.EnableAutomateRender(true)] - public class CreateNumericalVariableCommand : ScriptCommand + public sealed class CreateNumericalVariableCommand : ScriptCommand { [XmlAttribute] - [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_BothNumericalVariableName))] - [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] public string v_VariableName { get; set; } [XmlAttribute] @@ -31,11 +31,9 @@ public CreateNumericalVariableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - string numString = v_NumberValue.ConvertToUserVariable(engine); + string numString = v_NumberValue.ExpandValueOrUserVariable(engine); if (decimal.TryParse(numString, out _)) { numString.StoreInUserVariable(engine, v_VariableName); diff --git a/taskt/Core/Automation/Commands/Numerical/DecreaseNumericalVariableCommand.cs b/taskt/Core/Automation/Commands/Numerical/DecreaseNumericalVariableCommand.cs index 7efaa6598..6dd7cfcf2 100644 --- a/taskt/Core/Automation/Commands/Numerical/DecreaseNumericalVariableCommand.cs +++ b/taskt/Core/Automation/Commands/Numerical/DecreaseNumericalVariableCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Numerical Commands")] + [Attributes.ClassAttributes.Group("Numerical")] [Attributes.ClassAttributes.CommandSettings("Decrease Numerical Variable")] [Attributes.ClassAttributes.Description("This command allows you to Decrease Value in Numerical Variable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Decrease Value in Numerical Variable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class DecreaseNumericalVariableCommand : ScriptCommand + public sealed class DecreaseNumericalVariableCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_BothNumericalVariableName))] @@ -33,14 +34,12 @@ public DecreaseNumericalVariableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var variableName = VariableNameControls.GetWrappedVariableName(v_VariableName, engine); - var variableValue = new PropertyConvertTag(variableName, "Variable Name").ConvertToUserVariableAsDecimal(engine); + var variableValue = new PropertyConvertTag(variableName, "Variable Name").ExpandValueOrUserVariableAsDecimal(engine); - var add = this.ConvertToUserVariableAsDecimal(nameof(v_VariableName), engine); + var add = this.ExpandValueOrUserVariableAsDecimal(nameof(v_Value), engine); (variableValue - add).ToString().StoreInUserVariable(engine, variableName); } diff --git a/taskt/Core/Automation/Commands/Numerical/FormatNumberCommand.cs b/taskt/Core/Automation/Commands/Numerical/FormatNumberCommand.cs index 9403b4dab..846df6126 100644 --- a/taskt/Core/Automation/Commands/Numerical/FormatNumberCommand.cs +++ b/taskt/Core/Automation/Commands/Numerical/FormatNumberCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Numerical Commands")] + [Attributes.ClassAttributes.Group("Numerical")] [Attributes.ClassAttributes.CommandSettings("Format Number")] [Attributes.ClassAttributes.Description("This command allows you to Format Number.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Format Number.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] [Attributes.ClassAttributes.EnableAutomateRender(true)] - public class FormatNumberCommand : ScriptCommand + public sealed class FormatNumberCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] @@ -47,15 +48,13 @@ public FormatNumberCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //decimal value = new PropertyConvertTag(v_Number, "Number").ConvertToUserVariableAsDecimal(engine); //var value = this.ConvertToUserVariableAsDecimal(nameof(v_Number), "Number", engine); - var value = this.ConvertToUserVariableAsDecimal(nameof(v_Number), engine); + var value = this.ExpandValueOrUserVariableAsDecimal(nameof(v_Number), engine); - string format = v_Format.ConvertToUserVariable(engine); + string format = v_Format.ExpandValueOrUserVariable(engine); value.ToString(format).StoreInUserVariable(engine, v_Result); } @@ -63,7 +62,7 @@ public override void RunCommand(object sender) private void lnkFormatChecker_Click(object sender, EventArgs e) { TextBox txt = (TextBox)((CommandItemControl)sender).Tag; - UI.Forms.Supplement_Forms.frmFormatChecker.ShowFormatCheckerFormLinkClicked(txt, "Number"); + UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmFormatChecker.ShowFormatCheckerFormLinkClicked(txt, "Number"); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Numerical/IncreaseNumericalVariableCommand.cs b/taskt/Core/Automation/Commands/Numerical/IncreaseNumericalVariableCommand.cs index 314a8435d..493717228 100644 --- a/taskt/Core/Automation/Commands/Numerical/IncreaseNumericalVariableCommand.cs +++ b/taskt/Core/Automation/Commands/Numerical/IncreaseNumericalVariableCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Numerical Commands")] + [Attributes.ClassAttributes.Group("Numerical")] [Attributes.ClassAttributes.CommandSettings("Increase Numerical Variable")] [Attributes.ClassAttributes.Description("This command allows you to Increase Value in Numerical Variable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Increase Value in Numerical Variable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class IncreaseNumericalVariableCommand : ScriptCommand + public sealed class IncreaseNumericalVariableCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_BothNumericalVariableName))] @@ -33,16 +34,14 @@ public IncreaseNumericalVariableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var variableName = VariableNameControls.GetWrappedVariableName(v_VariableName, engine); - var variableValue = new PropertyConvertTag(variableName, "Variable Name").ConvertToUserVariableAsDecimal(engine); + var variableValue = new PropertyConvertTag(variableName, "Variable Name").ExpandValueOrUserVariableAsDecimal(engine); //var add = new PropertyConvertTag(v_Value, "v_Value", "Value").ConvertToUserVariableAsDecimal(this, engine); //var add = this.ConvertToUserVariableAsDecimal(nameof(v_Value), "Value To Increase", engine); - var add = this.ConvertToUserVariableAsDecimal(nameof(v_Value), engine); + var add = this.ExpandValueOrUserVariableAsDecimal(nameof(v_Value), engine); (variableValue + add).ToString().StoreInUserVariable(engine, variableName); } diff --git a/taskt/Core/Automation/Commands/Numerical/MathCalculationCommand.cs b/taskt/Core/Automation/Commands/Numerical/MathCalculationCommand.cs index f302590fe..2ea8f341e 100644 --- a/taskt/Core/Automation/Commands/Numerical/MathCalculationCommand.cs +++ b/taskt/Core/Automation/Commands/Numerical/MathCalculationCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Numerical Commands")] + [Attributes.ClassAttributes.Group("Numerical")] [Attributes.ClassAttributes.CommandSettings("Math Calculation")] [Attributes.ClassAttributes.Description("This command allows you to perform a math calculation and apply it to a variable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to perform a math calculation.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MathCalculationCommand : ScriptCommand + public sealed class MathCalculationCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -53,7 +54,7 @@ public class MathCalculationCommand : ScriptCommand public string v_DecimalSeperator { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] public string v_applyToVariableName { get; set; } public MathCalculationCommand() @@ -64,15 +65,15 @@ public MathCalculationCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { //get variablized string - var variableMath = v_InputValue.ConvertToUserVariable(sender); + var variableMath = v_InputValue.ExpandValueOrUserVariable(engine); try { - var decimalSeperator = v_DecimalSeperator.ConvertToUserVariable(sender); - var thousandSeperator = v_ThousandSeperator.ConvertToUserVariable(sender); + var decimalSeperator = v_DecimalSeperator.ExpandValueOrUserVariable(engine); + var thousandSeperator = v_ThousandSeperator.ExpandValueOrUserVariable(engine); //remove thousandths markers if (thousandSeperator != "") @@ -103,7 +104,7 @@ public override void RunCommand(object sender) //store string in variable - result.ToString().StoreInUserVariable(sender, v_applyToVariableName); + result.ToString().StoreInUserVariable(engine, v_applyToVariableName); } catch (Exception ex) { diff --git a/taskt/Core/Automation/Commands/Numerical/RandomNumberCommand.cs b/taskt/Core/Automation/Commands/Numerical/RandomNumberCommand.cs index a48c8b325..bdde61360 100644 --- a/taskt/Core/Automation/Commands/Numerical/RandomNumberCommand.cs +++ b/taskt/Core/Automation/Commands/Numerical/RandomNumberCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Numerical Commands")] + [Attributes.ClassAttributes.Group("Numerical")] [Attributes.ClassAttributes.CommandSettings("Random Number")] [Attributes.ClassAttributes.Description("This command allows you to get Random Number.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Random Number.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RandomNumberCommand : ScriptCommand + public sealed class RandomNumberCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -24,7 +25,7 @@ public class RandomNumberCommand : ScriptCommand public string v_RandomType { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] public string v_Result { get; set; } public RandomNumberCommand() @@ -35,13 +36,11 @@ public RandomNumberCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //var t = v_RandomType.GetUISelectionValue("v_RandomType", this, engine); //var t = this.GetUISelectionValue(nameof(v_RandomType), "Random Type", engine); - var t = this.GetUISelectionValue(nameof(v_RandomType), engine); + var t = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_RandomType), engine); Random rand = new Random(); diff --git a/taskt/Core/Automation/Commands/Numerical/RoundNumberCommand.cs b/taskt/Core/Automation/Commands/Numerical/RoundNumberCommand.cs index 18d870770..74cf68518 100644 --- a/taskt/Core/Automation/Commands/Numerical/RoundNumberCommand.cs +++ b/taskt/Core/Automation/Commands/Numerical/RoundNumberCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Numerical Commands")] + [Attributes.ClassAttributes.Group("Numerical")] [Attributes.ClassAttributes.CommandSettings("Round Number")] [Attributes.ClassAttributes.Description("This command allows you to Round up, down, or round off numbers.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Round up, down, or round off numbers.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RoundNumberCommand : ScriptCommand + public sealed class RoundNumberCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_Value))] @@ -29,7 +30,7 @@ public class RoundNumberCommand : ScriptCommand public string v_RoundType { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyVirtualProperty(nameof(NumberControls), nameof(NumberControls.v_OutputNumericalVariableName))] public string v_Result { get; set; } public RoundNumberCommand() @@ -40,17 +41,15 @@ public RoundNumberCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //decimal num = new PropertyConvertTag(v_Numeric, "Number").ConvertToUserVariableAsDecimal(engine); //var num = this.ConvertToUserVariableAsDecimal(nameof(v_Numeric), "Number", engine); - var num = this.ConvertToUserVariableAsDecimal(nameof(v_Numeric), engine); + var num = this.ExpandValueOrUserVariableAsDecimal(nameof(v_Numeric), engine); //var round = v_RoundType.GetUISelectionValue("v_RoundType", this, engine); //var round = this.GetUISelectionValue(nameof(v_RoundType), "Round Type", engine); - var round = this.GetUISelectionValue(nameof(v_RoundType), engine); + var round = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_RoundType), engine); decimal res = 0; switch (round) diff --git a/taskt/Core/Automation/Commands/Outlook/OutlookDeleteEmailsCommand.cs b/taskt/Core/Automation/Commands/Outlook/OutlookDeleteEmailsCommand.cs index 8a1ba055d..4bc46bfcc 100644 --- a/taskt/Core/Automation/Commands/Outlook/OutlookDeleteEmailsCommand.cs +++ b/taskt/Core/Automation/Commands/Outlook/OutlookDeleteEmailsCommand.cs @@ -12,12 +12,13 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Outlook Commands")] + [Attributes.ClassAttributes.Group("Outlook")] [Attributes.ClassAttributes.Description("This command allows you to delete emails with outlook")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to delete emails with your currenty logged in outlook account")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_smtp))] - public class OutlookDeleteEmailsCommand : ScriptCommand + public sealed class OutlookDeleteEmailsCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Provide the source mail folder name")] @@ -51,11 +52,10 @@ public OutlookDeleteEmailsCommand() this.CommandEnabled = true; this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var vSourceFolder = v_SourceFolder.ConvertToUserVariable(sender); - var vFilter = v_Filter.ConvertToUserVariable(sender); + var vSourceFolder = v_SourceFolder.ExpandValueOrUserVariable(engine); + var vFilter = v_Filter.ExpandValueOrUserVariable(engine); Application outlookApp = new Application(); AddressEntry currentUser = outlookApp.Session.CurrentUser.AddressEntry; @@ -104,7 +104,7 @@ public override void RunCommand(object sender) } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_SourceFolder", this, editor)); diff --git a/taskt/Core/Automation/Commands/Outlook/OutlookEmailCommand.cs b/taskt/Core/Automation/Commands/Outlook/OutlookEmailCommand.cs index 87aead171..1eb073a11 100644 --- a/taskt/Core/Automation/Commands/Outlook/OutlookEmailCommand.cs +++ b/taskt/Core/Automation/Commands/Outlook/OutlookEmailCommand.cs @@ -9,11 +9,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Outlook Commands")] + [Attributes.ClassAttributes.Group("Outlook")] [Attributes.ClassAttributes.Description("This command allows you to send emails with outlook")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to send emails with your currenty logged in outlook account")] [Attributes.ClassAttributes.ImplementationDescription("")] - public class OutlookEmailCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_smtp))] + public sealed class OutlookEmailCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Please Indicate Recipients (; delimited)")] @@ -66,14 +67,13 @@ public OutlookEmailCommand() this.v_BodyType = "Plain"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - - var vRecipients = v_Recipients.ConvertToUserVariable(sender); - var vAttachment = v_Attachment.ConvertToUserVariable(sender); - var vSubject = v_Subject.ConvertToUserVariable(sender); - var vBody = v_Body.ConvertToUserVariable(sender); - var vBodyType = v_BodyType.ConvertToUserVariable(sender); + var vRecipients = v_Recipients.ExpandValueOrUserVariable(engine); + var vAttachment = v_Attachment.ExpandValueOrUserVariable(engine); + var vSubject = v_Subject.ExpandValueOrUserVariable(engine); + var vBody = v_Body.ExpandValueOrUserVariable(engine); + var vBodyType = v_BodyType.ExpandValueOrUserVariable(engine); var splittext = vRecipients.Split(';'); @@ -111,7 +111,7 @@ public override void RunCommand(object sender) } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_Recipients", this, editor)); diff --git a/taskt/Core/Automation/Commands/Outlook/OutlookForwardEmailsCommand.cs b/taskt/Core/Automation/Commands/Outlook/OutlookForwardEmailsCommand.cs index 981473b03..b066ce7aa 100644 --- a/taskt/Core/Automation/Commands/Outlook/OutlookForwardEmailsCommand.cs +++ b/taskt/Core/Automation/Commands/Outlook/OutlookForwardEmailsCommand.cs @@ -12,11 +12,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Outlook Commands")] + [Attributes.ClassAttributes.Group("Outlook")] [Attributes.ClassAttributes.Description("This command allows you to forward emails with outlook")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to forward emails with your currenty logged in outlook account")] [Attributes.ClassAttributes.ImplementationDescription("")] - public class OutlookForwardEmailsCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_smtp))] + public sealed class OutlookForwardEmailsCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Provide the source mail folder name")] @@ -50,12 +51,11 @@ public OutlookForwardEmailsCommand() this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var vSourceFolder = v_SourceFolder.ConvertToUserVariable(sender); - var vFilter = v_Filter.ConvertToUserVariable(sender); - var vRecipients = v_Recipients.ConvertToUserVariable(sender); + var vSourceFolder = v_SourceFolder.ExpandValueOrUserVariable(engine); + var vFilter = v_Filter.ExpandValueOrUserVariable(engine); + var vRecipients = v_Recipients.ExpandValueOrUserVariable(engine); var splittext = vRecipients.Split(';'); @@ -94,7 +94,7 @@ public override void RunCommand(object sender) } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_SourceFolder", this, editor)); diff --git a/taskt/Core/Automation/Commands/Outlook/OutlookGetEmailsCommand.cs b/taskt/Core/Automation/Commands/Outlook/OutlookGetEmailsCommand.cs index 4343f0a76..64ad27f1c 100644 --- a/taskt/Core/Automation/Commands/Outlook/OutlookGetEmailsCommand.cs +++ b/taskt/Core/Automation/Commands/Outlook/OutlookGetEmailsCommand.cs @@ -12,12 +12,13 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Outlook Commands")] + [Attributes.ClassAttributes.Group("Outlook")] [Attributes.ClassAttributes.Description("This command allows you to get emails and attachments with outlook")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get emails and attachments with your currenty logged in outlook account")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_smtp))] - public class OutlookGetEmailsCommand : ScriptCommand + public sealed class OutlookGetEmailsCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Provide the source mail folder name")] @@ -94,13 +95,12 @@ public OutlookGetEmailsCommand() this.CommandEnabled = true; this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var vFolder = v_Folder.ConvertToUserVariable(sender); - var vFilter = v_Filter.ConvertToUserVariable(sender); - var vAttachmentDirectory = v_AttachmentDirectory.ConvertToUserVariable(sender); - var vMessageDirectory = v_MessageDirectory.ConvertToUserVariable(sender); + var vFolder = v_Folder.ExpandValueOrUserVariable(engine); + var vFilter = v_Filter.ExpandValueOrUserVariable(engine); + var vAttachmentDirectory = v_AttachmentDirectory.ExpandValueOrUserVariable(engine); + var vMessageDirectory = v_MessageDirectory.ExpandValueOrUserVariable(engine); if (vFolder == "") vFolder = "Inbox"; @@ -172,7 +172,7 @@ private void ProcessEmail(MailItem mail, string msgDirectory, string attDirector } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_Folder", this, editor)); diff --git a/taskt/Core/Automation/Commands/Outlook/OutlookMoveEmailsCommand.cs b/taskt/Core/Automation/Commands/Outlook/OutlookMoveEmailsCommand.cs index 7ed216594..52a1c2a8a 100644 --- a/taskt/Core/Automation/Commands/Outlook/OutlookMoveEmailsCommand.cs +++ b/taskt/Core/Automation/Commands/Outlook/OutlookMoveEmailsCommand.cs @@ -12,12 +12,13 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Outlook Commands")] + [Attributes.ClassAttributes.Group("Outlook")] [Attributes.ClassAttributes.Description("This command allows you to move/copy emails with outlook")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to move/copy emails with your currenty logged in outlook account")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_smtp))] - public class OutlookMoveEmailsCommand : ScriptCommand + public sealed class OutlookMoveEmailsCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Indicate whether to Move or Copy the emails")] @@ -68,12 +69,11 @@ public OutlookMoveEmailsCommand() this.CommandEnabled = true; this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var vSourceFolder = v_SourceFolder.ConvertToUserVariable(sender); - var vFilter = v_Filter.ConvertToUserVariable(sender); - var vDestinationFolder = v_DestinationFolder.ConvertToUserVariable(sender); + var vSourceFolder = v_SourceFolder.ExpandValueOrUserVariable(engine); + var vFilter = v_Filter.ExpandValueOrUserVariable(engine); + var vDestinationFolder = v_DestinationFolder.ExpandValueOrUserVariable(engine); Application outlookApp = new Application(); AddressEntry currentUser = outlookApp.Session.CurrentUser.AddressEntry; @@ -137,7 +137,7 @@ public override void RunCommand(object sender) } } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_OperationType", this, editor)); diff --git a/taskt/Core/Automation/Commands/Outlook/OutlookReplyToEmailsCommand.cs b/taskt/Core/Automation/Commands/Outlook/OutlookReplyToEmailsCommand.cs index 4bb5fe607..966169d29 100644 --- a/taskt/Core/Automation/Commands/Outlook/OutlookReplyToEmailsCommand.cs +++ b/taskt/Core/Automation/Commands/Outlook/OutlookReplyToEmailsCommand.cs @@ -12,11 +12,12 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Outlook Commands")] + [Attributes.ClassAttributes.Group("Outlook")] [Attributes.ClassAttributes.Description("This command allows you to reply to emails with outlook")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to reply to emails with your currenty logged in outlook account")] [Attributes.ClassAttributes.ImplementationDescription("")] - public class OutlookReplyToEmailsCommand : ScriptCommand + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_smtp))] + public sealed class OutlookReplyToEmailsCommand : ScriptCommand { [XmlAttribute] [Attributes.PropertyAttributes.PropertyDescription("Indicate whether to Reply or Reply All")] @@ -77,13 +78,12 @@ public OutlookReplyToEmailsCommand() this.v_BodyType = "Plain"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var vSourceFolder = v_SourceFolder.ConvertToUserVariable(sender); - var vFilter = v_Filter.ConvertToUserVariable(sender); - var vBody = v_Body.ConvertToUserVariable(sender); - var vAttachment = v_Attachment.ConvertToUserVariable(sender); + var vSourceFolder = v_SourceFolder.ExpandValueOrUserVariable(engine); + var vFilter = v_Filter.ExpandValueOrUserVariable(engine); + var vBody = v_Body.ExpandValueOrUserVariable(engine); + var vAttachment = v_Attachment.ExpandValueOrUserVariable(engine); Application outlookApp = new Application(); AddressEntry currentUser = outlookApp.Session.CurrentUser.AddressEntry; @@ -136,7 +136,7 @@ private void Reply(MailItem mail, string body, string attPath) mail.Send(); } - public override List Render(frmCommandEditor editor) + public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { base.Render(editor); RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_OperationType", this, editor)); diff --git a/taskt/Core/Automation/Commands/ProcessControls.cs b/taskt/Core/Automation/Commands/ProcessControls.cs new file mode 100644 index 000000000..ad2978711 --- /dev/null +++ b/taskt/Core/Automation/Commands/ProcessControls.cs @@ -0,0 +1,44 @@ +using System; +using System.Management; + +namespace taskt.Core.Automation.Commands +{ + static internal class ProcessControls + { + /// + /// get child processid + /// + /// + /// + /// + /// + public static int GetChildProcessId(int processId, int childIndex) + { + if (childIndex < 0) + { + throw new Exception("Child Index is Less than Zero. Value: " + childIndex); + } + + var query = "SELECT ProcessID FROM win32_process WHERE ParentProcessID = " + processId; + var result = new ManagementObjectSearcher(query); + var objCollection = result.Get(); + if (objCollection.Count < childIndex) + { + throw new Exception("Few Child Processes. Count: " + objCollection.Count); + } + + var cnt = 0; + var procId = -1; + foreach(var obj in objCollection) + { + if (cnt == childIndex) + { + procId = int.Parse(obj.Properties["ProcessID"].Value.ToString()); + break; + } + cnt++; + } + return procId; + } + } +} diff --git a/taskt/Core/Automation/Commands/PropertyControls.cs b/taskt/Core/Automation/Commands/PropertyControls.cs index da5195b6b..7c521ea43 100644 --- a/taskt/Core/Automation/Commands/PropertyControls.cs +++ b/taskt/Core/Automation/Commands/PropertyControls.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using System.Reflection; -using System.Windows.Forms; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands @@ -12,12 +11,6 @@ namespace taskt.Core.Automation.Commands /// internal static class PropertyControls { - public const string LabelPrefix = "lbl_"; - public const string Label2ndPrefix = "lbl2_"; - public const string HelperInfix = "_helper_"; - public const string CustomHelperInfix = "_customhelper_"; - public const string GroupPrefix = "group_"; - #region Property methods /// /// get parameters property info @@ -27,14 +20,16 @@ internal static class PropertyControls public static List GetParameterProperties(this ScriptCommand command, bool containsComment = false) { var props = command.GetType().GetProperties(); + IEnumerable ps; if (containsComment) { - return props.Where(p => (p.Name.StartsWith("v_"))).ToList(); + ps = props.Where(p => (p.Name.StartsWith("v_"))); } else { - return props.Where(p => (p.Name.StartsWith("v_") && (p.Name != "v_Comment"))).ToList(); + ps = props.Where(p => (p.Name.StartsWith("v_") && (p.Name != "v_Comment"))); } + return ps.OrderBy(p => p.GetCustomAttribute()?.order ?? new PropertyParameterOrder().order).ToList(); } @@ -160,6 +155,9 @@ public static List GetCustomAttributesWithVirtual(PropertyInfo propInfo, P case nameof(PropertyUISelectionOption): behavior = GetCustomAttributeWithVirtual(propInfo, virtualPropInfo)?.behavior ?? MultiAttributesBehavior.Merge; break; + case nameof(PropertyAvailableSystemVariable): + behavior = GetCustomAttributeWithVirtual(propInfo, virtualPropInfo)?.behavior ?? MultiAttributesBehavior.Merge; + break; } if (behavior == MultiAttributesBehavior.Merge) @@ -191,131 +189,5 @@ public static List GetCustomAttributesWithVirtual(PropertyInfo propInfo, P } } #endregion - - #region control search method - public static List GetControlGroup(this List ctrls, string parameterName, string nextParameterName = "") - { - List ret = new List(); - - int index; - index = ctrls.FindIndex(t => (t.Name == GroupPrefix + parameterName)); - if (index >= 0) - { - ret.Add(ctrls[index]); - } - else - { - index = ctrls.FindIndex(t => (t.Name == LabelPrefix + parameterName)); - int last = (nextParameterName == "") ? ctrls.Count : ctrls.FindIndex(t => (t.Name == LabelPrefix + nextParameterName)); - - for (int i = index; i < last; i++) - { - ret.Add(ctrls[i]); - } - } - - return ret; - } - - public static T GetPropertyControl(this Dictionary controls, string propertyName) where T : Control - { - if (controls.ContainsKey(propertyName)) - { - return (T)controls[propertyName]; - } - else - { - throw new Exception("Control '" + propertyName + "' does not exists."); - } - } - - public static Label GetPropertyControlLabel(this Dictionary controls, string propertyName) - { - if (controls.ContainsKey(LabelPrefix + propertyName)) - { - return (Label)controls[LabelPrefix + propertyName]; - } - else - { - throw new Exception("Label '" + LabelPrefix + propertyName + "' does not exists."); - } - } - - public static Label GetPropertyControl2ndLabel(this Dictionary controls, string propertyName) - { - if (controls.ContainsKey(Label2ndPrefix + propertyName)) - { - return (Label)controls[Label2ndPrefix + propertyName]; - } - else - { - throw new Exception("2nd Label '" + Label2ndPrefix + propertyName + "' does not exists."); - } - } - - public static (T body, Label label, Label label2nd) GetAllPropertyControl(this Dictionary controls, string propertyName, bool throwWhenLabelNotExists = true, bool throwWhen2ndLabelNotExists = false) where T : Control - { - T body = controls.GetPropertyControl(propertyName); - - Label label; - try - { - label = controls.GetPropertyControlLabel(propertyName); - } - catch (Exception ex) - { - if (throwWhenLabelNotExists) - { - throw ex; - } - else - { - label = null; - } - } - Label label2nd; - try - { - label2nd = controls.GetPropertyControl2ndLabel(propertyName); - } - catch (Exception ex) - { - if (throwWhen2ndLabelNotExists) - { - throw ex; - } - else - { - label2nd = null; - } - } - return (body, label, label2nd); - } - - public static Dictionary Get2ndLabelText(this Dictionary controls, string propertyName) - { - return controls.GetPropertyControlLabel(propertyName).Get2ndLabelTexts(); - } - - public static Dictionary Get2ndLabelTexts(this Label lbl) - { - if (lbl.Tag is Dictionary dic) - { - return dic; - } - else - { - throw new Exception(lbl.Name + " does not has Dictionary item for 2nd-Label"); - } - } - - public static void SecondLabelProcess(this Dictionary controls, string labelTextName, string label2ndName, string key) - { - var dic = controls.Get2ndLabelText(labelTextName); - var lbl = controls.GetPropertyControl2ndLabel(label2ndName); - - lbl.Text = dic.ContainsKey(key) ? dic[key] : ""; - } - #endregion } } diff --git a/taskt/Core/Automation/Commands/Regex/GetRegexMatchesCommand.cs b/taskt/Core/Automation/Commands/Regex/GetRegexMatchesCommand.cs index 57cc1fe3a..7dd852b50 100644 --- a/taskt/Core/Automation/Commands/Regex/GetRegexMatchesCommand.cs +++ b/taskt/Core/Automation/Commands/Regex/GetRegexMatchesCommand.cs @@ -8,14 +8,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Regex Commands")] + [Attributes.ClassAttributes.Group("Regex")] [Attributes.ClassAttributes.CommandSettings("Get Regex Matches")] [Attributes.ClassAttributes.Description("This command allows you to loop through an Excel Dataset")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to iterate over a series of Excel cells.")] [Attributes.ClassAttributes.ImplementationDescription("This command attempts to loop through a known Excel DataSet")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetRegexMatchesCommand : ScriptCommand + public sealed class GetRegexMatchesCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -45,12 +46,10 @@ public GetRegexMatchesCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var vInputData = v_InputData.ConvertToUserVariable(engine); - var vRegex = v_Regex.ConvertToUserVariable(engine); + var vInputData = v_InputData.ExpandValueOrUserVariable(engine); + var vRegex = v_Regex.ExpandValueOrUserVariable(engine); Match[] matches = Regex.Matches(vInputData, vRegex) .Cast() diff --git a/taskt/Core/Automation/Commands/Remote/RemoteAPICommand.cs b/taskt/Core/Automation/Commands/Remote/RemoteAPICommand.cs index 89e7e5e54..9aef57d09 100644 --- a/taskt/Core/Automation/Commands/Remote/RemoteAPICommand.cs +++ b/taskt/Core/Automation/Commands/Remote/RemoteAPICommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Remote Commands")] + [Attributes.ClassAttributes.Group("Remote")] [Attributes.ClassAttributes.CommandSettings("Remote API")] [Attributes.ClassAttributes.Description("This command allows you to execute automation against another taskt Client.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to automate against a taskt instance that enables Local Listener.")] [Attributes.ClassAttributes.ImplementationDescription("This command uses Core.Server.LocalTCPListener")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_remote))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RemoteAPICommand : ScriptCommand + public sealed class RemoteAPICommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -59,16 +60,14 @@ public RemoteAPICommand() //this.v_RequestTimeout = "5000"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - try { - var server = v_BaseURL.ConvertToUserVariable(engine); + var server = v_BaseURL.ExpandValueOrUserVariable(engine); //var paramType = v_ParameterType.ConvertToUserVariable(engine); - var paramType = this.GetUISelectionValue(nameof(v_ParameterType), engine); - var timeout = v_RequestTimeout.ConvertToUserVariable(engine); + var paramType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ParameterType), engine); + var timeout = v_RequestTimeout.ExpandValueOrUserVariable(engine); var response = Server.LocalTCPListener.SendAutomationTask(server, paramType, timeout); diff --git a/taskt/Core/Automation/Commands/Remote/RemoteTaskCommand.cs b/taskt/Core/Automation/Commands/Remote/RemoteTaskCommand.cs index dda60f32c..648419f90 100644 --- a/taskt/Core/Automation/Commands/Remote/RemoteTaskCommand.cs +++ b/taskt/Core/Automation/Commands/Remote/RemoteTaskCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Remote Commands")] + [Attributes.ClassAttributes.Group("Remote")] [Attributes.ClassAttributes.CommandSettings("Remote Task")] [Attributes.ClassAttributes.Description("This command allows you to execute a task remotely on another taskt instance")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to execute a command on another client that has local listener enabled")] [Attributes.ClassAttributes.ImplementationDescription("This command interfaces against Core.Server.LocalTCPListener")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_remote))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RemoteTaskCommand : ScriptCommand + public sealed class RemoteTaskCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -80,18 +81,17 @@ public RemoteTaskCommand() //this.v_RequestTimeout = "120000"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; try { - var server = v_BaseURL.ConvertToUserVariable(engine); + var server = v_BaseURL.ExpandValueOrUserVariable(engine); //var paramType = v_ParameterType.ConvertToUserVariable(engine); - var paramType = this.GetUISelectionValue(nameof(v_ParameterType), engine); - var parameter = v_Parameter.ConvertToUserVariable(engine); + var paramType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ParameterType), engine); + var parameter = v_Parameter.ExpandValueOrUserVariable(engine); //var awaitPreference = v_ExecuteAwait.ConvertToUserVariable(engine); - var awaitPreference = this.GetUISelectionValue(nameof(v_ExecuteAwait), engine); - var timeout = v_RequestTimeout.ConvertToUserVariable(engine); + var awaitPreference = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ExecuteAwait), engine); + var timeout = v_RequestTimeout.ExpandValueOrUserVariable(engine); var response = Server.LocalTCPListener.SendAutomationTask(server, paramType, timeout, parameter, awaitPreference); diff --git a/taskt/Core/Automation/Commands/Misc/CommentCommand.cs b/taskt/Core/Automation/Commands/Script/CommentCommand.cs similarity index 85% rename from taskt/Core/Automation/Commands/Misc/CommentCommand.cs rename to taskt/Core/Automation/Commands/Script/CommentCommand.cs index 6f1a0207c..f878bb134 100644 --- a/taskt/Core/Automation/Commands/Misc/CommentCommand.cs +++ b/taskt/Core/Automation/Commands/Script/CommentCommand.cs @@ -3,14 +3,14 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Misc Commands")] - [Attributes.ClassAttributes.SubGruop("Other")] + [Attributes.ClassAttributes.Group("Script")] [Attributes.ClassAttributes.CommandSettings("Comment")] [Attributes.ClassAttributes.Description("This command allows you to add an in-line comment to the script.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add code comments or document code. Usage of variables (ex. [vVar]) within the comment block will be parsed and displayed when running the script.")] [Attributes.ClassAttributes.ImplementationDescription("This command is for visual purposes only")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_comment))] [Attributes.ClassAttributes.EnableAutomateRender(true, true)] - public class CommentCommand : ScriptCommand + public sealed class CommentCommand : ScriptCommand { public CommentCommand() { diff --git a/taskt/Core/Automation/Commands/Script/IHaveSequenceAdditionalCommands.cs b/taskt/Core/Automation/Commands/Script/IHaveSequenceAdditionalCommands.cs new file mode 100644 index 000000000..e055bdaf5 --- /dev/null +++ b/taskt/Core/Automation/Commands/Script/IHaveSequenceAdditionalCommands.cs @@ -0,0 +1,7 @@ +namespace taskt.Core.Automation.Commands +{ + public interface IHaveSequenceAdditionalCommands : IHaveAdditionalCommands + { + // only imple + } +} diff --git a/taskt/Core/Automation/Commands/Misc/SequenceCommand.cs b/taskt/Core/Automation/Commands/Script/SequenceCommand.cs similarity index 81% rename from taskt/Core/Automation/Commands/Misc/SequenceCommand.cs rename to taskt/Core/Automation/Commands/Script/SequenceCommand.cs index d19427524..73258f135 100644 --- a/taskt/Core/Automation/Commands/Misc/SequenceCommand.cs +++ b/taskt/Core/Automation/Commands/Script/SequenceCommand.cs @@ -5,14 +5,14 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Misc Commands")] - [Attributes.ClassAttributes.SubGruop("Other")] + [Attributes.ClassAttributes.Group("Script")] [Attributes.ClassAttributes.CommandSettings("Sequence")] [Attributes.ClassAttributes.Description("Command that groups multiple actions")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to group multiple commands together.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements many commands in a list.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_sequence))] [Attributes.ClassAttributes.EnableAutomateRender(true, true)] - public class SequenceCommand : ScriptCommand + public sealed class SequenceCommand : ScriptCommand, IHaveSequenceAdditionalCommands { public List v_scriptActions = new List(); @@ -24,10 +24,8 @@ public SequenceCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender, Core.Script.ScriptAction parentCommand) + public override void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction parentCommand) { - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; - foreach (var item in v_scriptActions) { //exit if cancellation pending diff --git a/taskt/Core/Automation/Commands/ScriptCommand.cs b/taskt/Core/Automation/Commands/ScriptCommand.cs index a308092e8..8d5955fea 100644 --- a/taskt/Core/Automation/Commands/ScriptCommand.cs +++ b/taskt/Core/Automation/Commands/ScriptCommand.cs @@ -6,482 +6,46 @@ using System.Reflection; using taskt.UI.CustomControls; using taskt.Core.Automation.Attributes.ClassAttributes; +using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - //// API - //[XmlInclude(typeof(ExecuteDLLCommand))] - //[XmlInclude(typeof(RESTCommand))] - //[XmlInclude(typeof(HTTPRequestCommand))] - //[XmlInclude(typeof(HTTPQueryResultCommand))] - - //// Color - //[XmlInclude(typeof(CreateColorCommand))] - //[XmlInclude(typeof(CreateColorFromExcelColorCommand))] - //[XmlInclude(typeof(CreateColorFromHexCommand))] - //[XmlInclude(typeof(FormatColorCommand))] - - //// Data - //[XmlInclude(typeof(DateCalculationCommand))] - //[XmlInclude(typeof(FormatDataCommand))] - //[XmlInclude(typeof(LogDataCommand))] - //[XmlInclude(typeof(PDFTextExtractionCommand))] - - //// Database - //[XmlInclude(typeof(DatabaseDefineConnectionCommand))] - //[XmlInclude(typeof(DatabaseExecuteQueryCommand))] - - //// DataTable - //[XmlInclude(typeof(AddDataRowCommand))] - //[XmlInclude(typeof(AddDataTableColumnCommand))] - //[XmlInclude(typeof(AddDataTableRowByDictionaryCommand))] - //[XmlInclude(typeof(AddDataTableRowCommand))] - //[XmlInclude(typeof(AddDataTableRowsByDataTableCommand))] - //[XmlInclude(typeof(CheckDataTableColumnExistsCommand))] - //[XmlInclude(typeof(ConvertDataTableColumnToDataTableCommand))] - //[XmlInclude(typeof(ConvertDataTableColumnToDictionaryCommand))] - //[XmlInclude(typeof(ConvertDataTableColumnToJSONCommand))] - //[XmlInclude(typeof(ConvertDataTableColumnToListCommand))] - //[XmlInclude(typeof(ConvertDataTableRowToDataTableCommand))] - //[XmlInclude(typeof(ConvertDataTableRowToDictionaryCommand))] - //[XmlInclude(typeof(ConvertDataTableRowToJSONCommand))] - //[XmlInclude(typeof(ConvertDataTableRowToListCommand))] - //[XmlInclude(typeof(ConvertDataTableToJSONCommand))] - //[XmlInclude(typeof(CopyDataTableCommand))] - //[XmlInclude(typeof(CreateDataTableCommand))] - //[XmlInclude(typeof(DeleteDataTableColumnCommand))] - //[XmlInclude(typeof(DeleteDataTableRowCommand))] - //[XmlInclude(typeof(FilterDataTableColumnByRowValueCommand))] - //[XmlInclude(typeof(FilterDataTableCommand))] - //[XmlInclude(typeof(FilterDataTableRowByColumnValueCommand))] - //[XmlInclude(typeof(GetDataRowCommand))] - //[XmlInclude(typeof(GetDataRowCountCommand))] - //[XmlInclude(typeof(GetDataRowValueCommand))] - //[XmlInclude(typeof(GetDataTableColumnCountCommand))] - //[XmlInclude(typeof(GetDataTableColumnListCommand))] - //[XmlInclude(typeof(GetDataTableRowCountCommand))] - //[XmlInclude(typeof(GetDataTableValueCommand))] - //[XmlInclude(typeof(ReplaceDataTableColumnValueCommand))] - //[XmlInclude(typeof(ReplaceDataTableRowValueCommand))] - //[XmlInclude(typeof(ReplaceDataTableValueCommand))] - //[XmlInclude(typeof(ParseDatasetRowCommand))] - //[XmlInclude(typeof(RemoveDataRowCommand))] - //[XmlInclude(typeof(SetDataTableColumnValuesByDataTableCommand))] - //[XmlInclude(typeof(SetDataTableColumnValuesByListCommand))] - //[XmlInclude(typeof(SetDataTableRowValuesByDataTableCommand))] - //[XmlInclude(typeof(SetDataTableRowValuesByDictionaryCommand))] - //[XmlInclude(typeof(SetDataTableValueCommand))] - //[XmlInclude(typeof(WriteDataRowValueCommand))] - //[XmlInclude(typeof(LoadDataTableCommand))] - - //// DateTime - //[XmlInclude(typeof(CalculateDateTimeCommand))] - //[XmlInclude(typeof(ConvertDateTimeToExcelSerialCommand))] - //[XmlInclude(typeof(CreateDateTimeCommand))] - //[XmlInclude(typeof(CreateDateTimeFromExcelSerialCommand))] - //[XmlInclude(typeof(CreateDateTimeFromTextCommand))] - //[XmlInclude(typeof(GetDateTimeDifferencesCommand))] - //[XmlInclude(typeof(FormatDateTimeCommand))] - - //// Dictionary - //[XmlInclude(typeof(AddDictionaryCommand))] - //[XmlInclude(typeof(CheckDictionaryKeyExistsCommand))] - //[XmlInclude(typeof(CreateDictionaryCommand))] - //[XmlInclude(typeof(ConcatenateDictionaryCommand))] - //[XmlInclude(typeof(ConvertDictionaryToDataTableCommand))] - //[XmlInclude(typeof(ConvertDictionaryToJSONCommand))] - //[XmlInclude(typeof(ConvertDictionaryToListCommand))] - //[XmlInclude(typeof(CopyDictionaryCommand))] - //[XmlInclude(typeof(FilterDictionaryCommand))] - //[XmlInclude(typeof(GetDictionaryKeyFromValueCommand))] - //[XmlInclude(typeof(GetDictionaryKeysListCommand))] - //[XmlInclude(typeof(GetDictionaryValueCommand))] - //[XmlInclude(typeof(LoadDictionaryCommand))] - //[XmlInclude(typeof(RemoveDictionaryItemCommand))] - //[XmlInclude(typeof(ReplaceDictionaryCommand))] - //[XmlInclude(typeof(SetDictionaryValueCommand))] - - //// EMail - //[XmlInclude(typeof(MailKitGetAddressesAsDataTableCommand))] - //[XmlInclude(typeof(MailKitGetAddressesAsDictionaryCommand))] - //[XmlInclude(typeof(MailKitGetAddressesAsListCommand))] - //[XmlInclude(typeof(MailKitGetEmailAttachmentsNameCommand))] - //[XmlInclude(typeof(MailKitGetEMailFromEMailListCommand))] - //[XmlInclude(typeof(MailKitGetEMailTextCommand))] - //[XmlInclude(typeof(MailKitLoadEmailCommand))] - //[XmlInclude(typeof(MailKitRecieveEmailListUsingIMAPCommand))] - //[XmlInclude(typeof(MailKitRecieveEmailListUsingPOPCommand))] - //[XmlInclude(typeof(MailKitSaveEmailCommand))] - //[XmlInclude(typeof(MailKitSaveEmailAttachmentsCommand))] - //[XmlInclude(typeof(MailKitSendEmailCommand))] - - //// Engine - //[XmlInclude(typeof(ErrorHandlingCommand))] - //[XmlInclude(typeof(GetDataCommand))] - //[XmlInclude(typeof(PauseCommand))] - //[XmlInclude(typeof(SetEngineDelayCommand))] - //[XmlInclude(typeof(SetEnginePreferenceCommand))] - //[XmlInclude(typeof(ShowEngineContextCommand))] - //[XmlInclude(typeof(StopwatchCommand))] - //[XmlInclude(typeof(UploadDataCommand))] - - //// Error - //[XmlInclude(typeof(CatchExceptionCommand))] - //[XmlInclude(typeof(EndTryCommand))] - //[XmlInclude(typeof(FinallyCommand))] - //[XmlInclude(typeof(ThrowExceptionCommand))] - //[XmlInclude(typeof(TryCommand))] - - //// Excel - //[XmlInclude(typeof(ExcelActivateSheetCommand))] - //[XmlInclude(typeof(ExcelAddWorkbookCommand))] - //[XmlInclude(typeof(ExcelAddWorksheetCommand))] - //[XmlInclude(typeof(ExcelAppendCellCommand))] - //[XmlInclude(typeof(ExcelAppendRowCommand))] - //[XmlInclude(typeof(ExcelCheckCellValueExistsCommand))] - //[XmlInclude(typeof(ExcelCheckCellValueExistsRCCommand))] - //[XmlInclude(typeof(ExcelCheckExcelInstanceExistsCommand))] - //[XmlInclude(typeof(ExcelCheckWorksheetExistsCommand))] - //[XmlInclude(typeof(ExcelCloseApplicationCommand))] - //[XmlInclude(typeof(ExcelCopyWorksheetCommand))] - //[XmlInclude(typeof(ExcelCreateApplicationCommand))] - //[XmlInclude(typeof(ExcelDeleteCellCommand))] - //[XmlInclude(typeof(ExcelDeleteRowCommand))] - //[XmlInclude(typeof(ExcelDeleteWorksheetCommand))] - //[XmlInclude(typeof(ExcelGetCellCommand))] - //[XmlInclude(typeof(ExcelGetCellRCCommand))] - //[XmlInclude(typeof(ExcelGetColumnValuesAsDataTableCommand))] - //[XmlInclude(typeof(ExcelGetColumnValuesAsDictionaryCommand))] - //[XmlInclude(typeof(ExcelGetColumnValuesAsListCommand))] - //[XmlInclude(typeof(ExcelGetCurrentWorksheetCommand))] - //[XmlInclude(typeof(ExcelGetExcelInfoCommand))] - //[XmlInclude(typeof(ExcelGetLastRowCommand))] - //[XmlInclude(typeof(ExcelGetRangeCommand))] - //[XmlInclude(typeof(ExcelGetRangeCommandAsDT))] - //[XmlInclude(typeof(ExcelGetRangeValuesAsDataTableCommand))] - //[XmlInclude(typeof(ExcelGetRowValuesAsDataTableCommand))] - //[XmlInclude(typeof(ExcelGetRowValuesAsDictionaryCommand))] - //[XmlInclude(typeof(ExcelGetRowValuesAsListCommand))] - //[XmlInclude(typeof(ExcelGetWorksheetsCommand))] - //[XmlInclude(typeof(ExcelGetWorksheetInfoCommand))] - //[XmlInclude(typeof(ExcelGoToCellCommand))] - //[XmlInclude(typeof(ExcelOpenWorkbookCommand))] - //[XmlInclude(typeof(ExcelRenameWorksheetCommand))] - //[XmlInclude(typeof(ExcelRunMacroCommand))] - //[XmlInclude(typeof(ExcelSaveCommand))] - //[XmlInclude(typeof(ExcelSaveAsCommand))] - //[XmlInclude(typeof(ExcelSetCellCommand))] - //[XmlInclude(typeof(ExcelSetCellRCCommand))] - //[XmlInclude(typeof(ExcelSetColumnValuesFromDataTableCommand))] - //[XmlInclude(typeof(ExcelSetColumnValuesFromDictionaryCommand))] - //[XmlInclude(typeof(ExcelSetColumnValuesFromListCommand))] - //[XmlInclude(typeof(ExcelSetRowValuesFromDataTableCommand))] - //[XmlInclude(typeof(ExcelSetRowValuesFromDictionaryCommand))] - //[XmlInclude(typeof(ExcelSetRowValuesFromListCommand))] - //[XmlInclude(typeof(ExcelSplitRangeByColumnCommand))] - //[XmlInclude(typeof(ExcelWriteRangeCommand))] - //[XmlInclude(typeof(ExcelWriteRowCommand))] - - //// File - //[XmlInclude(typeof(CheckFileExistsCommand))] - //[XmlInclude(typeof(DeleteFileCommand))] - //[XmlInclude(typeof(ExtractFileCommand))] - //[XmlInclude(typeof(FormatFilePathCommnad))] - //[XmlInclude(typeof(GetFileInfoCommand))] - //[XmlInclude(typeof(GetFilesCommand))] - //[XmlInclude(typeof(MoveFileCommand))] - //[XmlInclude(typeof(RenameFileCommand))] - //[XmlInclude(typeof(WaitForFileToExistCommand))] - - //// Folder - //[XmlInclude(typeof(CheckFolderExistsCommand))] - //[XmlInclude(typeof(CreateFolderCommand))] - //[XmlInclude(typeof(DeleteFolderCommand))] - //[XmlInclude(typeof(FormatFolderPathCommnad))] - //[XmlInclude(typeof(GetFoldersCommand))] - //[XmlInclude(typeof(MoveFolderCommand))] - //[XmlInclude(typeof(RenameFolderCommand))] - //[XmlInclude(typeof(WaitForFolderToExistCommand))] - - //// IE - //[XmlInclude(typeof(IEBrowserCloseCommand))] - //[XmlInclude(typeof(IEBrowserCreateCommand))] - //[XmlInclude(typeof(IEBrowserElementActionCommand))] - //[XmlInclude(typeof(IEBrowserFindBrowserCommand))] - //[XmlInclude(typeof(IEBrowserNavigateURLCommand))] - - //// If - //[XmlInclude(typeof(BeginIfCommand))] - //[XmlInclude(typeof(BeginMultiIfCommand))] - //[XmlInclude(typeof(ElseCommand))] - //[XmlInclude(typeof(EndIfCommand))] - - //// Image - //[XmlInclude(typeof(OCRCommand))] - //[XmlInclude(typeof(ImageRecognitionCommand))] - //[XmlInclude(typeof(ScreenshotCommand))] - - //// Input - //[XmlInclude(typeof(FileDialogCommand))] - //[XmlInclude(typeof(FolderDialogCommand))] - //[XmlInclude(typeof(HTMLInputCommand))] - //[XmlInclude(typeof(UserInputCommand))] - //[XmlInclude(typeof(SendAdvancedKeyStrokesCommand))] - //[XmlInclude(typeof(SendHotkeyCommand))] - //[XmlInclude(typeof(SendKeysCommand))] - //[XmlInclude(typeof(SendMouseClickCommand))] - //[XmlInclude(typeof(SendMouseMoveCommand))] - //[XmlInclude(typeof(UIAutomationCommand))] - - //// JSON - //[XmlInclude(typeof(AddJSONArrayItemCommand))] - //[XmlInclude(typeof(AddJSONObjectPropertyCommand))] - //[XmlInclude(typeof(ConvertJSONToDataTableCommand))] - //[XmlInclude(typeof(ConvertJSONToDictionaryCommand))] - //[XmlInclude(typeof(ConvertJSONToListCommand))] - //[XmlInclude(typeof(CreateJSONVariableCommand))] - //[XmlInclude(typeof(GetJSONValueListCommand))] - //[XmlInclude(typeof(GetMultiJSONValueListCommand))] - //[XmlInclude(typeof(InsertJSONArrayItemCommand))] - //[XmlInclude(typeof(InsertJSONObjectPropertyCommand))] - //[XmlInclude(typeof(ParseJSONArrayCommand))] - //[XmlInclude(typeof(ReadJSONFileCommand))] - //[XmlInclude(typeof(RemoveJSONArrayItemCommand))] - //[XmlInclude(typeof(RemoveJSONPropertyCommand))] - //[XmlInclude(typeof(SetJSONValueCommand))] - - //// List - //[XmlInclude(typeof(AddListItemCommand))] - //[XmlInclude(typeof(CheckListItemExistsCommand))] - //[XmlInclude(typeof(ConcatenateListsCommand))] - //[XmlInclude(typeof(ConvertListToDataTableCommand))] - //[XmlInclude(typeof(ConvertListToDictionaryCommand))] - //[XmlInclude(typeof(ConvertListToJSONCommand))] - //[XmlInclude(typeof(CopyListCommand))] - //[XmlInclude(typeof(CreateListCommand))] - //[XmlInclude(typeof(FilterListCommand))] - //[XmlInclude(typeof(GetAverageFromListCommand))] - //[XmlInclude(typeof(GetListCountCommand))] - //[XmlInclude(typeof(GetListIndexFromValueCommand))] - //[XmlInclude(typeof(GetListItemCommand))] - //[XmlInclude(typeof(GetMaxFromListCommand))] - //[XmlInclude(typeof(GetMedianFromListCommand))] - //[XmlInclude(typeof(GetMinFromListCommand))] - //[XmlInclude(typeof(GetSumFromListCommand))] - //[XmlInclude(typeof(GetVarianceFromListCommand))] - //[XmlInclude(typeof(ReplaceListCommand))] - //[XmlInclude(typeof(ReverseListCommand))] - //[XmlInclude(typeof(SetListIndexCommand))] - //[XmlInclude(typeof(SetListItemCommand))] - //[XmlInclude(typeof(SortListCommand))] - - //// Loop - //[XmlInclude(typeof(BeginLoopCommand))] - //[XmlInclude(typeof(BeginMultiLoopCommand))] - //[XmlInclude(typeof(EndLoopCommand))] - //[XmlInclude(typeof(ExitLoopCommand))] - //[XmlInclude(typeof(BeginContinousLoopCommand))] - //[XmlInclude(typeof(BeginListLoopCommand))] - //[XmlInclude(typeof(BeginNumberOfTimesLoopCommand))] - //[XmlInclude(typeof(NextLoopCommand))] - - //// Misc - //[XmlInclude(typeof(ClipboardClearTextCommand))] - //[XmlInclude(typeof(ClipboardGetTextCommand))] - //[XmlInclude(typeof(ClipboardSetTextCommand))] - //[XmlInclude(typeof(CommentCommand))] - //[XmlInclude(typeof(CreateShortcutCommand))] - //[XmlInclude(typeof(EncryptionCommand))] - //[XmlInclude(typeof(MessageBoxCommand))] - //[XmlInclude(typeof(PingCommand))] - //[XmlInclude(typeof(PlaySystemSoundCommand))] - //[XmlInclude(typeof(SequenceCommand))] - //[XmlInclude(typeof(SMTPSendEmailCommand))] - - //// NLG - //[XmlInclude(typeof(NLGCreateInstanceCommand))] - //[XmlInclude(typeof(NLGGeneratePhraseCommand))] - //[XmlInclude(typeof(NLGSetParameterCommand))] - - //// Numeric - //[XmlInclude(typeof(CreateNumberVariableCommand))] - //[XmlInclude(typeof(DecreaseNumericalVariableCommand))] - //[XmlInclude(typeof(FormatNumberCommand))] - //[XmlInclude(typeof(IncreaseNumericalVariableCommand))] - //[XmlInclude(typeof(MathCalculationCommand))] - //[XmlInclude(typeof(RandomNumberCommand))] - //[XmlInclude(typeof(RoundNumberCommand))] - - //// Outlook - //[XmlInclude(typeof(OutlookDeleteEmailsCommand))] - //[XmlInclude(typeof(OutlookForwardEmailsCommand))] - //[XmlInclude(typeof(OutlookGetEmailsCommand))] - //[XmlInclude(typeof(OutlookMoveEmailsCommand))] - //[XmlInclude(typeof(OutlookReplyToEmailsCommand))] - //[XmlInclude(typeof(OutlookEmailCommand))] - - //// Program - //[XmlInclude(typeof(RunCustomCodeCommand))] - //[XmlInclude(typeof(RunScriptCommand))] - //[XmlInclude(typeof(StartProcessCommand))] - //[XmlInclude(typeof(StopProcessCommand))] - //[XmlInclude(typeof(RunPowershellCommand))] - - //// Regex - //[XmlInclude(typeof(GetRegexMatchesCommand))] - - //// Remote - //[XmlInclude(typeof(RemoteAPICommand))] - //[XmlInclude(typeof(RemoteTaskCommand))] - - //// System - //[XmlInclude(typeof(EnvironmentVariableCommand))] - //[XmlInclude(typeof(RemoteDesktopCommand))] - //[XmlInclude(typeof(OSVariableCommand))] - //[XmlInclude(typeof(SystemActionCommand))] - - //// Task - //[XmlInclude(typeof(LoadTaskCommand))] - //[XmlInclude(typeof(RunTaskCommand))] - //[XmlInclude(typeof(StopTaskCommand))] - //[XmlInclude(typeof(UnloadTaskCommand))] - - //// Text - //[XmlInclude(typeof(CheckTextCommand))] - //[XmlInclude(typeof(ConcatenateTextVariableCommand))] - //[XmlInclude(typeof(CreateTextVariableCommand))] - //[XmlInclude(typeof(ExtractionTextCommand))] - //[XmlInclude(typeof(GetWordCountCommand))] - //[XmlInclude(typeof(GetWordLengthCommand))] - //[XmlInclude(typeof(ModifyTextCommand))] - //[XmlInclude(typeof(ReadTextFileCommand))] - //[XmlInclude(typeof(RegExExtractionTextCommand))] - //[XmlInclude(typeof(ReplaceTextCommand))] - //[XmlInclude(typeof(SplitTextCommand))] - //[XmlInclude(typeof(SubstringTextCommand))] - //[XmlInclude(typeof(WriteTextFileCommand))] - - //// UIAutomation - //[XmlInclude(typeof(UIAutomationCheckElementExistByXPathCommand))] - //[XmlInclude(typeof(UIAutomationCheckElementExistCommand))] - //[XmlInclude(typeof(UIAutomationClickElementCommand))] - //[XmlInclude(typeof(UIAutomationExpandCollapseItemsInElementCommand))] - //[XmlInclude(typeof(UIAutomationGetChildElementCommand))] - //[XmlInclude(typeof(UIAutomationGetChildrenElementsInformationCommand))] - //[XmlInclude(typeof(UIAutomationGetElementFromElementCommand))] - //[XmlInclude(typeof(UIAutomationGetElementFromElementByXPathCommand))] - //[XmlInclude(typeof(UIAutomationGetElementFromTableElementCommand))] - //[XmlInclude(typeof(UIAutomationGetElementFromWindowCommand))] - //[XmlInclude(typeof(UIAutomationGetElementFromWindowByXPathCommand))] - //[XmlInclude(typeof(UIAutomationGetElementTreeXMLFromElementCommand))] - //[XmlInclude(typeof(UIAutomationGetParentElementCommand))] - //[XmlInclude(typeof(UIAutomationGetSelectedStateFromElementCommand))] - //[XmlInclude(typeof(UIAutomationGetSelectionItemsFromElementCommand))] - //[XmlInclude(typeof(UIAutomationGetTextFromElementCommand))] - //[XmlInclude(typeof(UIAutomationGetTextFromTableElementCommand))] - //[XmlInclude(typeof(UIAutomationSelectElementCommand))] - //[XmlInclude(typeof(UIAutomationSelectItemInElementCommand))] - //[XmlInclude(typeof(UIAutomationSetTextToElementCommand))] - //[XmlInclude(typeof(UIAutomationScrollElementCommand))] - //[XmlInclude(typeof(UIAutomationWaitForElementExistByXPathCommand))] - //[XmlInclude(typeof(UIAutomationWaitForElementExistCommand))] - - //// Variable - //[XmlInclude(typeof(VariableCommand))] - //[XmlInclude(typeof(AddVariableCommand))] - //[XmlInclude(typeof(CheckVariableExistsCommand))] - //[XmlInclude(typeof(GetVariableTypeCommand))] - //[XmlInclude(typeof(SetVariableIndexCommand))] - - //// Web - //[XmlInclude(typeof(SeleniumBrowserCheckBrowserInstanceExistsCommand))] - //[XmlInclude(typeof(SeleniumBrowserCloseCommand))] - //[XmlInclude(typeof(SeleniumBrowserCreateCommand))] - //[XmlInclude(typeof(SeleniumBrowserElementActionCommand))] - //[XmlInclude(typeof(SeleniumBrowserExecuteScriptCommand))] - //[XmlInclude(typeof(SeleniumBrowserGetAnElementValuesAsDataTableCommand))] - //[XmlInclude(typeof(SeleniumBrowserGetAnElementValuesAsDictionaryCommand))] - //[XmlInclude(typeof(SeleniumBrowserGetAnElementValuesAsListCommand))] - //[XmlInclude(typeof(SeleniumBrowserGetElementsValueAsDataTableCommand))] - //[XmlInclude(typeof(SeleniumBrowserGetElementsValueAsDictionaryCommand))] - //[XmlInclude(typeof(SeleniumBrowserGetElementsValueAsListCommand))] - //[XmlInclude(typeof(SeleniumBrowserGetElementsValuesAsDataTableCommand))] - //[XmlInclude(typeof(SeleniumBrowserGetTableValueAsDataTableCommand))] - //[XmlInclude(typeof(SeleniumBrowserInfoCommand))] - //[XmlInclude(typeof(SeleniumBrowserNavigateBackCommand))] - //[XmlInclude(typeof(SeleniumBrowserNavigateForwardCommand))] - //[XmlInclude(typeof(SeleniumBrowserNavigateURLCommand))] - //[XmlInclude(typeof(SeleniumBrowserRefreshCommand))] - //[XmlInclude(typeof(SeleniumBrowserResizeBrowser))] - //[XmlInclude(typeof(SeleniumBrowserSwitchFrameCommand))] - //[XmlInclude(typeof(SeleniumBrowserSwitchWindowCommand))] - //[XmlInclude(typeof(SeleniumBrowserTakeScreenshotCommand))] - - //// Window - //[XmlInclude(typeof(ActivateWindowCommand))] - //[XmlInclude(typeof(CheckWindowNameExistsCommand))] - //[XmlInclude(typeof(CloseWindowCommand))] - //[XmlInclude(typeof(GetWindowNamesCommand))] - //[XmlInclude(typeof(GetWindowPositionCommand))] - //[XmlInclude(typeof(GetWindowStateCommand))] - //[XmlInclude(typeof(MoveWindowCommand))] - //[XmlInclude(typeof(ResizeWindowCommand))] - //[XmlInclude(typeof(SetWindowStateCommand))] - //[XmlInclude(typeof(WaitForWindowCommand))] - - //// Word - //[XmlInclude(typeof(WordAddDocumentCommand))] - //[XmlInclude(typeof(WordAppendDataTableCommand))] - //[XmlInclude(typeof(WordAppendImageCommand))] - //[XmlInclude(typeof(WordAppendTextCommand))] - //[XmlInclude(typeof(WordCheckWordInstanceExistsCommand))] - //[XmlInclude(typeof(WordCloseApplicationCommand))] - //[XmlInclude(typeof(WordCreateApplicationCommand))] - //[XmlInclude(typeof(WordExportToPDFCommand))] - //[XmlInclude(typeof(WordOpenDocumentCommand))] - //[XmlInclude(typeof(WordReadDocumentCommand))] - //[XmlInclude(typeof(WordReplaceTextCommand))] - //[XmlInclude(typeof(WordSaveCommand))] - //[XmlInclude(typeof(WordSaveAsCommand))] - - - // ? - //[XmlInclude(typeof(ThickAppClickItemCommand))] - //[XmlInclude(typeof(ThickAppGetTextCommand))] - //[XmlInclude(typeof(BeginExcelDatasetLoopCommand))] - //[XmlInclude(typeof(DatabaseRunQueryCommand))] - //[XmlInclude(typeof(AddDataTableColumnAndFillValuesByListCommand))] - //[XmlInclude(typeof(AddDataTableColumnsAndFillValuesByDataTableCommand))] - - - public abstract class ScriptCommand + public abstract class ScriptCommand : ILUIParameterProperties, ICommandIDProperties { [XmlAttribute] public string CommandID { get; set; } + [XmlAttribute] public string CommandName { get; set; } + [XmlAttribute] public bool IsCommented { get; set; } + [XmlAttribute] public string SelectionName { get; set; } + [XmlAttribute] public int DefaultPause { get; set; } + [XmlAttribute] public int LineNumber { get; set; } + [XmlAttribute] public bool PauseBeforeExeucution { get; set; } + [XmlIgnore] public Color DisplayForeColor { get; set; } [XmlAttribute] - [Attributes.PropertyAttributes.PropertyDescription("Comment Field")] - [Attributes.PropertyAttributes.InputSpecification("Optional field to enter a custom comment which could potentially describe this command or the need for this command, if required")] - [Attributes.PropertyAttributes.SampleUsage("I am using this command to ...")] - [Attributes.PropertyAttributes.Remarks("")] - [Attributes.PropertyAttributes.PropertyRecommendedUIControl(Attributes.PropertyAttributes.PropertyRecommendedUIControl.RecommendeUIControlType.MultiLineTextBox)] - [Attributes.PropertyAttributes.PropertyTextBoxSetting(3, true)] - [Attributes.PropertyAttributes.PropertyIsOptional(true)] + [PropertyDescription("Comment Field")] + [InputSpecification("Optional field to enter a custom comment which could potentially describe this command or the need for this command, if required")] + [SampleUsage("I am using this command to ...")] + [Remarks("")] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.MultiLineTextBox)] + [PropertyTextBoxSetting(3, true)] + [PropertyIsOptional(true)] + [PropertyParameterOrder(int.MaxValue)] public string v_Comment { get; set; } [XmlAttribute] @@ -514,11 +78,20 @@ public abstract class ScriptCommand [XmlIgnore] [NonSerialized] - protected Dictionary ControlsList; + protected Dictionary _ControlsList; + + [XmlIgnore] + public Dictionary ControlsList + { + get + { + return this._ControlsList; + } + } public ScriptCommand() { - this.DisplayForeColor = System.Drawing.Color.SteelBlue; + this.DisplayForeColor = Color.SteelBlue; this.CommandEnabled = false; this.DefaultPause = 0; this.IsCommented = false; @@ -539,26 +112,22 @@ public ScriptCommand() this.CustomRendering = commandSettings.customeRender; } - public void GenerateID() - { - var id = Guid.NewGuid(); - this.CommandID = id.ToString(); - } + //public void GenerateID() + //{ + // var id = Guid.NewGuid(); + // this.CommandID = id.ToString(); + //} #region RunCommand - public virtual void RunCommand(object sender) + + public virtual void RunCommand(Engine.AutomationEngineInstance engine) { - //RunCommand((AutomationEngineInstance)sender); System.Threading.Thread.Sleep(DefaultPause); } - public virtual void RunCommand(object sender, Script.ScriptAction command) + public virtual void RunCommand(Engine.AutomationEngineInstance engine, Script.ScriptAction command) { System.Threading.Thread.Sleep(DefaultPause); } - //public virtual void RunCommand(AutomationEngineInstance engine) - //{ - // System.Threading.Thread.Sleep(DefaultPause); - //} #endregion #region GetDisplayValue @@ -569,13 +138,8 @@ public virtual string GetDisplayValue() #endregion #region Render, Refresh, etc - //public virtual List Render(UI.Forms.frmCommandEditor editor, object sender) - //{ - // RenderedControls = new List(); - // return RenderedControls; - //} - public virtual List Render(UI.Forms.frmCommandEditor editor) + public virtual List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { RenderedControls = new List(); @@ -584,15 +148,15 @@ public virtual List Render(UI.Forms.frmCommandEditor editor) { RenderedControls.AddRange(CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor, attrAutoRender.forceRenderComment)); - ControlsList = new Dictionary(); + this._ControlsList = new Dictionary(); foreach (Control control in RenderedControls) { - ControlsList.Add(control.Name, control); + this._ControlsList.Add(control.Name, control); if (control is FlowLayoutPanel flp) { foreach (Control c in flp.Controls) { - ControlsList.Add(c.Name, c); + this._ControlsList.Add(c.Name, c); } } } @@ -610,12 +174,12 @@ public virtual List Render() RenderedControls = new List(); return RenderedControls; } - public virtual void AfterShown() + public virtual void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { } - public virtual void Refresh(UI.Forms.frmCommandEditor editor = null) + public virtual void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { } @@ -626,7 +190,7 @@ public virtual void BeforeValidate() { } - public virtual bool IsValidate(UI.Forms.frmCommandEditor editor) + public virtual bool IsValidate(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { (this.IsValid, this.IsWarning, this.validationResult) = ValidationControls.CheckValidation(this); @@ -648,7 +212,7 @@ public virtual void ConvertToIntermediate(EngineSettings settings, List(prop, virtualProp) ?? new Attributes.PropertyAttributes.PropertyIntermediateConvert(); + var methods = PropertyControls.GetCustomAttributeWithVirtual(prop, virtualProp) ?? new PropertyIntermediateConvert(); if (methods.intermediateMethod.Length > 0) { @@ -689,7 +253,7 @@ public virtual void ConvertToRaw(EngineSettings settings) foreach (var prop in props) { var virtualProp = prop.GetVirtualProperty(); - var methods = PropertyControls.GetCustomAttributeWithVirtual(prop, virtualProp) ?? new Attributes.PropertyAttributes.PropertyIntermediateConvert(); + var methods = PropertyControls.GetCustomAttributeWithVirtual(prop, virtualProp) ?? new PropertyIntermediateConvert(); if (methods.rawMethod.Length > 0) { @@ -720,7 +284,22 @@ public void ConvertToRaw(EngineSettings settings, Dictionary con public ScriptCommand Clone() { - return (ScriptCommand)MemberwiseClone(); + var newCommand = (ScriptCommand)MemberwiseClone(); + var currentProps = this.GetParameterProperties(); + + var newProps = newCommand.GetParameterProperties(); + + for (int i = currentProps.Count - 1; i >=0 ; i--) + { + var v = currentProps[i].GetValue(this); + if (v is System.Data.DataTable table) + { + newProps[i].SetValue(newCommand, table.Copy()); + } + } + + //return (ScriptCommand)MemberwiseClone(); + return newCommand; } #region Math Replace @@ -775,7 +354,6 @@ public virtual void AddInstance(InstanceCounter counter) /// public virtual void RemoveInstance(InstanceCounter counter) { - InstanceCounterControls.RemoveInstance(this, counter); } #endregion diff --git a/taskt/Core/Automation/Commands/SelectionControls.cs b/taskt/Core/Automation/Commands/SelectionItemsControls.cs similarity index 64% rename from taskt/Core/Automation/Commands/SelectionControls.cs rename to taskt/Core/Automation/Commands/SelectionItemsControls.cs index 38df8445b..180362b00 100644 --- a/taskt/Core/Automation/Commands/SelectionControls.cs +++ b/taskt/Core/Automation/Commands/SelectionItemsControls.cs @@ -9,7 +9,7 @@ namespace taskt.Core.Automation.Commands /// /// methods for PropertyUISelection attributes /// - internal static class SelectionControls + internal static class SelectionItemsControls { /// /// yes no combobox @@ -20,10 +20,11 @@ internal static class SelectionControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyUISelectionOption("Yes")] [PropertyUISelectionOption("No")] + [PropertyParameterOrder(5000)] public static string v_YesNoComboBox { get; } /// - /// private GetUISelectionValue method. This method supports check selection value, first value, case sensitive. This method may use PropertyValidationRule, PropertyDisplayValue, PropertyDescription attributes. + /// private ExpandValueOrUserVariableAsSelectionItem method. This method supports check selection value, first value, case sensitive. This method may use PropertyValidationRule, PropertyDisplayValue, PropertyDescription attributes. /// /// /// @@ -31,7 +32,7 @@ internal static class SelectionControls /// /// /// value is not PropertyUISelectionOption - private static string GetUISelectionValue(PropertyInfo propInfo, string propertyValue, string propertyDescription, Engine.AutomationEngineInstance engine) + private static string ExpandValueOrUserVariableAsSelectionItem(PropertyInfo propInfo, string propertyValue, string propertyDescription, Engine.AutomationEngineInstance engine) { var virtualPropInfo = propInfo.GetVirtualProperty(); @@ -63,7 +64,7 @@ private static string GetUISelectionValue(PropertyInfo propInfo, string property propertyValue = attrIsOpt?.setBlankToValue ?? ""; } - string value = propertyValue.ConvertToUserVariable(engine); + string value = propertyValue.ExpandValueOrUserVariable(engine); var options = GetCustomAttributesWithVirtual(propInfo, virtualPropInfo); if (options.Count() > 0) @@ -110,9 +111,9 @@ private static string GetUISelectionValue(PropertyInfo propInfo, string property /// /// /// - public static string GetUISelectionValue(this ScriptCommand command, string propertyName, Engine.AutomationEngineInstance engine) + public static string ExpandValueOrUserVariableAsSelectionItem(this ScriptCommand command, string propertyName, Engine.AutomationEngineInstance engine) { - return GetUISelectionValue(command, propertyName, "", engine); + return ExpandValueOrUserVariableAsSelectionItem(command, propertyName, "", engine); } /// @@ -124,41 +125,41 @@ public static string GetUISelectionValue(this ScriptCommand command, string prop /// /// /// value is not PropertyUISelectionOption - public static string GetUISelectionValue(this ScriptCommand command, string propertyName, string propertyDescription, Engine.AutomationEngineInstance engine) + public static string ExpandValueOrUserVariableAsSelectionItem(this ScriptCommand command, string propertyName, string propertyDescription, Engine.AutomationEngineInstance engine) { var propInfo = command.GetProperty(propertyName); string propertyValue = propInfo.GetValue(command)?.ToString() ?? ""; - return GetUISelectionValue(propInfo, propertyValue, propertyDescription, engine); + return ExpandValueOrUserVariableAsSelectionItem(propInfo, propertyValue, propertyDescription, engine); } - /// - /// Get selected item value from PropertyConvertTag that specified property name, etc. This method supports check selection value, first value, case sensitive. - /// - /// - /// - /// - /// - /// value is not PropertyUISelectionOption - public static string GetUISelectionValue(this PropertyConvertTag p, ScriptCommand command, Engine.AutomationEngineInstance engine) - { - return GetUISelectionValue(command, p.Name, p.Description, engine); - } + ///// + ///// Get selected item value from PropertyConvertTag that specified property name, etc. This method supports check selection value, first value, case sensitive. + ///// + ///// + ///// + ///// + ///// + ///// value is not PropertyUISelectionOption + //public static string ExpandValueOrUserVariableAsSelectionItem(this PropertyConvertTag p, ScriptCommand command, Engine.AutomationEngineInstance engine) + //{ + // return ExpandValueOrUserVariableAsSelectionItem(command, p.Name, p.Description, engine); + //} - /// - /// Get or Convert to selected item value by specified target value, target property name. This method supports check selection value, first value, case sensitive. - /// - /// - /// - /// - /// - /// - /// value is not PropertyUISelectionOption - public static string GetUISelectionValue(this string text, string propertyName, ScriptCommand command, Engine.AutomationEngineInstance engine) - { - return new PropertyConvertTag(text, propertyName, "").GetUISelectionValue(command, engine); - } + ///// + ///// Get or Convert to selected item value by specified target value, target property name. This method supports check selection value, first value, case sensitive. + ///// + ///// + ///// + ///// + ///// + ///// + ///// value is not PropertyUISelectionOption + //public static string ExpandValueOrUserVariableAsSelectionItem(this string text, string propertyName, ScriptCommand command, Engine.AutomationEngineInstance engine) + //{ + // return new PropertyConvertTag(text, propertyName, "").ExpandValueOrUserVariableAsSelectionItem(command, engine); + //} /// /// Get Yes/No item from Property Name. This method supports check selection value, first value, case sensitive. @@ -168,9 +169,9 @@ public static string GetUISelectionValue(this string text, string propertyName, /// /// /// - public static bool GetYesNoSelectionValue(this ScriptCommand command, string propertyName, Engine.AutomationEngineInstance engine) + public static bool ExpandValueOrUserVariableAsYesNo(this ScriptCommand command, string propertyName, Engine.AutomationEngineInstance engine) { - var sel = command.GetUISelectionValue(propertyName, engine); + var sel = command.ExpandValueOrUserVariableAsSelectionItem(propertyName, engine); switch (sel) { case "yes": diff --git a/taskt/Core/Automation/Commands/SeleniumBrowserControls.cs b/taskt/Core/Automation/Commands/SeleniumBrowserControls.cs index 63fc37b95..e2a9677f2 100644 --- a/taskt/Core/Automation/Commands/SeleniumBrowserControls.cs +++ b/taskt/Core/Automation/Commands/SeleniumBrowserControls.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; +using System.Diagnostics; using System.Linq; using System.Windows.Forms; using OpenQA.Selenium; @@ -14,6 +15,7 @@ namespace taskt.Core.Automation.Commands /// internal static class SeleniumBrowserControls { + #region Virtual Property /// /// instance property /// @@ -29,6 +31,7 @@ internal static class SeleniumBrowserControls [PropertyShowSampleUsageInDescription(true)] [PropertyValidationRule("WebBrowser Instance", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Instance")] + [PropertyParameterOrder(5000)] public static string v_InputInstanceName { get; } /// @@ -56,6 +59,7 @@ internal static class SeleniumBrowserControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyValidationRule("Search Method", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Search Method")] + [PropertyParameterOrder(5000)] public static string v_SearchMethod { get; } /// @@ -69,6 +73,7 @@ internal static class SeleniumBrowserControls [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Search Parameter", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Search Parameter")] + [PropertyParameterOrder(5000)] public static string v_SearchParameter { get; } /// @@ -83,6 +88,7 @@ internal static class SeleniumBrowserControls [Remarks("")] [PropertyShowSampleUsageInDescription(true)] [PropertyTextBoxSetting(1, false)] + [PropertyParameterOrder(5000)] public static string v_ElementIndex { get; } /// @@ -107,6 +113,7 @@ internal static class SeleniumBrowserControls [PropertyDataGridViewSetting(true, true, true)] [PropertyDataGridViewColumnSettings("AttributeName", "Attribute Name")] [PropertyDataGridViewCellEditEvent(nameof(DataTableControls) + "+" + nameof(DataTableControls.AllEditableDataGridView_CellClick), PropertyDataGridViewCellEditEvent.DataGridViewCellEvent.CellClick)] + [PropertyParameterOrder(5000)] public static string v_AttributesName { get; } /// @@ -129,6 +136,7 @@ internal static class SeleniumBrowserControls [PropertyShowSampleUsageInDescription(true)] [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Attribute", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyParameterOrder(5000)] public static string v_AttributeName { get; } /// @@ -143,6 +151,7 @@ internal static class SeleniumBrowserControls [PropertyTextBoxSetting(1, false)] [PropertyIsOptional(true, "120")] [PropertyFirstValue("120")] + [PropertyParameterOrder(5000)] public static string v_WaitTime { get; } /// @@ -159,6 +168,7 @@ internal static class SeleniumBrowserControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("WebElement", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Element")] + [PropertyParameterOrder(5000)] public static string v_InputWebElementName { get; } /// @@ -174,6 +184,7 @@ internal static class SeleniumBrowserControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("WebElement", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Element")] + [PropertyParameterOrder(5000)] public static string v_OutputWebElementName { get; } /// @@ -186,7 +197,9 @@ internal static class SeleniumBrowserControls [PropertyUISelectionOption("Yes")] [PropertyUISelectionOption("No")] [PropertyIsOptional(true, "No")] + [PropertyParameterOrder(5000)] public static string v_ScrollToElement { get; } + #endregion #region methods @@ -200,7 +213,7 @@ internal static class SeleniumBrowserControls /// /// /// - public static IWebElement ConvertToUserVariableAsWebElement(this string str, string parameterName, Engine.AutomationEngineInstance engine) + public static IWebElement ExpandUserVariableAsWebElement(this string str, string parameterName, Engine.AutomationEngineInstance engine) { var v = str.GetRawVariable(engine); if (v.VariableValue is IWebElement e) @@ -228,9 +241,9 @@ public static void StoreInUserVariable(this IWebElement value, Core.Automation.E /// /// /// - public static IWebDriver GetSeleniumBrowserInstance(this string instanceName, Engine.AutomationEngineInstance engine) + public static IWebDriver ExpandValueOrUserVariableAsSeleniumBrowserInstance(this string instanceName, Engine.AutomationEngineInstance engine) { - var vInstance = instanceName.ConvertToUserVariable(engine); + var vInstance = instanceName.ExpandValueOrUserVariable(engine); var browserObject = engine.GetAppInstance(vInstance); if (browserObject is IWebDriver wd) @@ -346,7 +359,7 @@ private static Func GetWebElementSearchMethod(string } /// - /// get instance and searched an element + /// expand value or user variable as instance and searched an webElement /// /// /// @@ -356,7 +369,7 @@ private static Func GetWebElementSearchMethod(string /// /// /// - public static (IWebDriver, IWebElement) GetSeleniumBrowserInstanceAndElement(IWebDriver seleniumInstance, string searchMethod, string searchParameter, int index, int waitTime, Engine.AutomationEngineInstance engine) + public static (IWebDriver, IWebElement) ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElement(IWebDriver seleniumInstance, string searchMethod, string searchParameter, int index, int waitTime, Engine.AutomationEngineInstance engine) { var searchFunc = GetWebElementSearchMethod(searchMethod); @@ -406,7 +419,7 @@ public static (IWebDriver, IWebElement) GetSeleniumBrowserInstanceAndElement(IWe } /// - /// get instance and searched an element + /// expand value or user variable as instance and searched an webElement /// /// /// @@ -416,17 +429,17 @@ public static (IWebDriver, IWebElement) GetSeleniumBrowserInstanceAndElement(IWe /// /// /// - public static (IWebDriver, IWebElement) GetSeleniumBrowserInstanceAndElement(ScriptCommand command, string instanceParameterName, string searchMethodName, string searchParameterName, string elementIndexName, string waitTimeName, Engine.AutomationEngineInstance engine) + public static (IWebDriver, IWebElement) ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElement(ScriptCommand command, string instanceParameterName, string searchMethodName, string searchParameterName, string elementIndexName, string waitTimeName, Engine.AutomationEngineInstance engine) { - var instanceName = command.ConvertToUserVariable(instanceParameterName, "WebBrowser Instance Name", engine); - var seleniumInstance = instanceName.GetSeleniumBrowserInstance(engine); + var instanceName = command.ExpandValueOrUserVariable(instanceParameterName, "WebBrowser Instance Name", engine); + var seleniumInstance = instanceName.ExpandValueOrUserVariableAsSeleniumBrowserInstance(engine); - var searchParameter = command.ConvertToUserVariable(searchParameterName, "Search Parameter", engine); - var searchMethod = command.ConvertToUserVariable(searchMethodName, "Search Method", engine); + var searchParameter = command.ExpandValueOrUserVariable(searchParameterName, "Search Parameter", engine); + var searchMethod = command.ExpandValueOrUserVariable(searchMethodName, "Search Method", engine); - var waitTime = command.ConvertToUserVariableAsInteger(waitTimeName, engine); + var waitTime = command.ExpandValueOrUserVariableAsInteger(waitTimeName, engine); - var indexString = command.GetRawPropertyString(elementIndexName, "Index"); + var indexString = command.GetRawPropertyValueAsString(elementIndexName, "Index"); int index; if (string.IsNullOrEmpty(indexString)) { @@ -434,14 +447,14 @@ public static (IWebDriver, IWebElement) GetSeleniumBrowserInstanceAndElement(Scr } else { - index = command.ConvertToUserVariableAsInteger(elementIndexName, engine); + index = command.ExpandValueOrUserVariableAsInteger(elementIndexName, engine); } - return GetSeleniumBrowserInstanceAndElement(seleniumInstance, searchMethod, searchParameter, index, waitTime, engine); + return ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElement(seleniumInstance, searchMethod, searchParameter, index, waitTime, engine); } /// - /// get instance and searched elements + /// expand value or user variable as instance and searched an webElements /// /// /// @@ -450,7 +463,7 @@ public static (IWebDriver, IWebElement) GetSeleniumBrowserInstanceAndElement(Scr /// /// /// - public static (IWebDriver, List) GetSeleniumBrowserInstanceAndElements(IWebDriver seleniumInstance, string searchMethod, string searchParameter, int waitTime, Engine.AutomationEngineInstance engine) + public static (IWebDriver, List) ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElements(IWebDriver seleniumInstance, string searchMethod, string searchParameter, int waitTime, Engine.AutomationEngineInstance engine) { var searchFunc = GetWebElementSearchMethod(searchMethod); @@ -496,7 +509,7 @@ public static (IWebDriver, List) GetSeleniumBrowserInstanceAndEleme } /// - /// get instance and searched elements + /// expand value or user variable as instance and searched an webElements /// /// /// @@ -505,17 +518,17 @@ public static (IWebDriver, List) GetSeleniumBrowserInstanceAndEleme /// /// /// - public static (IWebDriver, List) GetSeleniumBrowserInstanceAndElements(ScriptCommand command, string instanceParameterName, string searchMethodName, string searchParameterName, string waitTimeName, Engine.AutomationEngineInstance engine) + public static (IWebDriver, List) ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElements(ScriptCommand command, string instanceParameterName, string searchMethodName, string searchParameterName, string waitTimeName, Engine.AutomationEngineInstance engine) { - var instanceName = command.ConvertToUserVariable(instanceParameterName, "WebBrowser Instance Name", engine); - var seleniumInstance = instanceName.GetSeleniumBrowserInstance(engine); + var instanceName = command.ExpandValueOrUserVariable(instanceParameterName, "WebBrowser Instance Name", engine); + var seleniumInstance = instanceName.ExpandValueOrUserVariableAsSeleniumBrowserInstance(engine); - var searchParameter = command.ConvertToUserVariable(searchParameterName, "Search Parameter", engine); - var searchMethod = command.ConvertToUserVariable(searchMethodName, "Search Method", engine); + var searchParameter = command.ExpandValueOrUserVariable(searchParameterName, "Search Parameter", engine); + var searchMethod = command.ExpandValueOrUserVariable(searchMethodName, "Search Method", engine); - var waitTime = command.ConvertToUserVariableAsInteger(waitTimeName, engine); + var waitTime = command.ExpandValueOrUserVariableAsInteger(waitTimeName, engine); - return GetSeleniumBrowserInstanceAndElements(seleniumInstance, searchMethod, searchParameter, waitTime, engine); + return ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElements(seleniumInstance, searchMethod, searchParameter, waitTime, engine); } #endregion @@ -534,7 +547,7 @@ public static void GetElementAttributes(IWebElement elem, DataTable attributes, int rows = attributes.Rows.Count; for (int i = 0; i < rows; i++) { - string attrName = (attributes.Rows[i][0]?.ToString() ?? "").ConvertToUserVariable(engine); + string attrName = (attributes.Rows[i][0]?.ToString() ?? "").ExpandValueOrUserVariable(engine); if (attrName != "") { setValueFunc(attrName, GetAttribute(elem, attrName, engine)); @@ -551,7 +564,7 @@ public static void GetElementAttributes(IWebElement elem, DataTable attributes, /// public static void GetElementsAttribute(List elems, string attributeValue, Engine.AutomationEngineInstance engine, Action setValueFunc) { - var attr = attributeValue.ConvertToUserVariable(engine); + var attr = attributeValue.ExpandValueOrUserVariable(engine); for (int i = 0; i < elems.Count; i++) { setValueFunc(i, attr, GetAttribute(elems[i], attr, engine)); @@ -568,7 +581,7 @@ public static void GetElementsAttribute(List elems, string attribut /// public static string GetAttribute(IWebElement element, string attributeName, Engine.AutomationEngineInstance engine) { - attributeName = attributeName.ConvertToUserVariable(engine); + attributeName = attributeName.ExpandValueOrUserVariable(engine); if (string.IsNullOrEmpty(attributeName)) { throw new Exception("Attribute Name is empty."); @@ -616,6 +629,66 @@ public static string GetAttribute(IWebElement element, string attributeName, Eng #endregion + #region WebElement methods + + public static string CreateXPath(IWebElement elem) + { + // MEMO: it's probably works fine. :-) + + string path = ""; + + var curElem = elem; + var curElemId = curElem.ToString(); + + // DBG + //Debug.WriteLine($"curElem: {curElem.ToString()}, {curElem.GetHashCode()}"); + + var pElem = curElem.FindElement(By.XPath("parent::*")); + while (true) + { + var cElems = pElem.FindElements(By.XPath($"{curElem.TagName.ToLower()}")); + if (cElems.Count > 1) + { + int index = 1; + foreach (var e in cElems) + { + if (e.ToString() == curElemId) + { + break; + } + index++; + } + path = $"/{curElem.TagName.ToLower()}[{index}]{path}"; + } + else + { + path = $"/{curElem.TagName.ToLower()}{path}"; + } + + // DGB + //Debug.WriteLine($"totyu: {path}"); + + if (curElem.TagName.ToLower() == "body") + { + path = $"/html{path}"; + break; + } + else + { + curElem = pElem; + curElemId = curElem.ToString(); + pElem = curElem.FindElement(By.XPath("parent::*")); + } + } + + // DBG + //Debug.WriteLine($"XPath: {path}"); + + return path; + } + + #endregion + #region tag methods public static bool CheckTagName(this IWebElement elem, string tagName) @@ -642,12 +715,12 @@ public static object ExcecuteScript(IWebDriver seleniumInstance, string script) public static void SearchMethodComboBox_SelectionChangeCommitted(Dictionary controlsList, ComboBox searchMethodComboBox, string indexParameterName) { string item = searchMethodComboBox.SelectedItem?.ToString().ToLower() ?? ""; - GeneralPropertyControls.SetVisibleParameterControlGroup(controlsList, indexParameterName, item.StartsWith("find elements")); + FormUIControls.SetVisibleParameterControlGroup(controlsList, indexParameterName, item.StartsWith("find elements")); } public static void ScrollToWebElement_SelectionChange(ComboBox scrollParameter, Dictionary controlsList, string instanceParameterName) { - GeneralPropertyControls.SetVisibleParameterControlGroup(controlsList, instanceParameterName, ((scrollParameter.SelectedItem?.ToString().ToLower() ?? "") != "no")); + FormUIControls.SetVisibleParameterControlGroup(controlsList, instanceParameterName, ((scrollParameter.SelectedItem?.ToString().ToLower() ?? "") != "no")); } #endregion diff --git a/taskt/Core/Automation/Commands/StopWatch/StopwatchCommand.cs b/taskt/Core/Automation/Commands/StopWatch/StopwatchCommand.cs index addd27ace..1e880abfd 100644 --- a/taskt/Core/Automation/Commands/StopWatch/StopwatchCommand.cs +++ b/taskt/Core/Automation/Commands/StopWatch/StopwatchCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("StopWatch Commands")] + [Attributes.ClassAttributes.Group("StopWatch")] [Attributes.ClassAttributes.CommandSettings("StopWatch")] [Attributes.ClassAttributes.Description("This command allows you to stop a program or a process.")] [Attributes.ClassAttributes.UsesDescription("Use this command to close an application by its name such as 'chrome'. Alternatively, you may use the Close Window or Thick App Command instead.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Process.CloseMainWindow'.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class StopwatchCommand : ScriptCommand + public sealed class StopwatchCommand : ScriptCommand { [XmlAttribute] [PropertyDescription("Stopwatch Instance Name")] @@ -72,12 +73,11 @@ public StopwatchCommand() //this.v_StopwatchAction = "Start Stopwatch"; } - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - var instanceName = v_StopwatchName.ConvertToUserVariable(engine); + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var instanceName = v_StopwatchName.ExpandValueOrUserVariable(engine); - var action = this.GetUISelectionValue(nameof(v_StopwatchAction), engine); + var action = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_StopwatchAction), engine); System.Diagnostics.Stopwatch stopwatch; switch (action) { @@ -116,7 +116,7 @@ public override void RunCommand(object sender) } else { - var format = v_ToStringFormat.ConvertToUserVariable(sender); + var format = v_ToStringFormat.ExpandValueOrUserVariable(engine); elapsedTime = stopwatch.Elapsed.ToString(format); } @@ -130,13 +130,13 @@ private void cmbStopWatchComboBox_SelectedValueChanged(object sender, EventArgs var selectedAction = ((ComboBox)sender).SelectedItem?.ToString() ?? ""; if (selectedAction == "Measure Stopwatch") { - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_userVariableName), true); - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_ToStringFormat), true); + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_userVariableName), true); + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_ToStringFormat), true); } else { - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_userVariableName), false); - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_ToStringFormat), false); + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_userVariableName), false); + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_ToStringFormat), false); } } } diff --git a/taskt/Core/Automation/Commands/System/GetEnvironmentVariableCommand.cs b/taskt/Core/Automation/Commands/System/GetEnvironmentVariableCommand.cs index 1ad8cbc1f..07a395d4d 100644 --- a/taskt/Core/Automation/Commands/System/GetEnvironmentVariableCommand.cs +++ b/taskt/Core/Automation/Commands/System/GetEnvironmentVariableCommand.cs @@ -8,14 +8,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("System Commands")] + [Attributes.ClassAttributes.Group("System")] [Attributes.ClassAttributes.CommandSettings("Get Environment Variable")] [Attributes.ClassAttributes.Description("This command allows you to exclusively select a system/environment variable")] [Attributes.ClassAttributes.UsesDescription("Use this command to exclusively retrieve a system variable")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_system))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetEnvironmentVariableCommand : ScriptCommand + public sealed class GetEnvironmentVariableCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -45,13 +46,11 @@ public GetEnvironmentVariableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var variables = Environment.GetEnvironmentVariables(); - var environmentVariable = v_EnvVariableName.ConvertToUserVariable(sender); + var environmentVariable = v_EnvVariableName.ExpandValueOrUserVariable(engine); var keys = variables.Keys.Cast().ToList(); if (keys.Contains(environmentVariable)) { diff --git a/taskt/Core/Automation/Commands/System/GetOSVariableCommand.cs b/taskt/Core/Automation/Commands/System/GetOSVariableCommand.cs index 587428af5..9c9162114 100644 --- a/taskt/Core/Automation/Commands/System/GetOSVariableCommand.cs +++ b/taskt/Core/Automation/Commands/System/GetOSVariableCommand.cs @@ -9,14 +9,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("System Commands")] + [Attributes.ClassAttributes.Group("System")] [Attributes.ClassAttributes.CommandSettings("Get OS Variable")] [Attributes.ClassAttributes.Description("This command allows you to exclusively select a system/environment variable")] [Attributes.ClassAttributes.UsesDescription("Use this command to exclusively retrieve a system variable")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_system))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetOSVariableCommand : ScriptCommand + public sealed class GetOSVariableCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -46,9 +47,9 @@ public GetOSVariableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var systemVariable = v_OSVariableName.ConvertToUserVariable(sender); + var systemVariable = v_OSVariableName.ExpandValueOrUserVariable(engine); ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem"); ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql); @@ -61,11 +62,10 @@ public override void RunCommand(object sender) if (prop.Name == systemVariable) { var sysValue = prop.Value?.ToString() ?? ""; - sysValue.StoreInUserVariable(sender, v_applyToVariableName); + sysValue.StoreInUserVariable(engine, v_applyToVariableName); return; } } - } throw new Exception("System Property '" + systemVariable + "' not found!"); diff --git a/taskt/Core/Automation/Commands/System/LaunchRemoteDesktopCommand.cs b/taskt/Core/Automation/Commands/System/LaunchRemoteDesktopCommand.cs index 02a6353c8..b6be425e6 100644 --- a/taskt/Core/Automation/Commands/System/LaunchRemoteDesktopCommand.cs +++ b/taskt/Core/Automation/Commands/System/LaunchRemoteDesktopCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("System Commands")] + [Attributes.ClassAttributes.Group("System")] [Attributes.ClassAttributes.CommandSettings("Launch Remote Desktop")] [Attributes.ClassAttributes.Description("This command allows you to stop a program or a process.")] [Attributes.ClassAttributes.UsesDescription("Use this command to close an application by its name such as 'chrome'. Alternatively, you may use the Close Window or Thick App Command instead.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Process.CloseMainWindow'.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_system))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class LaunchRemoteDesktopCommand : ScriptCommand + public sealed class LaunchRemoteDesktopCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -44,6 +45,15 @@ public class LaunchRemoteDesktopCommand : ScriptCommand [PropertyDetailSampleUsage("**{{{vPass}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Password")] public string v_Password { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Support CredSSP")] + [PropertyFirstValue("Yes")] + [PropertyIsOptional(true, "Yes")] + [PropertyValidationRule("CredSSP", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + public string v_SupportCredSSP { get; set; } + [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] [PropertyDescription("Width of the RDP Window")] @@ -66,6 +76,21 @@ public class LaunchRemoteDesktopCommand : ScriptCommand [PropertyDisplayText(false, "")] public string v_RDPHeight { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] + [PropertyDescription("Keyboard Hook Mode")] + [PropertyUISelectionOption("Client Computer")] + [PropertyUISelectionOption("Remote Server")] + [PropertyUISelectionOption("Remote Server Only When Full-Screen")] + [PropertyIsOptional(true, "Remote Server Only When Full-Screen")] + [PropertyFirstValue("Remote Server Only When Full-Screen")] + [PropertyDetailSampleUsage("Client Computer", "Windows key and its combination shortcuts work only on the client computer")] + [PropertyDetailSampleUsage("Remote Server", "Windows key and its combination shortcuts work only on the remote server")] + [PropertyDetailSampleUsage("Remote Server Only When Full-Screen", "Windows key and its combination shortcuts work only on the client computer. Remote Desktop cannot be made full screen.")] + [PropertyValidationRule("Keyborad Hook Mode", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(false, "")] + public string v_KeyboadHookMode { get; set; } + public LaunchRemoteDesktopCommand() { //this.CommandName = "RemoteDesktopCommand"; @@ -77,29 +102,41 @@ public LaunchRemoteDesktopCommand() //this.v_RDPHeight = SystemInformation.PrimaryMonitorSize.Height.ToString(); } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var machineName = v_MachineName.ConvertToUserVariable(sender); - var userName = v_UserName.ConvertToUserVariable(sender); - var password = v_Password.ConvertToUserVariable(sender); + var machineName = v_MachineName.ExpandValueOrUserVariable(engine); + var userName = v_UserName.ExpandValueOrUserVariable(engine); + var password = v_Password.ExpandValueOrUserVariable(engine); + var credSsp = this.ExpandValueOrUserVariableAsYesNo(nameof(v_SupportCredSSP), engine); - if (String.IsNullOrEmpty(v_RDPWidth)) + if (string.IsNullOrEmpty(v_RDPWidth)) { v_RDPWidth = SystemInformation.PrimaryMonitorSize.Width.ToString(); } - var width = this.ConvertToUserVariableAsInteger(nameof(v_RDPWidth), engine); + var width = this.ExpandValueOrUserVariableAsInteger(nameof(v_RDPWidth), engine); - if (String.IsNullOrEmpty(v_RDPHeight)) + if (string.IsNullOrEmpty(v_RDPHeight)) { v_RDPHeight = SystemInformation.PrimaryMonitorSize.Height.ToString(); } - var height = this.ConvertToUserVariableAsInteger(nameof(v_RDPHeight), engine); + var height = this.ExpandValueOrUserVariableAsInteger(nameof(v_RDPHeight), engine); + + int keyboardHook = 2; + switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_KeyboadHookMode), engine)) + { + case "client computer": + keyboardHook = 0; + break; + case "remote server": + keyboardHook = 1; + break; + default: + break; + } var result = engine.tasktEngineUI.Invoke(new Action(() => { - engine.tasktEngineUI.LaunchRDPSession(machineName, userName, password, width, height); + engine.tasktEngineUI.LaunchRDPSession(machineName, userName, password, credSsp, width, height, keyboardHook); })); } } diff --git a/taskt/Core/Automation/Commands/System/SystemActionCommand.cs b/taskt/Core/Automation/Commands/System/SystemActionCommand.cs index 9d68a2739..e80e4ee03 100644 --- a/taskt/Core/Automation/Commands/System/SystemActionCommand.cs +++ b/taskt/Core/Automation/Commands/System/SystemActionCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("System Commands")] + [Attributes.ClassAttributes.Group("System")] [Attributes.ClassAttributes.CommandSettings("System Action")] [Attributes.ClassAttributes.Description("This command allows you to perform an account action")] [Attributes.ClassAttributes.UsesDescription("Use this command to perform an action such as logoff, restart, shutdown or restart.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_script))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SystemActionCommand : ScriptCommand + public sealed class SystemActionCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -33,11 +34,9 @@ public SystemActionCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var action = this.GetUISelectionValue(nameof(v_ActionName), engine); + var action = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ActionName), engine); switch (action) { diff --git a/taskt/Core/Automation/Commands/Text/CheckTextCommand.cs b/taskt/Core/Automation/Commands/Text/CheckTextCommand.cs index 20c67b77b..8df0a9963 100644 --- a/taskt/Core/Automation/Commands/Text/CheckTextCommand.cs +++ b/taskt/Core/Automation/Commands/Text/CheckTextCommand.cs @@ -7,15 +7,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Check/Get")] [Attributes.ClassAttributes.CommandSettings("Check Text")] [Attributes.ClassAttributes.Description("This command allows you to check a Text")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check a Text")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CheckTextCommand : ScriptCommand + public sealed class CheckTextCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -77,21 +78,19 @@ public CheckTextCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var targetValue = v_userVariableName.ExpandValueOrUserVariable(engine); + var checkValue = v_CheckParameter.ExpandValueOrUserVariable(engine); - var targetValue = v_userVariableName.ConvertToUserVariable(engine); - var checkValue = v_CheckParameter.ConvertToUserVariable(engine); - - var caseSensitive = this.GetUISelectionValue(nameof(v_CaseSensitive), engine); + var caseSensitive = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_CaseSensitive), engine); if (caseSensitive == "no") { targetValue = targetValue.ToLower(); checkValue = checkValue.ToLower(); } - var checkMethod = this.GetUISelectionValue(nameof(v_CheckMethod), engine); + var checkMethod = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_CheckMethod), engine); bool resultValue = false; switch (checkMethod) { diff --git a/taskt/Core/Automation/Commands/Text/ConcatenateTextVariableCommand.cs b/taskt/Core/Automation/Commands/Text/ConcatenateTextVariableCommand.cs index 12e971201..4c6eacf9c 100644 --- a/taskt/Core/Automation/Commands/Text/ConcatenateTextVariableCommand.cs +++ b/taskt/Core/Automation/Commands/Text/ConcatenateTextVariableCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Concatenate Text Variable")] [Attributes.ClassAttributes.Description("This command allows you to you to concatenate text to Text Variable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to concatenate text to Text Variable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ConcatenateTextVariableCommand : ScriptCommand + public sealed class ConcatenateTextVariableCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_OutputTextVariableName))] @@ -55,17 +56,14 @@ public ConcatenateTextVariableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get engine - var engine = (Engine.AutomationEngineInstance)sender; - var targetVariable = VariableNameControls.GetWrappedVariableName(v_TargetVariable, engine); - var text = targetVariable.ConvertToUserVariable(engine); - var con = v_ConcatText.ConvertToUserVariable(engine); + var text = targetVariable.ExpandValueOrUserVariable(engine); + var con = v_ConcatText.ExpandValueOrUserVariable(engine); - var insertNewLine = this.GetUISelectionValue(nameof(v_InsertNewLine), "Insert New Line", engine); - var concatPosition = this.GetUISelectionValue(nameof(v_ConcatenatePosition), "Concatenate Position", engine); + var insertNewLine = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_InsertNewLine), "Insert New Line", engine); + var concatPosition = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ConcatenatePosition), "Concatenate Position", engine); switch (insertNewLine) { diff --git a/taskt/Core/Automation/Commands/Text/CreateTextVariableCommand.cs b/taskt/Core/Automation/Commands/Text/CreateTextVariableCommand.cs index d459be21d..963178375 100644 --- a/taskt/Core/Automation/Commands/Text/CreateTextVariableCommand.cs +++ b/taskt/Core/Automation/Commands/Text/CreateTextVariableCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Create Text Variable")] [Attributes.ClassAttributes.Description("This command allows you to create text variables.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create text variables.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CreateTextVariableCommand : ScriptCommand + public sealed class CreateTextVariableCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_OutputTextVariableName))] @@ -31,12 +32,9 @@ public CreateTextVariableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - - var valueToSet = v_Value.ConvertToUserVariable(engine); + var valueToSet = v_Value.ExpandValueOrUserVariable(engine); valueToSet.StoreInUserVariable(engine, v_userVariableName); } } diff --git a/taskt/Core/Automation/Commands/Text/EncryptDecryptTextCommand.cs b/taskt/Core/Automation/Commands/Text/EncryptDecryptTextCommand.cs index 071c1fb35..cf61bb63c 100644 --- a/taskt/Core/Automation/Commands/Text/EncryptDecryptTextCommand.cs +++ b/taskt/Core/Automation/Commands/Text/EncryptDecryptTextCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Encrypt Decrypt Text")] [Attributes.ClassAttributes.Description("This command handles text encryption")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to store some data encrypted")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class EncryptDecryptTextCommand : ScriptCommand + public sealed class EncryptDecryptTextCommand : ScriptCommand { [XmlElement] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -53,17 +54,15 @@ public EncryptDecryptTextCommand() //this.v_PassPhrase = "TASKT"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //get variablized input - var variableInput = v_InputValue.ConvertToUserVariable(engine); - var passphrase = v_PassPhrase.ConvertToUserVariable(engine); + var variableInput = v_InputValue.ExpandValueOrUserVariable(engine); + var passphrase = v_PassPhrase.ExpandValueOrUserVariable(engine); string resultData = ""; - var encType = this.GetUISelectionValue(nameof(v_EncryptionType), engine); + var encType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_EncryptionType), engine); switch (encType) { case "encrypt": diff --git a/taskt/Core/Automation/Commands/Text/ExtractionTextCommand.cs b/taskt/Core/Automation/Commands/Text/ExtractionTextCommand.cs index 4c00e5036..e593a2319 100644 --- a/taskt/Core/Automation/Commands/Text/ExtractionTextCommand.cs +++ b/taskt/Core/Automation/Commands/Text/ExtractionTextCommand.cs @@ -9,15 +9,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Extraction Text")] [Attributes.ClassAttributes.Description("This command allows you to perform advanced string extraction.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to extract a piece of text from a larger text or variable")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ExtractionTextCommand : ScriptCommand + public sealed class ExtractionTextCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -76,16 +77,14 @@ public ExtractionTextCommand() //this.v_TextExtractionTable.Columns.Add("Parameter Value"); } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //get variablized input - var variableInput = v_InputValue.ConvertToUserVariable(engine); + var variableInput = v_InputValue.ExpandValueOrUserVariable(engine); var parms = DataTableControls.GetFieldValues(v_TextExtractionTable, "Parameter Name", "Parameter Value", engine); string extractedText = ""; - switch (this.GetUISelectionValue(nameof(v_TextExtractionType), engine)) + switch (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_TextExtractionType), engine)) { case "extract all after text": extractedText = ExtractLeadingText(variableInput, parms, engine); @@ -103,7 +102,7 @@ public override void RunCommand(object sender) } //store variable - extractedText.StoreInUserVariable(sender, v_applyToVariableName); + extractedText.StoreInUserVariable(engine, v_applyToVariableName); } private void cmbTextExtraction_SelectionChangeCommitted(object sender, EventArgs e) @@ -149,7 +148,7 @@ private static string ExtractLeadingText(string targetText, Dictionary SearchTextPositions(string targetText, string searchTex } return positions; } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_TextExtractionTable)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_TextExtractionTable); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Text/GetWordCountCommand.cs b/taskt/Core/Automation/Commands/Text/GetWordCountCommand.cs index 9e1059b1f..c650af3fd 100644 --- a/taskt/Core/Automation/Commands/Text/GetWordCountCommand.cs +++ b/taskt/Core/Automation/Commands/Text/GetWordCountCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Check/Get")] [Attributes.ClassAttributes.CommandSettings("Get Word Count")] [Attributes.ClassAttributes.Description("This command allows you to you to retrieve the word count of a Text or Variable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to find word count of a Text or Variable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetWordCountCommand : ScriptCommand + public sealed class GetWordCountCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -32,13 +33,10 @@ public GetWordCountCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get engine - var engine = (Engine.AutomationEngineInstance)sender; - //get input value - var stringRequiringCount = v_InputValue.ConvertToUserVariable(engine); + var stringRequiringCount = v_InputValue.ExpandValueOrUserVariable(engine); //count number of words var wordCount = stringRequiringCount.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries).Length; diff --git a/taskt/Core/Automation/Commands/Text/GetWordLengthCommand.cs b/taskt/Core/Automation/Commands/Text/GetWordLengthCommand.cs index aa4610c98..d98a3a916 100644 --- a/taskt/Core/Automation/Commands/Text/GetWordLengthCommand.cs +++ b/taskt/Core/Automation/Commands/Text/GetWordLengthCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Check/Get")] [Attributes.ClassAttributes.CommandSettings("Get Word Length")] [Attributes.ClassAttributes.Description("This command allows you to retrieve the length of a Text or Variable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to find the length of a Text or Variable")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetWordLengthCommand : ScriptCommand + public sealed class GetWordLengthCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -31,13 +32,10 @@ public GetWordLengthCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get engine - var engine = (Engine.AutomationEngineInstance)sender; - //get input value - var stringRequiringLength = v_InputValue.ConvertToUserVariable(engine); + var stringRequiringLength = v_InputValue.ExpandValueOrUserVariable(engine); ////count number of words //var stringLength = stringRequiringLength.Length; diff --git a/taskt/Core/Automation/Commands/Text/ModifyTextCommand.cs b/taskt/Core/Automation/Commands/Text/ModifyTextCommand.cs index ec940d725..d812c3368 100644 --- a/taskt/Core/Automation/Commands/Text/ModifyTextCommand.cs +++ b/taskt/Core/Automation/Commands/Text/ModifyTextCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Modify Text")] [Attributes.ClassAttributes.Description("This command allows you to trim Text, convert Text, etc.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to trim Text, convert Text, etc.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ModifyTextCommand : ScriptCommand + public sealed class ModifyTextCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -47,14 +48,12 @@ public ModifyTextCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var stringValue = v_userVariableName.ConvertToUserVariable(engine); + var stringValue = v_userVariableName.ExpandValueOrUserVariable(engine); //var caseType = v_ConvertType.ConvertToUserVariable(sender); - var caseType = this.GetUISelectionValue(nameof(v_ConvertType), engine); + var caseType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ConvertType), engine); switch (caseType) { case "to upper case": diff --git a/taskt/Core/Automation/Commands/Text/ReadTextFileCommand.cs b/taskt/Core/Automation/Commands/Text/ReadTextFileCommand.cs index 588c9eae7..32c8d2f70 100644 --- a/taskt/Core/Automation/Commands/Text/ReadTextFileCommand.cs +++ b/taskt/Core/Automation/Commands/Text/ReadTextFileCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("File")] [Attributes.ClassAttributes.CommandSettings("Read Text File")] [Attributes.ClassAttributes.Description("This command allows you to read text file into a variable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to read data from text files.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ReadTextFileCommand : ScriptCommand + public sealed class ReadTextFileCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_FilePath))] @@ -47,10 +48,8 @@ public ReadTextFileCommand() //this.v_ReadOption = "Content"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //bool isURL = FilePathControls.IsURL(v_FilePath.ConvertToUserVariable(engine)); //string result; @@ -82,7 +81,7 @@ public override void RunCommand(object sender) WebClient webClient = new WebClient(); webClient.Encoding = System.Text.Encoding.UTF8; webClient.Headers.Add("user-agent", "request"); - result = webClient.DownloadString(v_FilePath.ConvertToUserVariable(engine)); + result = webClient.DownloadString(v_FilePath.ExpandValueOrUserVariable(engine)); } else { @@ -90,7 +89,7 @@ public override void RunCommand(object sender) } //var readPreference = v_ReadOption.GetUISelectionValue("v_ReadOption", this, engine); - var readPreference = this.GetUISelectionValue(nameof(v_ReadOption), engine); + var readPreference = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ReadOption), engine); if (readPreference == "line count") { result = result.Replace("\r\n", "\n"); // \n\n -> \n diff --git a/taskt/Core/Automation/Commands/Text/RegExExtractionTextCommand.cs b/taskt/Core/Automation/Commands/Text/RegExExtractionTextCommand.cs index 0270e89c1..c3a1bea37 100644 --- a/taskt/Core/Automation/Commands/Text/RegExExtractionTextCommand.cs +++ b/taskt/Core/Automation/Commands/Text/RegExExtractionTextCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("RegEx Extraction Text")] [Attributes.ClassAttributes.Description("This command allows you to perform advanced string formatting using RegEx.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to perform an advanced RegEx extraction from a text or variable")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class RegExExtractionTextCommand : ScriptCommand + public sealed class RegExExtractionTextCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -60,10 +61,8 @@ public RegExExtractionTextCommand() //v_MatchGroupIndex = "0"; } - public override void RunCommand(object sender) - { - var engine = (Engine.AutomationEngineInstance)sender; - + public override void RunCommand(Engine.AutomationEngineInstance engine) + { ////get variablized strings //var variableInput = v_InputValue.ConvertToUserVariable(engine); //var variableExtractorPattern = v_RegExExtractor.ConvertToUserVariable(engine); @@ -86,14 +85,14 @@ public override void RunCommand(object sender) // matchedValue.StoreInUserVariable(sender, v_applyToVariableName); //} - var variableInput = v_InputValue.ConvertToUserVariable(engine); - var variableExtractorPattern = v_RegExExtractor.ConvertToUserVariable(engine); + var variableInput = v_InputValue.ExpandValueOrUserVariable(engine); + var variableExtractorPattern = v_RegExExtractor.ExpandValueOrUserVariable(engine); var regex = new Regex(variableExtractorPattern); var matches = regex.Match(variableInput); if (matches.Groups.Count > 0) { - var matchGroup = this.ConvertToUserVariableAsInteger(nameof(v_MatchGroupIndex), engine); + var matchGroup = this.ExpandValueOrUserVariableAsInteger(nameof(v_MatchGroupIndex), engine); if (matchGroup < 0) { diff --git a/taskt/Core/Automation/Commands/Text/ReplaceTextCommand.cs b/taskt/Core/Automation/Commands/Text/ReplaceTextCommand.cs index 039071913..d6b6396d7 100644 --- a/taskt/Core/Automation/Commands/Text/ReplaceTextCommand.cs +++ b/taskt/Core/Automation/Commands/Text/ReplaceTextCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Replace Text")] [Attributes.ClassAttributes.Description("This command allows you to replace text")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to replace existing text within text or a variable with new text")] [Attributes.ClassAttributes.ImplementationDescription("This command uses the String.Substring method to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ReplaceTextCommand : ScriptCommand + public sealed class ReplaceTextCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -53,16 +54,14 @@ public ReplaceTextCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //get full text - string targetText = v_userVariableName.ConvertToUserVariable(engine); + string targetText = v_userVariableName.ExpandValueOrUserVariable(engine); //get replacement text and value - string replacementText = v_replacementText.ConvertToUserVariable(engine); - string replacementValue = v_replacementValue.ConvertToUserVariable(engine); + string replacementText = v_replacementText.ExpandValueOrUserVariable(engine); + string replacementValue = v_replacementValue.ExpandValueOrUserVariable(engine); //perform replacement targetText = targetText.Replace(replacementText, replacementValue); diff --git a/taskt/Core/Automation/Commands/Text/SplitTextCommand.cs b/taskt/Core/Automation/Commands/Text/SplitTextCommand.cs index 59f4649cd..a72bd458c 100644 --- a/taskt/Core/Automation/Commands/Text/SplitTextCommand.cs +++ b/taskt/Core/Automation/Commands/Text/SplitTextCommand.cs @@ -8,15 +8,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Split Text")] [Attributes.ClassAttributes.Description("This command allows you to split a Text")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to split a single Text or variable into multiple items")] [Attributes.ClassAttributes.ImplementationDescription("This command uses the String.Split method to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SplitTextCommand : ScriptCommand + public sealed class SplitTextCommand : ScriptCommand, ICanHandleList { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -48,13 +49,11 @@ public SplitTextCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var stringVariable = v_userVariableName.ExpandValueOrUserVariable(engine); - var stringVariable = v_userVariableName.ConvertToUserVariable(engine); - - var split = v_splitCharacter.ConvertToUserVariable(engine); + var split = v_splitCharacter.ExpandValueOrUserVariable(engine); List splitString; switch (split) @@ -70,7 +69,8 @@ public override void RunCommand(object sender) break; } - splitString.StoreInUserVariable(engine, v_applyConvertToUserVariableName); + //splitString.StoreInUserVariable(engine, v_applyConvertToUserVariableName); + this.StoreListInUserVariable(splitString, nameof(v_applyConvertToUserVariableName), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Text/SubstringTextCommand.cs b/taskt/Core/Automation/Commands/Text/SubstringTextCommand.cs index 87c85bec3..e38a87bee 100644 --- a/taskt/Core/Automation/Commands/Text/SubstringTextCommand.cs +++ b/taskt/Core/Automation/Commands/Text/SubstringTextCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("Action")] [Attributes.ClassAttributes.CommandSettings("Substring Text")] [Attributes.ClassAttributes.Description("This command allows you to trim a Text")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to select a subset of text or variable")] [Attributes.ClassAttributes.ImplementationDescription("This command uses the String.Substring method to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SubstringTextCommand : ScriptCommand + public sealed class SubstringTextCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_Text_MultiLine))] @@ -55,14 +56,12 @@ public SubstringTextCommand() //v_stringLength = "-1"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var variableName = v_userVariableName.ExpandValueOrUserVariable(engine); - var variableName = v_userVariableName.ConvertToUserVariable(engine); - - var startIndex = this.ConvertToUserVariableAsInteger(nameof(v_startIndex), engine); - var stringLength = this.ConvertToUserVariableAsInteger(nameof(v_stringLength), engine); + var startIndex = this.ExpandValueOrUserVariableAsInteger(nameof(v_startIndex), engine); + var stringLength = this.ExpandValueOrUserVariableAsInteger(nameof(v_stringLength), engine); //apply substring string subStr; diff --git a/taskt/Core/Automation/Commands/Text/WriteTextFileCommand.cs b/taskt/Core/Automation/Commands/Text/WriteTextFileCommand.cs index 817c22b6f..709643427 100644 --- a/taskt/Core/Automation/Commands/Text/WriteTextFileCommand.cs +++ b/taskt/Core/Automation/Commands/Text/WriteTextFileCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Text Commands")] + [Attributes.ClassAttributes.Group("Text")] [Attributes.ClassAttributes.SubGruop("File")] [Attributes.ClassAttributes.CommandSettings("Write Text File")] [Attributes.ClassAttributes.Description("This command writes specified data to a text file")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to write data to text files.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements '' to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_files))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WriteTextFileCommand : ScriptCommand + public sealed class WriteTextFileCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(TextControls), nameof(TextControls.v_FilePath))] @@ -49,10 +50,8 @@ public WriteTextFileCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //convert variables //string filePath; //if (FilePathControls.ContainsFileCounter(v_FilePath, engine)) @@ -63,16 +62,16 @@ public override void RunCommand(object sender) //{ // filePath = FilePathControls.FormatFilePath_NoFileCounter(v_FilePath, engine, "txt"); //} - var filePath = this.ConvertToUserVariableAsFilePath(nameof(v_FilePath), engine); + var filePath = this.ExpandValueOrUserVariableAsFilePath(nameof(v_FilePath), engine); //var outputText = v_TextToWrite.ConvertToUserVariable(sender).ToString().Replace("[crLF]",Environment.NewLine); - var outputText = v_TextToWrite.ConvertToUserVariable(engine); - if (this.GetUISelectionValue(nameof(v_ReplaceToLineBreak), engine) == "yes") + var outputText = v_TextToWrite.ExpandValueOrUserVariable(engine); + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ReplaceToLineBreak), engine) == "yes") { outputText = outputText.Replace("[crLF]", Environment.NewLine); } - var isOverwrite = this.GetUISelectionValue(nameof(v_Overwrite), engine); + var isOverwrite = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_Overwrite), engine); //append or overwrite as necessary if (isOverwrite == "append") { diff --git a/taskt/Core/Automation/Commands/TextControls.cs b/taskt/Core/Automation/Commands/TextControls.cs index dcbbdf310..038e3ada4 100644 --- a/taskt/Core/Automation/Commands/TextControls.cs +++ b/taskt/Core/Automation/Commands/TextControls.cs @@ -1,4 +1,6 @@ -using taskt.Core.Automation.Attributes.PropertyAttributes; +using System.Text; +using System; +using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { @@ -7,6 +9,7 @@ namespace taskt.Core.Automation.Commands /// internal static class TextControls { + #region Virtual Property /// /// text /// @@ -19,6 +22,7 @@ internal static class TextControls [PropertyShowSampleUsageInDescription(true)] [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyDisplayText(true, "Text")] + [PropertyParameterOrder(5000)] public static string v_Text { get; } /// @@ -34,6 +38,7 @@ internal static class TextControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.MultiLineTextBox)] [PropertyDisplayText(true, "Text")] + [PropertyParameterOrder(5000)] public static string v_Text_MultiLine { get; } /// @@ -50,6 +55,7 @@ internal static class TextControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("Variable", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Variable")] + [PropertyParameterOrder(5000)] public static string v_OutputTextVariableName { get; set; } @@ -68,6 +74,45 @@ internal static class TextControls [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("File Path", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Path")] + [PropertyParameterOrder(5000)] public static string v_FilePath { get; } + #endregion + + public static string ConvertToBase64(this string text) + { + return ConvertToBase64(text, Encoding.UTF8); + } + + public static string ConvertToBase64(this string text, Encoding encoding) + { + byte[] textAsBytes = encoding.GetBytes(text); + return Convert.ToBase64String(textAsBytes); + } + + public static bool TryParseBase64(this string text, out string decodedText) + { + return TryParseBase64(text, Encoding.UTF8, out decodedText); + } + + public static bool TryParseBase64(this string text, Encoding encoding, out string decodedText) + { + if (string.IsNullOrEmpty(text)) + { + decodedText = text; + return false; + } + + try + { + byte[] textAsBytes = Convert.FromBase64String(text); + decodedText = encoding.GetString(textAsBytes); + return true; + } + catch (Exception) + { + decodedText = null; + return false; + } + } } } diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationCheckUIElementExistByXPathCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationCheckUIElementExistByXPathCommand.cs index 8547fafa6..db5e9c258 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationCheckUIElementExistByXPathCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationCheckUIElementExistByXPathCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement")] [Attributes.ClassAttributes.CommandSettings("Check UIElement Exist By XPath")] [Attributes.ClassAttributes.Description("This command allows you to check UIElement existence.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to check UIElement existence.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationCheckUIElementExistByXPathCommand : ScriptCommand + public sealed class UIAutomationCheckUIElementExistByXPathCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -42,10 +43,8 @@ public UIAutomationCheckUIElementExistByXPathCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - try { UIElementControls.SearchGUIElementByXPath(this, engine); diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationCheckUIElementExistCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationCheckUIElementExistCommand.cs index c6f549375..d0825980a 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationCheckUIElementExistCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationCheckUIElementExistCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement")] [Attributes.ClassAttributes.CommandSettings("Check UIElement Exist")] [Attributes.ClassAttributes.Description("This command allows you to to check UIElement existence.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to check UIElement existence")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationCheckUIElementExistCommand : ScriptCommand + public sealed class UIAutomationCheckUIElementExistCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -31,8 +32,8 @@ public class UIAutomationCheckUIElementExistCommand : ScriptCommand [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_WaitTime))] - [PropertyIsOptional(true, "0")] - [PropertyFirstValue("0")] + //[PropertyIsOptional(true, "0")] + //[PropertyFirstValue("0")] public string v_WaitTime { get; set; } public UIAutomationCheckUIElementExistCommand() @@ -43,10 +44,8 @@ public UIAutomationCheckUIElementExistCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - try { UIElementControls.SearchGUIElement(this, engine); @@ -58,10 +57,18 @@ public override void RunCommand(object sender) } } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { //AutomationElementControls.RenderSearchParameterDataGridView((DataGridView)ControlsList[nameof(v_SearchParameters)]); UIElementControls.RenderSearchParameterDataGridView(ControlsList.GetPropertyControl(nameof(v_SearchParameters))); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_SearchParameters)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_SearchParameters); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationClickUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationClickUIElementCommand.cs index 453e0e8bc..39c2aaff3 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationClickUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationClickUIElementCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("UIElement Action")] [Attributes.ClassAttributes.CommandSettings("Click UIElement")] [Attributes.ClassAttributes.Description("This command allows you to Click UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to Click UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationClickUIElementCommand : ScriptCommand + public sealed class UIAutomationClickUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -32,7 +33,7 @@ public class UIAutomationClickUIElementCommand : ScriptCommand public string v_YOffset { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Activate Window before Click")] [PropertyIsOptional(true, "Yes")] public string v_ActivateWindow { get; set; } @@ -45,20 +46,18 @@ public UIAutomationClickUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetElement = v_TargetElement.GetUIElementVariable(engine); + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); string windowName = UIElementControls.GetWindowName(targetElement); - if (this.GetYesNoSelectionValue(nameof(v_ActivateWindow), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ActivateWindow), engine)) { var activateWindow = new ActivateWindowCommand() { v_WindowName = windowName }; - activateWindow.RunCommand(sender); + activateWindow.RunCommand(engine); } System.Windows.Point point; @@ -69,10 +68,10 @@ public override void RunCommand(object sender) var moveWindow = new MoveWindowCommand() { v_WindowName = windowName, - v_XWindowPosition = "0", - v_YWindowPosition = "0" + v_XPosition = "0", + v_YPosition = "0" }; - moveWindow.RunCommand(sender); + moveWindow.RunCommand(engine); targetElement.TryGetClickablePoint(out point); } if ((point.X < 0.0) || (point.Y < 0.0)) @@ -80,10 +79,10 @@ public override void RunCommand(object sender) var moveWindow = new MoveWindowCommand() { v_WindowName = windowName, - v_XWindowPosition = "0", - v_YWindowPosition = "0" + v_XPosition = "0", + v_YPosition = "0" }; - moveWindow.RunCommand(sender); + moveWindow.RunCommand(engine); if (!targetElement.TryGetClickablePoint(out point)) { @@ -96,9 +95,9 @@ public override void RunCommand(object sender) throw new Exception("No Clickable Point in UIElement '" + v_TargetElement + "'"); } - var click = this.GetUISelectionValue(nameof(v_ClickType), engine); - var xAd = this.ConvertToUserVariableAsInteger(nameof(v_XOffset), engine); - var yAd = this.ConvertToUserVariableAsInteger(nameof(v_YOffset), engine); + var click = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ClickType), engine); + var xAd = this.ExpandValueOrUserVariableAsInteger(nameof(v_XOffset), engine); + var yAd = this.ExpandValueOrUserVariableAsInteger(nameof(v_YOffset), engine); var mouseClick = new MoveMouseCommand() { @@ -106,7 +105,7 @@ public override void RunCommand(object sender) v_XMousePosition = (point.X + xAd).ToString(), v_YMousePosition = (point.Y + yAd).ToString() }; - mouseClick.RunCommand(sender); + mouseClick.RunCommand(engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationExpandCollapseItemsInUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationExpandCollapseItemsInUIElementCommand.cs index 51152e3b5..56054fcd2 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationExpandCollapseItemsInUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationExpandCollapseItemsInUIElementCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("UIElement Action")] [Attributes.ClassAttributes.CommandSettings("Expand Collapse Items In UIElement")] [Attributes.ClassAttributes.Description("This command allows you to Expand or Collapse Items in UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to Expand or Collapse Items in UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationExpandCollapseItemsInUIElementCommand : ScriptCommand + public sealed class UIAutomationExpandCollapseItemsInUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -40,12 +41,11 @@ public UIAutomationExpandCollapseItemsInUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetElement = v_TargetElement.GetUIElementVariable(engine); - var state = v_ItemsState.GetUISelectionValue("v_ItemsState", this, engine); + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); + //var state = v_ItemsState.ExpandValueOrUserVariableAsSelectionItem("v_ItemsState", this, engine); + var state = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ItemsState), engine); if (targetElement.TryGetCurrentPattern(ExpandCollapsePattern.Pattern, out object exColPtn)) { diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetChildrenUIElementsInformationCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetChildrenUIElementsInformationCommand.cs index 13de4d13a..f8cbd25e8 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetChildrenUIElementsInformationCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetChildrenUIElementsInformationCommand.cs @@ -8,14 +8,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Get From UIElement")] [Attributes.ClassAttributes.CommandSettings("Get Children Elements Information")] [Attributes.ClassAttributes.Description("This command allows you to get Children UIElements Information from UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get Children UIElements Information from UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationGetChildrenUIElementsInformationCommand : ScriptCommand + public sealed class UIAutomationGetChildrenUIElementsInformationCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -37,11 +38,9 @@ public UIAutomationGetChildrenUIElementsInformationCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetElement = v_RootElement.GetUIElementVariable(engine); + var targetElement = v_RootElement.ExpandUserVariableAsUIElement(engine); var elems = UIElementControls.GetChildrenUIElements(targetElement, v_SearchParameters, engine); @@ -56,10 +55,18 @@ public override void RunCommand(object sender) result.Trim().StoreInUserVariable(engine, v_ResultVariable); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { //AutomationElementControls.RenderSearchParameterDataGridView((DataGridView)ControlsList[nameof(v_SearchParameters)]); UIElementControls.RenderSearchParameterDataGridView(ControlsList.GetPropertyControl(nameof(v_SearchParameters))); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_SearchParameters)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_SearchParameters); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetPropertyValueFromUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetPropertyValueFromUIElementCommand.cs index d29b6ac8d..7fa2bb351 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetPropertyValueFromUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetPropertyValueFromUIElementCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Get From UIElement")] [Attributes.ClassAttributes.CommandSettings("Get Property Value From UIElement")] [Attributes.ClassAttributes.Description("This command allows you to get Property Value from UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get Property Value from UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationGetPropertyValueFromUIElementCommand : ScriptCommand + public sealed class UIAutomationGetPropertyValueFromUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -56,13 +57,11 @@ public UIAutomationGetPropertyValueFromUIElementCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); - var targetElement = v_TargetElement.GetUIElementVariable(engine); - - var propName = this.GetUISelectionValue(nameof(v_PropertyName), engine); + var propName = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_PropertyName), engine); switch (propName) { case "name": diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetSelectedStateFromUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetSelectedStateFromUIElementCommand.cs index d6bbd8fc0..5e0babdb9 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetSelectedStateFromUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetSelectedStateFromUIElementCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Get From UIElement")] [Attributes.ClassAttributes.CommandSettings("Get Selected State From UIElement")] [Attributes.ClassAttributes.Description("This command allows you to get Selected State from UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get Selected State from UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationGetSelectedStateFromUIElementCommand : ScriptCommand + public sealed class UIAutomationGetSelectedStateFromUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -33,11 +34,9 @@ public UIAutomationGetSelectedStateFromUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetElement = v_TargetElement.GetUIElementVariable(engine); + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); bool checkState; if (targetElement.TryGetCurrentPattern(TogglePattern.Pattern, out object patternObj)) diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetSelectionItemsFromUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetSelectionItemsFromUIElementCommand.cs index 931233612..2f0deec94 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetSelectionItemsFromUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetSelectionItemsFromUIElementCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Get From UIElement")] [Attributes.ClassAttributes.CommandSettings("Get Selection Items From UIElement")] [Attributes.ClassAttributes.Description("This command allows you to get Selection Items Name from UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get Selection Items Name from UIElement. Search for only Child Elements.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationGetSelectionItemsFromUIElementCommand : ScriptCommand + public sealed class UIAutomationGetSelectionItemsFromUIElementCommand : ScriptCommand, ICanHandleList { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -32,20 +33,19 @@ public UIAutomationGetSelectionItemsFromUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetElement = v_TargetElement.GetUIElementVariable(engine); + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); var items = UIElementControls.GetSelectionItems(targetElement); - List res = new List(); + var res = new List(); foreach(var item in items) { res.Add(item.Current.Name); } - res.StoreInUserVariable(engine, v_ListVariable); + //res.StoreInUserVariable(engine, v_ListVariable); + this.StoreListInUserVariable(res, nameof(v_ListVariable), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetTextFromTableUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetTextFromTableUIElementCommand.cs index 4d9562ffa..2b6f28ce7 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetTextFromTableUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetTextFromTableUIElementCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Get From UIElement")] [Attributes.ClassAttributes.CommandSettings("Get Text From Table UIElement")] [Attributes.ClassAttributes.Description("This command allows you to get Text Value from Table UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get Text Value from Table UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationGetTextFromTableUIElementCommand : ScriptCommand + public sealed class UIAutomationGetTextFromTableUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -54,13 +55,11 @@ public UIAutomationGetTextFromTableUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetElement = v_TargetElement.GetUIElementVariable(engine); - int row = v_Row.ConvertToUserVariableAsInteger("v_Row", engine); - int column = v_Column.ConvertToUserVariableAsInteger("v_Column", engine); + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); + int row = v_Row.ExpandValueOrUserVariableAsInteger("v_Row", engine); + int column = v_Column.ExpandValueOrUserVariableAsInteger("v_Column", engine); AutomationElement cellElem = UIElementControls.GetTableUIElement(targetElement, row, column); diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetTextFromUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetTextFromUIElementCommand.cs index 47be41ed6..d3f8bf0ab 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetTextFromUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetTextFromUIElementCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Get From UIElement")] [Attributes.ClassAttributes.CommandSettings("Get Text From UIElement")] [Attributes.ClassAttributes.Description("This command allows you to get Text Value from UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get Text Value from UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationGetTextFromUIElementCommand : ScriptCommand + public sealed class UIAutomationGetTextFromUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -31,11 +32,9 @@ public UIAutomationGetTextFromUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetElement = v_TargetElement.GetUIElementVariable(engine); + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); string res = UIElementControls.GetTextValue(targetElement); res.StoreInUserVariable(engine, v_TextVariable); diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetUIElementPositionCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetUIElementPositionCommand.cs new file mode 100644 index 000000000..9943e0e64 --- /dev/null +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetUIElementPositionCommand.cs @@ -0,0 +1,97 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("UIAutomation")] + [Attributes.ClassAttributes.SubGruop("Get From UIElement")] + [Attributes.ClassAttributes.CommandSettings("Get UIElement Position")] + [Attributes.ClassAttributes.Description("This command allows you to get UIElement Position.")] + [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get UIElement Position.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class UIAutomationGetUIElementPositionCommand : ScriptCommand + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] + public string v_TargetElement { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] + [PropertyDescription("Variable Name to Store X Position")] + [PropertyIsOptional(true)] + [PropertyValidationRule("X Position", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "X")] + public string v_XPosition { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] + [PropertyDescription("Variable Name to Store Y Position")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Y Position", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Y Position")] + public string v_YPosition { get; set; } + + [XmlAttribute] + [PropertyDescription("Base position")] + [InputSpecification("", true)] + [SampleUsage("")] + [Remarks("")] + [PropertyUISelectionOption("Top Left")] + [PropertyUISelectionOption("Bottom Right")] + [PropertyUISelectionOption("Top Right")] + [PropertyUISelectionOption("Bottom Left")] + [PropertyUISelectionOption("Center")] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyIsOptional(true, "Top Left")] + public string v_PositionBase { get; set; } + + public UIAutomationGetUIElementPositionCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); + + var rct = targetElement.Current.BoundingRectangle; + + double x = 0.0, y = 0.0; + switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_PositionBase), engine)) + { + case "top left": + x = rct.Left; + y = rct.Top; + break; + case "bottom right": + x = rct.Right; + y = rct.Bottom; + break; + case "top right": + x = rct.Right; + y = rct.Top; + break; + case "bottom left": + x = rct.Left; + y = rct.Bottom; + break; + case "center": + x = (rct.Right - rct.Left) / 2.0; + y = (rct.Bottom - rct.Top) / 2.0; + break; + } + + if (!string.IsNullOrEmpty(v_XPosition)) + { + x.StoreInUserVariable(engine, v_XPosition); + } + if (!string.IsNullOrEmpty(v_YPosition)) + { + y.StoreInUserVariable(engine, v_YPosition); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetUIElementSizeCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetUIElementSizeCommand.cs new file mode 100644 index 000000000..94460ae9b --- /dev/null +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetUIElementSizeCommand.cs @@ -0,0 +1,57 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("UIAutomation")] + [Attributes.ClassAttributes.SubGruop("Get From UIElement")] + [Attributes.ClassAttributes.CommandSettings("Get UIElement Size")] + [Attributes.ClassAttributes.Description("This command allows you to get UIElement Size.")] + [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get UIElement Size.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class UIAutomationGetUIElementSizeCommand : ScriptCommand + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] + public string v_TargetElement { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] + [PropertyDescription("Variable Name to Store Width")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Width", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Width")] + public string v_Width { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] + [PropertyDescription("Variable Name to Store Height")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Height", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Height")] + public string v_Height { get; set; } + + public UIAutomationGetUIElementSizeCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); + + var rct = targetElement.Current.BoundingRectangle; + if (!string.IsNullOrEmpty(v_Width)) + { + rct.Width.StoreInUserVariable(engine, v_Width); + } + if (!string.IsNullOrEmpty(v_Height)) + { + rct.Height.StoreInUserVariable(engine, v_Height); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetUIElementTreeXMLFromUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetUIElementTreeXMLFromUIElementCommand.cs index b3e797561..a2bf05bde 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetUIElementTreeXMLFromUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationGetUIElementTreeXMLFromUIElementCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Get From UIElement")] [Attributes.ClassAttributes.CommandSettings("Get UIElement Tree XML From UIElement")] [Attributes.ClassAttributes.Description("This command allows you to get UIElement Tree XML from UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get UIElement Tree XML from UIElement. XML content is based on WinAppDriver UI Recorder.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationGetUIElementTreeXMLFromUIElementCommand : ScriptCommand + public sealed class UIAutomationGetUIElementTreeXMLFromUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -41,11 +42,9 @@ public UIAutomationGetUIElementTreeXMLFromUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetElement = v_TargetElement.GetUIElementVariable(engine); + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); //var xml = AutomationElementControls.GetElementXml(targetElement, out _); (var xml, _) = UIElementControls.GetElementXml(targetElement); using(System.IO.StringWriter sw = new System.IO.StringWriter()) diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationScrollUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationScrollUIElementCommand.cs index 133d5cfd1..283759bb8 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationScrollUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationScrollUIElementCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("UIElement Action")] [Attributes.ClassAttributes.CommandSettings("Scroll UIElement")] [Attributes.ClassAttributes.Description("This command allows you to Scroll UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to Scroll UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationScrollUIElementCommand : ScriptCommand + public sealed class UIAutomationScrollUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -52,14 +53,14 @@ public UIAutomationScrollUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); + //var scrollbarType = v_ScrollBarType.ExpandValueOrUserVariableAsSelectionItem("v_ScrollBarType", this, engine); + var scrollbarType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ScrollBarType), engine); - var targetElement = v_TargetElement.GetUIElementVariable(engine); - var scrollbarType = v_ScrollBarType.GetUISelectionValue("v_ScrollBarType", this, engine); - - var dirAndAmo = v_DirectionAndAmount.GetUISelectionValue("v_DirectionAndAmount", this, engine); + //var dirAndAmo = v_DirectionAndAmount.ExpandValueOrUserVariableAsSelectionItem("v_DirectionAndAmount", this, engine); + var dirAndAmo = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_DirectionAndAmount), engine); ScrollAmount amount = ScrollAmount.NoAmount; switch (dirAndAmo) { diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchChildUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchChildUIElementCommand.cs index f960dfe9b..638bf09d3 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchChildUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchChildUIElementCommand.cs @@ -8,14 +8,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement")] [Attributes.ClassAttributes.CommandSettings("Search Child UIElement")] [Attributes.ClassAttributes.Description("This command allows you to get Child Element from UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get Child UIElement from UIElement. Search only for Child UIElements.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSearchChildUIElementCommand : ScriptCommand + public sealed class UIAutomationSearchChildUIElementCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -52,12 +53,10 @@ public UIAutomationSearchChildUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var rootElement = v_RootElement.GetUIElementVariable(engine); - int index = v_Index.ConvertToUserVariableAsInteger("v_Index", engine); + var rootElement = v_RootElement.ExpandUserVariableAsUIElement(engine); + int index = v_Index.ExpandValueOrUserVariableAsInteger("v_Index", engine); var elems = UIElementControls.GetChildrenUIElements(rootElement, v_SearchParameters, engine); if (elems.Count > 0) @@ -70,10 +69,18 @@ public override void RunCommand(object sender) } } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { //AutomationElementControls.RenderSearchParameterDataGridView((DataGridView)ControlsList[nameof(v_SearchParameters)]); UIElementControls.RenderSearchParameterDataGridView(ControlsList.GetPropertyControl(nameof(v_SearchParameters))); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_SearchParameters)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_SearchParameters); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchParentUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchParentUIElementCommand.cs index 195d79701..443a301e1 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchParentUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchParentUIElementCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement")] [Attributes.ClassAttributes.CommandSettings("Search Parent UIElement")] [Attributes.ClassAttributes.Description("This command allows you to get Parent UIElement from UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get Parent UIElement from UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSearchParentUIElementCommand : ScriptCommand + public sealed class UIAutomationSearchParentUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -36,13 +37,11 @@ public UIAutomationSearchParentUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var rootElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); - var rootElement = v_TargetElement.GetUIElementVariable(engine); - - var waitTime = this.ConvertToUserVariableAsInteger(nameof(v_WaitTime), engine); + var waitTime = this.ExpandValueOrUserVariableAsInteger(nameof(v_WaitTime), engine); object ret = WaitControls.WaitProcess(waitTime, "Parent Element", new Func<(bool, object)>(() => { diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementAndWindowByXPathCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementAndWindowByXPathCommand.cs index 36bd517e2..06c0f44ae 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementAndWindowByXPathCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementAndWindowByXPathCommand.cs @@ -1,24 +1,25 @@ using System; using System.Xml.Serialization; -using taskt.Core.Automation.Attributes.PropertyAttributes; -using taskt.UI.Forms; using System.Windows.Forms; using taskt.UI.CustomControls; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement & Window")] [Attributes.ClassAttributes.CommandSettings("Search UIElement And Window By XPath")] [Attributes.ClassAttributes.Description("This command allows you to get UIElement from Window Name using by XPath.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get UIElement from Window Name. XPath does not support to use parent and sibling for root element.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSearchUIElementAndWindowByXPathCommand : ScriptCommand + public sealed class UIAutomationSearchUIElementAndWindowByXPathCommand : ScriptCommand { [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowName))] public string v_WindowName { get; set; } [XmlAttribute] @@ -30,26 +31,34 @@ public class UIAutomationSearchUIElementAndWindowByXPathCommand : ScriptCommand public string v_AutomationElementVariable { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_CompareMethod))] + public string v_CompareMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] public string v_MatchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_TargetWindowIndex))] public string v_TargetWindowIndex { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WindowWaitTime { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + public string v_WaitTimeForWindow { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_WaitTime))] public string v_ElementWaitTime { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowNameResult))] + public string v_NameResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_HandleResult { get; set; } + public UIAutomationSearchUIElementAndWindowByXPathCommand() { //this.CommandName = "UIAutomationGetElementFromWindowByXPathCommand"; @@ -58,10 +67,8 @@ public UIAutomationSearchUIElementAndWindowByXPathCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //var winElem = AutomationElementControls.GetWindowAutomationElement(this, engine); //var waitTime = this.ConvertToUserVariableAsInteger(nameof(v_ElementWaitTime), engine); @@ -71,37 +78,63 @@ public override void RunCommand(object sender) //elem.StoreInUserVariable(engine, v_AutomationElementVariable); - var varName = VariableNameControls.GetInnerVariableName(0, engine, false); - - var winSearch = new UIAutomationSearchUIElementFromWindowCommand() - { - v_WindowName = this.v_WindowName, - v_SearchMethod = this.v_SearchMethod, - v_MatchMethod = this.v_MatchMethod, - v_TargetWindowIndex = this.v_TargetWindowIndex, - v_WindowWaitTime = this.v_WindowWaitTime, - v_AutomationElementVariable = varName - }; - winSearch.RunCommand(engine); - - var searchElem = new UIAutomationSearchUIElementFromUIElementByXPathCommand() + //var varName = VariableNameControls.GetInnerVariableName(0, engine, false); + + //var winSearch = new UIAutomationSearchUIElementFromWindowCommand() + //{ + // v_WindowName = this.v_WindowName, + // v_CompareMethod = this.v_CompareMethod, + // v_MatchMethod = this.v_MatchMethod, + // v_TargetWindowIndex = this.v_TargetWindowIndex, + // v_WaitTimeForWindow = this.v_WaitTimeForWindow, + // v_AutomationElementVariable = varName, + // v_NameResult = this.v_NameResult, + // v_HandleResult = this.v_HandleResult, + //}; + //winSearch.RunCommand(engine); + + //var searchElem = new UIAutomationSearchUIElementFromUIElementByXPathCommand() + //{ + // v_TargetElement = varName, + // v_SearchXPath = this.v_SearchXPath, + // v_AutomationElementVariable = this.v_AutomationElementVariable, + // v_WaitTime = this.v_ElementWaitTime + //}; + //searchElem.RunCommand(engine); + + using(var myVar = new InnerScriptVariable(engine)) { - v_TargetElement = varName, - v_SearchXPath = this.v_SearchXPath, - v_AutomationElementVariable = this.v_AutomationElementVariable, - v_WaitTime = this.v_ElementWaitTime - }; - searchElem.RunCommand(engine); + var winSearch = new UIAutomationSearchUIElementFromWindowCommand() + { + v_WindowName = this.v_WindowName, + v_CompareMethod = this.v_CompareMethod, + v_MatchMethod = this.v_MatchMethod, + v_TargetWindowIndex = this.v_TargetWindowIndex, + v_WaitTimeForWindow = this.v_WaitTimeForWindow, + v_AutomationElementVariable = myVar.VariableName, + v_NameResult = this.v_NameResult, + v_HandleResult = this.v_HandleResult, + }; + winSearch.RunCommand(engine); + + var searchElem = new UIAutomationSearchUIElementFromUIElementByXPathCommand() + { + v_TargetElement = myVar.VariableName, + v_SearchXPath = this.v_SearchXPath, + v_AutomationElementVariable = this.v_AutomationElementVariable, + v_WaitTime = this.v_ElementWaitTime + }; + searchElem.RunCommand(engine); + } } private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + WindowControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); } - public override void Refresh(frmCommandEditor editor) + public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - base.Refresh(); ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); } } diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementAndWindowCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementAndWindowCommand.cs index c93b70c46..110af75b9 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementAndWindowCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementAndWindowCommand.cs @@ -1,25 +1,26 @@ using System; using System.Data; using System.Xml.Serialization; -using taskt.Core.Automation.Attributes.PropertyAttributes; -using taskt.UI.Forms; using System.Windows.Forms; using taskt.UI.CustomControls; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement & Window")] [Attributes.ClassAttributes.CommandSettings("Search UIElement And Window")] [Attributes.ClassAttributes.Description("This command allows you to get UIElement from Window Name.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get UIElement from Window Name.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSearchUIElementAndWindowCommand : ScriptCommand + public sealed class UIAutomationSearchUIElementAndWindowCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowName))] public string v_WindowName { get; set; } [XmlElement] @@ -31,34 +32,40 @@ public class UIAutomationSearchUIElementAndWindowCommand : ScriptCommand public string v_AutomationElementVariable { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_CompareMethod))] + public string v_CompareMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] public string v_MatchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_TargetWindowIndex))] public string v_TargetWindowIndex { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WindowWaitTime { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + public string v_WaitTimeForWindow { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_WaitTime))] public string v_ElementWaitTime { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowNameResult))] + public string v_NameResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_HandleResult { get; set; } + public UIAutomationSearchUIElementAndWindowCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //var winElem = AutomationElementControls.GetWindowAutomationElement(this, engine); //var waitTile = this.ConvertToUserVariableAsInteger(nameof(v_ElementWaitTime), engine); @@ -67,44 +74,76 @@ public override void RunCommand(object sender) //elem.StoreInUserVariable(engine, v_AutomationElementVariable); - var varName = VariableNameControls.GetInnerVariableName(0, engine, false); - - var winSearch = new UIAutomationSearchUIElementFromWindowCommand() - { - v_WindowName = this.v_WindowName, - v_SearchMethod = this.v_SearchMethod, - v_MatchMethod = this.v_MatchMethod, - v_TargetWindowIndex = this.v_TargetWindowIndex, - v_WindowWaitTime = this.v_WindowWaitTime, - v_AutomationElementVariable = varName - }; - winSearch.RunCommand(engine); - - var searchElem = new UIAutomationSearchUIElementFromUIElementCommand() + //var varName = VariableNameControls.GetInnerVariableName(0, engine, false); + + //var winSearch = new UIAutomationSearchUIElementFromWindowCommand() + //{ + // v_WindowName = this.v_WindowName, + // v_CompareMethod = this.v_CompareMethod, + // v_MatchMethod = this.v_MatchMethod, + // v_TargetWindowIndex = this.v_TargetWindowIndex, + // v_WaitTimeForWindow = this.v_WaitTimeForWindow, + // v_AutomationElementVariable = varName, + // v_NameResult = this.v_NameResult, + // v_HandleResult = this.v_HandleResult, + //}; + //winSearch.RunCommand(engine); + + //var searchElem = new UIAutomationSearchUIElementFromUIElementCommand() + //{ + // v_TargetElement = varName, + // v_SearchParameters = this.v_SearchParameters, + // v_AutomationElementVariable = this.v_AutomationElementVariable, + // v_WaitTime = this.v_ElementWaitTime + //}; + //searchElem.RunCommand(engine); + + using (var myVar = new InnerScriptVariable(engine)) { - v_TargetElement = varName, - v_SearchParameters = this.v_SearchParameters, - v_AutomationElementVariable = this.v_AutomationElementVariable, - v_WaitTime = this.v_ElementWaitTime - }; - searchElem.RunCommand(engine); + var winSearch = new UIAutomationSearchUIElementFromWindowCommand() + { + v_WindowName = this.v_WindowName, + v_CompareMethod = this.v_CompareMethod, + v_MatchMethod = this.v_MatchMethod, + v_TargetWindowIndex = this.v_TargetWindowIndex, + v_WaitTimeForWindow = this.v_WaitTimeForWindow, + v_AutomationElementVariable = myVar.VariableName, + v_NameResult = this.v_NameResult, + v_HandleResult = this.v_HandleResult, + }; + winSearch.RunCommand(engine); + + var searchElem = new UIAutomationSearchUIElementFromUIElementCommand() + { + v_TargetElement = myVar.VariableName, + v_SearchParameters = this.v_SearchParameters, + v_AutomationElementVariable = this.v_AutomationElementVariable, + v_WaitTime = this.v_ElementWaitTime + }; + searchElem.RunCommand(engine); + } } private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + WindowControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); } - public override void Refresh(frmCommandEditor editor) + public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - base.Refresh(); ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { //AutomationElementControls.RenderSearchParameterDataGridView((DataGridView)ControlsList[nameof(v_SearchParameters)]); UIElementControls.RenderSearchParameterDataGridView(ControlsList.GetPropertyControl(nameof(v_SearchParameters))); } + + public override void BeforeValidate() + { + var dgvSearch = FormUIControls.GetPropertyControl(ControlsList, nameof(v_SearchParameters)); + DataTableControls.BeforeValidate(dgvSearch, v_SearchParameters); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromTableUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromTableUIElementCommand.cs index 2853816f4..a0bce8fb6 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromTableUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromTableUIElementCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement")] [Attributes.ClassAttributes.CommandSettings("Search UIElement From Table UIElement")] [Attributes.ClassAttributes.Description("This command allows you to get UIElement from Table UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get UIElement from Table UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSearchUIElementFromTableUIElementCommand : ScriptCommand + public sealed class UIAutomationSearchUIElementFromTableUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -54,13 +55,11 @@ public UIAutomationSearchUIElementFromTableUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetElement = v_TargetElement.GetUIElementVariable(engine); - int row = v_Row.ConvertToUserVariableAsInteger("v_Row", engine); - int column = v_Column.ConvertToUserVariableAsInteger("v_Column", engine); + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); + int row = v_Row.ExpandValueOrUserVariableAsInteger("v_Row", engine); + int column = v_Column.ExpandValueOrUserVariableAsInteger("v_Column", engine); AutomationElement cellElem = UIElementControls.GetTableUIElement(targetElement, row, column); cellElem.StoreInUserVariable(engine, v_AutomationElementVariable); diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromUIElementByXPathCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromUIElementByXPathCommand.cs index d982719cf..88d98f700 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromUIElementByXPathCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromUIElementByXPathCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement")] [Attributes.ClassAttributes.CommandSettings("Search UIElement From UIElement By XPath")] [Attributes.ClassAttributes.Description("This command allows you to get UIElement from UIElement using by XPath.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get UIElement from UIElement. XPath does not support to use parent and sibling for root element.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSearchUIElementFromUIElementByXPathCommand : ScriptCommand + public sealed class UIAutomationSearchUIElementFromUIElementByXPathCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -44,10 +45,8 @@ public UIAutomationSearchUIElementFromUIElementByXPathCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var elem = UIElementControls.SearchGUIElementByXPath(this, engine); elem.StoreInUserVariable(engine, v_AutomationElementVariable); } diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromUIElementCommand.cs index d67dfdde1..1234ba159 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromUIElementCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement")] [Attributes.ClassAttributes.CommandSettings("Search UIElement From UIElement")] [Attributes.ClassAttributes.Description("This command allows you to get UIElement from UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get UIElement from UIElement. Search for Descendants Elements.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSearchUIElementFromUIElementCommand : ScriptCommand + public sealed class UIAutomationSearchUIElementFromUIElementCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -41,18 +42,24 @@ public UIAutomationSearchUIElementFromUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var elem = UIElementControls.SearchGUIElement(this, engine); elem.StoreInUserVariable(engine, v_AutomationElementVariable); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { //AutomationElementControls.RenderSearchParameterDataGridView((DataGridView)ControlsList[nameof(v_SearchParameters)]); UIElementControls.RenderSearchParameterDataGridView(ControlsList.GetPropertyControl(nameof(v_SearchParameters))); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_SearchParameters)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_SearchParameters); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromWindowCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromWindowCommand.cs index 443958126..419948b77 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromWindowCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSearchUIElementFromWindowCommand.cs @@ -1,24 +1,24 @@ using System; using System.Xml.Serialization; using System.Windows.Forms; -using taskt.Core.Automation.Attributes.PropertyAttributes; -using taskt.UI.Forms; using taskt.UI.CustomControls; +using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search Window")] [Attributes.ClassAttributes.CommandSettings("Search UIElement From Window")] [Attributes.ClassAttributes.Description("This command allows you to get UIElement from Window Name using by XPath.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to get UIElement from Window Name. XPath does not support to use parent and sibling for root element.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSearchUIElementFromWindowCommand : ScriptCommand + public sealed class UIAutomationSearchUIElementFromWindowCommand : ScriptCommand { [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowName))] public string v_WindowName { get; set; } [XmlAttribute] @@ -26,21 +26,29 @@ public class UIAutomationSearchUIElementFromWindowCommand : ScriptCommand public string v_AutomationElementVariable { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_CompareMethod))] + public string v_CompareMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] public string v_MatchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_TargetWindowIndex))] public string v_TargetWindowIndex { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WindowWaitTime { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + public string v_WaitTimeForWindow { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowNameResult))] + public string v_NameResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_HandleResult { get; set; } public UIAutomationSearchUIElementFromWindowCommand() { @@ -50,21 +58,18 @@ public UIAutomationSearchUIElementFromWindowCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - UIElementControls.GetWindowUIElement(this, engine); } private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + WindowControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); } - public override void Refresh(frmCommandEditor editor) + public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - base.Refresh(); //var cmb = (ComboBox)ControlsList[nameof(v_WindowName)]; //cmb.AddWindowNames(); ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSelectItemInUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSelectItemInUIElementCommand.cs index f8721f749..1788f9806 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSelectItemInUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSelectItemInUIElementCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("UIElement Action")] [Attributes.ClassAttributes.CommandSettings("Select Item In UIElement")] [Attributes.ClassAttributes.Description("This command allows you to Select a Item in UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to Select a Item in UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSelectItemInUIElementCommand : ScriptCommand + public sealed class UIAutomationSelectItemInUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -38,15 +39,13 @@ public UIAutomationSelectItemInUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); - var targetElement = v_TargetElement.GetUIElementVariable(engine); + var itemName = v_Item.ExpandValueOrUserVariable(engine); - var itemName = v_Item.ConvertToUserVariable(engine); - - var items = UIElementControls.GetSelectionItems(targetElement, true); + var items = UIElementControls.GetSelectionItems(targetElement); bool isSelected = false; foreach(var item in items) { diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSelectUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSelectUIElementCommand.cs index 50d4c0b1e..4ff979732 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSelectUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSelectUIElementCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("UIElement Action")] [Attributes.ClassAttributes.CommandSettings("Select UIElement")] [Attributes.ClassAttributes.Description("This command allows you to Select UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to Select UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSelectUIElementCommand : ScriptCommand + public sealed class UIAutomationSelectUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -28,11 +29,9 @@ public UIAutomationSelectUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var targetElement = v_TargetElement.GetUIElementVariable(engine); + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); if (targetElement.TryGetCurrentPattern(TogglePattern.Pattern, out object checkPtn)) { diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSetTextToUIElementCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSetTextToUIElementCommand.cs index 19b933327..0aa4438c1 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSetTextToUIElementCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationSetTextToUIElementCommand.cs @@ -2,19 +2,21 @@ using System.Xml.Serialization; using System.Windows.Automation; using taskt.Core.Automation.Attributes.PropertyAttributes; +using System.Windows.Forms; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("UIElement Action")] [Attributes.ClassAttributes.CommandSettings("Set Text To UIElement")] [Attributes.ClassAttributes.Description("This command allows you to set Text Value from UIElement.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to set Text Value from UIElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationSetTextToUIElementCommand : ScriptCommand + public sealed class UIAutomationSetTextToUIElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -37,18 +39,31 @@ public UIAutomationSetTextToUIElementCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var targetElement = v_TargetElement.ExpandUserVariableAsUIElement(engine); - var targetElement = v_TargetElement.GetUIElementVariable(engine); + var ct = targetElement.GetCurrentPropertyValue(AutomationElement.ControlTypeProperty) as ControlType; + if (ct == ControlType.Spinner) + { + //targetElement = UIElementControls.SearchGUIElementByXPath(targetElement, "/Edit[1]", 10, engine); + targetElement = targetElement.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); + } - string textValue = v_TextVariable.ConvertToUserVariable(sender); + string textValue = v_TextVariable.ExpandValueOrUserVariable(engine); - // todo: support range value pattern - if (targetElement.TryGetCurrentPattern(ValuePattern.Pattern, out object textPtn)) + if (targetElement.TryGetCurrentPattern(ValuePattern.Pattern, out object valPtn)) + { + ((ValuePattern)valPtn).SetValue(textValue); + } + else if (targetElement.TryGetCurrentPattern(TextPattern.Pattern, out _)) { - ((ValuePattern)textPtn).SetValue(textValue); + targetElement.SetFocus(); + System.Threading.Thread.Sleep(100); + SendKeys.SendWait("^{HOME}"); + SendKeys.SendWait("^+{END}"); + SendKeys.SendWait("{DEL}"); + SendKeys.SendWait(textValue); } else { diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationUIElementActionByXPathCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationUIElementActionByXPathCommand.cs index 067cead36..32a3f1823 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationUIElementActionByXPathCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationUIElementActionByXPathCommand.cs @@ -1,26 +1,26 @@ using System; -using System.Collections.Generic; -using System.Linq; +using System.Windows.Forms; using System.Xml.Serialization; using System.Data; using taskt.Core.Automation.Attributes.PropertyAttributes; -using System.Windows.Forms; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("UIElement Action")] [Attributes.ClassAttributes.CommandSettings("UIElement Action By XPath")] [Attributes.ClassAttributes.Description("Combined implementation of the ThickAppClick/GetText command but includes an advanced Window Recorder to record the required element.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Windows UI Automation' to find elements and invokes a Variable Command to assign data and achieve automation")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationUIElementActionByXPathCommand : ScriptCommand + public sealed class UIAutomationUIElementActionByXPathCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowName))] public string v_WindowName { get; set; } [XmlAttribute] @@ -37,6 +37,9 @@ public class UIAutomationUIElementActionByXPathCommand : ScriptCommand [PropertyUISelectionOption("Get Text From UIElement")] [PropertyUISelectionOption("Get Selected State From UIElement")] [PropertyUISelectionOption("Get Text From Table UIElement")] + [PropertyUISelectionOption("Get UIElement Position")] + [PropertyUISelectionOption("Get UIElement Size")] + [PropertyUISelectionOption("Wait For UIElement To Exists")] [PropertyUISelectionOption("Wait For UIElement To Exists")] [PropertySelectionChangeEvent(nameof(cmbActionType_SelectedItemChange))] [PropertyDisplayText(true, "Action")] @@ -55,172 +58,357 @@ public class UIAutomationUIElementActionByXPathCommand : ScriptCommand public DataTable v_UIAActionParameters { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_CompareMethod))] + public string v_CompareMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] public string v_MatchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_TargetWindowIndex))] public string v_TargetWindowIndex { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WindowWaitTime { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + public string v_WaitTimeForWindow { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_WaitTime))] public string v_ElementWaitTime { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowNameResult))] + public string v_NameResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_HandleResult { get; set; } + public UIAutomationUIElementActionByXPathCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var elemAction = this.GetUISelectionValue(nameof(v_AutomationType), engine); + var elemAction = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_AutomationType), engine); - var winElemVar = VariableNameControls.GetInnerVariableName(0, engine); - var winElem = new UIAutomationSearchUIElementFromWindowCommand() - { - v_WindowName = this.v_WindowName, - v_SearchMethod = this.v_SearchMethod, - v_MatchMethod = this.v_MatchMethod, - v_TargetWindowIndex = this.v_TargetWindowIndex, - v_WindowWaitTime = this.v_WindowWaitTime, - v_AutomationElementVariable = winElemVar, - }; - winElem.RunCommand(engine); - - var p = DataTableControls.GetFieldValues(v_UIAActionParameters, "Parameter Name", "Parameter Value", false, engine); - var trgElemVar = VariableNameControls.GetInnerVariableName(1, engine); - - switch (elemAction) - { - case "check uielement exists": - var chkElem = new UIAutomationCheckUIElementExistByXPathCommand() - { - v_TargetElement = winElemVar, - v_SearchXPath = this.v_UIASearchParameters, - v_WaitTime = this.v_ElementWaitTime, - v_Result = p["Apply To Variable"], - }; - chkElem.RunCommand(engine); - return; - - default: - var trgElem = new UIAutomationSearchUIElementFromUIElementByXPathCommand() - { - v_TargetElement = winElemVar, - v_SearchXPath = this.v_UIASearchParameters, - v_WaitTime = this.v_ElementWaitTime, - v_AutomationElementVariable = trgElemVar, - }; - trgElem.RunCommand(engine); - break; - } + //var winElemVar = VariableNameControls.GetInnerVariableName(0, engine); + //var winElem = new UIAutomationSearchUIElementFromWindowCommand() + //{ + // v_WindowName = this.v_WindowName, + // v_CompareMethod = this.v_CompareMethod, + // v_MatchMethod = this.v_MatchMethod, + // v_TargetWindowIndex = this.v_TargetWindowIndex, + // v_WaitTimeForWindow = this.v_WaitTimeForWindow, + // v_AutomationElementVariable = winElemVar, + // v_NameResult = this.v_NameResult, + // v_HandleResult = this.v_HandleResult, + //}; + //winElem.RunCommand(engine); + + //var p = DataTableControls.GetFieldValues(v_UIAActionParameters, "Parameter Name", "Parameter Value", false, engine); + //var trgElemVar = VariableNameControls.GetInnerVariableName(1, engine); + + //switch (elemAction) + //{ + // case "check uielement exists": + // var chkElem = new UIAutomationCheckUIElementExistByXPathCommand() + // { + // v_TargetElement = winElemVar, + // v_SearchXPath = this.v_UIASearchParameters, + // v_WaitTime = this.v_ElementWaitTime, + // v_Result = p["Apply To Variable"], + // }; + // chkElem.RunCommand(engine); + // return; + + // default: + // var trgElem = new UIAutomationSearchUIElementFromUIElementByXPathCommand() + // { + // v_TargetElement = winElemVar, + // v_SearchXPath = this.v_UIASearchParameters, + // v_WaitTime = this.v_ElementWaitTime, + // v_AutomationElementVariable = trgElemVar, + // }; + // trgElem.RunCommand(engine); + // break; + //} + + //switch (elemAction) + //{ + // case "click uielement": + // var clickCmd = new UIAutomationClickUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_ClickType = p["Click Type"], + // v_XOffset = p["X Offset"], + // v_YOffset = p["Y Offset"], + // }; + // clickCmd.RunCommand(engine); + // break; + // case "expand collapse items in uielement": + // var expandCmd = new UIAutomationExpandCollapseItemsInUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_ItemsState = p["Items State"], + // }; + // expandCmd.RunCommand(engine); + // break; + // case "scroll uielement": + // var scrollCmd = new UIAutomationScrollUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_ScrollBarType = p["ScrollBar Type"], + // v_DirectionAndAmount = p["Scroll Method"], + // }; + // scrollCmd.RunCommand(engine); + // break; + // case "select uielement": + // var selectCmd = new UIAutomationSelectUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // }; + // selectCmd.RunCommand(engine); + // break; + // case "select item in uielement": + // var selectItemCmd = new UIAutomationSelectItemInUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_Item = p["Item Value"], + // }; + // selectItemCmd.RunCommand(engine); + // break; + // case "set text to uielement": + // var setTextCmd = new UIAutomationSetTextToUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_TextVariable = p["Text To Set"], + // }; + // setTextCmd.RunCommand(engine); + // break; + // case "get property value from uielement": + // var propValueCmd = new UIAutomationGetPropertyValueFromUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_PropertyName = p["Property Name"], + // v_Result = p["Apply To Variable"], + // }; + // propValueCmd.RunCommand(engine); + // break; + // case "check uielement exists": + // true.StoreInUserVariable(engine, p["Apply To Variable"]); + // break; + // case "get text from uielement": + // var getTextCmd = new UIAutomationGetTextFromUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_TextVariable = p["Apply To Variable"], + // }; + // getTextCmd.RunCommand(engine); + // break; + // case "get selected state from uielement": + // var getSelectedCmd = new UIAutomationGetSelectedStateFromUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_ResultVariable = p["Apply To Variable"], + // }; + // getSelectedCmd.RunCommand(engine); + // break; + // case "get text from table uielement": + // var getTableCmd = new UIAutomationGetTextFromTableUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_Row = p["Row"], + // v_Column = p["Column"], + // v_TextVariable = p["Apply To Variable"], + // }; + // getTableCmd.RunCommand(engine); + // break; + // case "get uielement position": + // var getElemPosCmd = new UIAutomationGetUIElementPositionCommand() + // { + // v_TargetElement = trgElemVar, + // v_XPosition = p["X Variable"], + // v_YPosition = p["Y Variable"], + // v_PositionBase = p["Base Position"], + // }; + // getElemPosCmd.RunCommand(engine); + // break; + // case "get uielement size": + // var getElemSizeCmd = new UIAutomationGetUIElementSizeCommand() + // { + // v_TargetElement = trgElemVar, + // v_Width = p["Width Variable"], + // v_Height = p["Height Variable"], + // }; + // getElemSizeCmd.RunCommand(engine); + // break; + //} - switch (elemAction) + using(var myWinElem = new InnerScriptVariable(engine)) { - case "click uielement": - var clickCmd = new UIAutomationClickUIElementCommand() - { - v_TargetElement = trgElemVar, - v_ClickType = p["Click Type"], - v_XOffset = p["X Offset"], - v_YOffset = p["Y Offset"], - }; - clickCmd.RunCommand(engine); - break; - case "expand collapse items in uielement": - var expandCmd = new UIAutomationExpandCollapseItemsInUIElementCommand() - { - v_TargetElement = trgElemVar, - v_ItemsState = p["Items State"], - }; - expandCmd.RunCommand(engine); - break; - case "scroll uielement": - var scrollCmd = new UIAutomationScrollUIElementCommand() - { - v_TargetElement = trgElemVar, - v_ScrollBarType = p["ScrollBar Type"], - v_DirectionAndAmount = p["Scroll Method"], - }; - scrollCmd.RunCommand(engine); - break; - case "select uielement": - var selectCmd = new UIAutomationSelectUIElementCommand() - { - v_TargetElement = trgElemVar, - }; - selectCmd.RunCommand(engine); - break; - case "select item in uielement": - var selectItemCmd = new UIAutomationSelectItemInUIElementCommand() - { - v_TargetElement = trgElemVar, - v_Item = p["Item Value"], - }; - selectItemCmd.RunCommand(engine); - break; - case "set text to uielement": - var setTextCmd = new UIAutomationSetTextToUIElementCommand() - { - v_TargetElement = trgElemVar, - v_TextVariable = p["Text To Set"], - }; - setTextCmd.RunCommand(engine); - break; - case "get property value from uielement": - var propValueCmd = new UIAutomationGetPropertyValueFromUIElementCommand() - { - v_TargetElement = trgElemVar, - v_PropertyName = p["Property Name"], - v_Result = p["Apply To Variable"], - }; - propValueCmd.RunCommand(engine); - break; - case "check uielement exists": - true.StoreInUserVariable(engine, p["Apply To Variable"]); - break; - case "get text from uielement": - var getTextCmd = new UIAutomationGetTextFromUIElementCommand() - { - v_TargetElement = trgElemVar, - v_TextVariable = p["Apply To Variable"], - }; - getTextCmd.RunCommand(engine); - break; - case "get selected state from uielement": - var getSelectedCmd = new UIAutomationGetSelectedStateFromUIElementCommand() + var winElem = new UIAutomationSearchUIElementFromWindowCommand() + { + v_WindowName = this.v_WindowName, + v_CompareMethod = this.v_CompareMethod, + v_MatchMethod = this.v_MatchMethod, + v_TargetWindowIndex = this.v_TargetWindowIndex, + v_WaitTimeForWindow = this.v_WaitTimeForWindow, + v_AutomationElementVariable = myWinElem.VariableName, + v_NameResult = this.v_NameResult, + v_HandleResult = this.v_HandleResult, + }; + winElem.RunCommand(engine); + + var p = DataTableControls.GetFieldValues(v_UIAActionParameters, "Parameter Name", "Parameter Value", false, engine); + + using (var myTrgElem = new InnerScriptVariable(engine)) + { + switch (elemAction) { - v_TargetElement = trgElemVar, - v_ResultVariable = p["Apply To Variable"], - }; - getSelectedCmd.RunCommand(engine); - break; - case "get text from table uielement": - var getTableCmd = new UIAutomationGetTextFromTableUIElementCommand() + case "check uielement exists": + var chkElem = new UIAutomationCheckUIElementExistByXPathCommand() + { + v_TargetElement = myWinElem.VariableName, + v_SearchXPath = this.v_UIASearchParameters, + v_WaitTime = this.v_ElementWaitTime, + v_Result = p["Apply To Variable"], + }; + chkElem.RunCommand(engine); + return; + + default: + var trgElem = new UIAutomationSearchUIElementFromUIElementByXPathCommand() + { + v_TargetElement = myWinElem.VariableName, + v_SearchXPath = this.v_UIASearchParameters, + v_WaitTime = this.v_ElementWaitTime, + v_AutomationElementVariable = myTrgElem.VariableName, + }; + trgElem.RunCommand(engine); + break; + } + + switch (elemAction) { - v_TargetElement = trgElemVar, - v_Row = p["Row"], - v_Column = p["Column"], - v_TextVariable = p["Apply To Variable"], - }; - getTableCmd.RunCommand(engine); - break; + case "click uielement": + var clickCmd = new UIAutomationClickUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_ClickType = p["Click Type"], + v_XOffset = p["X Offset"], + v_YOffset = p["Y Offset"], + }; + clickCmd.RunCommand(engine); + break; + case "expand collapse items in uielement": + var expandCmd = new UIAutomationExpandCollapseItemsInUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_ItemsState = p["Items State"], + }; + expandCmd.RunCommand(engine); + break; + case "scroll uielement": + var scrollCmd = new UIAutomationScrollUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_ScrollBarType = p["ScrollBar Type"], + v_DirectionAndAmount = p["Scroll Method"], + }; + scrollCmd.RunCommand(engine); + break; + case "select uielement": + var selectCmd = new UIAutomationSelectUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + }; + selectCmd.RunCommand(engine); + break; + case "select item in uielement": + var selectItemCmd = new UIAutomationSelectItemInUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_Item = p["Item Value"], + }; + selectItemCmd.RunCommand(engine); + break; + case "set text to uielement": + var setTextCmd = new UIAutomationSetTextToUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_TextVariable = p["Text To Set"], + }; + setTextCmd.RunCommand(engine); + break; + case "get property value from uielement": + var propValueCmd = new UIAutomationGetPropertyValueFromUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_PropertyName = p["Property Name"], + v_Result = p["Apply To Variable"], + }; + propValueCmd.RunCommand(engine); + break; + case "check uielement exists": + true.StoreInUserVariable(engine, p["Apply To Variable"]); + break; + case "get text from uielement": + var getTextCmd = new UIAutomationGetTextFromUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_TextVariable = p["Apply To Variable"], + }; + getTextCmd.RunCommand(engine); + break; + case "get selected state from uielement": + var getSelectedCmd = new UIAutomationGetSelectedStateFromUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_ResultVariable = p["Apply To Variable"], + }; + getSelectedCmd.RunCommand(engine); + break; + case "get text from table uielement": + var getTableCmd = new UIAutomationGetTextFromTableUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_Row = p["Row"], + v_Column = p["Column"], + v_TextVariable = p["Apply To Variable"], + }; + getTableCmd.RunCommand(engine); + break; + case "get uielement position": + var getElemPosCmd = new UIAutomationGetUIElementPositionCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_XPosition = p["X Variable"], + v_YPosition = p["Y Variable"], + v_PositionBase = p["Base Position"], + }; + getElemPosCmd.RunCommand(engine); + break; + case "get uielement size": + var getElemSizeCmd = new UIAutomationGetUIElementSizeCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_Width = p["Width Variable"], + v_Height = p["Height Variable"], + }; + getElemSizeCmd.RunCommand(engine); + break; + } + } } } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - var cmb = PropertyControls.GetPropertyControl(ControlsList, nameof(v_AutomationType)); - var dgv = PropertyControls.GetPropertyControl(ControlsList, nameof(v_UIAActionParameters)); + var cmb = FormUIControls.GetPropertyControl(ControlsList, nameof(v_AutomationType)); + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_UIAActionParameters)); actionParameterProcess(dgv, cmb.SelectedItem?.ToString() ?? ""); } @@ -228,7 +416,7 @@ private void cmbActionType_SelectedItemChange(object sender, EventArgs e) { var a = ((ComboBox)sender).SelectedItem?.ToString() ?? ""; - var dgv = PropertyControls.GetPropertyControl(this.ControlsList, nameof(v_UIAActionParameters)); + var dgv = FormUIControls.GetPropertyControl(this.ControlsList, nameof(v_UIAActionParameters)); var table = v_UIAActionParameters; table.Rows.Clear(); switch (a.ToLower()) @@ -237,38 +425,53 @@ private void cmbActionType_SelectedItemChange(object sender, EventArgs e) table.Rows.Add(new string[] { "Click Type", "" }); table.Rows.Add(new string[] { "X Offset", "" }); table.Rows.Add(new string[] { "Y Offset", "" }); - break; + case "expand collapse items in uielement": table.Rows.Add(new string[] { "Items State", "" }); - break; + case "scroll uielement": table.Rows.Add(new string[] { "ScrollBar Type", "" }); table.Rows.Add(new string[] { "Scroll Method", "" }); - break; + case "select item in uielement": table.Rows.Add(new string[] { "Item Value", "" }); break; + case "set text to uielement": table.Rows.Add(new string[] { "Text To Set", "" }); break; + case "get property value from uielement": table.Rows.Add(new string[] { "Property Name", "" }); table.Rows.Add(new string[] { "Apply To Variable", "" }); - break; + case "get text from table uielement": table.Rows.Add(new string[] { "Row", "" }); table.Rows.Add(new string[] { "Column", "" }); table.Rows.Add(new string[] { "Apply To Variable", "" }); break; + + case "get uielement position": + table.Rows.Add(new string[] { "X Variable", "" }); + table.Rows.Add(new string[] { "Y Variable", "" }); + table.Rows.Add(new string[] { "Base Position", "" }); + break; + + case "get uielement size": + table.Rows.Add(new string[] { "Width Variable", "" }); + table.Rows.Add(new string[] { "Height Variable", "" }); + break; + case "check uielement exists": case "get text from uielement": case "get selected state from uielement": table.Rows.Add(new string[] { "Apply To Variable", "" }); break; + case "select uielement": case "wait for uielement to exists": // nothing @@ -355,17 +558,29 @@ private static void actionParameterProcess(DataGridView dgv, string actionType) }); dgv.Rows[0].Cells[1] = propNames; break; + case "get uielement position": + var positionName = new DataGridViewComboBoxCell(); + positionName.Items.AddRange(new string[] + { + "Top Left", + "Bottom Right", + "Top Right", + "Bottom Left", + "Center", + }); + dgv.Rows[2].Cells[1] = positionName; + break; } } private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + WindowControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); } public override void BeforeValidate() { - var dgvAction = PropertyControls.GetPropertyControl(ControlsList, nameof(v_UIAActionParameters)); + var dgvAction = FormUIControls.GetPropertyControl(ControlsList, nameof(v_UIAActionParameters)); DataTableControls.BeforeValidate(dgvAction, v_UIAActionParameters); } } diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationUIElementActionCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationUIElementActionCommand.cs index 20420715f..f9b30eb9a 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationUIElementActionCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationUIElementActionCommand.cs @@ -1,27 +1,27 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; using System.Data; -using taskt.Core.Automation.Attributes.PropertyAttributes; using System.Windows.Forms; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("UIElement Action")] [Attributes.ClassAttributes.CommandSettings("UIElement Action")] [Attributes.ClassAttributes.Description("Combined implementation of the ThickAppClick/GetText command but includes an advanced Window Recorder to record the required element.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'Windows UI Automation' to find elements and invokes a Variable Command to assign data and achieve automation")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationUIElementActionCommand : ScriptCommand + public sealed class UIAutomationUIElementActionCommand : ScriptCommand, IHaveDataTableElements { - // todo: XPath command [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowName))] public string v_WindowName { get; set; } [XmlAttribute] @@ -38,6 +38,8 @@ public class UIAutomationUIElementActionCommand : ScriptCommand [PropertyUISelectionOption("Get Text From UIElement")] [PropertyUISelectionOption("Get Selected State From UIElement")] [PropertyUISelectionOption("Get Text From Table UIElement")] + [PropertyUISelectionOption("Get UIElement Position")] + [PropertyUISelectionOption("Get UIElement Size")] [PropertyUISelectionOption("Wait For UIElement To Exists")] [PropertySelectionChangeEvent(nameof(cmbActionType_SelectedItemChange))] [PropertyDisplayText(true, "Action")] @@ -56,395 +58,359 @@ public class UIAutomationUIElementActionCommand : ScriptCommand public DataTable v_UIAActionParameters { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_CompareMethod))] + public string v_CompareMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] public string v_MatchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_TargetWindowIndex))] public string v_TargetWindowIndex { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WindowWaitTime { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + public string v_WaitTimeForWindow { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_WaitTime))] public string v_ElementWaitTime { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowNameResult))] + public string v_NameResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_HandleResult { get; set; } + public UIAutomationUIElementActionCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var elemAction = this.GetUISelectionValue(nameof(v_AutomationType), engine); - - var winElemVar = VariableNameControls.GetInnerVariableName(0, engine); - var winElem = new UIAutomationSearchUIElementFromWindowCommand() - { - v_WindowName = this.v_WindowName, - v_SearchMethod = this.v_SearchMethod, - v_MatchMethod = this.v_MatchMethod, - v_TargetWindowIndex = this.v_TargetWindowIndex, - v_WindowWaitTime = this.v_WindowWaitTime, - v_AutomationElementVariable = winElemVar, - }; - winElem.RunCommand(engine); - - var p = DataTableControls.GetFieldValues(v_UIAActionParameters, "Parameter Name", "Parameter Value", false, engine); - var trgElemVar = VariableNameControls.GetInnerVariableName(1, engine); - - switch (elemAction) - { - case "check uielement exists": - var chkElem = new UIAutomationCheckUIElementExistCommand() - { - v_TargetElement = winElemVar, - v_SearchParameters = this.v_UIASearchParameters, - v_WaitTime = this.v_ElementWaitTime, - v_Result = p["Apply To Variable"], - }; - chkElem.RunCommand(engine); - return; - - default: - var trgElem = new UIAutomationSearchUIElementFromUIElementCommand() - { - v_TargetElement = winElemVar, - v_SearchParameters = this.v_UIASearchParameters, - v_WaitTime = this.v_ElementWaitTime, - v_AutomationElementVariable = trgElemVar, - }; - trgElem.RunCommand(engine); - break; - } - - switch (elemAction) - { - case "click uielement": - var clickCmd = new UIAutomationClickUIElementCommand() - { - v_TargetElement = trgElemVar, - v_ClickType = p["Click Type"], - v_XOffset = p["X Offset"], - v_YOffset = p["Y Offset"], - }; - clickCmd.RunCommand(engine); - break; - case "expand collapse items in uielement": - var expandCmd = new UIAutomationExpandCollapseItemsInUIElementCommand() - { - v_TargetElement = trgElemVar, - v_ItemsState = p["Items State"], - }; - expandCmd.RunCommand(engine); - break; - case "scroll uielement": - var scrollCmd = new UIAutomationScrollUIElementCommand() - { - v_TargetElement = trgElemVar, - v_ScrollBarType = p["ScrollBar Type"], - v_DirectionAndAmount = p["Scroll Method"], - }; - scrollCmd.RunCommand(engine); - break; - case "select uielement": - var selectCmd = new UIAutomationSelectUIElementCommand() - { - v_TargetElement = trgElemVar, - }; - selectCmd.RunCommand(engine); - break; - case "select item in uielement": - var selectItemCmd = new UIAutomationSelectItemInUIElementCommand() - { - v_TargetElement = trgElemVar, - v_Item = p["Item Value"], - }; - selectItemCmd.RunCommand(engine); - break; - case "set text to uielement": - var setTextCmd = new UIAutomationSetTextToUIElementCommand() - { - v_TargetElement = trgElemVar, - v_TextVariable = p["Text To Set"], - }; - setTextCmd.RunCommand(engine); - break; - case "get property value from uielement": - var propValueCmd = new UIAutomationGetPropertyValueFromUIElementCommand() - { - v_TargetElement = trgElemVar, - v_PropertyName = p["Property Name"], - v_Result = p["Apply To Variable"], - }; - propValueCmd.RunCommand(engine); - break; - case "check uielement exists": - true.StoreInUserVariable(engine, p["Apply To Variable"]); - break; - case "get text from uielement": - var getTextCmd = new UIAutomationGetTextFromUIElementCommand() - { - v_TargetElement = trgElemVar, - v_TextVariable = p["Apply To Variable"], - }; - getTextCmd.RunCommand(engine); - break; - case "get selected state from uielement": - var getSelectedCmd = new UIAutomationGetSelectedStateFromUIElementCommand() - { - v_TargetElement = trgElemVar, - v_ResultVariable = p["Apply To Variable"], - }; - getSelectedCmd.RunCommand(engine); - break; - case "get text from table uielement": - var getTableCmd = new UIAutomationGetTextFromTableUIElementCommand() - { - v_TargetElement = trgElemVar, - v_Row = p["Row"], - v_Column = p["Column"], - v_TextVariable = p["Apply To Variable"], - }; - getTableCmd.RunCommand(engine); - break; - } - - ////create variable window name - //var variableWindowName = v_WindowName.ConvertToUserVariable(sender); + var elemAction = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_AutomationType), engine); - //if (variableWindowName == engine.engineSettings.CurrentWindowKeyword) + //var winElemVar = VariableNameControls.GetInnerVariableName(0, engine); + //var winElem = new UIAutomationSearchUIElementFromWindowCommand() //{ - // //variableWindowName = User32Functions.GetActiveWindowTitle(); - // variableWindowName = WindowNameControls.GetActiveWindowTitle(); - //} - //else + // v_WindowName = this.v_WindowName, + // v_CompareMethod = this.v_CompareMethod, + // v_MatchMethod = this.v_MatchMethod, + // v_TargetWindowIndex = this.v_TargetWindowIndex, + // v_WaitTimeForWindow = this.v_WaitTimeForWindow, + // v_AutomationElementVariable = winElemVar, + // v_NameResult = this.v_NameResult, + // v_HandleResult = this.v_HandleResult, + //}; + //winElem.RunCommand(engine); + + //var p = DataTableControls.GetFieldValues(v_UIAActionParameters, "Parameter Name", "Parameter Value", false, engine); + //var trgElemVar = VariableNameControls.GetInnerVariableName(1, engine); + + //switch (elemAction) //{ - // // search and activate window - // var searchMethod = v_SearchMethod.ConvertToUserVariable(sender); - // if (String.IsNullOrEmpty(searchMethod)) - // { - // searchMethod = "Contains"; - // } - - // if (searchMethod != "Exact match") - // { - // ActivateWindowCommand activateWindow = new ActivateWindowCommand + // case "check uielement exists": + // var chkElem = new UIAutomationCheckUIElementExistCommand() // { - // v_WindowName = variableWindowName, - // v_SearchMethod = searchMethod + // v_TargetElement = winElemVar, + // v_SearchParameters = this.v_UIASearchParameters, + // v_WaitTime = this.v_ElementWaitTime, + // v_Result = p["Apply To Variable"], // }; - // activateWindow.RunCommand(sender); - // System.Threading.Thread.Sleep(500); // wait a bit - // //variableWindowName = User32Functions.GetActiveWindowTitle(); - // variableWindowName = WindowNameControls.GetActiveWindowTitle(); - // } - //} - - //var requiredHandle = SearchForGUIElement(sender, variableWindowName); - - ////if element exists type - //if (v_AutomationType == "Check If Element Exists") - //{ - // //apply to variable - // var applyToVariable = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Apply To Variable" - // select rw.Field("Parameter Value")).FirstOrDefault(); - - - // //remove brackets from variable - // applyToVariable = applyToVariable.Replace(engine.engineSettings.VariableStartMarker, "").Replace(engine.engineSettings.VariableEndMarker, ""); - - // //declare search result - // string searchResult; - - // //determine search result - // if (requiredHandle == null) - // { - // searchResult = "FALSE"; - - // } - // else - // { - // searchResult = "TRUE"; - // } - - // //store data - // searchResult.StoreInUserVariable(sender, applyToVariable); + // chkElem.RunCommand(engine); + // return; + // default: + // var trgElem = new UIAutomationSearchUIElementFromUIElementCommand() + // { + // v_TargetElement = winElemVar, + // v_SearchParameters = this.v_UIASearchParameters, + // v_WaitTime = this.v_ElementWaitTime, + // v_AutomationElementVariable = trgElemVar, + // }; + // trgElem.RunCommand(engine); + // break; //} - ////determine element click type - //else if (v_AutomationType == "Click Element") + //// todo: use same method + //switch (elemAction) //{ - - // //if handle was not found - // if (requiredHandle == null) - // throw new Exception("Element was not found in window '" + variableWindowName + "'"); - - // //create search params - // var clickType = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Click Type" - // select rw.Field("Parameter Value")).FirstOrDefault(); - - // //get x adjust - // var xAdjust = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "X Adjustment" - // select rw.Field("Parameter Value")).FirstOrDefault(); - - // //get y adjust - // var yAdjust = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Y Adjustment" - // select rw.Field("Parameter Value")).FirstOrDefault(); - - // //convert potential variable - // var xAdjustVariable = xAdjust.ConvertToUserVariable(sender); - // var yAdjustVariable = yAdjust.ConvertToUserVariable(sender); - - // //parse to int - // var xAdjustInt = int.Parse(xAdjustVariable); - // var yAdjustInt = int.Parse(yAdjustVariable); - - // //get clickable point - // var newPoint = requiredHandle.GetClickablePoint(); - - // //send mousemove command - // var newMouseMove = new MoveMouseCommand - // { - // v_XMousePosition = (newPoint.X + xAdjustInt).ToString(), - // v_YMousePosition = (newPoint.Y + yAdjustInt).ToString(), - // v_MouseClick = clickType - // }; - - // //run commands - // newMouseMove.RunCommand(sender); + // case "click uielement": + // var clickCmd = new UIAutomationClickUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_ClickType = p["Click Type"], + // v_XOffset = p["X Offset"], + // v_YOffset = p["Y Offset"], + // }; + // clickCmd.RunCommand(engine); + // break; + // case "expand collapse items in uielement": + // var expandCmd = new UIAutomationExpandCollapseItemsInUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_ItemsState = p["Items State"], + // }; + // expandCmd.RunCommand(engine); + // break; + // case "scroll uielement": + // var scrollCmd = new UIAutomationScrollUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_ScrollBarType = p["ScrollBar Type"], + // v_DirectionAndAmount = p["Scroll Method"], + // }; + // scrollCmd.RunCommand(engine); + // break; + // case "select uielement": + // var selectCmd = new UIAutomationSelectUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // }; + // selectCmd.RunCommand(engine); + // break; + // case "select item in uielement": + // var selectItemCmd = new UIAutomationSelectItemInUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_Item = p["Item Value"], + // }; + // selectItemCmd.RunCommand(engine); + // break; + // case "set text to uielement": + // var setTextCmd = new UIAutomationSetTextToUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_TextVariable = p["Text To Set"], + // }; + // setTextCmd.RunCommand(engine); + // break; + // case "get property value from uielement": + // var propValueCmd = new UIAutomationGetPropertyValueFromUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_PropertyName = p["Property Name"], + // v_Result = p["Apply To Variable"], + // }; + // propValueCmd.RunCommand(engine); + // break; + // case "check uielement exists": + // true.StoreInUserVariable(engine, p["Apply To Variable"]); + // break; + // case "get text from uielement": + // var getTextCmd = new UIAutomationGetTextFromUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_TextVariable = p["Apply To Variable"], + // }; + // getTextCmd.RunCommand(engine); + // break; + // case "get selected state from uielement": + // var getSelectedCmd = new UIAutomationGetSelectedStateFromUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_ResultVariable = p["Apply To Variable"], + // }; + // getSelectedCmd.RunCommand(engine); + // break; + // case "get text from table uielement": + // var getTableCmd = new UIAutomationGetTextFromTableUIElementCommand() + // { + // v_TargetElement = trgElemVar, + // v_Row = p["Row"], + // v_Column = p["Column"], + // v_TextVariable = p["Apply To Variable"], + // }; + // getTableCmd.RunCommand(engine); + // break; + // case "get uielement position": + // var getElemPosCmd = new UIAutomationGetUIElementPositionCommand() + // { + // v_TargetElement = trgElemVar, + // v_XPosition = p["X Variable"], + // v_YPosition = p["Y Variable"], + // v_PositionBase = p["Base Position"], + // }; + // getElemPosCmd.RunCommand(engine); + // break; + // case "get uielement size": + // var getElemSizeCmd = new UIAutomationGetUIElementSizeCommand() + // { + // v_TargetElement = trgElemVar, + // v_Width = p["Width Variable"], + // v_Height = p["Height Variable"], + // }; + // getElemSizeCmd.RunCommand(engine); + // break; //} - //else if (v_AutomationType == "Get Value From Element") - //{ - - // //if handle was not found - // if (requiredHandle == null) - // throw new Exception("Element was not found in window '" + variableWindowName + "'"); - // //get value from property - // var propertyName = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Get Value From" - // select rw.Field("Parameter Value")).FirstOrDefault(); - - // //apply to variable - // var applyToVariable = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Apply To Variable" - // select rw.Field("Parameter Value")).FirstOrDefault(); - - // //remove brackets from variable - // applyToVariable = applyToVariable.Replace(engine.engineSettings.VariableStartMarker, "").Replace(engine.engineSettings.VariableEndMarker, ""); - - // //get required value - // var requiredValue = requiredHandle.Current.GetType().GetRuntimeProperty(propertyName)?.GetValue(requiredHandle.Current).ToString(); - - // //store into variable - // requiredValue.StoreInUserVariable(sender, applyToVariable); - //} - //else if (v_AutomationType == "Get Text Value From Element") - //{ - // //apply to variable - // var applyToVariable = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Apply To Variable" - // select rw.Field("Parameter Value")).FirstOrDefault(); - - // object patternObj; - // if (requiredHandle.TryGetCurrentPattern(ValuePattern.Pattern, out patternObj)) - // { - // // TextBox - // ((ValuePattern)patternObj).Current.Value.StoreInUserVariable(sender, applyToVariable); - // } - // else if (requiredHandle.TryGetCurrentPattern(TextPattern.Pattern, out patternObj)) - // { - // // TextBox Multilune - // TextPattern tPtn = (TextPattern)patternObj; - // tPtn.DocumentRange.GetText(-1).StoreInUserVariable(sender, applyToVariable); - // } - // else if (requiredHandle.TryGetCurrentPattern(SelectionPattern.Pattern, out patternObj)) - // { - // ((SelectionPattern)patternObj).Current.GetSelection()[0].GetCurrentPropertyValue(AutomationElement.NameProperty).ToString().StoreInUserVariable(sender, applyToVariable); - // } - // else - // { - // requiredHandle.Current.Name.StoreInUserVariable(sender, applyToVariable); - // } - //} - //else if (v_AutomationType == "Get Selected State From Element") - //{ - // //apply to variable - // var applyToVariable = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Apply To Variable" - // select rw.Field("Parameter Value")).FirstOrDefault(); - // object patternObj; - // bool checkState; - // if (requiredHandle.TryGetCurrentPattern(TogglePattern.Pattern, out patternObj)) - // { - // checkState = (((TogglePattern)patternObj).Current.ToggleState == ToggleState.On); - // } - // else if (requiredHandle.TryGetCurrentPattern(SelectionItemPattern.Pattern, out patternObj)) - // { - // checkState = ((SelectionItemPattern)patternObj).Current.IsSelected; - // } - // else - // { - // throw new Exception("Thie element is not CheckBox or RadioButton."); - // } - // (checkState ? "TRUE" : "FALSE").StoreInUserVariable(sender, applyToVariable); - //} - //else if (v_AutomationType == "Get Value From Table Element") - //{ - // // row, column - // var vTarget = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Target" - // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender); - // var vRow = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Row" - // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender); - // var vColumn = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Column" - // select rw.Field("Parameter Value")).FirstOrDefault().ConvertToUserVariable(sender); - // //apply to variable - // var applyToVariable = (from rw in v_UIAActionParameters.AsEnumerable() - // where rw.Field("Parameter Name") == "Apply To Variable" - // select rw.Field("Parameter Value")).FirstOrDefault(); - // int row, col; - - - // object dgvPattern; - // if (requiredHandle.TryGetCurrentPattern(TablePattern.Pattern, out dgvPattern)) - // { - // row = int.Parse(vRow); - // col = int.Parse(vColumn); - // var cell = ((TablePattern)dgvPattern).GetItem(row, col); - // cell.Current.Name.StoreInUserVariable(sender, applyToVariable); - // } - // else - // { - // throw new Exception("This table is not supported."); - // } - - //} - //else - //{ - // throw new NotImplementedException("Automation type '" + v_AutomationType + "' not supported."); - //} + using(var myWinElem = new InnerScriptVariable(engine)) + { + var winElem = new UIAutomationSearchUIElementFromWindowCommand() + { + v_WindowName = this.v_WindowName, + v_CompareMethod = this.v_CompareMethod, + v_MatchMethod = this.v_MatchMethod, + v_TargetWindowIndex = this.v_TargetWindowIndex, + v_WaitTimeForWindow = this.v_WaitTimeForWindow, + v_AutomationElementVariable = myWinElem.VariableName, + v_NameResult = this.v_NameResult, + v_HandleResult = this.v_HandleResult, + }; + winElem.RunCommand(engine); + + var p = DataTableControls.GetFieldValues(v_UIAActionParameters, "Parameter Name", "Parameter Value", false, engine); + + using (var myTrgElem = new InnerScriptVariable(engine)) + { + switch (elemAction) + { + case "check uielement exists": + var chkElem = new UIAutomationCheckUIElementExistCommand() + { + v_TargetElement = myWinElem.VariableName, + v_SearchParameters = this.v_UIASearchParameters, + v_WaitTime = this.v_ElementWaitTime, + v_Result = p["Apply To Variable"], + }; + chkElem.RunCommand(engine); + return; + + default: + var trgElem = new UIAutomationSearchUIElementFromUIElementCommand() + { + v_TargetElement = myWinElem.VariableName, + v_SearchParameters = this.v_UIASearchParameters, + v_WaitTime = this.v_ElementWaitTime, + v_AutomationElementVariable = myTrgElem.VariableName, + }; + trgElem.RunCommand(engine); + break; + } + + // todo: use same method + switch (elemAction) + { + case "click uielement": + var clickCmd = new UIAutomationClickUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_ClickType = p["Click Type"], + v_XOffset = p["X Offset"], + v_YOffset = p["Y Offset"], + }; + clickCmd.RunCommand(engine); + break; + case "expand collapse items in uielement": + var expandCmd = new UIAutomationExpandCollapseItemsInUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_ItemsState = p["Items State"], + }; + expandCmd.RunCommand(engine); + break; + case "scroll uielement": + var scrollCmd = new UIAutomationScrollUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_ScrollBarType = p["ScrollBar Type"], + v_DirectionAndAmount = p["Scroll Method"], + }; + scrollCmd.RunCommand(engine); + break; + case "select uielement": + var selectCmd = new UIAutomationSelectUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + }; + selectCmd.RunCommand(engine); + break; + case "select item in uielement": + var selectItemCmd = new UIAutomationSelectItemInUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_Item = p["Item Value"], + }; + selectItemCmd.RunCommand(engine); + break; + case "set text to uielement": + var setTextCmd = new UIAutomationSetTextToUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_TextVariable = p["Text To Set"], + }; + setTextCmd.RunCommand(engine); + break; + case "get property value from uielement": + var propValueCmd = new UIAutomationGetPropertyValueFromUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_PropertyName = p["Property Name"], + v_Result = p["Apply To Variable"], + }; + propValueCmd.RunCommand(engine); + break; + case "check uielement exists": + true.StoreInUserVariable(engine, p["Apply To Variable"]); + break; + case "get text from uielement": + var getTextCmd = new UIAutomationGetTextFromUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_TextVariable = p["Apply To Variable"], + }; + getTextCmd.RunCommand(engine); + break; + case "get selected state from uielement": + var getSelectedCmd = new UIAutomationGetSelectedStateFromUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_ResultVariable = p["Apply To Variable"], + }; + getSelectedCmd.RunCommand(engine); + break; + case "get text from table uielement": + var getTableCmd = new UIAutomationGetTextFromTableUIElementCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_Row = p["Row"], + v_Column = p["Column"], + v_TextVariable = p["Apply To Variable"], + }; + getTableCmd.RunCommand(engine); + break; + case "get uielement position": + var getElemPosCmd = new UIAutomationGetUIElementPositionCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_XPosition = p["X Variable"], + v_YPosition = p["Y Variable"], + v_PositionBase = p["Base Position"], + }; + getElemPosCmd.RunCommand(engine); + break; + case "get uielement size": + var getElemSizeCmd = new UIAutomationGetUIElementSizeCommand() + { + v_TargetElement = myTrgElem.VariableName, + v_Width = p["Width Variable"], + v_Height = p["Height Variable"], + }; + getElemSizeCmd.RunCommand(engine); + break; + } + } + } } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - var cmb = PropertyControls.GetPropertyControl(ControlsList, nameof(v_AutomationType)); - var dgv = PropertyControls.GetPropertyControl(ControlsList, nameof(v_UIAActionParameters)); + var cmb = FormUIControls.GetPropertyControl(ControlsList, nameof(v_AutomationType)); + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_UIAActionParameters)); actionParameterProcess(dgv, cmb.SelectedItem?.ToString() ?? ""); } @@ -452,7 +418,7 @@ private void cmbActionType_SelectedItemChange(object sender, EventArgs e) { var a = ((ComboBox)sender).SelectedItem?.ToString() ?? ""; - var dgv = PropertyControls.GetPropertyControl(this.ControlsList, nameof(v_UIAActionParameters)); + var dgv = FormUIControls.GetPropertyControl(this.ControlsList, nameof(v_UIAActionParameters)); var table = v_UIAActionParameters; table.Rows.Clear(); switch (a.ToLower()) @@ -461,100 +427,52 @@ private void cmbActionType_SelectedItemChange(object sender, EventArgs e) table.Rows.Add(new string[] { "Click Type", "" }); table.Rows.Add(new string[] { "X Offset", "" }); table.Rows.Add(new string[] { "Y Offset", "" }); - - //var clickType = new DataGridViewComboBoxCell(); - //clickType.Items.AddRange(new string[] - //{ - // "Left Click", - // "Middle Click", - // "Right Click", - // "Left Down", - // "Middle Down", - // "Right Down", - // "Left Up", - // "Middle Up", - // "Right Up", - // "Double Left Click", - // "None", - //}); - //dgv.Rows[0].Cells[1] = clickType; break; + case "expand collapse items in uielement": table.Rows.Add(new string[] { "Items State", "" }); - //var itemState = new DataGridViewComboBoxCell(); - //itemState.Items.AddRange(new string[] - //{ - // "Expand", - // "Collapse" - //}); - //dgv.Rows[0].Cells[1] = itemState; break; case "scroll uielement": table.Rows.Add(new string[] { "ScrollBar Type", "" }); table.Rows.Add(new string[] { "Scroll Method", "" }); - //var barType = new DataGridViewComboBoxCell(); - //barType.Items.AddRange(new string[] - //{ - // "Vertical", - // "Horizonal", - //}); - //var scrollMethod = new DataGridViewComboBoxCell(); - //scrollMethod.Items.AddRange(new string[] - //{ - // "Scroll Small Down or Right", - // "Scroll Large Down or Right", - // "Scroll Small Up or Left", - // "Scroll Large Up or Left", - //}); - //dgv.Rows[0].Cells[1] = barType; - //dgv.Rows[1].Cells[1] = scrollMethod; break; + case "select item in uielement": table.Rows.Add(new string[] { "Item Value", "" }); break; + case "set text to uielement": table.Rows.Add(new string[] { "Text To Set", "" }); break; + case "get property value from uielement": table.Rows.Add(new string[] { "Property Name", "" }); table.Rows.Add(new string[] { "Apply To Variable", "" }); - //var propNames = new DataGridViewComboBoxCell(); - //propNames.Items.AddRange(new string[] - //{ - // "Name", - // "ControlType", - // "LocalizedControlType", - // "IsEnabled", - // "IsOffscreen", - // "IsKeyboardFocusable", - // "HasKeyboardFocusable", - // "AccessKey", - // "ProcessId", - // "AutomationId", - // "FrameworkId", - // "ClassName", - // "IsContentElement", - // "IsPassword", - // "AcceleratorKey", - // "HelpText", - // "IsControlElement", - // "IsRequiredForForm", - // "ItemStatus", - // "ItemType", - // "NativeWindowHandle", - //}); - //dgv.Rows[0].Cells[1] = propNames; break; + case "get text from table uielement": table.Rows.Add(new string[] { "Row", "" }); table.Rows.Add(new string[] { "Column", "" }); table.Rows.Add(new string[] { "Apply To Variable", "" }); break; + + case "get uielement position": + table.Rows.Add(new string[] { "X Variable", "" }); + table.Rows.Add(new string[] { "Y Variable", "" }); + table.Rows.Add(new string[] { "Base Position", ""}); + break; + + case "get uielement size": + table.Rows.Add(new string[] { "Width Variable", "" }); + table.Rows.Add(new string[] { "Height Variable", "" }); + break; + case "check uielement exists": case "get text from uielement": case "get selected state from uielement": table.Rows.Add(new string[] { "Apply To Variable", "" }); break; + case "select uielement": case "wait for uielement to exists": // nothing @@ -641,20 +559,32 @@ private static void actionParameterProcess(DataGridView dgv, string actionType) }); dgv.Rows[0].Cells[1] = propNames; break; + case "get uielement position": + var positionName = new DataGridViewComboBoxCell(); + positionName.Items.AddRange(new string[] + { + "Top Left", + "Bottom Right", + "Top Right", + "Bottom Left", + "Center", + }); + dgv.Rows[2].Cells[1] = positionName; + break; } } private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + WindowControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); } public override void BeforeValidate() { - var dgvAction = PropertyControls.GetPropertyControl(ControlsList, nameof(v_UIAActionParameters)); + var dgvAction = FormUIControls.GetPropertyControl(ControlsList, nameof(v_UIAActionParameters)); DataTableControls.BeforeValidate(dgvAction, v_UIAActionParameters); - var dgvSearch = PropertyControls.GetPropertyControl(ControlsList, nameof(v_UIASearchParameters)); + var dgvSearch = FormUIControls.GetPropertyControl(ControlsList, nameof(v_UIASearchParameters)); DataTableControls.BeforeValidate(dgvSearch, v_UIASearchParameters); } diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationWaitForUIElementToExistsByXPathCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationWaitForUIElementToExistsByXPathCommand.cs index 6618b556e..447ade469 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationWaitForUIElementToExistsByXPathCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationWaitForUIElementToExistsByXPathCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement")] [Attributes.ClassAttributes.CommandSettings("Wait For UIElement To Exists By XPath")] [Attributes.ClassAttributes.Description("This command allows you to Wait until the UIElement exists using by XPath.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to Wait until the UIElement exists using by XPath.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationWaitForUIElementToExistsByXPathCommand : ScriptCommand + public sealed class UIAutomationWaitForUIElementToExistsByXPathCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -35,10 +36,8 @@ public UIAutomationWaitForUIElementToExistsByXPathCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - UIElementControls.SearchGUIElementByXPath(this, engine); } } diff --git a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationWaitForUIElementToExistsCommand.cs b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationWaitForUIElementToExistsCommand.cs index effe88c46..7fca5ce2d 100644 --- a/taskt/Core/Automation/Commands/UIAutomation/UIAutomationWaitForUIElementToExistsCommand.cs +++ b/taskt/Core/Automation/Commands/UIAutomation/UIAutomationWaitForUIElementToExistsCommand.cs @@ -7,14 +7,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("UIAutomation Commands")] + [Attributes.ClassAttributes.Group("UIAutomation")] [Attributes.ClassAttributes.SubGruop("Search UIElement")] [Attributes.ClassAttributes.CommandSettings("Wait For UIElement To Exists")] [Attributes.ClassAttributes.Description("This command allows you to Wait until the UIElement exists.")] [Attributes.ClassAttributes.ImplementationDescription("Use this command when you want to Wait until the UIElement exists.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class UIAutomationWaitForUIElementToExistsCommand : ScriptCommand + public sealed class UIAutomationWaitForUIElementToExistsCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(UIElementControls), nameof(UIElementControls.v_InputUIElementName))] @@ -36,17 +37,23 @@ public UIAutomationWaitForUIElementToExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - UIElementControls.SearchGUIElement(this, engine); } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { //AutomationElementControls.RenderSearchParameterDataGridView((DataGridView)ControlsList[nameof(v_SearchParameters)]); UIElementControls.RenderSearchParameterDataGridView(ControlsList.GetPropertyControl(nameof(v_SearchParameters))); } + + public override void BeforeValidate() + { + base.BeforeValidate(); + + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_SearchParameters)); + DataTableControls.BeforeValidate_NoRowAdding(dgv, v_SearchParameters); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/UIElementControls.cs b/taskt/Core/Automation/Commands/UIElementControls.cs index eacf06429..e5e9b9f2d 100644 --- a/taskt/Core/Automation/Commands/UIElementControls.cs +++ b/taskt/Core/Automation/Commands/UIElementControls.cs @@ -8,6 +8,7 @@ using System.Security; using System.Windows.Forms; using taskt.Core.Automation.Attributes.PropertyAttributes; +using System.Diagnostics; namespace taskt.Core.Automation.Commands { @@ -21,20 +22,20 @@ internal static class UIElementControls /// /// UIElement type for Reflection /// - private static Type TypeOfAutomationElement = typeof(AutomationElement); + private static readonly Type TypeOfAutomationElement = typeof(AutomationElement); /// /// ControlType type for Reflection /// - private static Type TypeOfControlType = typeof(ControlType); + private static readonly Type TypeOfControlType = typeof(ControlType); - private static string[] TargetControlTypes = new string[] + private static readonly string[] TargetControlTypes = new string[] { "AcceleratorKey", "AccessKey", "AutomationId", "ClassName", "ControlType", "FrameworkId", "HasKeyboardFocus", "HelpText", "IsContentElement", "IsControlElement", "IsEnabled", "IsKeyboardFocusable", "IsOffscreen", "IsPassword", "IsRequiredForForm", "ItemStatus", "ItemType", - "LocalizedControlType", "Name", "NativeWindowHandle", "ProcessID", + "LocalizedControlType", "Name", "NativeWindowHandle", "ProcessId", }; #endregion @@ -53,13 +54,14 @@ internal static class UIElementControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("UIElement", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Element")] + [PropertyParameterOrder(5000)] public static string v_InputUIElementName { get; } /// /// output UIElement property /// [PropertyDescription("UIElement Variable Name")] - [InputSpecification(" Variable Name", true)] + [InputSpecification("UIElement Variable Name", true)] [PropertyDetailSampleUsage("**vElement**", PropertyDetailSampleUsage.ValueType.VariableValue)] [PropertyDetailSampleUsage("**{{{vElement}}}**", PropertyDetailSampleUsage.ValueType.VariableValue)] [Remarks("")] @@ -70,13 +72,14 @@ internal static class UIElementControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("UIElement", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Element")] + [PropertyParameterOrder(5000)] public static string v_OutputUIElementName { get; } /// /// New output UIElement name /// [PropertyDescription("UIElement Variable Name")] - [InputSpecification(" Variable Name", true)] + [InputSpecification("UIElement Variable Name", true)] [PropertyDetailSampleUsage("**vNewElement**", PropertyDetailSampleUsage.ValueType.VariableValue)] [PropertyDetailSampleUsage("**{{{vNewElement}}}**", PropertyDetailSampleUsage.ValueType.VariableValue)] [Remarks("")] @@ -87,6 +90,7 @@ internal static class UIElementControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("New UIElement", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "New UIElement")] + [PropertyParameterOrder(5000)] public static string v_NewOutputUIElementName { get; } /// @@ -103,6 +107,7 @@ internal static class UIElementControls [PropertyValidationRule("XPath", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "XPath")] [PropertyCustomUIHelper("GUI Inspect Tool", nameof(UIElementControls) + "+" + nameof(lnkGUIInspectTool_UsedByXPath_Click))] + [PropertyParameterOrder(5000)] public static string v_XPath { get; } /// @@ -120,9 +125,10 @@ internal static class UIElementControls [PropertyDataGridViewColumnSettings("Enabled", "Enabled", false, PropertyDataGridViewColumnSettings.DataGridViewColumnType.CheckBox)] [PropertyDataGridViewColumnSettings("ParameterName", "Parameter Name", true, PropertyDataGridViewColumnSettings.DataGridViewColumnType.TextBox)] [PropertyDataGridViewColumnSettings("ParameterValue", "Parameter Value", false, PropertyDataGridViewColumnSettings.DataGridViewColumnType.TextBox)] - [PropertyDataGridViewCellEditEvent(nameof(UIElementControls) + "+" + nameof(UIElementControls.UIAutomationDataGridView_CellBeginEdit), PropertyDataGridViewCellEditEvent.DataGridViewCellEvent.CellBeginEdit)] - [PropertyDataGridViewCellEditEvent(nameof(UIElementControls) + "+" + nameof(UIElementControls.UIAutomationDataGridView_CellClick), PropertyDataGridViewCellEditEvent.DataGridViewCellEvent.CellClick)] + [PropertyDataGridViewCellEditEvent(nameof(UIElementControls) + "+" + nameof(UIAutomationDataGridView_CellBeginEdit), PropertyDataGridViewCellEditEvent.DataGridViewCellEvent.CellBeginEdit)] + [PropertyDataGridViewCellEditEvent(nameof(UIElementControls) + "+" + nameof(UIAutomationDataGridView_CellClick), PropertyDataGridViewCellEditEvent.DataGridViewCellEvent.CellClick)] [PropertyDataGridViewInitMethod(nameof(UIElementControls) + "+" + nameof(CreateEmptyParamters))] + [PropertyParameterOrder(5000)] public static string v_SearchParameters { get; } /// @@ -137,19 +143,20 @@ internal static class UIElementControls [PropertyTextBoxSetting(1, false)] [PropertyIsOptional(true, "10")] [PropertyFirstValue("10")] + [PropertyParameterOrder(5000)] public static string v_WaitTime { get; } #endregion #region variable methods /// - /// get UIElement from Specified variable name + /// expand user variable as UIElement /// /// /// /// /// - public static AutomationElement GetUIElementVariable(this string variableName, Engine.AutomationEngineInstance engine) + public static AutomationElement ExpandUserVariableAsUIElement(this string variableName, Engine.AutomationEngineInstance engine) { Script.ScriptVariable v = variableName.GetRawVariable(engine); if (v.VariableValue is AutomationElement e) @@ -163,28 +170,28 @@ public static AutomationElement GetUIElementVariable(this string variableName, E } /// - /// get UIElement from specified parameter name + /// expand user variable as UIElement /// /// /// /// /// - public static AutomationElement CovnertToUserVariableAsUIElement(this ScriptCommand command, string parameterName, Engine.AutomationEngineInstance engine) + public static AutomationElement ExpandUserVariableAsUIElement(this ScriptCommand command, string parameterName, Engine.AutomationEngineInstance engine) { var prop = command.GetProperty(parameterName); var value = prop?.GetValue(command)?.ToString() ?? ""; - return GetUIElementVariable(value, engine); + return ExpandUserVariableAsUIElement(value, engine); } /// - /// convert variable to string as XPath + /// expand user variable string as XPath /// /// /// /// - public static string ConvertToUserVariableAsXPath(this string value, Engine.AutomationEngineInstance engine) + public static string ExpandUserVariableAsXPath(this string value, Engine.AutomationEngineInstance engine) { - var p = value.ConvertToUserVariable(engine); + var p = value.ExpandValueOrUserVariable(engine); if (!p.StartsWith(".")) { p = "." + p; @@ -193,28 +200,28 @@ public static string ConvertToUserVariableAsXPath(this string value, Engine.Auto } /// - /// convert variable to string as XPath + /// expand variable string as XPath /// /// /// /// /// - public static string ConvertToUserVariableAsXPath(this ScriptCommand command, string parameterName, Engine.AutomationEngineInstance engine) + public static string ExpandUserVariableAsXPath(this ScriptCommand command, string parameterName, Engine.AutomationEngineInstance engine) { var prop = command.GetProperty(parameterName); var value = prop?.GetValue(command)?.ToString() ?? ""; - return ConvertToUserVariableAsXPath(value, engine); + return ExpandUserVariableAsXPath(value, engine); } /// /// store AutomationElement /// /// - /// + /// /// - public static void StoreInUserVariable(this AutomationElement value, Engine.AutomationEngineInstance sender, string targetVariable) + public static void StoreInUserVariable(this AutomationElement value, Engine.AutomationEngineInstance engine, string targetVariable) { - ExtensionMethods.StoreInUserVariable(targetVariable, value, sender, false); + ExtensionMethods.StoreInUserVariable(targetVariable, value, engine, false); } #endregion @@ -242,7 +249,7 @@ public static AutomationElement GetFromWindowName(string windowName, Engine.Auto // try window handle try { - IntPtr wHnd = WindowNameControls.FindWindowHandle(windowName, "exact match", engine); + IntPtr wHnd = WindowControls.FindWindowHandle(windowName, "exact match", engine); windowElement = AutomationElement.FromHandle(wHnd); } catch @@ -324,7 +331,7 @@ private static void parseInspectToolResult(string result, DataTable table, Combo case "LocalizedControlType": case "Name": case "NativeWindowHandle": - case "ProcessID": + case "ProcessId": DataTableControls.SetParameterValue(table, value, name, "ParameterName", "ParameterValue"); break; @@ -352,22 +359,11 @@ private static void parseInspectToolResult(string result, DataTable table, Combo } else { - var f = new UI.Forms.Supplemental.frmDialog("No Inspect Tool Results", "Fail Parse", UI.Forms.Supplemental.frmDialog.DialogType.OkOnly, 0); + var f = new UI.Forms.General.frmDialog("No Inspect Tool Results", "Fail Parse", UI.Forms.General.frmDialog.DialogType.OkOnly, 0); f.ShowDialog(); } } - public static void InspectToolParserClicked(DataTable table, ComboBox windowNames = null) - { - using (UI.Forms.Supplement_Forms.frmInspectParser frm = new UI.Forms.Supplement_Forms.frmInspectParser()) - { - if (frm.ShowDialog() == System.Windows.Forms.DialogResult.OK) - { - parseInspectToolResult(frm.inspectResult, table, windowNames); - } - } - } - private static string parseControlTypeInspectToolResult(string value) { var spt = value.Split(' '); @@ -473,17 +469,92 @@ private static Condition CreateSearchCondition(DataTable table, Engine.Automatio } var parameterName = row.Field("ParameterName") ?? ""; - var parameterValue = row.Field("ParameterValue") ?? ""; ; + var parameterValue = (row.Field("ParameterValue") ?? "").ExpandValueOrUserVariable(engine); - PropertyCondition propCondition; - if (bool.TryParse(parameterValue, out bool bValue)) + // value correction + switch (parameterName) { - propCondition = CreatePropertyCondition(parameterName, bValue); + case "HasKeyboardFocus": + case "IsContentElement": + case "IsControlElement": + case "IsEnabled": + case "IsKeyboardFocusable": + case "IsOffscreen": + case "IsPassword": + case "IsRequiredForForm": + if (string.IsNullOrEmpty(parameterValue)) + { + parameterValue = "False"; + } + else + { + switch (parameterValue.ToLower()) + { + case "yes": + parameterValue = "True"; + break; + case "no": + parameterValue = "False"; + break; + } + } + if (!bool.TryParse(parameterValue, out _)) + { + throw new Exception($"Invalid ParamterValue. Value must be 'True' or 'False'. ParameterName: '{parameterName}', ParameteValue: '{parameterValue}'"); + } + break; + + case "NativeWindowHandle": + case "ProcessId": + if (string.IsNullOrEmpty(parameterValue)) + { + parameterValue = "0"; + } + if (!Int32.TryParse(parameterValue, out _)) + { + throw new Exception($"Invalid ParamterValue. Value must be Int32 value. ParameterName: '{parameterName}', ParameteValue: '{parameterValue}'"); + } + break; } - else + + // DBG + //Debug.WriteLine($"Name: '{parameterName}', Value: '{parameterValue}'"); + + PropertyCondition propCondition = null; + + switch (parameterName) { - propCondition = CreatePropertyCondition(parameterName, parameterValue); + case "HasKeyboardFocus": + case "IsContentElement": + case "IsControlElement": + case "IsEnabled": + case "IsKeyboardFocusable": + case "IsOffscreen": + case "IsPassword": + case "IsRequiredForForm": + propCondition = CreatePropertyCondition(parameterName, bool.Parse(parameterValue)); + break; + + case "NativeWindowHandle": + case "ProcessId": + propCondition = CreatePropertyCondition(parameterName, Int32.Parse(parameterValue)); + break; + + case "AcceleratorKey": + case "AccessKey": + case "AutomationId": + case "ClassName": + case "ControlType": + case "FrameworkId": + case "HelpText": + case "ItemStatus": + case "ItemType": + case "LocalizedControlType": + case "Name": + propCondition = CreatePropertyCondition(parameterName, parameterValue); + break; } + conditionList.Add(propCondition); } @@ -506,7 +577,7 @@ private static Condition CreateSearchCondition(DataTable table, Engine.Automatio /// /// /// - private static AutomationElement DeepSearchGUIElement(AutomationElement rootElement, Condition searchCondition) + private static AutomationElement DeepSearchGUIElement(AutomationElement rootElement, Condition searchCondition, DateTime endTime) { TreeWalker walker = TreeWalker.RawViewWalker; @@ -524,35 +595,71 @@ private static AutomationElement DeepSearchGUIElement(AutomationElement rootElem }; } - var ret = WalkerSearch(rootElement, conditions, walker); + var ret = WalkerSearch_DepthFirst(rootElement, conditions, walker, endTime); + //var ret = WalkerSearch_WidthFirst_Reverse(rootElement, conditions, walker, endTime); return ret; } /// - /// Search GUI Element used by TreeWalker + /// Search GUI Element used by TreeWalker (Depth First) /// /// /// /// /// - private static AutomationElement WalkerSearch(AutomationElement rootElement, PropertyCondition[] searchConditions, TreeWalker walker) + private static AutomationElement WalkerSearch_DepthFirst(AutomationElement rootElement, PropertyCondition[] searchConditions, TreeWalker walker, DateTime endTime) { AutomationElement node = walker.GetFirstChild(rootElement); AutomationElement ret = null; while (node != null) { - var result = searchConditions.All(c => node.GetCurrentPropertyValue(c.Property) == c.Value); + // DBG + //Console.WriteLine($"# Node: {node.Current.Name}"); + + bool result = true; + foreach (var c in searchConditions) + { + object p = node.GetCurrentPropertyValue(c.Property); + + switch (c.Property.ProgrammaticName) + { + case "AutomationElementIdentifiers.ControlTypeProperty": + // ControlType compare + result &= (c.Value.ToString() == ((ControlType)p).Id.ToString()); + // DBG + //Console.WriteLine($"Property: '{c.Property.ProgrammaticName}', Value Cond: '{c.Value.ToString()}', Value Node: '{((ControlType)p).Id.ToString()}'"); + break; + + default: + // normal compare + result &= (c.Value.ToString() == p.ToString()); + // DBG + //Console.WriteLine($"Property: '{c.Property.ProgrammaticName}', Value Cond: '{c.Value.ToString()}', Value Node: '{p.ToString()}'"); + break; + } + + if (!result) + { + break; + } + } + if (result) { ret = node; break; } + // Time up! not found. + if (DateTime.Now > endTime) + { + break; + } // search child node if (walker.GetFirstChild(node) != null) { - ret = WalkerSearch(node, searchConditions, walker); + ret = WalkerSearch_DepthFirst(node, searchConditions, walker, endTime); if (ret != null) { break; @@ -566,6 +673,80 @@ private static AutomationElement WalkerSearch(AutomationElement rootElement, Pro return ret; } + /// + /// Search GUI Element used by TreeWalker (Depth First, Reverse) + /// + /// + /// + /// + /// + /// + private static AutomationElement WalkerSearch_DepthFirst_Reverse(AutomationElement rootElement, PropertyCondition[] searchConditions, TreeWalker walker, DateTime endTime) + { + AutomationElement node = walker.GetLastChild(rootElement); + AutomationElement ret = null; + + while (node != null) + { + // DBG + //Console.WriteLine($"# Node: {node.Current.Name}"); + + bool result = true; + foreach (var c in searchConditions) + { + object p = node.GetCurrentPropertyValue(c.Property); + + switch (c.Property.ProgrammaticName) + { + case "AutomationElementIdentifiers.ControlTypeProperty": + // ControlType compare + result &= (c.Value.ToString() == ((ControlType)p).Id.ToString()); + // DBG + //Console.WriteLine($"Property: '{c.Property.ProgrammaticName}', Value Cond: '{c.Value.ToString()}', Value Node: '{((ControlType)p).Id.ToString()}'"); + break; + + default: + // normal compare + result &= (c.Value.ToString() == p.ToString()); + // DBG + //Console.WriteLine($"Property: '{c.Property.ProgrammaticName}', Value Cond: '{c.Value.ToString()}', Value Node: '{p.ToString()}'"); + break; + } + + if (!result) + { + break; + } + } + + if (result) + { + ret = node; + break; + } + // Time up! not found. + if (DateTime.Now > endTime) + { + break; + } + + // search child node + if (walker.GetLastChild(node) != null) + { + ret = WalkerSearch_DepthFirst_Reverse(node, searchConditions, walker, endTime); + if (ret != null) + { + break; + } + } + + // previous sibling + node = walker.GetPreviousSibling(node); + } + + return ret; + } + /// /// Search GUI Element by specified conditions DataTable /// @@ -573,13 +754,16 @@ private static AutomationElement WalkerSearch(AutomationElement rootElement, Pro /// /// /// - private static AutomationElement SearchGUIElement(AutomationElement rootElement, DataTable conditionTable, Engine.AutomationEngineInstance engine) + private static AutomationElement SearchGUIElement(AutomationElement rootElement, DataTable conditionTable, Engine.AutomationEngineInstance engine, DateTime endTime) { Condition searchConditions = CreateSearchCondition(conditionTable, engine); - var element = rootElement.FindFirst(TreeScope.Descendants, searchConditions) ?? - rootElement.FindFirst(TreeScope.Subtree, searchConditions) ?? - DeepSearchGUIElement(rootElement, searchConditions); + // NOTE: stop hung up + //var element = rootElement.FindFirst(TreeScope.Descendants, searchConditions) ?? + // rootElement.FindFirst(TreeScope.Subtree, searchConditions) ?? + // DeepSearchGUIElement(rootElement, searchConditions); + + var element = DeepSearchGUIElement(rootElement, searchConditions, endTime); // if element not found, don't throw exception here return element; @@ -599,7 +783,8 @@ public static AutomationElement SearchGUIElement(AutomationElement elem, DataTab var ret = WaitControls.WaitProcess(waitTime, "AutomationElement", new Func<(bool, object)>(() => { - var e = SearchGUIElement(elem, conditionTable, engine); + var endTime = DateTime.Now.AddSeconds(waitTime); + var e = SearchGUIElement(elem, conditionTable, engine, endTime); if (e != null) { return (true, e); @@ -632,9 +817,9 @@ public static AutomationElement SearchGUIElement(AutomationElement elem, DataTab /// public static AutomationElement SearchGUIElement(ScriptCommand command, string elementName, string conditionName, string waitTimeName, Engine.AutomationEngineInstance engine) { - var elem = command.CovnertToUserVariableAsUIElement(elementName, engine); - var table = command.ConvertToUserVariableAsDataTable(conditionName, engine); - var waitTime = command.ConvertToUserVariableAsInteger(waitTimeName, engine); + var elem = command.ExpandUserVariableAsUIElement(elementName, engine); + var table = command.ConvertParameterToDataTable(conditionName, engine); + var waitTime = command.ExpandValueOrUserVariableAsInteger(waitTimeName, engine); return SearchGUIElement(elem, table, waitTime, engine); } @@ -669,7 +854,7 @@ public static AutomationElement GetWindowUIElement(ScriptCommand command, Engine { AutomationElement ret = null; - WindowNameControls.WindowAction(command, engine, + WindowControls.WindowAction(command, engine, new Action>(wins => { ret = AutomationElement.FromHandle(wins[0].Item1); @@ -677,7 +862,7 @@ public static AutomationElement GetWindowUIElement(ScriptCommand command, Engine if (!string.IsNullOrEmpty(resultName)) { //var resultValue = command.ConvertToUserVariable(resultName, "Result", engine); - var resultValue = command.GetRawPropertyString(resultName, "Result"); + var resultValue = command.GetRawPropertyValueAsString(resultName, "Result"); ret.StoreInUserVariable(engine, resultValue); } @@ -788,7 +973,7 @@ public static string GetWindowName(AutomationElement targetElement) catch { // try other method - var windowNames = WindowNameControls.GetAllWindowTitles(); + var windowNames = WindowControls.GetAllWindowTitles(); if ((targetElement.Current.NativeWindowHandle != 0) && (windowNames.Contains(targetElement.Current.Name))) { return targetElement.Current.Name; @@ -841,21 +1026,26 @@ public static int GetWindowHandle(AutomationElement targetElement) public static string GetTextValue(AutomationElement targetElement) { - object patternObj; - if (targetElement.TryGetCurrentPattern(ValuePattern.Pattern, out patternObj)) + //object patternObj; + if (targetElement.TryGetCurrentPattern(RangeValuePattern.Pattern, out object rPtn)) + { + // bar + return ((RangeValuePattern)rPtn).Current.Value.ToString(); + } + else if (targetElement.TryGetCurrentPattern(ValuePattern.Pattern, out object vPtn)) { // TextBox - return ((ValuePattern)patternObj).Current.Value; + return ((ValuePattern)vPtn).Current.Value; } - else if (targetElement.TryGetCurrentPattern(TextPattern.Pattern, out patternObj)) + else if (targetElement.TryGetCurrentPattern(TextPattern.Pattern, out object tPtn)) { // TextBox Multilune - return ((TextPattern)patternObj).DocumentRange.GetText(-1); + return ((TextPattern)tPtn).DocumentRange.GetText(-1); } - else if (targetElement.TryGetCurrentPattern(SelectionPattern.Pattern, out patternObj)) + else if (targetElement.TryGetCurrentPattern(SelectionPattern.Pattern, out object sPtn)) { // combobox - AutomationElement selElem = ((SelectionPattern)patternObj).Current.GetSelection()[0]; + AutomationElement selElem = ((SelectionPattern)sPtn).Current.GetSelection()[0]; return selElem.Current.Name; } else @@ -867,68 +1057,90 @@ public static string GetTextValue(AutomationElement targetElement) public static AutomationElement GetTableUIElement(AutomationElement targetElement, int row, int column) { - object tryObj; - if (!targetElement.TryGetCurrentPattern(GridPattern.Pattern, out tryObj)) + if (targetElement.TryGetCurrentPattern(GridPattern.Pattern, out object gridObj)) { - throw new Exception("UIElement is not Table Element"); - } - GridPattern gridPtn = (GridPattern)tryObj; + var cosutomRows = targetElement.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Custom)); + if (cosutomRows.Count > 0) + { + // DataGridView (.net) + if (cosutomRows.Count > row) + { + var r = cosutomRows[row + 1]; + var cols = r.FindAll(TreeScope.Children, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); + if (cols.Count > column) + { + return cols[column]; + } + } - AutomationElement cellElem = gridPtn.GetItem(row, column); - if (cellElem == null) + throw new Exception("Table Row: '" + row + "', Column: '" + column + "' does not exists"); + } + else + { + // listView + AutomationElement cellElem = ((GridPattern)gridObj).GetItem(row, column); + if (cellElem == null) + { + throw new Exception("Table Row: '" + row + "', Column: '" + column + "' does not exists"); + } + return cellElem; + } + } + else { - throw new Exception("Table Row: '" + row + "', Column: '" + column + "' does not exists"); + throw new Exception("UIElement is not Table Element"); } - - return cellElem; } - public static List GetSelectionItems(AutomationElement targetElement, bool collapseAfter = true) + public static List GetSelectionItems(AutomationElement targetElement) { - AutomationElement rootElement = targetElement; - - object ptnResult; - - ptnResult = rootElement.GetCurrentPropertyValue(AutomationElement.IsGridPatternAvailableProperty); - if ((bool)ptnResult) - { - // DataGridView - var elems = rootElement.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, true)); + var getListItemFunc = new Func>( el => { + var elems = el.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, true)); List ret = new List(); foreach (AutomationElement elem in elems) { ret.Add(elem); } return ret; + }); + + AutomationElement rootElement = targetElement; + + if ((bool)rootElement.GetCurrentPropertyValue(AutomationElement.IsGridPatternAvailableProperty) || + (bool)rootElement.GetCurrentPropertyValue(AutomationElement.IsSelectionPatternAvailableProperty)) + { + // DataGridView-ComboBox, ListBox + return getListItemFunc(rootElement); } else { - // ComboBox - ptnResult = rootElement.GetCurrentPropertyValue(AutomationElement.IsExpandCollapsePatternAvailableProperty); - if (!(bool)ptnResult) + // ComboBox, TreeView + bool isCmb = (bool)rootElement.GetCurrentPropertyValue(AutomationElement.IsExpandCollapsePatternAvailableProperty); + + if (!isCmb) { rootElement = GetParentUIElement(rootElement); + isCmb = (bool)rootElement.GetCurrentPropertyValue(AutomationElement.IsExpandCollapsePatternAvailableProperty); } - ptnResult = rootElement.GetCurrentPropertyValue(AutomationElement.IsExpandCollapsePatternAvailableProperty); - if ((bool)ptnResult) + if ((bool)isCmb) { object selPtn = rootElement.GetCurrentPattern(ExpandCollapsePattern.Pattern); ExpandCollapsePattern ecPtn = (ExpandCollapsePattern)selPtn; ecPtn.Expand(); + System.Threading.Thread.Sleep(500); - var elems = rootElement.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.IsSelectionItemPatternAvailableProperty, true)); - List ret = new List(); - foreach (AutomationElement elem in elems) - { - ret.Add(elem); - } + // dbg + //System.Threading.Thread.Sleep(1000); + //Console.WriteLine("Expanded"); - if (collapseAfter) - { - ecPtn.Collapse(); - } + var ret = getListItemFunc(rootElement); + + //if (collapseAfter) + //{ + // ecPtn.Collapse(); + //} return ret; } else @@ -1037,19 +1249,11 @@ public static AutomationElement SearchGUIElementByXPath(AutomationElement rootEl } } - //public static AutomationElement SearchGUIElementByXPath(ScriptCommand command, AutomationElement elem, string xpathName, string waitTimeName, Engine.AutomationEngineInstance engine) - //{ - // var xpath = command.ConvertToUserVariableAsXPath(xpathName, engine); - // var wait = command.ConvertToUserVariableAsInteger(waitTimeName, engine); - - // return SearchGUIElementByXPath(elem, xpath, wait, engine); - //} - public static AutomationElement SearchGUIElementByXPath(ScriptCommand command, string rootElementName, string xpathName, string waitTimeName, Engine.AutomationEngineInstance engine) { - var element = command.CovnertToUserVariableAsUIElement(rootElementName, engine); - var xpath = command.ConvertToUserVariableAsXPath(xpathName, engine); - var wait = command.ConvertToUserVariableAsInteger(waitTimeName, engine); + var element = command.ExpandUserVariableAsUIElement(rootElementName, engine); + var xpath = command.ExpandUserVariableAsXPath(xpathName, engine); + var wait = command.ExpandValueOrUserVariableAsInteger(waitTimeName, engine); return SearchGUIElementByXPath(element, xpath, wait, engine); } @@ -1074,14 +1278,16 @@ public static TreeNode GetElementTreeNode(string windowName, Engine.AutomationEn var tree = CreateTreeNodeFromAutomationElement(root); xml = CreateXmlElement(root); - GetChildElementTreeNode(tree, xml, root, walker); + GetChildElementTreeNode(tree, xml, root, walker, 1, engine); return tree; } - private static void GetChildElementTreeNode(TreeNode tree, XElement xml, AutomationElement rootElement, TreeWalker walker) + private static void GetChildElementTreeNode(TreeNode tree, XElement xml, AutomationElement rootElement, TreeWalker walker, int depth, Engine.AutomationEngineInstance engine) { AutomationElement node = walker.GetFirstChild(rootElement); + + int siblingCount = 0; while(node != null) { var item = CreateTreeNodeFromAutomationElement(node); @@ -1090,9 +1296,15 @@ private static void GetChildElementTreeNode(TreeNode tree, XElement xml, Automat var childXml = CreateXmlElement(node); xml.Add(childXml); - if (walker.GetFirstChild(node) != null) + if ((walker.GetFirstChild(node) != null) && (depth < engine.engineSettings.MaxUIElementInpectDepth)) + { + GetChildElementTreeNode(item, childXml, node, walker, (depth + 1), engine); + } + + siblingCount++; + if (siblingCount >= engine.engineSettings.MaxUIElementInspectSiblingNodes) { - GetChildElementTreeNode(item, childXml, node, walker); + break; } node = walker.GetNextSibling(node); @@ -1136,6 +1348,25 @@ public static string GetInspectResultFromAutomationElement(AutomationElement ele res += "ItemStatus:\t\"" + elem.Current.ItemStatus + "\"\r\n"; res += "ItemType:\t\"" + elem.Current.ItemType + "\"\r\n"; res += "NativeWindowHandle:\t" + elem.Current.NativeWindowHandle.ToString() + "\r\n"; + + res += "IsDockPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsDockPatternAvailableProperty) + "\r\n"; + res += "IsExpandCollapsePatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsExpandCollapsePatternAvailableProperty) + "\r\n"; + res += "IsGridPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsGridPatternAvailableProperty) + "\r\n"; + res += "IsGridItemPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsGridItemPatternAvailableProperty) + "\r\n"; + res += "IsInvokePatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsInvokePatternAvailableProperty) + "\r\n"; + res += "IsMultipleViewPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsMultipleViewPatternAvailableProperty) + "\r\n"; + res += "IsRangeValuePatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsRangeValuePatternAvailableProperty) + "\r\n"; + res += "IsScrollPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsScrollPatternAvailableProperty) + "\r\n"; + res += "IsScrollItemPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsScrollItemPatternAvailableProperty) + "\r\n"; + res += "IsSelectionPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsSelectionPatternAvailableProperty) + "\r\n"; + res += "IsSelectionItemPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsSelectionItemPatternAvailableProperty) + "\r\n"; + res += "IsTablePatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsTablePatternAvailableProperty) + "\r\n"; + res += "IsTableItemPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsTableItemPatternAvailableProperty) + "\r\n"; + res += "IsTextPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsTextPatternAvailableProperty) + "\r\n"; + res += "IsTogglePatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsTogglePatternAvailableProperty) + "\r\n"; + res += "IsTransformPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsTransformPatternAvailableProperty) + "\r\n"; + res += "IsValuePatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsValuePatternAvailableProperty) + "\r\n"; + res += "IsWindowPatternAvailableProperty:\t" + (bool)elem.GetCurrentPropertyValue(AutomationElement.IsWindowPatternAvailableProperty) + "\r\n"; } catch(Exception ex) { @@ -1266,11 +1497,12 @@ private static string CreateXPath(XElement elemNode, bool useNameAttribute = tru /// public static void lnkGUIInspectTool_UsedByXPath_Click(object sender, EventArgs e) { - using (var fm = new UI.Forms.Supplement_Forms.frmGUIInspect()) + using (var fm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmGUIInspect()) { - if (fm.ShowDialog() == System.Windows.Forms.DialogResult.OK) + var trgCtrl = (Control)sender; + if (fm.ShowDialog(trgCtrl.FindForm()) == DialogResult.OK) { - object ctrl = ((Control)sender).Tag; + object ctrl = trgCtrl.Tag; if (ctrl is TextBox txt) { txt.Text = fm.XPath; @@ -1311,9 +1543,9 @@ private static void dgvUpdateProcess(object sender, Action updateFunc /// public static void lnkGUIInspectTool_UsedByInspectResult_Click(object sender, EventArgs e) { - using (var fm = new UI.Forms.Supplement_Forms.frmGUIInspect()) + using (var fm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmGUIInspect()) { - if (fm.ShowDialog() == System.Windows.Forms.DialogResult.OK) + if (fm.ShowDialog(((Control)sender).FindForm()) == DialogResult.OK) { dgvUpdateProcess(sender, new Action((tbl) => { @@ -1343,9 +1575,9 @@ public static void lnkAddEmptyParameter_Click(object sender, EventArgs e) /// public static void lnkInspectToolParser_Click(object sender, EventArgs e) { - using (var fm = new UI.Forms.Supplement_Forms.frmInspectParser()) + using (var fm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmInspectParser()) { - if (fm.ShowDialog() == System.Windows.Forms.DialogResult.OK) + if (fm.ShowDialog(((Control)sender).FindForm()) == DialogResult.OK) { dgvUpdateProcess(sender, new Action((tbl) => { @@ -1355,27 +1587,6 @@ public static void lnkInspectToolParser_Click(object sender, EventArgs e) } } - public static void GUIInspectTool_UsedByXPath_Clicked(TextBox txtXPath) - { - using(var fm = new UI.Forms.Supplement_Forms.frmGUIInspect()) - { - if (fm.ShowDialog() == System.Windows.Forms.DialogResult.OK) - { - txtXPath.Text = fm.XPath; - } - } - } - public static void GUIInspectTool_UsedByInspectResult_Clicked(DataTable searchParams) - { - using (var fm = new UI.Forms.Supplement_Forms.frmGUIInspect()) - { - if (fm.ShowDialog() == System.Windows.Forms.DialogResult.OK) - { - string result = fm.InspectResult; - parseInspectToolResult(result, searchParams); - } - } - } public static void UIAutomationDataGridView_CellClick(object sender, DataGridViewCellEventArgs e) { var myDGV = (DataGridView)sender; diff --git a/taskt/Core/Automation/Commands/Variable/CheckVariableExistsCommand.cs b/taskt/Core/Automation/Commands/Variable/CheckVariableExistsCommand.cs index fdb2c3a14..52accc15c 100644 --- a/taskt/Core/Automation/Commands/Variable/CheckVariableExistsCommand.cs +++ b/taskt/Core/Automation/Commands/Variable/CheckVariableExistsCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Variable Commands")] + [Attributes.ClassAttributes.Group("Variable")] [Attributes.ClassAttributes.CommandSettings("Check Variable Exists")] [Attributes.ClassAttributes.Description("This command allows you to check variable existance.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check variable existance.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CheckVariableExistsCommand : ScriptCommand + public sealed class CheckVariableExistsCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(VariableNameControls), nameof(VariableNameControls.v_VariableName))] @@ -31,11 +32,8 @@ public CheckVariableExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - var variableName = VariableNameControls.GetVariableName(v_userVariableName, engine); VariableNameControls.IsVariableExists(variableName, engine).StoreInUserVariable(engine, v_Result); } diff --git a/taskt/Core/Automation/Commands/Variable/GetVariableIndexCommand.cs b/taskt/Core/Automation/Commands/Variable/GetVariableIndexCommand.cs index 3ca466e4e..8792a259b 100644 --- a/taskt/Core/Automation/Commands/Variable/GetVariableIndexCommand.cs +++ b/taskt/Core/Automation/Commands/Variable/GetVariableIndexCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Variable Commands")] + [Attributes.ClassAttributes.Group("Variable")] [Attributes.ClassAttributes.CommandSettings("Get Variable Index")] [Attributes.ClassAttributes.Description("This command allows you to get Variable Index.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Variable Index.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetVariableIndexCommand : ScriptCommand + public sealed class GetVariableIndexCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(VariableNameControls), nameof(VariableNameControls.v_VariableName))] @@ -27,11 +28,8 @@ public GetVariableIndexCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - var variableName = VariableNameControls.GetVariableName(v_userVariableName, engine); var rawVarialbe = variableName.GetRawVariable(engine); rawVarialbe.CurrentPosition.ToString().StoreInUserVariable(engine, v_Result); diff --git a/taskt/Core/Automation/Commands/Variable/GetVariableTypeCommand.cs b/taskt/Core/Automation/Commands/Variable/GetVariableTypeCommand.cs index 3b04f426c..6cdc9ded4 100644 --- a/taskt/Core/Automation/Commands/Variable/GetVariableTypeCommand.cs +++ b/taskt/Core/Automation/Commands/Variable/GetVariableTypeCommand.cs @@ -10,14 +10,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Variable Commands")] + [Attributes.ClassAttributes.Group("Variable")] [Attributes.ClassAttributes.CommandSettings("Get Variable Type")] [Attributes.ClassAttributes.Description("This command allows you to get variable type.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get variable type.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetVariableTypeCommand : ScriptCommand + public sealed class GetVariableTypeCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(VariableNameControls), nameof(VariableNameControls.v_VariableName))] @@ -35,11 +36,8 @@ public GetVariableTypeCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - var rawValue = v_userVariableName.GetRawVariable(engine).VariableValue; string result; if (rawValue is List) diff --git a/taskt/Core/Automation/Commands/Variable/NewVariableCommand.cs b/taskt/Core/Automation/Commands/Variable/NewVariableCommand.cs index be07d7fc3..62f0bab88 100644 --- a/taskt/Core/Automation/Commands/Variable/NewVariableCommand.cs +++ b/taskt/Core/Automation/Commands/Variable/NewVariableCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Variable Commands")] + [Attributes.ClassAttributes.Group("Variable")] [Attributes.ClassAttributes.CommandSettings("New Variable")] [Attributes.ClassAttributes.Description("This command allows you to explicitly add a variable if you are not using **Set Variable* with the setting **Create Missing Variables** at runtime.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to modify the value of variables. You can even use variables to modify other variables.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class NewVariableCommand : ScriptCommand + public sealed class NewVariableCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(VariableNameControls), nameof(VariableNameControls.v_VariableName))] @@ -44,14 +45,11 @@ public NewVariableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; + var variableValue = v_Input.ExpandValueOrUserVariable(engine); - var variableValue = v_Input.ConvertToUserVariable(engine); - - var ifExists = this.GetUISelectionValue(nameof(v_IfExists), engine); + var ifExists = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_IfExists), engine); var variableName = VariableNameControls.GetVariableName(v_userVariableName, engine); if (VariableNameControls.IsVariableExists(variableName, engine)) { diff --git a/taskt/Core/Automation/Commands/Variable/SetVariableIndexCommand.cs b/taskt/Core/Automation/Commands/Variable/SetVariableIndexCommand.cs index 499805fad..955307240 100644 --- a/taskt/Core/Automation/Commands/Variable/SetVariableIndexCommand.cs +++ b/taskt/Core/Automation/Commands/Variable/SetVariableIndexCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Variable Commands")] + [Attributes.ClassAttributes.Group("Variable")] [Attributes.ClassAttributes.CommandSettings("Set Variable Index")] [Attributes.ClassAttributes.Description("This command allows you to modify variables.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to modify the value of variables. You can even use variables to modify other variables.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetVariableIndexCommand : ScriptCommand + public sealed class SetVariableIndexCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(VariableNameControls), nameof(VariableNameControls.v_VariableName))] @@ -41,15 +42,12 @@ public SetVariableIndexCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; - var variableName = VariableNameControls.GetVariableName(v_userVariableName, engine); var rawVariable = variableName.GetRawVariable(engine); - var index = this.ConvertToUserVariableAsInteger(nameof(v_Index), engine); + var index = this.ExpandValueOrUserVariableAsInteger(nameof(v_Index), engine); rawVariable.CurrentPosition = index; } } diff --git a/taskt/Core/Automation/Commands/Variable/SetVariableValueCommand.cs b/taskt/Core/Automation/Commands/Variable/SetVariableValueCommand.cs index 56e7e43d2..039757c7b 100644 --- a/taskt/Core/Automation/Commands/Variable/SetVariableValueCommand.cs +++ b/taskt/Core/Automation/Commands/Variable/SetVariableValueCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Variable Commands")] + [Attributes.ClassAttributes.Group("Variable")] [Attributes.ClassAttributes.CommandSettings("Set Variable Value")] [Attributes.ClassAttributes.Description("This command allows you to modify variables.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to modify the value of variables. You can even use variables to modify other variables.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements actions against VariableList from the scripting engine.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetVariableValueCommand : ScriptCommand + public sealed class SetVariableValueCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(VariableNameControls), nameof(VariableNameControls.v_VariableName))] @@ -24,14 +25,19 @@ public class SetVariableValueCommand : ScriptCommand public string v_Input { get; set; } [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Convert Variables in Input Text Above")] - [PropertyUISelectionOption("Yes")] - [PropertyUISelectionOption("No")] - [InputSpecification("", true)] [Remarks("If **{{{vNum}}}** has **'1'** and You select **'Yes'**, Variable will be Assigned **'1'**. If You Select **'No'**, Variable will be assigned **'{{{vNum}}}'**.")] [PropertyIsOptional(true, "Yes")] public string v_ReplaceInputVariables { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Create New Variable when that Variable Does not Exist")] + [PropertyIsOptional(true, "No")] + [Remarks("This command ignores the 'Create Missing Variable During Execution' value in the Settings")] + public string v_CreateNewVariable { get; set; } + public SetVariableValueCommand() { //this.CommandName = "VariableCommand"; @@ -41,16 +47,23 @@ public SetVariableValueCommand() //this.v_ReplaceInputVariables = "Yes"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get sending instance - var engine = (Engine.AutomationEngineInstance)sender; + //var isRepalce = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ReplaceInputVariables), engine); + //string variableValue; + //if (isRepalce == "yes") + //{ + // variableValue = v_Input.ExpandValueOrUserVariable(engine); + //} + //else + //{ + // variableValue = v_Input; + //} - var isRepalce = this.GetUISelectionValue(nameof(v_ReplaceInputVariables), engine); string variableValue; - if (isRepalce == "yes") + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ReplaceInputVariables), engine)) { - variableValue = v_Input.ConvertToUserVariable(engine); + variableValue = v_Input.ExpandValueOrUserVariable(engine); } else { @@ -58,7 +71,8 @@ public override void RunCommand(object sender) } var variableName = VariableNameControls.GetVariableName(v_userVariableName, engine); - if (VariableNameControls.IsVariableExists(variableName, engine)) + if (VariableNameControls.IsVariableExists(variableName, engine) || + this.ExpandValueOrUserVariableAsYesNo(nameof(v_CreateNewVariable), engine)) { variableValue.StoreInUserVariable(engine, variableName); } diff --git a/taskt/Core/Automation/Commands/VariableNameControls.cs b/taskt/Core/Automation/Commands/VariableNameControls.cs index 7233af7be..5a028f4ef 100644 --- a/taskt/Core/Automation/Commands/VariableNameControls.cs +++ b/taskt/Core/Automation/Commands/VariableNameControls.cs @@ -10,8 +10,67 @@ namespace taskt.Core.Automation.Commands /// internal static class VariableNameControls { - #region - private const string InnerVariablePrefix = "__INNER_"; + #region const, properties + /// + /// inner variable name prefix + /// + public const string INNER_VARIABLE_PREFIX = "__INNER_"; + /// + /// inner variable start marker + /// + private const string INTERNAL_VARIABLE_START_MARKER_KEYWORD = "{{{"; + /// + /// inner variable end marker + /// + private const string INTERNAL_VARIABLE_END_MARKER_KEYWORD = "}}}"; + + /// + /// disallow variable name character list + /// + public static readonly List DisallowVariableCharList = new List() + { + "+", "-", "*", "%", + "[", "]", "{", "}", + ".", + " ", "\t", "\r", "\n", + IntermediateControls.INTERMEDIATE_VALIABLE_START_MARKER, IntermediateControls.INTERMEDIATE_VALIABLE_END_MARKER, + IntermediateControls.INTERMEDIATE_KEYWORD_START_MARKER, IntermediateControls.INTERMEDIATE_VALIABLE_END_MARKER, + }; + + /// + /// reserved key name, not use variable name + /// + public static readonly List ReservedKeyNameList = new List() + { + "BACKSPACE", "BS", "BKSP", + "BREAK", + "CAPSLOCK", + "DELETE", "DEL", + "UP", "DOWN", "LEFT", "RIGHT", + "END", + "ENTER", + "INSERT", "INS", + "NUMLOCK", + "PGDN", + "PGUP", + "SCROLLROCK", + "TAB", + "F1", "F2", "F3", "F4", "F5", "F6", + "F7", "F8", "F9", "F10", "F11", "F12", + "ADD", "SUBTRACT", "MULTIPLY", "DIVIDE", + "WIN_KEY", + }; + + /// + /// disallow head variable name charactor list + /// + public static readonly List DisallowHeadVariableCharList = new List() + { + "0", "1", "2", "3", + "4", "5", "6", "7", + "8", "9", + INNER_VARIABLE_PREFIX, + }; #endregion #region virtual properties @@ -28,6 +87,7 @@ internal static class VariableNameControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] [PropertyValidationRule("Variable", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Variable")] + [PropertyParameterOrder(5000)] public static string v_VariableName { get; } /// @@ -42,6 +102,7 @@ internal static class VariableNameControls [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.MultiLineTextBox)] [PropertyShowSampleUsageInDescription(true)] [PropertyDisplayText(true, "Value")] + [PropertyParameterOrder(5000)] public static string v_VariableValue { get; } #endregion @@ -54,7 +115,7 @@ internal static class VariableNameControls /// public static bool IsVariableExists(string name, Engine.AutomationEngineInstance engine) { - return engine.VariableList.Any(v => (v.VariableName == name.ConvertToUserVariable(engine))); + return engine.VariableList.Any(v => (v.VariableName == name.ExpandValueOrUserVariable(engine))); } /// @@ -65,7 +126,7 @@ public static bool IsVariableExists(string name, Engine.AutomationEngineInstance /// public static string GetVariableName(string name, Engine.AutomationEngineInstance engine) { - if (IsWrapVariableMarker(name, engine) && engine.engineSettings.IgnoreFirstVariableMarkerInOutputParameter) + if (IsWrappedVariableMarker(name, engine) && engine.engineSettings.IgnoreFirstVariableMarkerInOutputParameter) { var len = name.Length; var s = engine.engineSettings.VariableStartMarker.Length; @@ -83,9 +144,31 @@ public static string GetVariableName(string name, Engine.AutomationEngineInstanc /// name is not converted /// /// - public static bool IsWrapVariableMarker(string name, Engine.AutomationEngineInstance engine) + public static bool IsWrappedVariableMarker(string name, Engine.AutomationEngineInstance engine) { - return (name.StartsWith(engine.engineSettings.VariableStartMarker) && name.EndsWith(engine.engineSettings.VariableEndMarker)); + return IsWrappedVariableMarker(name, engine.engineSettings); + } + + /// + /// check string starts variable start maker and ends variable ends marker + /// + /// name is not converted + /// + /// + public static bool IsWrappedVariableMarker(string name, ApplicationSettings settings) + { + return IsWrappedVariableMarker(name, settings.EngineSettings); + } + + /// + /// check string starts variable start maker and ends variable ends marker + /// + /// name is not converted + /// + /// + private static bool IsWrappedVariableMarker(string name, EngineSettings settings) + { + return (name.StartsWith(settings.VariableStartMarker) && name.EndsWith(settings.VariableEndMarker)); } /// @@ -96,57 +179,154 @@ public static bool IsWrapVariableMarker(string name, Engine.AutomationEngineInst /// public static string GetWrappedVariableName(string name, Engine.AutomationEngineInstance engine) { - if (IsWrapVariableMarker(name, engine)) + if (IsWrappedVariableMarker(name, engine)) { return name; } else { - return engine.engineSettings.VariableStartMarker + name + engine.engineSettings.VariableEndMarker; + return GetWrappedVariableName(name, engine.engineSettings); } } - #endregion - #region inner variable methods + /// + /// get wrapped variable name. + /// + /// name is not converted + /// + /// + public static string GetWrappedVariableName(string name, ApplicationSettings settings) + { + if (IsWrappedVariableMarker(name, settings)) + { + return name; + } + else + { + return GetWrappedVariableName(name, settings.EngineSettings); + } + } /// - /// get inner variable value + /// get wrapped variable name. /// - /// - /// + /// name is not converted + /// /// - public static Script.ScriptVariable GetInnerVariable(int index, Engine.AutomationEngineInstance engine) + private static string GetWrappedVariableName(string name, EngineSettings settings) { - return GetInnerVariableName(index, engine).GetRawVariable(engine); + return settings.VariableStartMarker + name + settings.VariableEndMarker; } /// - /// set inner variable value + /// get variable names /// - /// - /// - /// - public static void SetInnerVariable(object value, int index, Engine.AutomationEngineInstance engine) + /// + /// + public static List GetVariableNames(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - Script.ScriptVariable v = GetInnerVariableName(index, engine).GetRawVariable(engine); - v.VariableValue = value; + return editor?.scriptVariables.Select(t => t.VariableName).ToList() ?? new List(); } /// - /// get inner variable name + /// check valid variable name /// - /// - /// + /// /// - public static string GetInnerVariableName(int index, Engine.AutomationEngineInstance engine, bool wrapped = true) + public static bool IsValidVariableName(string name) { - var varName = InnerVariablePrefix + index.ToString(); - if (wrapped) + //foreach (string s in ReservedKeyNameList) + //{ + // if (name == s) + // { + // return false; + // } + //} + if (ReservedKeyNameList.Contains(name)) + { + return false; + } + + foreach (string s in DisallowVariableCharList) { - varName = GetWrappedVariableName(varName, engine); + if (name.Contains(s)) + { + return false; + } } - return varName; + + foreach(string s in DisallowHeadVariableCharList) + { + if (name.StartsWith(s)) + { + return false; + } + } + + //if (name.StartsWith("__INNER_")) + //{ + // return false; + //} + return true; + } + #endregion + + #region keywords methods + + public static string ReplaceKeywordsToSystemVariable(string txt, Engine.AutomationEngineInstance engine) + { + return txt.Replace(INTERNAL_VARIABLE_START_MARKER_KEYWORD, engine.engineSettings.VariableStartMarker) + .Replace(INTERNAL_VARIABLE_END_MARKER_KEYWORD, engine.engineSettings.VariableEndMarker); } + + public static string ReplaceKeywordsToSystemVariable(string txt, ApplicationSettings settings) + { + return txt.Replace(INTERNAL_VARIABLE_START_MARKER_KEYWORD, settings.EngineSettings.VariableStartMarker) + .Replace(INTERNAL_VARIABLE_END_MARKER_KEYWORD, settings.EngineSettings.VariableEndMarker); + } + + #endregion + + #region inner variable methods + + ///// + ///// get inner variable value + ///// + ///// + ///// + ///// + //public static Script.ScriptVariable GetInnerVariable(int index, Engine.AutomationEngineInstance engine) + //{ + // return GetInnerVariableName(index, engine).GetRawVariable(engine); + //} + + ///// + ///// set inner variable value + ///// + ///// + ///// + ///// + //public static void SetInnerVariable(object value, int index, Engine.AutomationEngineInstance engine) + //{ + // Script.ScriptVariable v = GetInnerVariableName(index, engine).GetRawVariable(engine); + // v.VariableValue = value; + //} + + ///// + ///// get inner variable name + ///// + ///// + ///// + ///// + //public static string GetInnerVariableName(int index, Engine.AutomationEngineInstance engine, bool wrapped = true) + //{ + // var varName = INNER_VARIABLE_PREFIX + index.ToString(); + // if (wrapped) + // { + // varName = GetWrappedVariableName(varName, engine); + // } + // return varName; + //} #endregion } } diff --git a/taskt/Core/Automation/Commands/WaitControls.cs b/taskt/Core/Automation/Commands/WaitControls.cs index 3d88ea8d5..af3cf270e 100644 --- a/taskt/Core/Automation/Commands/WaitControls.cs +++ b/taskt/Core/Automation/Commands/WaitControls.cs @@ -19,7 +19,7 @@ internal static class WaitControls /// public static object WaitProcess(this ScriptCommand command, string waitTimeName, string targetName, Func<(bool, object)> waitFunc, Engine.AutomationEngineInstance engine) { - int pauseTime = command.ConvertToUserVariableAsInteger(waitTimeName, "Wait Time", engine); + int pauseTime = command.ExpandValueOrUserVariableAsInteger(waitTimeName, "Wait Time", engine); return WaitProcess(pauseTime, targetName, waitFunc, engine); } diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCheckBrowserInstanceExistsCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCheckBrowserInstanceExistsCommand.cs index 2ee56f7e5..e8c20a42d 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCheckBrowserInstanceExistsCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCheckBrowserInstanceExistsCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Instance")] [Attributes.ClassAttributes.CommandSettings("Check Browser Instance Exists")] [Attributes.ClassAttributes.Description("This command returns existance of browser instance.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to close an open instance of Excel.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserCheckBrowserInstanceExistsCommand : ScriptCommand + public sealed class SeleniumBrowserCheckBrowserInstanceExistsCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -33,13 +34,11 @@ public SeleniumBrowserCheckBrowserInstanceExistsCommand() //this.v_InstanceName = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - try { - var _ = v_InstanceName.GetSeleniumBrowserInstance(engine); + var _ = v_InstanceName.ExpandValueOrUserVariableAsSeleniumBrowserInstance(engine); true.StoreInUserVariable(engine, v_applyToVariableName); } catch diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCheckWebElementExistsCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCheckWebElementExistsCommand.cs index 4a4ff9506..61ca1ce27 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCheckWebElementExistsCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCheckWebElementExistsCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Search WebElement")] [Attributes.ClassAttributes.CommandSettings("Check WebElement Exists")] [Attributes.ClassAttributes.Description("This command allows you to check WebElement existance.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check WebElement existance.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.ImplementationDescription("")] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserCheckWebElementExistsCommand : ScriptCommand + public sealed class SeleniumBrowserCheckWebElementExistsCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -46,13 +47,11 @@ public SeleniumBrowserCheckWebElementExistsCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - try { - SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); + SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); true.StoreInUserVariable(engine, v_Result); } catch diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserClearTextInWebElementCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserClearTextInWebElementCommand.cs index 56f6f159e..8efef3509 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserClearTextInWebElementCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserClearTextInWebElementCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("WebElement Action")] [Attributes.ClassAttributes.CommandSettings("Clear Text In WebElement")] [Attributes.ClassAttributes.Description("This command allows you to Clear Text in WebElement.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Clear Text in WebElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.ImplementationDescription("")] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserClearTextInWebElementCommand : ScriptCommand + public sealed class SeleniumBrowserClearTextInWebElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputWebElementName))] @@ -43,11 +44,9 @@ public SeleniumBrowserClearTextInWebElementCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - if (this.GetYesNoSelectionValue(nameof(v_ScrollToElement), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ScrollToElement), engine)) { var scroll = new SeleniumBrowserScrollToWebElementCommand { @@ -58,7 +57,7 @@ public override void RunCommand(object sender) scroll.RunCommand(engine); } - var elem = v_WebElement.ConvertToUserVariableAsWebElement("WebElement", engine); + var elem = v_WebElement.ExpandUserVariableAsWebElement("WebElement", engine); switch (elem.TagName.ToLower()) { @@ -67,7 +66,7 @@ public override void RunCommand(object sender) elem.Clear(); break; default: - if (this.GetUISelectionValue(nameof(v_WhenClearNotSupported), engine) == "error") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenClearNotSupported), engine) == "error") { throw new Exception("Specified WebElement does not support Clear Text. TagName: '" + elem.TagName + "'"); } diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserClickWebElementCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserClickWebElementCommand.cs index 10d4cf39a..ee0d1434c 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserClickWebElementCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserClickWebElementCommand.cs @@ -7,15 +7,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("WebElement Action")] [Attributes.ClassAttributes.CommandSettings("Click WebElement")] [Attributes.ClassAttributes.Description("This command allows you to Click to WebElement.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Click to WebElement.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.ImplementationDescription("")] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserClickWebElementCommand : ScriptCommand + public sealed class SeleniumBrowserClickWebElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputWebElementName))] @@ -63,11 +64,9 @@ public SeleniumBrowserClickWebElementCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - if (this.GetYesNoSelectionValue(nameof(v_ScrollToElement), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ScrollToElement), engine)) { var scrollCommand = new SeleniumBrowserScrollToWebElementCommand() { @@ -78,8 +77,8 @@ public override void RunCommand(object sender) scrollCommand.RunCommand(engine); } - var elem = v_WebElement.ConvertToUserVariableAsWebElement("WebElement", engine); - var clickType = this.GetUISelectionValue(nameof(v_ClickType), engine); + var elem = v_WebElement.ExpandUserVariableAsWebElement("WebElement", engine); + var clickType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ClickType), engine); Action clickAction; switch (clickType) @@ -93,7 +92,7 @@ public override void RunCommand(object sender) default: clickAction = new Action(() => { - var seleniumInstance = v_InstanceName.GetSeleniumBrowserInstance(engine); + var seleniumInstance = v_InstanceName.ExpandValueOrUserVariableAsSeleniumBrowserInstance(engine); var scrollJson = JObject.Parse(SeleniumBrowserControls.ExcecuteScript(seleniumInstance, "return JSON.stringify({x: window.scrollX, y: window.scrollY})").ToString()); @@ -116,8 +115,8 @@ public override void RunCommand(object sender) //Console.WriteLine($"Brow x:{screenX}, y:{screenY}"); //Console.WriteLine($"Scroll x:{scrollX}, y:{scrollY}"); - var offsetX = this.ConvertToUserVariableAsInteger(nameof(v_XOffset), engine); - var offsetY = this.ConvertToUserVariableAsInteger(nameof(v_YOffset), engine); + var offsetX = this.ExpandValueOrUserVariableAsInteger(nameof(v_XOffset), engine); + var offsetY = this.ExpandValueOrUserVariableAsInteger(nameof(v_YOffset), engine); var clickX = elementLocation.X - scrollX + screenX + offsetX; var clickY = elementLocation.Y - scrollY + screenY + offsetY; @@ -142,7 +141,7 @@ public override void RunCommand(object sender) } catch { - if (this.GetUISelectionValue(nameof(v_WhenFailClick), engine) == "error") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenFailClick), engine) == "error") { throw new Exception("Fail Click WebElement. Click Type: '" + clickType + "', Location: (" + elem.Location.X + ", " + elem.Location.Y + ")"); } @@ -157,18 +156,18 @@ private void cmbScrollToElement_SelectionChange(object sender, EventArgs e) var inst = ControlsList.GetPropertyControl(nameof(v_InstanceName)); useInstance = useInstance && ((inst.SelectedItem?.ToString().ToLower() ?? "") != "invoke click"); - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_InstanceName), useInstance); + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_InstanceName), useInstance); } private void cmdClickType_SelectinChange(object sender, EventArgs e) { var useOffset = (((ComboBox)sender).SelectedItem?.ToString().ToLower() ?? "") != "invoke click"; - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_XOffset), useOffset); ; - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_YOffset), useOffset); ; + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_XOffset), useOffset); ; + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_YOffset), useOffset); ; var scroll = ControlsList.GetPropertyControl(nameof(v_ScrollToElement)); var useInstance = useOffset || ((scroll.SelectedItem?.ToString().ToLower() ?? "") != "no"); - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_InstanceName), useInstance); + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_InstanceName), useInstance); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCloseWebBrowserInstanceCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCloseWebBrowserInstanceCommand.cs index cb5878c15..42a2da3ff 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCloseWebBrowserInstanceCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCloseWebBrowserInstanceCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Instance")] [Attributes.ClassAttributes.CommandSettings("Close Web Browser Instance")] [Attributes.ClassAttributes.Description("This command allows you to close a Selenium web browser session.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to close and end a web browser session.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Selenium to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserCloseWebBrowserInstanceCommand : ScriptCommand + public sealed class SeleniumBrowserCloseWebBrowserInstanceCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -27,12 +28,10 @@ public SeleniumBrowserCloseWebBrowserInstanceCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var vInstance = v_InstanceName.ConvertToUserVariable(engine); - var seleniumInstance = v_InstanceName.GetSeleniumBrowserInstance(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); + var seleniumInstance = v_InstanceName.ExpandValueOrUserVariableAsSeleniumBrowserInstance(engine); seleniumInstance.Quit(); seleniumInstance.Dispose(); diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCreateWebBrowserInstanceCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCreateWebBrowserInstanceCommand.cs index bf370d20e..961b26516 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCreateWebBrowserInstanceCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserCreateWebBrowserInstanceCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Instance")] [Attributes.ClassAttributes.CommandSettings("Create Web Browser Instance")] [Attributes.ClassAttributes.Description("This command allows you to create a new Selenium web browser session which enables automation for websites.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create a browser that will eventually perform web automation such as checking an internal company intranet site to retrieve data.\nIf this command does not work, please check your browser version, and WebDriver version.\nYou can check the WebDriver version with \"foo.exe -v\" in command prompt.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Selenium to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserCreateWebBrowserInstanceCommand : ScriptCommand + public sealed class SeleniumBrowserCreateWebBrowserInstanceCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -23,6 +24,20 @@ public class SeleniumBrowserCreateWebBrowserInstanceCommand : ScriptCommand [PropertyTextBoxSetting(1, false)] public string v_InstanceName { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] + [PropertyDescription("Web Browser Type")] + [PropertyUISelectionOption("Edge")] + [PropertyUISelectionOption("Chrome")] + [PropertyUISelectionOption("Firefox")] + [PropertyUISelectionOption("IE")] + [InputSpecification("", true)] + [Remarks("")] + [PropertyIsOptional(true, "Chrome")] + [PropertyFirstValue("Chrome")] + [PropertyDisplayText(true, "Web Browser Type")] + public string v_EngineType { get; set; } + [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] [PropertyDescription("Instance Tracking (After task ends)")] @@ -53,7 +68,7 @@ public class SeleniumBrowserCreateWebBrowserInstanceCommand : ScriptCommand [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] - [PropertyDescription("We bBrowser Command Line Options")] + [PropertyDescription("Web Browser Command Line Options")] [InputSpecification("Command Line Options", true)] [SampleUsage("user-data-dir=c:\\users\\public\\SeleniumTasktProfile")] [Remarks("")] @@ -62,18 +77,8 @@ public class SeleniumBrowserCreateWebBrowserInstanceCommand : ScriptCommand public string v_SeleniumOptions { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] - [PropertyDescription("Web Browser Type")] - [PropertyUISelectionOption("Edge")] - [PropertyUISelectionOption("Chrome")] - [PropertyUISelectionOption("Firefox")] - [PropertyUISelectionOption("IE")] - [InputSpecification("", true)] - [Remarks("")] - [PropertyIsOptional(true, "Chrome")] - [PropertyFirstValue("Chrome")] - [PropertyDisplayText(true, "Web Browser Type")] - public string v_EngineType { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_Handle { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] @@ -101,6 +106,15 @@ public class SeleniumBrowserCreateWebBrowserInstanceCommand : ScriptCommand [PropertyDisplayText(false, "")] public string v_WebDriverPath { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] + [PropertyDescription("Use Headless")] + [PropertyIsOptional(true, "No")] + [PropertyFirstValue("No")] + [PropertyDisplayText(false, "")] + [Remarks("Headless mode does not show WebBrowser window")] + public string v_HeadlessMode { get; set; } + public SeleniumBrowserCreateWebBrowserInstanceCommand() { //this.CommandName = "SeleniumBrowserCreateCommand"; @@ -111,33 +125,36 @@ public SeleniumBrowserCreateWebBrowserInstanceCommand() //this.v_InstanceName = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var seleniumEngine = SelectionControls.GetUISelectionValue(this, nameof(v_EngineType), engine); + var seleniumEngine = SelectionItemsControls.ExpandValueOrUserVariableAsSelectionItem(this, nameof(v_EngineType), engine); var driverPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Application.ExecutablePath), "Resources"); - var browserPath = v_BrowserPath.ConvertToUserVariable(sender); - var webDriverPath = v_WebDriverPath.ConvertToUserVariable(sender); + var browserPath = v_BrowserPath.ExpandValueOrUserVariable(engine); + var webDriverPath = v_WebDriverPath.ExpandValueOrUserVariable(engine); OpenQA.Selenium.DriverService driverService; OpenQA.Selenium.IWebDriver webDriver; if (seleniumEngine == "chrome") { OpenQA.Selenium.Chrome.ChromeOptions options = new OpenQA.Selenium.Chrome.ChromeOptions(); - if (!String.IsNullOrEmpty(browserPath)) + if (!string.IsNullOrEmpty(browserPath)) { options.BinaryLocation = browserPath; } - if (!String.IsNullOrEmpty(v_SeleniumOptions)) + if (!string.IsNullOrEmpty(v_SeleniumOptions)) { - var convertedOptions = v_SeleniumOptions.ConvertToUserVariable(sender); + var convertedOptions = v_SeleniumOptions.ExpandValueOrUserVariable(engine); options.AddArguments(convertedOptions); } - if (!String.IsNullOrEmpty(webDriverPath)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_HeadlessMode), engine)) + { + options.AddArgument("--headless"); + } + + if (!string.IsNullOrEmpty(webDriverPath)) { driverService = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService(System.IO.Path.GetDirectoryName(webDriverPath), System.IO.Path.GetFileName(webDriverPath)); } @@ -152,7 +169,18 @@ public override void RunCommand(object sender) { OpenQA.Selenium.Edge.EdgeOptions options = new OpenQA.Selenium.Edge.EdgeOptions(); - if (!String.IsNullOrEmpty(webDriverPath)) + if (!string.IsNullOrEmpty(v_SeleniumOptions)) + { + var convertedOptions = v_SeleniumOptions.ExpandValueOrUserVariable(engine); + options.AddArguments(convertedOptions); + } + + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_HeadlessMode), engine)) + { + options.AddArgument("--headless"); + } + + if (!string.IsNullOrEmpty(webDriverPath)) { driverService = OpenQA.Selenium.Edge.EdgeDriverService.CreateDefaultService(System.IO.Path.GetDirectoryName(webDriverPath), System.IO.Path.GetFileName(webDriverPath)); } @@ -166,16 +194,29 @@ public override void RunCommand(object sender) else if (seleniumEngine == "firefox") { OpenQA.Selenium.Firefox.FirefoxOptions options = new OpenQA.Selenium.Firefox.FirefoxOptions(); - if (!String.IsNullOrEmpty(browserPath)) + if (!string.IsNullOrEmpty(browserPath)) { - options.BrowserExecutableLocation = browserPath; + //options.BrowserExecutableLocation = browserPath; + options.BinaryLocation = browserPath; } else { - options.BrowserExecutableLocation = @"c:\Program Files\Mozilla Firefox\firefox.exe"; + //options.BrowserExecutableLocation = @"c:\Program Files\Mozilla Firefox\firefox.exe"; + options.BinaryLocation = @"c:\Program Files\Mozilla Firefox\firefox.exe"; + } + + if (!string.IsNullOrEmpty(v_SeleniumOptions)) + { + var convertedOptions = v_SeleniumOptions.ExpandValueOrUserVariable(engine); + options.AddArguments(convertedOptions); + } + + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_HeadlessMode), engine)) + { + options.AddArgument("-headless"); } - if (!String.IsNullOrEmpty(webDriverPath)) + if (!string.IsNullOrEmpty(webDriverPath)) { driverService = OpenQA.Selenium.Firefox.FirefoxDriverService.CreateDefaultService(System.IO.Path.GetDirectoryName(webDriverPath), System.IO.Path.GetFileName(webDriverPath)); } @@ -197,20 +238,47 @@ public override void RunCommand(object sender) } //add app instance - var instanceName = v_InstanceName.ConvertToUserVariable(sender); + var instanceName = v_InstanceName.ExpandValueOrUserVariable(engine); engine.AddAppInstance(instanceName, webDriver); - var instanceTracking = SelectionControls.GetUISelectionValue(this, nameof(v_InstanceTracking), engine); + var instanceTracking = SelectionItemsControls.ExpandValueOrUserVariableAsSelectionItem(this, nameof(v_InstanceTracking), engine); if (instanceTracking != "forget instance") { GlobalAppInstances.AddInstance(instanceName, webDriver); } - var browserWindowOption = SelectionControls.GetUISelectionValue(this, nameof(v_BrowserWindowOption), engine); + var browserWindowOption = SelectionItemsControls.ExpandValueOrUserVariableAsSelectionItem(this, nameof(v_BrowserWindowOption), engine); if (browserWindowOption == "maximize") { webDriver.Manage().Window.Maximize(); } + + if (!string.IsNullOrEmpty(v_Handle)) + { + var procId = ProcessControls.GetChildProcessId(driverService.ProcessId, 1); + if (seleniumEngine == "firefox") + { + procId = ProcessControls.GetChildProcessId(procId, 0); + } + var whnd = WindowControls.ConvertProcessIdToWindowHandle(procId); + whnd.ToInt32().StoreInUserVariable(engine, v_Handle); + } + } + + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + { + if (!editor.appSettings.ClientSettings.SupportIECommand) + { + var cmb = ControlsList.GetPropertyControl(nameof(v_EngineType)); + for (int i = cmb.Items.Count - 1; i >= 0; i--) + { + if (cmb.Items[i].ToString() == "IE") + { + cmb.Items.RemoveAt(i); + break; + } + } + } } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserExecuteScriptCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserExecuteScriptCommand.cs index 1c387d3f6..9f3223a7d 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserExecuteScriptCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserExecuteScriptCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Web Browser Actions")] [Attributes.ClassAttributes.CommandSettings("Execute Script")] [Attributes.ClassAttributes.Description("This command allows you to execute a script in a Selenium web browser session.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Selenium to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserExecuteScriptCommand : ScriptCommand + public sealed class SeleniumBrowserExecuteScriptCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -89,27 +90,25 @@ public SeleniumBrowserExecuteScriptCommand() //this.v_CodeType = "Code"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var codeType = SelectionControls.GetUISelectionValue(this, nameof(v_CodeType), engine); + var codeType = SelectionItemsControls.ExpandValueOrUserVariableAsSelectionItem(this, nameof(v_CodeType), engine); string script = ""; if (codeType == "code") { - script = v_ScriptCode.ConvertToUserVariable(sender); + script = v_ScriptCode.ExpandValueOrUserVariable(engine); } else if (codeType == "file") { //string scriptFiile = FilePathControls.FormatFilePath_NoFileCounter(v_ScriptCode, engine, "js", true); - var scriptFile = v_ScriptCode.ConvertToUserVariableAsFilePath(new PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtensionAndExists, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "js"), engine); + var scriptFile = v_ScriptCode.ExpandValueOrUserVariableAsFilePath(new PropertyFilePathSetting(false, PropertyFilePathSetting.ExtensionBehavior.RequiredExtensionAndExists, PropertyFilePathSetting.FileCounterBehavior.NoSupport, "js"), engine); script = System.IO.File.ReadAllText(scriptFile); } - var args = v_Args.ConvertToUserVariable(sender); + var args = v_Args.ExpandValueOrUserVariable(engine); - var seleniumInstance = v_InstanceName.GetSeleniumBrowserInstance(engine); + var seleniumInstance = v_InstanceName.ExpandValueOrUserVariableAsSeleniumBrowserInstance(engine); //configure timeout //var inputTimeout = v_TimeOut.ConvertToUserVariable(sender); @@ -118,7 +117,7 @@ public override void RunCommand(object sender) //{ // timeOut = -1; //} - var timeOut = this.ConvertToUserVariableAsInteger(nameof(v_TimeOut), engine); + var timeOut = this.ExpandValueOrUserVariableAsInteger(nameof(v_TimeOut), engine); //set driver timeout if (timeOut > 0) @@ -130,7 +129,7 @@ public override void RunCommand(object sender) OpenQA.Selenium.IJavaScriptExecutor js = (OpenQA.Selenium.IJavaScriptExecutor)seleniumInstance; object result; - if (String.IsNullOrEmpty(args)) + if (string.IsNullOrEmpty(args)) { if (timeOut > 1) { @@ -156,7 +155,7 @@ public override void RunCommand(object sender) //apply result to variable if ((result != null) && (!string.IsNullOrEmpty(v_userVariableName))) { - result.ToString().StoreInUserVariable(sender, v_userVariableName); + result.ToString().StoreInUserVariable(engine, v_userVariableName); } } } diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsDataTableCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsDataTableCommand.cs index 514536a9f..816fa6a24 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsDataTableCommand.cs @@ -7,15 +7,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Scraping")] [Attributes.ClassAttributes.CommandSettings("Get A WebElement Values As DataTable")] [Attributes.ClassAttributes.Description("This command allows you to get Attributes value for a WebElement As DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Attributes value for a WebElement As DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetAWebElementValuesAsDataTableCommand : ScriptCommand + public sealed class SeleniumBrowserGetAWebElementValuesAsDataTableCommand : ScriptCommand, ICanHandleDataTable, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -54,12 +55,10 @@ public SeleniumBrowserGetAWebElementValuesAsDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //(var _, var trgElem) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), engine); - (var _, var trgElem) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); + (var _, var trgElem) = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); DataTable newDT = new DataTable(); @@ -78,7 +77,8 @@ public override void RunCommand(object sender) }) ); - newDT.StoreInUserVariable(engine, v_DataTableVariableName); + //newDT.StoreInUserVariable(engine, v_DataTableVariableName); + this.StoreDataTableInUserVariable(newDT, nameof(v_DataTableVariableName), engine); } private void SearchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsDictionaryCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsDictionaryCommand.cs index 25c0c5258..ad87b5ae1 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsDictionaryCommand.cs @@ -9,15 +9,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Scraping")] [Attributes.ClassAttributes.CommandSettings("Get A WebElement Values As Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to get Attributes value for a WebElement As Dictionary.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Attributes value for a WebElement As Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetAWebElementValuesAsDictionaryCommand : ScriptCommand + public sealed class SeleniumBrowserGetAWebElementValuesAsDictionaryCommand : ScriptCommand, ICanHandleDictionary, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -56,12 +57,10 @@ public SeleniumBrowserGetAWebElementValuesAsDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //(var _, var trgElem) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), engine); - (var _, var trgElem) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); + (var _, var trgElem) = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); Dictionary newDic = new Dictionary(); @@ -78,7 +77,8 @@ public override void RunCommand(object sender) }) ); - newDic.StoreInUserVariable(engine, v_DictionaryVariableName); + //newDic.StoreInUserVariable(engine, v_DictionaryVariableName); + this.StoreDictionaryInUserVariable(newDic, nameof(v_DictionaryVariableName), engine); } private void SearchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsListCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsListCommand.cs index 1735134c6..1f00fbc90 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsListCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAWebElementValuesAsListCommand.cs @@ -8,15 +8,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Scraping")] [Attributes.ClassAttributes.CommandSettings("Get A WebElement Values As List")] [Attributes.ClassAttributes.Description("This command allows you to get Attributes value for a WebElement As List.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Attributes value for a WebElement As List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetAWebElementValuesAsListCommand : ScriptCommand + public sealed class SeleniumBrowserGetAWebElementValuesAsListCommand : ScriptCommand, IHaveDataTableElements, ICanHandleList { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -55,12 +56,10 @@ public SeleniumBrowserGetAWebElementValuesAsListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //(var _, var trgElem) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), engine); - (var _, var trgElem) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); + (var _, var trgElem) = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); List newList = new List(); @@ -70,7 +69,8 @@ public override void RunCommand(object sender) }) ); - newList.StoreInUserVariable(engine, v_ListVariableName); + //newList.StoreInUserVariable(engine, v_ListVariableName); + this.StoreListInUserVariable(newList, nameof(v_ListVariableName), engine); } diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAttributeFromWebElementCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAttributeFromWebElementCommand.cs index 9780c53b7..46f8c4639 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAttributeFromWebElementCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetAttributeFromWebElementCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Get From WebElement")] [Attributes.ClassAttributes.CommandSettings("Get Attribute From WebElement")] [Attributes.ClassAttributes.Description("This command allows you to Get Attribute Value from WebElement.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get Attribute Value from WebElement.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetAttributeFromWebElementCommand : ScriptCommand + public sealed class SeleniumBrowserGetAttributeFromWebElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputWebElementName))] @@ -56,11 +57,9 @@ public SeleniumBrowserGetAttributeFromWebElementCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - if (this.GetYesNoSelectionValue(nameof(v_ScrollToElement), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ScrollToElement), engine)) { var scrollCommand = new SeleniumBrowserScrollToWebElementCommand() { @@ -71,9 +70,9 @@ public override void RunCommand(object sender) scrollCommand.RunCommand(engine); } - var elem = v_WebElement.ConvertToUserVariableAsWebElement("WebElement", engine); + var elem = v_WebElement.ExpandUserVariableAsWebElement("WebElement", engine); - var attributeName = v_AttributeName.ConvertToUserVariable(engine); + var attributeName = v_AttributeName.ExpandValueOrUserVariable(engine); var v = elem.GetAttribute(attributeName); @@ -83,7 +82,7 @@ public override void RunCommand(object sender) } else { - if (this.GetUISelectionValue(nameof(v_WhenNoAttribute), engine) == "error") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenNoAttribute), engine) == "error") { throw new Exception("Attribute '" + attributeName + "' does not exists."); } diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetHTMLFromWebElementCommand .cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetHTMLFromWebElementCommand .cs index dcea82f2a..15e66ce7e 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetHTMLFromWebElementCommand .cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetHTMLFromWebElementCommand .cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Get From WebElement")] [Attributes.ClassAttributes.CommandSettings("Get HTML From WebElement")] [Attributes.ClassAttributes.Description("This command allows you to Get HTML from WebElement.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get HTML from WebElement.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetHTMLFromWebElementCommand : ScriptCommand + public sealed class SeleniumBrowserGetHTMLFromWebElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputWebElementName))] @@ -36,10 +37,8 @@ public SeleniumBrowserGetHTMLFromWebElementCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - var getAttribute = new SeleniumBrowserGetAttributeFromWebElementCommand() { v_WebElement = this.v_WebElement, diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetMatchedWebElementsCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetMatchedWebElementsCommand.cs index 101a2dcc4..d24c49a24 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetMatchedWebElementsCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetMatchedWebElementsCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Search WebElement")] [Attributes.ClassAttributes.CommandSettings("Get Matched WebElements")] [Attributes.ClassAttributes.Description("This command allows you to get Matched WebElements HTML.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Matched WebElements HTML.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetMatchedWebElementsCommand : ScriptCommand + public sealed class SeleniumBrowserGetMatchedWebElementsCommand : ScriptCommand, IListResultProperties { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -40,18 +41,17 @@ public SeleniumBrowserGetMatchedWebElementsCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var _, var trgElem) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); + (var _, var trgElem) = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); var lst = new List(); foreach(var elem in trgElem) { lst.Add(elem.GetAttribute("outerHTML")); } - lst.StoreInUserVariable(engine, v_Result); + //lst.StoreInUserVariable(engine, v_Result); + this.StoreListInUserVariable(lst, engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetOptionsFromWebElementCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetOptionsFromWebElementCommand.cs index e9163a46d..16fb0797a 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetOptionsFromWebElementCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetOptionsFromWebElementCommand.cs @@ -8,15 +8,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Get From WebElement")] [Attributes.ClassAttributes.CommandSettings("Get Options From WebElement")] [Attributes.ClassAttributes.Description("This command allows you to Get Options Value from WebElement.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get Options Value from WebElement.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetOptionsFromWebElementCommand : ScriptCommand + public sealed class SeleniumBrowserGetOptionsFromWebElementCommand : ScriptCommand, IListResultProperties { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputWebElementName))] @@ -59,13 +60,11 @@ public SeleniumBrowserGetOptionsFromWebElementCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var elem = v_WebElement.ExpandUserVariableAsWebElement("WebElement", engine); - var elem = v_WebElement.ConvertToUserVariableAsWebElement("WebElement", engine); - - if (this.GetYesNoSelectionValue(nameof(v_ScrollToElement), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ScrollToElement), engine)) { var scrollCommand = new SeleniumBrowserScrollToWebElementCommand() { @@ -84,9 +83,9 @@ public override void RunCommand(object sender) var sel = new SelectElement(elem); var options = sel.Options; - var attributeName = v_AttributeName.ConvertToUserVariable(engine); + var attributeName = v_AttributeName.ExpandValueOrUserVariable(engine); - var throwError = (this.GetUISelectionValue(nameof(v_WhenNoAttribute), engine) == "error"); + var throwError = (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenNoAttribute), engine) == "error"); var lst = new List(); foreach(var opt in options) @@ -108,7 +107,8 @@ public override void RunCommand(object sender) lst.Add(a); } } - lst.StoreInUserVariable(engine, v_Result); + //lst.StoreInUserVariable(engine, v_Result); + this.StoreListInUserVariable(lst, engine); } private void cmbScrollToElement_SelectionChange(object sender, EventArgs e) diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetTableValueAsDataTableCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetTableValueAsDataTableCommand.cs index 0da12b267..6407847dc 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetTableValueAsDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetTableValueAsDataTableCommand.cs @@ -8,15 +8,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Scraping")] [Attributes.ClassAttributes.CommandSettings("Get Table Value As DataTable")] [Attributes.ClassAttributes.Description("This command allows you to get a Table Values As DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a Table Values As DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetTableValueAsDataTableCommand : ScriptCommand + public sealed class SeleniumBrowserGetTableValueAsDataTableCommand : ScriptCommand, ICanHandleDataTable { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -73,23 +74,21 @@ public SeleniumBrowserGetTableValueAsDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //(var _, var trgElem) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), engine); - (var _, var trgElem) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); + (var _, var trgElem) = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); if (trgElem.TagName.ToLower() != "table") { throw new Exception("Element is not Table"); } - var attrName = v_AttributeName.ConvertToUserVariable(engine); + var attrName = v_AttributeName.ExpandValueOrUserVariable(engine); - var firstRowMethod = this.GetUISelectionValue(nameof(v_FirstRowMethod), engine); + var firstRowMethod = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_FirstRowMethod), engine); - DataTable newDT = new DataTable(); + var newDT = new DataTable(); var trs = trgElem.FindElements(By.XPath("child::tr | child::thead/tr | child::tbody/tr | child::tfoot/tr")); if (trs.Count > 0) @@ -141,7 +140,8 @@ public override void RunCommand(object sender) } } - newDT.StoreInUserVariable(engine, v_DataTableVariableName); + //newDT.StoreInUserVariable(engine, v_DataTableVariableName); + this.StoreDataTableInUserVariable(newDT, nameof(v_DataTableVariableName), engine); } private void SearchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetTextFromWebElementCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetTextFromWebElementCommand.cs index 9cef6cf74..de150a740 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetTextFromWebElementCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetTextFromWebElementCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Get From WebElement")] [Attributes.ClassAttributes.CommandSettings("Get Text From WebElement")] [Attributes.ClassAttributes.Description("This command allows you to Get Text Value from WebElement.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get Text Value from WebElement.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetTextFromWebElementCommand : ScriptCommand + public sealed class SeleniumBrowserGetTextFromWebElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputWebElementName))] @@ -38,11 +39,9 @@ public SeleniumBrowserGetTextFromWebElementCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - if (this.GetYesNoSelectionValue(nameof(v_ScrollToElement), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ScrollToElement), engine)) { var scrollCommand = new SeleniumBrowserScrollToWebElementCommand() { @@ -53,7 +52,7 @@ public override void RunCommand(object sender) scrollCommand.RunCommand(engine); } - var elem = v_WebElement.ConvertToUserVariableAsWebElement("WebElement", engine); + var elem = v_WebElement.ExpandUserVariableAsWebElement("WebElement", engine); var v = elem.Text; diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebBrowserInfoCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebBrowserInfoCommand.cs index 668d01ac7..b3a7c37a8 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebBrowserInfoCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebBrowserInfoCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Instance")] [Attributes.ClassAttributes.CommandSettings("Get Web Browser Info")] [Attributes.ClassAttributes.Description("This command allows you to navigate a Selenium web browser session to a given URL or resource.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to navigate an existing Selenium instance to a known URL or web resource")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Selenium to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetWebBrowserInfoCommand : ScriptCommand + public sealed class SeleniumBrowserGetWebBrowserInfoCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -46,13 +47,11 @@ public SeleniumBrowserGetWebBrowserInfoCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var seleniumInstance = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstance(v_InstanceName, engine); - var seleniumInstance = SeleniumBrowserControls.GetSeleniumBrowserInstance(v_InstanceName, engine); - - var requestedInfo = this.GetUISelectionValue(nameof(v_InfoType), engine); + var requestedInfo = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_InfoType), engine); string info = ""; switch (requestedInfo) { @@ -74,7 +73,7 @@ public override void RunCommand(object sender) } //store data - info.StoreInUserVariable(sender, v_applyToVariableName); + info.StoreInUserVariable(engine, v_applyToVariableName); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementPositionCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementPositionCommand.cs new file mode 100644 index 000000000..b45472f19 --- /dev/null +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementPositionCommand.cs @@ -0,0 +1,101 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Web Browser")] + [Attributes.ClassAttributes.SubGruop("Get From WebElement")] + [Attributes.ClassAttributes.CommandSettings("Get WebElement Position")] + [Attributes.ClassAttributes.Description("This command allows you to Get WebElement Position.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get WebElement Position.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class SeleniumWebElementPositionCommand : ScriptCommand + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputWebElementName))] + public string v_WebElement { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store X Position")] + [InputSpecification("X Position")] + [PropertyIsOptional(true)] + [PropertyValidationRule("X Position", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "X Position")] + public string v_XPosition { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Y Position")] + [InputSpecification("Y Position")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Y Position", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Y Position")] + public string v_YPosition { get; set; } + + [XmlAttribute] + [PropertyDescription("Base position")] + [InputSpecification("", true)] + [SampleUsage("")] + [Remarks("")] + [PropertyUISelectionOption("Top Left")] + [PropertyUISelectionOption("Bottom Right")] + [PropertyUISelectionOption("Top Right")] + [PropertyUISelectionOption("Bottom Left")] + [PropertyUISelectionOption("Center")] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyIsOptional(true, "Top Left")] + public string v_PositionBase { get; set; } + + public SeleniumWebElementPositionCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var elem = v_WebElement.ExpandUserVariableAsWebElement("WebElement", engine); + + var loc = elem.Location; + var size = elem.Size; + + int x = 0, y = 0; + switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_PositionBase), engine)) + { + case "top left": + x = loc.X; + y = loc.Y; + break; + case "bottom right": + x = loc.X + size.Width; + y = loc.Y + size.Height; + break; + case "top right": + x = loc.X + size.Width; + y = loc.Y; + break; + case "bottom left": + x = loc.X; + y = loc.Y + size.Height; + break; + case "center": + x = (loc.X + size.Width) / 2; + y = (loc.Y + size.Height) / 2; + break; + } + + if (!string.IsNullOrEmpty(v_XPosition)) + { + x.StoreInUserVariable(engine, v_XPosition); + } + if (!string.IsNullOrEmpty(v_YPosition)) + { + y.StoreInUserVariable(engine, v_YPosition); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementSizeCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementSizeCommand.cs new file mode 100644 index 000000000..e1c4dfbf1 --- /dev/null +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementSizeCommand.cs @@ -0,0 +1,59 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Web Browser")] + [Attributes.ClassAttributes.SubGruop("Get From WebElement")] + [Attributes.ClassAttributes.CommandSettings("Get WebElement Size")] + [Attributes.ClassAttributes.Description("This command allows you to Get WebElement Size.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get WebElement Size.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class SeleniumWebElementSizeCommand : ScriptCommand + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputWebElementName))] + public string v_WebElement { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Width")] + [InputSpecification("Width")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Width", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Width")] + public string v_Width { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Height")] + [InputSpecification("Height")] + [PropertyIsOptional(true)] + [PropertyValidationRule("Height", PropertyValidationRule.ValidationRuleFlags.None)] + [PropertyDisplayText(true, "Height")] + public string v_Height { get; set; } + + public SeleniumWebElementSizeCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + var elem = v_WebElement.ExpandUserVariableAsWebElement("WebElement", engine); + + if (!string.IsNullOrEmpty(v_Width)) + { + elem.Size.Width.StoreInUserVariable(engine, v_Width); + } + if (!string.IsNullOrEmpty(v_Height)) + { + elem.Size.Height.StoreInUserVariable(engine, v_Height); + } + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsCountCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsCountCommand.cs index 8902e6f20..9b4d5f0a7 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsCountCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsCountCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Search WebElement")] [Attributes.ClassAttributes.CommandSettings("Get WebElements Count")] [Attributes.ClassAttributes.Description("This command allows you to count WebElements.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to count WebElements.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetWebElementsCountCommand : ScriptCommand + public sealed class SeleniumBrowserGetWebElementsCountCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -39,13 +40,11 @@ public SeleniumBrowserGetWebElementsCountCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - try { - (var _, var trgElem) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); + (var _, var trgElem) = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); trgElem.Count.ToString().StoreInUserVariable(engine, v_Result); } diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsDataTableCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsDataTableCommand.cs index c9e271d27..17d0d2790 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsDataTableCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Scraping")] [Attributes.ClassAttributes.CommandSettings("Get WebElements Value As DataTable")] [Attributes.ClassAttributes.Description("This command allows you to get a Attribute value for WegElements As DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a Attribute value for WegElements As DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetWebElementsValueAsDataTableCommand : ScriptCommand + public sealed class SeleniumBrowserGetWebElementsValueAsDataTableCommand : ScriptCommand, ICanHandleDataTable { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -48,12 +49,10 @@ public SeleniumBrowserGetWebElementsValueAsDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //(var _, var elems) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), engine); - (var _, var elems) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); + (var _, var elems) = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); DataTable newDT = new DataTable(); @@ -68,7 +67,8 @@ public override void RunCommand(object sender) }) ); - newDT.StoreInUserVariable(engine, v_DataTableVariableName); + //newDT.StoreInUserVariable(engine, v_DataTableVariableName); + this.StoreDataTableInUserVariable(newDT, nameof(v_DataTableVariableName), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsDictionaryCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsDictionaryCommand.cs index fd1459c0f..c26a3a6e9 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsDictionaryCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsDictionaryCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Scraping")] [Attributes.ClassAttributes.CommandSettings("Get WebElements Value As Dictionary")] [Attributes.ClassAttributes.Description("This command allows you to get a Attribute value for WegElements As Dictionary.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a Attribute value for WegElements As Dictionary.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetWebElementsValueAsDictionaryCommand : ScriptCommand + public sealed class SeleniumBrowserGetWebElementsValueAsDictionaryCommand : ScriptCommand,ICanHandleDictionary { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -48,14 +49,12 @@ public SeleniumBrowserGetWebElementsValueAsDictionaryCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //(var _, var elems) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), engine); - (var _, var elems) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); + (var _, var elems) = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); - Dictionary newDic = new Dictionary(); + var newDic = new Dictionary(); SeleniumBrowserControls.GetElementsAttribute(elems, v_AttributeName, engine, new Action((idx, name, value) => { @@ -63,7 +62,8 @@ public override void RunCommand(object sender) }) ); - newDic.StoreInUserVariable(engine, v_DictionaryVariableName); + //newDic.StoreInUserVariable(engine, v_DictionaryVariableName); + this.StoreDictionaryInUserVariable(newDic, nameof(v_DictionaryVariableName), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsListCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsListCommand.cs index aab01e620..b872f244e 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsListCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValueAsListCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Scraping")] [Attributes.ClassAttributes.CommandSettings("Get WebElements Value As List")] [Attributes.ClassAttributes.Description("This command allows you to get a Attribute value for WegElements As List.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a Attribute value for WegElements As List.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetWebElementsValueAsListCommand : ScriptCommand + public sealed class SeleniumBrowserGetWebElementsValueAsListCommand : ScriptCommand, ICanHandleList { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -48,12 +49,10 @@ public SeleniumBrowserGetWebElementsValueAsListCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //(var _, var elems) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), engine); - (var _, var elems) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); + (var _, var elems) = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); List newList = new List(); @@ -63,7 +62,8 @@ public override void RunCommand(object sender) }) ); - newList.StoreInUserVariable(engine, v_ListVariableName); + //newList.StoreInUserVariable(engine, v_ListVariableName); + this.StoreListInUserVariable(newList, nameof(v_ListVariableName), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValuesAsDataTableCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValuesAsDataTableCommand.cs index f9a149280..747e0e72d 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValuesAsDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserGetWebElementsValuesAsDataTableCommand.cs @@ -7,15 +7,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Scraping")] [Attributes.ClassAttributes.CommandSettings("Get WebElements Values As DataTable")] [Attributes.ClassAttributes.Description("This command allows you to get Attributes value for WegElements As DataTable.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get Attributes value for WegElements As DataTable.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserGetWebElementsValuesAsDataTableCommand : ScriptCommand + public sealed class SeleniumBrowserGetWebElementsValuesAsDataTableCommand : ScriptCommand, ICanHandleDataTable, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -49,19 +50,17 @@ public SeleniumBrowserGetWebElementsValuesAsDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - //(var _, var elems) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), engine); - (var _, var elems) = SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); + (var _, var elems) = SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElements(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_WaitTime), engine); - DataTable newDT = new DataTable(); + var newDT = new DataTable(); int attrs = v_AttributesName.Rows.Count; for (int i = 0; i (() => { diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSelectOptionForWebElementCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSelectOptionForWebElementCommand.cs index 0b8578264..df9f8cb1f 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSelectOptionForWebElementCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSelectOptionForWebElementCommand.cs @@ -7,15 +7,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("WebElement Action")] [Attributes.ClassAttributes.CommandSettings("Select Option For WebElement")] [Attributes.ClassAttributes.Description("This command allows you to Select an Option for WebElement.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Select an Option for WebElement.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserSelectOptionForWebElementCommand : ScriptCommand + public sealed class SeleniumBrowserSelectOptionForWebElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputWebElementName))] @@ -68,13 +69,11 @@ public SeleniumBrowserSelectOptionForWebElementCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var elem = v_WebElement.ExpandUserVariableAsWebElement("WebElement", engine); - var elem = v_WebElement.ConvertToUserVariableAsWebElement("WebElement", engine); - - if (this.GetYesNoSelectionValue(nameof(v_ScrollToElement), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ScrollToElement), engine)) { var scrollCommand = new SeleniumBrowserScrollToWebElementCommand() { @@ -91,8 +90,8 @@ public override void RunCommand(object sender) } var sel = new SelectElement(elem); - var value = v_SelectionValue.ConvertToUserVariable(engine); - var selectType = this.GetUISelectionValue(nameof(v_SelectionType), engine); + var value = v_SelectionValue.ExpandValueOrUserVariable(engine); + var selectType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_SelectionType), engine); try { switch (selectType) @@ -131,7 +130,7 @@ public override void RunCommand(object sender) } catch { - if (this.GetUISelectionValue(nameof(v_WhenFailSelectAction), engine) == "error") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenFailSelectAction), engine) == "error") { throw new Exception($"Fail Select Option. Type:'{selectType}', Value:'{value}'"); } @@ -141,7 +140,7 @@ public override void RunCommand(object sender) private void cmbSelectionType_SelectionChange(object sender, EventArgs e) { var showFlag = (((ComboBox)sender).SelectedItem?.ToString().ToLower() != "deselect all"); - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_SelectionValue), showFlag); + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_SelectionValue), showFlag); } private void cmbScrollToElement_SelectionChange(object sender, EventArgs e) diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSetTextToWebElementCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSetTextToWebElementCommand.cs index 1e2140c01..8a47b9773 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSetTextToWebElementCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSetTextToWebElementCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("WebElement Action")] [Attributes.ClassAttributes.CommandSettings("Set Text To WebElement")] [Attributes.ClassAttributes.Description("This command allows you to Set Text in WebElement.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Set Text in WebElement.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserSetTextToWebElementCommand : ScriptCommand + public sealed class SeleniumBrowserSetTextToWebElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputWebElementName))] @@ -26,13 +27,13 @@ public class SeleniumBrowserSetTextToWebElementCommand : ScriptCommand public string v_TextToSet { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Clear Text before Setting Text")] [PropertyIsOptional(true, "No")] public string v_ClearTextBeforeSetting { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(SelectionControls), nameof(SelectionControls.v_YesNoComboBox))] + [PropertyVirtualProperty(nameof(SelectionItemsControls), nameof(SelectionItemsControls.v_YesNoComboBox))] [PropertyDescription("Encrypted Text")] [PropertyIsOptional(true, "No")] public string v_EncryptedText { get; set; } @@ -60,11 +61,9 @@ public SeleniumBrowserSetTextToWebElementCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - if (this.GetYesNoSelectionValue(nameof(v_ScrollToElement), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ScrollToElement), engine)) { var scroll = new SeleniumBrowserScrollToWebElementCommand { @@ -75,9 +74,9 @@ public override void RunCommand(object sender) scroll.RunCommand(engine); } - var elem = v_WebElement.ConvertToUserVariableAsWebElement("WebElement", engine); + var elem = v_WebElement.ExpandUserVariableAsWebElement("WebElement", engine); - if (this.GetYesNoSelectionValue(nameof(v_ClearTextBeforeSetting), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ClearTextBeforeSetting), engine)) { var clearText = new SeleniumBrowserClearTextInWebElementCommand { @@ -87,9 +86,9 @@ public override void RunCommand(object sender) clearText.RunCommand(engine); } - var textToSet = v_TextToSet.ConvertToUserVariable(engine); + var textToSet = v_TextToSet.ExpandValueOrUserVariable(engine); - if (this.GetYesNoSelectionValue(nameof(v_EncryptedText), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_EncryptedText), engine)) { textToSet = EncryptionServices.DecryptString(textToSet, "TASKT"); } @@ -100,7 +99,7 @@ public override void RunCommand(object sender) } catch { - if (this.GetUISelectionValue(nameof(v_WhenSetNotSupported), engine) == "error") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenSetNotSupported), engine) == "error") { throw new Exception("Fail Setting Text. TagName: '" + elem.TagName + "'"); } diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchFrameToWebElementCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchFrameToWebElementCommand.cs index 599cf4ca7..bcc7c03f2 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchFrameToWebElementCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchFrameToWebElementCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("WebElement Action")] [Attributes.ClassAttributes.CommandSettings("Switch Frame To WebElement")] [Attributes.ClassAttributes.Description("This command allows you to Switch Frame to WebElement.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Switch Frame to WebElement.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserSwitchFrameToWebElementCommand : ScriptCommand + public sealed class SeleniumBrowserSwitchFrameToWebElementCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -40,11 +41,9 @@ public SeleniumBrowserSwitchFrameToWebElementCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - if (this.GetYesNoSelectionValue(nameof(v_ScrollToElement), engine)) + if (this.ExpandValueOrUserVariableAsYesNo(nameof(v_ScrollToElement), engine)) { var scrollCommand = new SeleniumBrowserScrollToWebElementCommand() { @@ -55,7 +54,7 @@ public override void RunCommand(object sender) scrollCommand.RunCommand(engine); } - var elem = v_WebElement.ConvertToUserVariableAsWebElement("WebElement", engine); + var elem = v_WebElement.ExpandUserVariableAsWebElement("WebElement", engine); switch (elem.TagName.ToLower()) { case "frame": @@ -65,7 +64,7 @@ public override void RunCommand(object sender) throw new Exception("WebElement is not frame or iframe"); } - var seleniumInstance = v_InstanceName.GetSeleniumBrowserInstance(engine); + var seleniumInstance = v_InstanceName.ExpandValueOrUserVariableAsSeleniumBrowserInstance(engine); try { @@ -73,7 +72,7 @@ public override void RunCommand(object sender) } catch { - if (this.GetUISelectionValue(nameof(v_WhenFailSwitch), engine) == "error") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenFailSwitch), engine) == "error") { throw new Exception("Fail Switch to Frame."); } diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchWebBrowserFrameCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchWebBrowserFrameCommand.cs index 93502c213..de0e15da9 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchWebBrowserFrameCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchWebBrowserFrameCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Web Browser Actions")] [Attributes.ClassAttributes.CommandSettings("Switch Web Browser Frame")] [Attributes.ClassAttributes.Description("This command allows you to create a new Selenium web browser session which enables automation for websites.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create a browser that will eventually perform web automation such as checking an internal company intranet site to retrieve data")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Selenium to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserSwitchWebBrowserFrameCommand : ScriptCommand + public sealed class SeleniumBrowserSwitchWebBrowserFrameCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -58,13 +59,11 @@ public SeleniumBrowserSwitchWebBrowserFrameCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var seleniumInstance = v_InstanceName.ExpandValueOrUserVariableAsSeleniumBrowserInstance(engine); - var seleniumInstance = v_InstanceName.GetSeleniumBrowserInstance(engine); - - var selectionType = this.GetUISelectionValue(nameof(v_SelectionType), engine); + var selectionType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_SelectionType), engine); switch (selectionType) { case "index": @@ -72,12 +71,12 @@ public override void RunCommand(object sender) { v_FrameParameter = "0"; } - var frameIndex = this.ConvertToUserVariableAsInteger(nameof(v_FrameParameter), engine); + var frameIndex = this.ExpandValueOrUserVariableAsInteger(nameof(v_FrameParameter), engine); seleniumInstance.SwitchTo().Frame(frameIndex); break; case "name or id": - var frameName = v_FrameParameter.ConvertToUserVariable(engine); + var frameName = v_FrameParameter.ExpandValueOrUserVariable(engine); seleniumInstance.SwitchTo().Frame(frameName); break; diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchWebBrowserWindowCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchWebBrowserWindowCommand.cs index 3a47ea708..ebb47d60c 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchWebBrowserWindowCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserSwitchWebBrowserWindowCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Web Browser Actions")] [Attributes.ClassAttributes.CommandSettings("Switch Web Browser Window")] [Attributes.ClassAttributes.Description("This command allows you to create a new Selenium web browser session which enables automation for websites.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to create a browser that will eventually perform web automation such as checking an internal company intranet site to retrieve data")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Selenium to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserSwitchWebBrowserWindowCommand : ScriptCommand + public sealed class SeleniumBrowserSwitchWebBrowserWindowCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -80,20 +81,18 @@ public SeleniumBrowserSwitchWebBrowserWindowCommand() //this.v_CaseSensitiveMatch = "Yes"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var seleniumInstance = v_InstanceName.ExpandValueOrUserVariableAsSeleniumBrowserInstance(engine); - var seleniumInstance = v_InstanceName.GetSeleniumBrowserInstance(engine); + var matchType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WindowMatchType), engine); - var matchType = this.GetUISelectionValue(nameof(v_WindowMatchType), engine); - - var exactMatchRequired = this.GetUISelectionValue(nameof(v_MatchSpecification), engine); - var caseSensitive = this.GetUISelectionValue(nameof(v_CaseSensitiveMatch), engine); + var exactMatchRequired = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_MatchSpecification), engine); + var caseSensitive = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_CaseSensitiveMatch), engine); Func matchFunc = getMatchFunc(matchType, exactMatchRequired, caseSensitive); - var matchParam = v_MatchParameter.ConvertToUserVariable(sender); + var matchParam = v_MatchParameter.ExpandValueOrUserVariable(engine); var handles = seleniumInstance.WindowHandles; var currentHandle = seleniumInstance.CurrentWindowHandle; var matchFound = false; diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserTakeScreenshotCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserTakeScreenshotCommand.cs index 14e8e6679..f37edd0f9 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserTakeScreenshotCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserTakeScreenshotCommand.cs @@ -6,15 +6,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Web Browser Actions")] [Attributes.ClassAttributes.CommandSettings("Take Screenshot")] [Attributes.ClassAttributes.Description("This command allows you to take a screenshot in Selenium web browser session.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to take a screenshot from the current displayed webpage within the web browser.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Selenium to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserTakeScreenshotCommand : ScriptCommand + public sealed class SeleniumBrowserTakeScreenshotCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -58,19 +59,18 @@ public SeleniumBrowserTakeScreenshotCommand() //this.v_SeleniumScreenshotFileNameParameter = "screenshot_001"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + var seleniumInstance = v_InstanceName.ExpandValueOrUserVariableAsSeleniumBrowserInstance(engine); - var seleniumInstance = v_InstanceName.GetSeleniumBrowserInstance(engine); - - var screenshotPath = v_SeleniumScreenshotPathParameter.ConvertToUserVariable(sender); - var screenshotFileName = v_SeleniumScreenshotFileNameParameter.ConvertToUserVariable(sender); + var screenshotPath = v_SeleniumScreenshotPathParameter.ExpandValueOrUserVariable(engine); + var screenshotFileName = v_SeleniumScreenshotFileNameParameter.ExpandValueOrUserVariable(engine); // take the screenshot Screenshot image = ((ITakesScreenshot)seleniumInstance).GetScreenshot(); // save the screenshot to the entered folder by provided name for the screenshot file name - image.SaveAsFile(screenshotPath + "/" + screenshotFileName + ".png", ScreenshotImageFormat.Png); + //image.SaveAsFile(screenshotPath + "/" + screenshotFileName + ".png", ScreenshotImageFormat.Png); + image.SaveAsFile(screenshotPath + "/" + screenshotFileName + ".png"); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserWaitForWebElementToExistsCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserWaitForWebElementToExistsCommand.cs index 36d8901a2..75a8eb783 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserWaitForWebElementToExistsCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserWaitForWebElementToExistsCommand.cs @@ -5,15 +5,16 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("Search WebElement")] [Attributes.ClassAttributes.CommandSettings("Wait For WebElement To Exists")] [Attributes.ClassAttributes.Description("This command allows you to Wait for WebElement exists.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Wait for WebElement exists.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SeleniumBrowserWaitForWebElementToExistsCommand : ScriptCommand + public sealed class SeleniumBrowserWaitForWebElementToExistsCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -39,11 +40,9 @@ public SeleniumBrowserWaitForWebElementToExistsCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - SeleniumBrowserControls.GetSeleniumBrowserInstanceAndElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); + SeleniumBrowserControls.ExpandValueOrUserVariableAsSeleniumBrowserInstanceAndWebElement(this, nameof(v_InstanceName), nameof(v_SeleniumSearchType), nameof(v_SeleniumSearchParameter), nameof(v_ElementIndex), nameof(v_WaitTime), engine); } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserWebElementActionCommand.cs b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserWebElementActionCommand.cs index 9c831cccd..fec1fbafd 100644 --- a/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserWebElementActionCommand.cs +++ b/taskt/Core/Automation/Commands/WebBrowser/SeleniumBrowserWebElementActionCommand.cs @@ -3,18 +3,20 @@ using System.Windows.Forms; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Script; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Web Browser Commands")] + [Attributes.ClassAttributes.Group("Web Browser")] [Attributes.ClassAttributes.SubGruop("WebElement Action")] [Attributes.ClassAttributes.CommandSettings("WebElement Action")] [Attributes.ClassAttributes.Description("This command allows you to close a Selenium web browser session.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to manipulate, set, or get data on a webpage within the web browser.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Selenium to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_web))] [Attributes.ClassAttributes.EnableAutomateRender(true)] - public class SeleniumBrowserWebElementActionCommand : ScriptCommand + public sealed class SeleniumBrowserWebElementActionCommand : ScriptCommand, IHaveDataTableElements { [XmlAttribute] [PropertyVirtualProperty(nameof(SeleniumBrowserControls), nameof(SeleniumBrowserControls.v_InputInstanceName))] @@ -35,9 +37,9 @@ public class SeleniumBrowserWebElementActionCommand : ScriptCommand [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] - [PropertyDescription("Element Action")] + [PropertyDescription("WebElement Action")] [PropertyUISelectionOption("Click WebElement")] - [PropertyUISelectionOption("Clear WebElement")] + [PropertyUISelectionOption("Clear Text")] [PropertyUISelectionOption("Set Text")] [PropertyUISelectionOption("Get Text")] [PropertyUISelectionOption("Get Attribute")] @@ -45,9 +47,12 @@ public class SeleniumBrowserWebElementActionCommand : ScriptCommand [PropertyUISelectionOption("Wait For WebElement To Exists")] [PropertyUISelectionOption("Switch To Frame")] [PropertyUISelectionOption("Get WebElements Count")] + [PropertyUISelectionOption("Get WebElement Position")] + [PropertyUISelectionOption("Get WebElement Size")] [PropertyUISelectionOption("Get Options")] [PropertyUISelectionOption("Select Option")] [PropertySelectionChangeEvent(nameof(cmbSeleniumAction_SelectionChangeCommitted))] + [PropertyValidationRule("WebElement Action", PropertyValidationRule.ValidationRuleFlags.Empty)] public string v_SeleniumElementAction { get; set; } [XmlElement] @@ -76,11 +81,9 @@ public SeleniumBrowserWebElementActionCommand() { } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var actionType = this.GetUISelectionValue(nameof(v_SeleniumElementAction), engine); + var actionType = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_SeleniumElementAction), engine); var parameters = DataTableControls.GetFieldValues(v_WebActionParameterTable, "Parameter Name", "Parameter Value", false, engine); switch (actionType) { @@ -118,113 +121,238 @@ public override void RunCommand(object sender) getCount.RunCommand(engine); break; default: - var elemVariable = VariableNameControls.GetInnerVariableName(0, engine); - var searchElement = new SeleniumBrowserSearchWebElementCommand() - { - v_InstanceName = this.v_InstanceName, - v_SeleniumSearchType = this.v_SeleniumSearchType, - v_SeleniumSearchParameter = this.v_SeleniumSearchParameter, - v_ElementIndex = this.v_SeleniumElementIndex, - v_Result = elemVariable, - v_WaitTime = this.v_WaitTime, - }; - searchElement.RunCommand(engine); + //var elemVariable = VariableNameControls.GetInnerVariableName(0, engine); + //var searchElement = new SeleniumBrowserSearchWebElementCommand() + //{ + // v_InstanceName = this.v_InstanceName, + // v_SeleniumSearchType = this.v_SeleniumSearchType, + // v_SeleniumSearchParameter = this.v_SeleniumSearchParameter, + // v_ElementIndex = this.v_SeleniumElementIndex, + // v_Result = elemVariable, + // v_WaitTime = this.v_WaitTime, + //}; + //searchElement.RunCommand(engine); - switch (actionType) + //switch (actionType) + //{ + // case "click webelement": + // var clickElement = new SeleniumBrowserClickWebElementCommand() + // { + // v_WebElement = elemVariable, + // v_ClickType = parameters["Click Type"], + // v_XOffset = parameters["X Offset"], + // v_YOffset = parameters["Y Offset"], + // v_ScrollToElement = this.v_ScrollToElement, + // }; + // clickElement.RunCommand(engine); + // break; + // case "clear text": + // var clearElement = new SeleniumBrowserClearTextInWebElementCommand() + // { + // v_WebElement = elemVariable, + // }; + // clearElement.RunCommand(engine); + // break; + // case "set text": + // var setText = new SeleniumBrowserSetTextToWebElementCommand() + // { + // v_WebElement = elemVariable, + // v_TextToSet = parameters["Text To Set"], + // v_ClearTextBeforeSetting = parameters["Clear Element Before Setting Text"], + // v_EncryptedText = parameters["Encrypted Text"], + // }; + // setText.RunCommand(engine); + // break; + // case "get text": + // var getText = new SeleniumBrowserGetTextFromWebElementCommand() + // { + // v_WebElement = elemVariable, + // v_Result = parameters["Variable Name"], + // }; + // getText.RunCommand(engine); + // break; + // case "get attribute": + // var getAttribute = new SeleniumBrowserGetAttributeFromWebElementCommand() + // { + // v_WebElement = elemVariable, + // v_AttributeName = parameters["Attribute Name"], + // v_Result = parameters["Variable Name"], + // }; + // getAttribute.RunCommand(engine); + // break; + // case "switch to frame": + // var switchToFrame = new SeleniumBrowserSwitchFrameToWebElementCommand() + // { + // v_InstanceName = this.v_InstanceName, + // v_WebElement = elemVariable, + // }; + // switchToFrame.RunCommand(engine); + // break; + // case "get options": + // var getOptions = new SeleniumBrowserGetOptionsFromWebElementCommand() + // { + // v_WebElement = elemVariable, + // v_AttributeName = parameters["Attribute Name"], + // v_Result = parameters["Variable Name"], + // }; + // getOptions.RunCommand(engine); + // break; + // case "get webelement position": + // var getPos = new SeleniumWebElementPositionCommand() + // { + // v_WebElement = elemVariable, + // v_XPosition = parameters["X Variable"], + // v_YPosition = parameters["Y Variable"], + // v_PositionBase = parameters["Base Position"], + // }; + // getPos.RunCommand(engine); + // break; + // case "get webelement size": + // var getSize = new SeleniumWebElementSizeCommand() + // { + // v_WebElement = elemVariable, + // v_Width = parameters["Width Variable"], + // v_Height = parameters["Height Variable"], + // }; + // getSize.RunCommand(engine); + // break; + // case "select option": + // var selectOption = new SeleniumBrowserSelectOptionForWebElementCommand() + // { + // v_WebElement = elemVariable, + // v_SelectionType = parameters["Selection Type"], + // v_SelectionValue = parameters["Selection Parameter"], + // }; + // selectOption.RunCommand(engine); + // break; + //} + using (var myWebElem = new InnerScriptVariable(engine)) { - case "click webelement": - var clickElement = new SeleniumBrowserClickWebElementCommand() - { - v_WebElement = elemVariable, - v_ClickType = parameters["Click Type"], - v_XOffset = parameters["X Offset"], - v_YOffset = parameters["Y Offset"], - v_ScrollToElement = this.v_ScrollToElement, - }; - clickElement.RunCommand(engine); - break; - case "clear webelement": - var clearElement = new SeleniumBrowserClearTextInWebElementCommand() - { - v_WebElement = elemVariable, - }; - clearElement.RunCommand(engine); - break; - case "set text": - var setText = new SeleniumBrowserSetTextToWebElementCommand() - { - v_WebElement = elemVariable, - v_TextToSet = parameters["Text To Set"], - v_ClearTextBeforeSetting = parameters["Clear Element Before Setting Text"], - v_EncryptedText = parameters["Encrypted Text"], - }; - setText.RunCommand(engine); - break; - case "get text": - var getText = new SeleniumBrowserGetTextFromWebElementCommand() - { - v_WebElement = elemVariable, - v_Result = parameters["Variable Name"], - }; - getText.RunCommand(engine); - break; - case "get attribute": - var getAttribute = new SeleniumBrowserGetAttributeFromWebElementCommand() - { - v_WebElement = elemVariable, - v_AttributeName = parameters["Attribute Name"], - v_Result = parameters["Variable Name"], - }; - getAttribute.RunCommand(engine); - break; - case "switch to frame": - var switchToFrame = new SeleniumBrowserSwitchFrameToWebElementCommand() - { - v_WebElement = elemVariable, - }; - switchToFrame.RunCommand(engine); - break; - case "get options": - var getOptions = new SeleniumBrowserGetOptionsFromWebElementCommand() - { - v_WebElement = elemVariable, - v_AttributeName = parameters["Attribute Name"], - v_Result = parameters["Variable Name"], - }; - getOptions.RunCommand(engine); - break; - case "select option": - var selectOption = new SeleniumBrowserSelectOptionForWebElementCommand() - { - v_WebElement = elemVariable, - v_SelectionType = parameters["Selection Type"], - v_SelectionValue = parameters["Selection Parameter"], - }; - selectOption.RunCommand(engine); - break; + var searchElement = new SeleniumBrowserSearchWebElementCommand() + { + v_InstanceName = this.v_InstanceName, + v_SeleniumSearchType = this.v_SeleniumSearchType, + v_SeleniumSearchParameter = this.v_SeleniumSearchParameter, + v_ElementIndex = this.v_SeleniumElementIndex, + v_Result = myWebElem.VariableName, + v_WaitTime = this.v_WaitTime, + }; + searchElement.RunCommand(engine); + + switch (actionType) + { + case "click webelement": + var clickElement = new SeleniumBrowserClickWebElementCommand() + { + v_WebElement = myWebElem.VariableName, + v_ClickType = parameters["Click Type"], + v_XOffset = parameters["X Offset"], + v_YOffset = parameters["Y Offset"], + v_ScrollToElement = this.v_ScrollToElement, + }; + clickElement.RunCommand(engine); + break; + case "clear text": + var clearElement = new SeleniumBrowserClearTextInWebElementCommand() + { + v_WebElement = myWebElem.VariableName, + }; + clearElement.RunCommand(engine); + break; + case "set text": + var setText = new SeleniumBrowserSetTextToWebElementCommand() + { + v_WebElement = myWebElem.VariableName, + v_TextToSet = parameters["Text To Set"], + v_ClearTextBeforeSetting = parameters["Clear Element Before Setting Text"], + v_EncryptedText = parameters["Encrypted Text"], + }; + setText.RunCommand(engine); + break; + case "get text": + var getText = new SeleniumBrowserGetTextFromWebElementCommand() + { + v_WebElement = myWebElem.VariableName, + v_Result = parameters["Variable Name"], + }; + getText.RunCommand(engine); + break; + case "get attribute": + var getAttribute = new SeleniumBrowserGetAttributeFromWebElementCommand() + { + v_WebElement = myWebElem.VariableName, + v_AttributeName = parameters["Attribute Name"], + v_Result = parameters["Variable Name"], + }; + getAttribute.RunCommand(engine); + break; + case "switch to frame": + var switchToFrame = new SeleniumBrowserSwitchFrameToWebElementCommand() + { + v_InstanceName = this.v_InstanceName, + v_WebElement = myWebElem.VariableName, + }; + switchToFrame.RunCommand(engine); + break; + case "get options": + var getOptions = new SeleniumBrowserGetOptionsFromWebElementCommand() + { + v_WebElement = myWebElem.VariableName, + v_AttributeName = parameters["Attribute Name"], + v_Result = parameters["Variable Name"], + }; + getOptions.RunCommand(engine); + break; + case "get webelement position": + var getPos = new SeleniumWebElementPositionCommand() + { + v_WebElement = myWebElem.VariableName, + v_XPosition = parameters["X Variable"], + v_YPosition = parameters["Y Variable"], + v_PositionBase = parameters["Base Position"], + }; + getPos.RunCommand(engine); + break; + case "get webelement size": + var getSize = new SeleniumWebElementSizeCommand() + { + v_WebElement = myWebElem.VariableName, + v_Width = parameters["Width Variable"], + v_Height = parameters["Height Variable"], + }; + getSize.RunCommand(engine); + break; + case "select option": + var selectOption = new SeleniumBrowserSelectOptionForWebElementCommand() + { + v_WebElement = myWebElem.VariableName, + v_SelectionType = parameters["Selection Type"], + v_SelectionValue = parameters["Selection Parameter"], + }; + selectOption.RunCommand(engine); + break; + } } break; } } - public override void AfterShown() + public override void AfterShown(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) { - var cmb = PropertyControls.GetPropertyControl(ControlsList, nameof(v_SeleniumElementAction)); - var dgv = PropertyControls.GetPropertyControl(ControlsList, nameof(v_WebActionParameterTable)); + var cmb = FormUIControls.GetPropertyControl(ControlsList, nameof(v_SeleniumElementAction)); + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_WebActionParameterTable)); actionParameterProcess(dgv, cmb.SelectedItem?.ToString() ?? ""); } private void cmbSearchType_SelectionChangeCommited(object sender, EventArgs e) { var searchType = ((ComboBox)sender).SelectedItem?.ToString().ToLower() ?? ""; - GeneralPropertyControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_SeleniumElementIndex), !searchType.StartsWith("find element ")); + FormUIControls.SetVisibleParameterControlGroup(ControlsList, nameof(v_SeleniumElementIndex), !searchType.StartsWith("find element ")); } private void cmbSeleniumAction_SelectionChangeCommitted(object sender, EventArgs e) { - var dgv = PropertyControls.GetPropertyControl(ControlsList, nameof(v_WebActionParameterTable)); - - //actionParameterProcess(dgv, v_WebActionParameterTable, (ComboBox)sender); + var dgv = FormUIControls.GetPropertyControl(ControlsList, nameof(v_WebActionParameterTable)); v_WebActionParameterTable.Clear(); @@ -262,6 +390,17 @@ private void cmbSeleniumAction_SelectionChangeCommitted(object sender, EventArgs v_WebActionParameterTable.Rows.Add("Y Offset"); break; + case "get webelement position": + v_WebActionParameterTable.Rows.Add("X Variable"); + v_WebActionParameterTable.Rows.Add("Y Variable"); + v_WebActionParameterTable.Rows.Add("Base Position", ""); + break; + + case "get webelement size": + v_WebActionParameterTable.Rows.Add("Width Variable"); + v_WebActionParameterTable.Rows.Add("Height Variable"); + break; + case "clear webelement": case "switch to frame": case "wait for webelement to exist": @@ -272,54 +411,6 @@ private void cmbSeleniumAction_SelectionChangeCommitted(object sender, EventArgs dgv.DataSource = v_WebActionParameterTable; actionParameterProcess(dgv, actionType); - - //switch (actionType) - //{ - // case "set text": - // var clearBefore = new DataGridViewComboBoxCell(); - // clearBefore.Items.AddRange(new string[] { "", "Yes", "No" }); - // var encrypted = new DataGridViewComboBoxCell(); - // encrypted.Items.AddRange(new string[] { "", "Yes", "No" }); - // //dgv.Rows[1].Cells[1].Value = ""; - // dgv.Rows[1].Cells[1] = clearBefore; - // //dgv.Rows[2].Cells[1].Value = ""; - // dgv.Rows[2].Cells[1] = encrypted; - // break; - // case "select option": - // var selectionType = new DataGridViewComboBoxCell(); - // selectionType.Items.AddRange(new string[] { - // "Select By Index", - // "Select By Text", - // "Select By Value", - // "Deselect By Index", - // "Deselect By Text", - // "Deselect By Value", - // "Deselect All", - // }); - // //dgv.Rows[0].Cells[1].Value = "Select By Value"; - // dgv.Rows[0].Cells[1] = selectionType; - // break; - // case "click webelement": - // var clickType = new DataGridViewComboBoxCell(); - // clickType.Items.AddRange(new string[] - // { - // "Left Click", - // "Middle Click", - // "Right Click", - // "Left Down", - // "Middle Down", - // "Right Down", - // "Left Up", - // "Middle Up", - // "Right Up", - // "Double Left Click", - // "None", - // "Invoke Click", - // }); - // //dgv.Rows[0].Cells[1].Value = "Invoke Click"; - // dgv.Rows[0].Cells[1] = clickType; - // break; - //} } private static void actionParameterProcess(DataGridView dgv, string actionType) @@ -334,6 +425,7 @@ private static void actionParameterProcess(DataGridView dgv, string actionType) dgv.Rows[1].Cells[1] = clearBefore; dgv.Rows[2].Cells[1] = encrypted; break; + case "select option": var selectionType = new DataGridViewComboBoxCell(); selectionType.Items.AddRange(new string[] { @@ -347,6 +439,7 @@ private static void actionParameterProcess(DataGridView dgv, string actionType) }); dgv.Rows[0].Cells[1] = selectionType; break; + case "click webelement": var clickType = new DataGridViewComboBoxCell(); clickType.Items.AddRange(new string[] @@ -366,6 +459,19 @@ private static void actionParameterProcess(DataGridView dgv, string actionType) }); dgv.Rows[0].Cells[1] = clickType; break; + + case "get webelement position": + var basePosCmd = new DataGridViewComboBoxCell(); + basePosCmd.Items.AddRange(new string[] + { + "Top Left", + "Bottom Right", + "Top Right", + "Bottom Left", + "Center", + }); + dgv.Rows[2].Cells[1] = basePosCmd; + break; } } @@ -373,5 +479,11 @@ public override string GetDisplayValue() { return base.GetDisplayValue() + " [" + v_SeleniumSearchType + " and " + v_SeleniumElementAction + ", Instance Name: '" + v_InstanceName + "']"; } + + public override void BeforeValidate() + { + base.BeforeValidate(); + DataTableControls.BeforeValidate((DataGridView)ControlsList[nameof(v_WebActionParameterTable)], v_WebActionParameterTable); + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/AAnyWindowNameCommands.cs b/taskt/Core/Automation/Commands/Window/AAnyWindowNameCommands.cs new file mode 100644 index 000000000..494f0f617 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/AAnyWindowNameCommands.cs @@ -0,0 +1,49 @@ +using System; +using System.Windows.Forms; +using System.Xml.Serialization; +using taskt.UI.CustomControls; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// Abstract class for Any Window Name commands + /// + [Serializable] + public abstract class AAnyWindowNameCommands : ScriptCommand, ILAnyWindowNameProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowName))] + [PropertyParameterOrder(5000)] + public virtual string v_WindowName { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_CompareMethod))] + [PropertyParameterOrder(6000)] + public virtual string v_CompareMethod { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + [PropertyParameterOrder(8000)] + public virtual string v_WaitTimeForWindow { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WindowNameResult))] + [PropertyParameterOrder(8100)] + public virtual string v_NameResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + [PropertyParameterOrder(8200)] + public virtual string v_HandleResult { get; set; } + + public AAnyWindowNameCommands() + { + } + + public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + { + ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/AWindowHandleCommands.cs b/taskt/Core/Automation/Commands/Window/AWindowHandleCommands.cs new file mode 100644 index 000000000..88fdbf9b6 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/AWindowHandleCommands.cs @@ -0,0 +1,27 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// Abstract class for Window Handle command + /// + [Serializable] + public abstract class AWindowHandleCommands : ScriptCommand, ILWindowHandleProperties + { + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_InputWindowHandle))] + [PropertyParameterOrder(5000)] + public virtual string v_WindowHandle { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_WaitTime))] + [PropertyParameterOrder(6000)] + public virtual string v_WaitTimeForWindow { get; set; } + + public AWindowHandleCommands() + { + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/AWindowNameCommands.cs b/taskt/Core/Automation/Commands/Window/AWindowNameCommands.cs new file mode 100644 index 000000000..000e555fb --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/AWindowNameCommands.cs @@ -0,0 +1,62 @@ +using System; +using System.Windows.Forms; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + /// + /// Abstract class for Window Name commands + /// + [Serializable] + public abstract class AWindowNameCommands : AAnyWindowNameCommands, IWindowNameProperties + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //[PropertyParameterOrder(5000)] + //public string v_WindowName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //[PropertyParameterOrder(6000)] + //public string v_SearchMethod { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod))] + [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] + [PropertyParameterOrder(7000)] + public virtual string v_MatchMethod { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_TargetWindowIndex))] + [PropertyParameterOrder(7100)] + public virtual string v_TargetWindowIndex { get; set; } + + //[XmlAttribute] + //public override string v_WaitTime { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //[PropertyParameterOrder(7300)] + //public string v_NameResult { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //[PropertyParameterOrder(7400)] + //public string v_HandleResult { get; set; } + + public AWindowNameCommands() + { + } + + protected void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + { + WindowControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + } + + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/ActivateWindowByWindowHandleCommand.cs b/taskt/Core/Automation/Commands/Window/ActivateWindowByWindowHandleCommand.cs new file mode 100644 index 000000000..e266e3be7 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/ActivateWindowByWindowHandleCommand.cs @@ -0,0 +1,39 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Window Handle Actions")] + [Attributes.ClassAttributes.CommandSettings("Activate Window By Window Handle")] + [Attributes.ClassAttributes.Description("This command activates a window and brings it to the front.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to active a window by name or bring it to attention.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ActivateWindowByWindowHandleCommand : AWindowHandleCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + public ActivateWindowByWindowHandleCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + WindowControls.ActivateWindow(whnd); + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/ActivateWindowCommand.cs b/taskt/Core/Automation/Commands/Window/ActivateWindowCommand.cs index 371a66c9c..74f1ae719 100644 --- a/taskt/Core/Automation/Commands/Window/ActivateWindowCommand.cs +++ b/taskt/Core/Automation/Commands/Window/ActivateWindowCommand.cs @@ -1,51 +1,48 @@ using System; -using System.Windows.Forms; -using System.Xml.Serialization; -using taskt.UI.Forms; -using taskt.UI.CustomControls; -using taskt.Core.Automation.Attributes.PropertyAttributes; +using System.Collections.Generic; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Window Commands")] + [Attributes.ClassAttributes.Group("Window")] [Attributes.ClassAttributes.SubGruop("Window Actions")] [Attributes.ClassAttributes.CommandSettings("Activate Window")] [Attributes.ClassAttributes.Description("This command activates a window and brings it to the front.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to active a window by name or bring it to attention.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ActivateWindowCommand : ScriptCommand + public sealed class ActivateWindowCommand : AWindowNameCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] - public string v_WindowName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod))] - [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] - public string v_MatchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod))] + //[PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] + //public string v_MatchMethod { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] - public string v_TargetWindowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + //public string v_TargetWindowIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] - public string v_NameResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowHandleResult))] - public string v_HandleResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } public ActivateWindowCommand() { @@ -55,49 +52,29 @@ public ActivateWindowCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - //var wins = WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitTime), engine); - - //foreach(var win in wins) - //{ - // WindowNameControls.ActivateWindow(win.Item1); - //} - - //WindowNameControls.StoreWindowNamesAndHandles(wins, v_NameResult, v_HandleResult, engine); - //WindowNameControls.WindowAction(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitTime), engine, - // new Action>(wins => - // { - // foreach(var win in wins) - // { - // WindowNameControls.ActivateWindow(win.Item1); - // } - // }), nameof(v_NameResult), nameof(v_HandleResult) - //); - WindowNameControls.WindowAction(this, engine, - new Action>(wins => + WindowControls.WindowAction(this, engine, + new Action>(wins => { foreach (var win in wins) { - WindowNameControls.ActivateWindow(win.Item1); + WindowControls.ActivateWindow(win.Item1); } }) ); } - private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) - { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); - } + //private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + //{ + // WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + //} - public override void Refresh(frmCommandEditor editor) - { - base.Refresh(); - //ComboBox cmb = (ComboBox)ControlsList[nameof(v_WindowName)]; - //cmb.AddWindowNames(); - ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); - } + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // //ComboBox cmb = (ComboBox)ControlsList[nameof(v_WindowName)]; + // //cmb.AddWindowNames(); + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/CheckWindowHandleExistsCommand.cs b/taskt/Core/Automation/Commands/Window/CheckWindowHandleExistsCommand.cs new file mode 100644 index 000000000..f0426b049 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/CheckWindowHandleExistsCommand.cs @@ -0,0 +1,53 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Get From Window Handle")] + [Attributes.ClassAttributes.CommandSettings("Check Window Handle Exists")] + [Attributes.ClassAttributes.Description("This command returns a existence of Window Handle.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check a existence of Window Handle.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class CheckWindowHandleExistsCommand : AWindowHandleCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] + [Remarks("When Window Exists, Result is **True**")] + [PropertyParameterOrder(5500)] + public string v_Result { get; set; } + + [XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + [PropertyIsOptional(true, "0")] + [PropertyFirstValue("0")] + public override string v_WaitTimeForWindow { get; set; } + + public CheckWindowHandleExistsCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + true.StoreInUserVariable(engine, v_Result); + }), + new Action(ex => + { + false.StoreInUserVariable(engine, v_Result); + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/CheckWindowNameExistsCommand.cs b/taskt/Core/Automation/Commands/Window/CheckWindowNameExistsCommand.cs index 04b01d30d..3e48a57a5 100644 --- a/taskt/Core/Automation/Commands/Window/CheckWindowNameExistsCommand.cs +++ b/taskt/Core/Automation/Commands/Window/CheckWindowNameExistsCommand.cs @@ -1,49 +1,49 @@ using System; -using System.Windows.Forms; using System.Xml.Serialization; -using taskt.UI.Forms; -using taskt.UI.CustomControls; +using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Window Commands")] + [Attributes.ClassAttributes.Group("Window")] [Attributes.ClassAttributes.SubGruop("Window State")] [Attributes.ClassAttributes.CommandSettings("Check Window Name Exists")] [Attributes.ClassAttributes.Description("This command returns a existence of window name.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check a existence of window name.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CheckWindowNameExistsCommand : ScriptCommand + public sealed class CheckWindowNameExistsCommand : AAnyWindowNameCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] - public string v_WindowName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(BooleanControls), nameof(BooleanControls.v_Result))] [Remarks("When Window Exists, Result is **True**")] + [PropertyParameterOrder(6100)] public string v_UserVariableName { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] [PropertyIsOptional(true, "0")] [PropertyFirstValue("0")] - public string v_WaitTime { get; set; } + public override string v_WaitTimeForWindow { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] - public string v_NameResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowHandleResult))] - public string v_HandleResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } public CheckWindowNameExistsCommand() { @@ -53,31 +53,10 @@ public CheckWindowNameExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - //try - //{ - // var handles = WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_WaitTime), engine); - - // (handles.Count > 0).StoreInUserVariable(engine, v_UserVariableName); - //} - //catch - //{ - // false.StoreInUserVariable(engine, v_UserVariableName); - //} - //WindowNameControls.WindowAction(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_WaitTime), engine, - // new Action>(wins => - // { - // (wins.Count > 0).StoreInUserVariable(engine, v_UserVariableName); - // }), nameof(v_NameResult), nameof(v_HandleResult), new Action(ex => - // { - // false.StoreInUserVariable(engine, v_UserVariableName); - // }) - //); - WindowNameControls.WindowAction(this, engine, - new Action>(wins => + WindowControls.WindowAction(this, engine, + new Action>(wins => { (wins.Count > 0).StoreInUserVariable(engine, v_UserVariableName); }), @@ -88,12 +67,11 @@ public override void RunCommand(object sender) ); } - public override void Refresh(frmCommandEditor editor) - { - base.Refresh(); - //ComboBox cmb = (ComboBox)ControlsList[nameof(v_WindowName)]; - //cmb.AddWindowNames(); - ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); - } + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // //ComboBox cmb = (ComboBox)ControlsList[nameof(v_WindowName)]; + // //cmb.AddWindowNames(); + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/CloseWindowByWindowHandleCommand.cs b/taskt/Core/Automation/Commands/Window/CloseWindowByWindowHandleCommand.cs new file mode 100644 index 000000000..f25291781 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/CloseWindowByWindowHandleCommand.cs @@ -0,0 +1,39 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Window Handle Actions")] + [Attributes.ClassAttributes.CommandSettings("Close Window By Window Handle")] + [Attributes.ClassAttributes.Description("This command closes an open window.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to close an existing window by name.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window_close))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class CloseWindowByWindowHandle : AWindowHandleCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + public CloseWindowByWindowHandle() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + WindowControls.CloseWindow(whnd); + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/CloseWindowCommand.cs b/taskt/Core/Automation/Commands/Window/CloseWindowCommand.cs index 129a736f3..027851bab 100644 --- a/taskt/Core/Automation/Commands/Window/CloseWindowCommand.cs +++ b/taskt/Core/Automation/Commands/Window/CloseWindowCommand.cs @@ -1,51 +1,48 @@ using System; -using System.Windows.Forms; -using System.Xml.Serialization; -using taskt.UI.CustomControls; -using taskt.UI.Forms; -using taskt.Core.Automation.Attributes.PropertyAttributes; +using System.Collections.Generic; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Window Commands")] + [Attributes.ClassAttributes.Group("Window")] [Attributes.ClassAttributes.SubGruop("Window Actions")] [Attributes.ClassAttributes.CommandSettings("Close Window")] [Attributes.ClassAttributes.Description("This command closes an open window.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to close an existing window by name.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window_close))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class CloseWindowCommand : ScriptCommand + public sealed class CloseWindowCommand : AWindowNameCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] - public string v_WindowName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod))] - [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] - public string v_MatchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod))] + //[PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] + //public string v_MatchMethod { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] - public string v_TargetWindowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + //public string v_TargetWindowIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] - public string v_NameResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowHandleResult))] - public string v_HandleResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } public CloseWindowCommand() { @@ -55,46 +52,27 @@ public CloseWindowCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Automation.Engine.AutomationEngineInstance)sender; - - //var wins = WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitTime), engine); - - //foreach(var win in wins) - //{ - // WindowNameControls.CloseWindow(win.Item1); - //} - - //WindowNameControls.WindowAction(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitTime), engine, - // new Action>(wins => - // { - // foreach (var win in wins) - // { - // WindowNameControls.CloseWindow(win.Item1); - // } - // }), nameof(v_NameResult), nameof(v_HandleResult) - //); - WindowNameControls.WindowAction(this, engine, - new Action>(wins => + WindowControls.WindowAction(this, engine, + new Action>(wins => { foreach (var win in wins) { - WindowNameControls.CloseWindow(win.Item1); + WindowControls.CloseWindow(win.Item1); } }) ); } - private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) - { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); - } + //private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + //{ + // WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + //} - public override void Refresh(frmCommandEditor editor) - { - base.Refresh(); - ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); - } + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/EM_WindowPositionPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Window/EM_WindowPositionPropertiesExtensionMethods.cs new file mode 100644 index 000000000..2bbb1d73e --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/EM_WindowPositionPropertiesExtensionMethods.cs @@ -0,0 +1,65 @@ +using System; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + /// + /// window position properties extention methods + /// + public static class EM_WindowPositionPropertiesExtensionMethods + { + /// + /// expand value or variable as Window X Position + /// + /// + /// + /// + /// + public static int ExpandValueOrVariableAsWindowXPosition(this IWindowPositionProperties command, IntPtr whnd, AutomationEngineInstance engine) + { + var v = command.v_XPosition; + var rect = WindowControls.GetWindowRect(whnd); + + if ((v == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentPosition.VariableName, engine)) || + (v == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentXPosition.VariableName, engine))) + { + return rect.left; + } + else if (v == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentYPosition.VariableName, engine)) + { + return rect.top; + } + else + { + return v.ExpandValueOrUserVariableAsInteger("Window X Position", engine); + } + } + + /// + /// expand value or variable as Window Y Position + /// + /// + /// + /// + /// + public static int ExpandValueOrVariableAsWindowYPosition(this IWindowPositionProperties command, IntPtr whnd, AutomationEngineInstance engine) + { + var v = command.v_XPosition; + var rect = WindowControls.GetWindowRect(whnd); + + if ((v == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentPosition.VariableName, engine)) || + (v == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentYPosition.VariableName, engine))) + { + return rect.top; + } + else if (v == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentXPosition.VariableName, engine)) + { + return rect.left; + } + else + { + return v.ExpandValueOrUserVariableAsInteger("Window Y Position", engine); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Window/EM_WindowSizePropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/Window/EM_WindowSizePropertiesExtensionMethods.cs new file mode 100644 index 000000000..5709b3ee2 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/EM_WindowSizePropertiesExtensionMethods.cs @@ -0,0 +1,65 @@ +using System; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for IWindowSizeProperties Extension methods + /// + public static class EM_WindowSizePropertiesExtensionMethods + { + /// + /// expand value or variable as Window Width + /// + /// + /// + /// + /// + public static int ExpandValueOrVariableAsWindowWidth(this IWindowSizeProperties command, IntPtr whnd, AutomationEngineInstance engine) + { + var w = command.v_Width; + var rect = WindowControls.GetWindowRect(whnd); + + if ((w == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentSize.VariableName, engine)) || + (w == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentWidth.VariableName, engine))) + { + return rect.GetWidth(); + } + else if (w == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentHeight.VariableName, engine)) + { + return rect.GetHeight(); + } + else + { + return w.ExpandValueOrUserVariableAsInteger("Window Width", engine); + } + } + + /// + /// expand value or variable as Window Height + /// + /// + /// + /// + /// + public static int ExpandValueOrVariableAsWindowHeight(this IWindowSizeProperties command, IntPtr whnd, AutomationEngineInstance engine) + { + var w = command.v_Height; + var rect = WindowControls.GetWindowRect(whnd); + + if ((w == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentSize.VariableName, engine)) || + (w == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentHeight.VariableName, engine))) + { + return rect.GetHeight(); + } + else if (w == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentWidth.VariableName, engine)) + { + return rect.GetWidth(); + } + else + { + return w.ExpandValueOrUserVariableAsInteger("Window Height", engine); + } + } + } +} diff --git a/taskt/Core/Automation/Commands/Window/GetProcessNameFromWindowHandleCommand.cs b/taskt/Core/Automation/Commands/Window/GetProcessNameFromWindowHandleCommand.cs new file mode 100644 index 000000000..3fec13905 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/GetProcessNameFromWindowHandleCommand.cs @@ -0,0 +1,52 @@ +using System; +using System.Diagnostics; +using System.Linq; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Get From Window Handle")] + [Attributes.ClassAttributes.CommandSettings("Get Process Name From Window Handle")] + [Attributes.ClassAttributes.Description("This command returns process name.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get process name.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetProcessNameFromWindowHandleCommand : AWindowHandleCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Process Name")] + [PropertyParameterOrder(5500)] + public string v_Result { get; set; } + + [XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + [PropertyIsOptional(true, "0")] + [PropertyFirstValue("0")] + public override string v_WaitTimeForWindow { get; set; } + + public GetProcessNameFromWindowHandleCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + var proc = Process.GetProcesses().Where(p => (p.MainWindowHandle == whnd)).First(); + proc.ProcessName.StoreInUserVariable(engine, v_Result); + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/GetProcessNameFromWindowName.cs b/taskt/Core/Automation/Commands/Window/GetProcessNameFromWindowName.cs new file mode 100644 index 000000000..992d34edd --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/GetProcessNameFromWindowName.cs @@ -0,0 +1,84 @@ +using System; +using System.Diagnostics; +using System.Xml.Serialization; +using System.Collections.Generic; +using taskt.Core.Automation.Attributes.PropertyAttributes; +using System.Linq; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Window Actions")] + [Attributes.ClassAttributes.CommandSettings("Get Process Name From Window Name")] + [Attributes.ClassAttributes.Description("This command allows you to Get Process Name from Window Name.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get Process Name from Window Name.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetProcessNameFromWindowNameCommand : AWindowNameCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyValidationRule("Result", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyParameterOrder(6500)] + public string v_Result { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] + //[PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] + //public string v_MatchMethod { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] + public override string v_MatchMethod { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + //public string v_TargetWindowIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + //[XmlAttribute] + //public string v_NameResult { get; set; } + + //[XmlAttribute] + //public string v_HandleResult { get; set; } + + public GetProcessNameFromWindowNameCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowAction( this, engine, + new Action>(wins => + { + var proc = Process.GetProcesses().Where(p => (p.MainWindowHandle == wins[0].Item1)).First(); + proc.ProcessName.StoreInUserVariable(engine, v_Result); + }) + ); + } + + //private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + //{ + // WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + //} + + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/GetWindowHandleFromWindowName.cs b/taskt/Core/Automation/Commands/Window/GetWindowHandleFromWindowName.cs new file mode 100644 index 000000000..f0d393e2d --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/GetWindowHandleFromWindowName.cs @@ -0,0 +1,74 @@ +using System; +using System.Xml.Serialization; +using System.Collections.Generic; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Window Actions")] + [Attributes.ClassAttributes.CommandSettings("Get Window Handle From Window Name")] + [Attributes.ClassAttributes.Description("This command allows you to Get Window Handle from Window Name.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to Get Window Handle from Window Name.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetWindowHandleFromWindowNameCommand : AWindowNameCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } + + [XmlAttribute] + [PropertyIsOptional(false)] + [PropertyValidationRule("Window Handle", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyParameterOrder(6500)] + public override string v_HandleResult { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] + public override string v_MatchMethod { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + //public string v_TargetWindowIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } + + public GetWindowHandleFromWindowNameCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowAction(this, engine, + new Action>(wins => + { + wins[0].Item1.StoreInUserVariable(engine, v_HandleResult); + }) + ); + } + + //private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + //{ + // WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + //} + + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/GetWindowNameFromWindowHandleCommand.cs b/taskt/Core/Automation/Commands/Window/GetWindowNameFromWindowHandleCommand.cs new file mode 100644 index 000000000..b2705b5c4 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/GetWindowNameFromWindowHandleCommand.cs @@ -0,0 +1,50 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Get From Window Handle")] + [Attributes.ClassAttributes.CommandSettings("Get Window Name From Window Handle")] + [Attributes.ClassAttributes.Description("This command returns window names.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want window names.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetWindowNameFromWindowHandleCommand : AWindowHandleCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Store Window Name")] + [PropertyParameterOrder(5500)] + public string v_Result { get; set; } + + [XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + [PropertyIsOptional(true, "0")] + [PropertyFirstValue("0")] + public override string v_WaitTimeForWindow { get; set; } + + public GetWindowNameFromWindowHandleCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + var n = WindowControls.GetWindowTitle(whnd); + n.StoreInUserVariable(engine, v_Result); + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/GetWindowNamesCommand.cs b/taskt/Core/Automation/Commands/Window/GetWindowNamesCommand.cs index 4e5011747..62e898eff 100644 --- a/taskt/Core/Automation/Commands/Window/GetWindowNamesCommand.cs +++ b/taskt/Core/Automation/Commands/Window/GetWindowNamesCommand.cs @@ -1,35 +1,34 @@ using System; using System.Collections.Generic; -using System.Windows.Forms; using System.Xml.Serialization; -using taskt.UI.Forms; -using taskt.UI.CustomControls; using taskt.Core.Automation.Attributes.PropertyAttributes; using System.Linq; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Window Commands")] + [Attributes.ClassAttributes.Group("Window")] [Attributes.ClassAttributes.SubGruop("Window State")] [Attributes.ClassAttributes.CommandSettings("Get Window Names")] [Attributes.ClassAttributes.Description("This command returns window names.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want window names.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetWindowNamesCommand : ScriptCommand + public sealed class GetWindowNamesCommand : AAnyWindowNameCommands, ICanHandleList { - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] - public string v_WindowName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(ListControls), nameof(ListControls.v_OutputListName))] + [PropertyParameterOrder(6500)] public string v_UserVariableName { get; set; } [XmlAttribute] @@ -42,21 +41,22 @@ public class GetWindowNamesCommand : ScriptCommand [PropertyDetailSampleUsage("**Ignore**", "Nothing to do. Get Empty LIST")] [PropertyDetailSampleUsage("**Error**", "Rise a Error")] [PropertyIsOptional(true, "Ignore")] + [PropertyParameterOrder(6600)] public string v_WhenWindowNotFound { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] [PropertyIsOptional(true, "0")] [PropertyFirstValue("0")] - public string v_WaitTime { get; set; } + public override string v_WaitTimeForWindow { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] - public string v_NameResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowHandleResult))] - public string v_HandleResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } public GetWindowNamesCommand() { @@ -66,57 +66,22 @@ public GetWindowNamesCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - //try - //{ - // var wins = WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_WaitTime), engine); - // wins.Select(w => w.Item2).ToList().StoreInUserVariable(engine, v_UserVariableName); - //} - //catch (Exception ex) - //{ - // var whenNotFound = this.GetUISelectionValue(nameof(v_WhenWindowNotFound), engine); - // switch(whenNotFound) - // { - // case "ignore": - // new List().StoreInUserVariable(engine, v_UserVariableName); - // break; - // case "error": - // throw ex; - // } - //} - //WindowNameControls.WindowAction(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_WaitTime), engine, - // new Action>(wins => - // { - // wins.Select(w => w.Item2).ToList().StoreInUserVariable(engine, v_UserVariableName); - // }), nameof(v_NameResult), nameof(v_HandleResult), - // new Action(ex => - // { - // var whenNotFound = this.GetUISelectionValue(nameof(v_WhenWindowNotFound), engine); - // switch (whenNotFound) - // { - // case "ignore": - // new List().StoreInUserVariable(engine, v_UserVariableName); - // break; - // case "error": - // throw ex; - // } - // }) - //); - WindowNameControls.WindowAction(this, engine, + WindowControls.WindowAction(this, engine, new Action>(wins => { - wins.Select(w => w.Item2).ToList().StoreInUserVariable(engine, v_UserVariableName); + //wins.Select(w => w.Item2).ToList().StoreInUserVariable(engine, v_UserVariableName); + this.StoreListInUserVariable(wins.Select(w => w.Item2).ToList(), nameof(v_UserVariableName), engine); }), new Action(ex => { - var whenNotFound = this.GetUISelectionValue(nameof(v_WhenWindowNotFound), engine); + var whenNotFound = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WhenWindowNotFound), engine); switch (whenNotFound) { case "ignore": - new List().StoreInUserVariable(engine, v_UserVariableName); + //new List().StoreInUserVariable(engine, v_UserVariableName); + this.StoreListInUserVariable(new List(), nameof(v_UserVariableName), engine); break; case "error": throw ex; @@ -125,10 +90,9 @@ public override void RunCommand(object sender) ); } - public override void Refresh(frmCommandEditor editor) - { - base.Refresh(); - ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); - } + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/GetWindowPositionCommand.cs b/taskt/Core/Automation/Commands/Window/GetWindowPositionCommand.cs index ccb537d86..242782f01 100644 --- a/taskt/Core/Automation/Commands/Window/GetWindowPositionCommand.cs +++ b/taskt/Core/Automation/Commands/Window/GetWindowPositionCommand.cs @@ -1,45 +1,45 @@ using System; -using System.Windows.Forms; using System.Xml.Serialization; -using taskt.UI.Forms; -using taskt.UI.CustomControls; +using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; -using System.Security.Principal; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Window Commands")] + [Attributes.ClassAttributes.Group("Window")] [Attributes.ClassAttributes.SubGruop("Window State")] [Attributes.ClassAttributes.CommandSettings("Get Window Position")] [Attributes.ClassAttributes.Description("This command returns window position.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want window position.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetWindowPositionCommand : ScriptCommand + public sealed class GetWindowPositionCommand : AWindowNameCommands, IWindowPositionProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] - public string v_WindowName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] [PropertyDescription("Variable Name to Recieve the Window Position X")] [PropertyIsOptional(true)] [PropertyDisplayText(false, "")] - public string v_VariablePositionX { get; set; } + [PropertyParameterOrder(6500)] + public string v_XPosition { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] [PropertyDescription("Variable Name to Recieve the Window Position Y")] [PropertyIsOptional(true)] [PropertyDisplayText(false, "")] - public string v_VariablePositionY { get; set; } + [PropertyParameterOrder(6500)] + public string v_YPosition { get; set; } [XmlAttribute] [PropertyDescription("Base position")] @@ -53,28 +53,28 @@ public class GetWindowPositionCommand : ScriptCommand [PropertyUISelectionOption("Center")] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyIsOptional(true, "Top Left")] + [PropertyParameterOrder(6500)] public string v_PositionBase { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] - [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] - public string v_MatchMethod { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] + public override string v_MatchMethod { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] - public string v_TargetWindowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + //public string v_TargetWindowIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] - public string v_NameResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowHandleResult))] - public string v_HandleResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } public GetWindowPositionCommand() { @@ -83,57 +83,17 @@ public GetWindowPositionCommand() //this.CommandEnabled = true; //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - //var wins = WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitTime), engine); - //var whnd = wins[0].Item1; - - //var pos = WindowNameControls.GetWindowPosition(whnd); - - //int x = 0, y = 0; - //switch(this.GetUISelectionValue(nameof(v_PositionBase), engine)) - //{ - // case "top left": - // x = pos.left; - // y = pos.top; - // break; - // case "bottom right": - // x = pos.right; - // y = pos.bottom; - // break; - // case "top right": - // x = pos.right; - // y = pos.top; - // break; - // case "bottom left": - // x = pos.left; - // y = pos.bottom; - // break; - // case "center": - // x = (pos.right + pos.left) / 2; - // y = (pos.top + pos.bottom) / 2; - // break; - //} - //if (!String.IsNullOrEmpty(v_VariablePositionX)) - //{ - // x.ToString().StoreInUserVariable(engine, v_VariablePositionX); - //} - //if (!String.IsNullOrEmpty(v_VariablePositionY)) - //{ - // y.ToString().StoreInUserVariable(engine, v_VariablePositionY); - //} - - WindowNameControls.WindowAction(this, engine, - new Action>(wins => + WindowControls.WindowAction(this, engine, + new Action>(wins => { var whnd = wins[0].Item1; - var pos = WindowNameControls.GetWindowPosition(whnd); + var pos = WindowControls.GetWindowRect(whnd); int x = 0, y = 0; - switch (this.GetUISelectionValue(nameof(v_PositionBase), engine)) + switch (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_PositionBase), engine)) { case "top left": x = pos.left; @@ -156,27 +116,26 @@ public override void RunCommand(object sender) y = (pos.top + pos.bottom) / 2; break; } - if (!String.IsNullOrEmpty(v_VariablePositionX)) + if (!string.IsNullOrEmpty(v_XPosition)) { - x.ToString().StoreInUserVariable(engine, v_VariablePositionX); + x.ToString().StoreInUserVariable(engine, v_XPosition); } - if (!String.IsNullOrEmpty(v_VariablePositionY)) + if (!string.IsNullOrEmpty(v_YPosition)) { - y.ToString().StoreInUserVariable(engine, v_VariablePositionY); + y.ToString().StoreInUserVariable(engine, v_YPosition); } }) ); } - public override void Refresh(frmCommandEditor editor) - { - base.Refresh(); - ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); - } + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} - private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) - { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); - } + //private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + //{ + // WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/GetWindowPositionFromWindowHandleCommand.cs b/taskt/Core/Automation/Commands/Window/GetWindowPositionFromWindowHandleCommand.cs new file mode 100644 index 000000000..d0c4abf58 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/GetWindowPositionFromWindowHandleCommand.cs @@ -0,0 +1,104 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Get From Window Handle")] + [Attributes.ClassAttributes.CommandSettings("Get Window Position From Window Handle")] + [Attributes.ClassAttributes.Description("This command returns window position.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want window position.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetWindowPositionFromWindowHandleCommand : AWindowHandleCommands, IWindowPositionProperties + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Recieve the Window Position X")] + [PropertyIsOptional(true)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(5001)] + public string v_XPosition { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Recieve the Window Position Y")] + [PropertyIsOptional(true)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(5002)] + public string v_YPosition { get; set; } + + [XmlAttribute] + [PropertyDescription("Base position")] + [InputSpecification("", true)] + [SampleUsage("")] + [Remarks("")] + [PropertyUISelectionOption("Top Left")] + [PropertyUISelectionOption("Bottom Right")] + [PropertyUISelectionOption("Top Right")] + [PropertyUISelectionOption("Bottom Left")] + [PropertyUISelectionOption("Center")] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyIsOptional(true, "Top Left")] + [PropertyParameterOrder(5003)] + public string v_PositionBase { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + public GetWindowPositionFromWindowHandleCommand() + { + } + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + var pos = WindowControls.GetWindowRect(whnd); + + int x = 0, y = 0; + switch (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_PositionBase), engine)) + { + case "top left": + x = pos.left; + y = pos.top; + break; + case "bottom right": + x = pos.right; + y = pos.bottom; + break; + case "top right": + x = pos.right; + y = pos.top; + break; + case "bottom left": + x = pos.left; + y = pos.bottom; + break; + case "center": + x = (pos.right + pos.left) / 2; + y = (pos.top + pos.bottom) / 2; + break; + } + if (!string.IsNullOrEmpty(v_XPosition)) + { + x.ToString().StoreInUserVariable(engine, v_XPosition); + } + if (!string.IsNullOrEmpty(v_YPosition)) + { + y.ToString().StoreInUserVariable(engine, v_YPosition); + } + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/GetWindowSizeCommand.cs b/taskt/Core/Automation/Commands/Window/GetWindowSizeCommand.cs new file mode 100644 index 000000000..ab96c779c --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/GetWindowSizeCommand.cs @@ -0,0 +1,98 @@ +using System; +using System.Xml.Serialization; +using System.Collections.Generic; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Window State")] + [Attributes.ClassAttributes.CommandSettings("Get Window Size")] + [Attributes.ClassAttributes.Description("This command returns window size.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want window size.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetWindowSizeCommand : AWindowNameCommands, IWindowSizeProperties + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Recieve the Window Width")] + [PropertyIsOptional(true)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(6500)] + public string v_Width { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Recieve the Window Height")] + [PropertyIsOptional(true)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(6500)] + public string v_Height { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] + public override string v_MatchMethod { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + //public string v_TargetWindowIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } + + public GetWindowSizeCommand() + { + } + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowAction(this, engine, + new Action>(wins => + { + var whnd = wins[0].Item1; + + var rct = WindowControls.GetWindowRect(whnd); + + if (!string.IsNullOrEmpty(v_Width)) + { + (rct.right - rct.left).StoreInUserVariable(engine, v_Width); + } + if (!string.IsNullOrEmpty(v_Height)) + { + (rct.bottom - rct.top).StoreInUserVariable(engine, v_Height); + } + }) + ); + } + + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} + + //private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + //{ + // WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + //} + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/GetWindowSizeFromWindowHandleCommand.cs b/taskt/Core/Automation/Commands/Window/GetWindowSizeFromWindowHandleCommand.cs new file mode 100644 index 000000000..9d002a99a --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/GetWindowSizeFromWindowHandleCommand.cs @@ -0,0 +1,66 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Get From Window Handle")] + [Attributes.ClassAttributes.CommandSettings("Get Window Size From Window Handle")] + [Attributes.ClassAttributes.Description("This command returns window size.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want window size.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetWindowSizeFromWindowHandleCommand : AWindowHandleCommands, IWindowSizeProperties + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Recieve the Window Width")] + [PropertyIsOptional(true)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(5500)] + public string v_Width { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [PropertyDescription("Variable Name to Recieve the Window Height")] + [PropertyIsOptional(true)] + [PropertyDisplayText(false, "")] + [PropertyParameterOrder(5500)] + public string v_Height { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + public GetWindowSizeFromWindowHandleCommand() + { + } + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + var rct = WindowControls.GetWindowRect(whnd); + + if (!string.IsNullOrEmpty(v_Width)) + { + (rct.right - rct.left).StoreInUserVariable(engine, v_Width); + } + if (!string.IsNullOrEmpty(v_Height)) + { + (rct.bottom - rct.top).StoreInUserVariable(engine, v_Height); + } + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/GetWindowStateCommand.cs b/taskt/Core/Automation/Commands/Window/GetWindowStateCommand.cs index 4fddfa3f1..3fff75113 100644 --- a/taskt/Core/Automation/Commands/Window/GetWindowStateCommand.cs +++ b/taskt/Core/Automation/Commands/Window/GetWindowStateCommand.cs @@ -1,57 +1,55 @@ using System; -using System.Windows.Forms; using System.Xml.Serialization; -using taskt.UI.Forms; -using taskt.UI.CustomControls; +using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; -using System.Security.Principal; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Window Commands")] + [Attributes.ClassAttributes.Group("Window")] [Attributes.ClassAttributes.SubGruop("Window State")] [Attributes.ClassAttributes.CommandSettings("Get Window State")] [Attributes.ClassAttributes.Description("This command returns a state of window name.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a window state.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class GetWindowStateCommand : ScriptCommand + public sealed class GetWindowStateCommand : AWindowNameCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] - public string v_WindowName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] [Remarks("Restore is **1**, Minimize is **2**, Maximize is **3**")] - public string v_UserVariableName { get; set; } + [PropertyParameterOrder(6500)] + public string v_WindowState { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod_Single))] - [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] - public string v_MatchMethod { get; set; } + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_MatchMethod_Single))] + public override string v_MatchMethod { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] - public string v_TargetWindowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + //public string v_TargetWindowIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] - public string v_NameResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowHandleResult))] - public string v_HandleResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } public GetWindowStateCommand() { @@ -61,36 +59,27 @@ public GetWindowStateCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - //var wins = WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitTime), engine); - //var whnd = wins[0].Item1; - - //var state = WindowNameControls.GetWindowState(whnd); - //state.ToString().StoreInUserVariable(engine, v_UserVariableName); - - WindowNameControls.WindowAction(this, engine, - new Action>(wins => + WindowControls.WindowAction(this, engine, + new Action>(wins => { var whnd = wins[0].Item1; - var state = WindowNameControls.GetWindowState(whnd); - state.ToString().StoreInUserVariable(engine, v_UserVariableName); + var state = WindowControls.GetWindowState(whnd); + state.ToString().StoreInUserVariable(engine, v_WindowState); }) ); } - public override void Refresh(frmCommandEditor editor) - { - base.Refresh(); - ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); - } + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} - private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) - { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); - } + //private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + //{ + // WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/GetWindowStateFromWindowHandleCommand.cs b/taskt/Core/Automation/Commands/Window/GetWindowStateFromWindowHandleCommand.cs new file mode 100644 index 000000000..8f1b655b1 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/GetWindowStateFromWindowHandleCommand.cs @@ -0,0 +1,48 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Get From Window Handle")] + [Attributes.ClassAttributes.CommandSettings("Get Window State From Window Handle")] + [Attributes.ClassAttributes.Description("This command returns a state of window name.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get a window state.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class GetWindowStateFromWindowHandleCommand : AWindowHandleCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_Result))] + [Remarks("Restore is **1**, Minimize is **2**, Maximize is **3**")] + [PropertyParameterOrder(5500)] + public string v_WindowState { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + public GetWindowStateFromWindowHandleCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + var state = WindowControls.GetWindowState(whnd); + state.StoreInUserVariable(engine, v_WindowState); + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/ILAnyWindowNameProperties.cs b/taskt/Core/Automation/Commands/Window/ILAnyWindowNameProperties.cs new file mode 100644 index 000000000..93166da64 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/ILAnyWindowNameProperties.cs @@ -0,0 +1,33 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// any window name commands properties + /// + public interface ILAnyWindowNameProperties : ILExpandableProperties + { + /// + /// window name + /// + string v_WindowName { get; set; } + + /// + /// compare method (contains, starts-with, ...) + /// + string v_CompareMethod { get; set; } + + /// + /// wait time for window + /// + string v_WaitTimeForWindow { get; set; } + + /// + /// found window name + /// + string v_NameResult { get; set; } + + /// + /// found window handle + /// + string v_HandleResult { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Window/ILWindowHandleProperties.cs b/taskt/Core/Automation/Commands/Window/ILWindowHandleProperties.cs new file mode 100644 index 000000000..cc931542b --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/ILWindowHandleProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// window handle command properties + /// + public interface ILWindowHandleProperties : ILExpandableProperties + { + /// + /// window handle + /// + string v_WindowHandle { get; set; } + + /// + /// wait time for window + /// + string v_WaitTimeForWindow { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Window/IWindowNameProperties.cs b/taskt/Core/Automation/Commands/Window/IWindowNameProperties.cs new file mode 100644 index 000000000..69edf2f65 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/IWindowNameProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// window name commands properties + /// + public interface IWindowNameProperties : ILAnyWindowNameProperties + { + /// + /// match method (first, last, index) + /// + string v_MatchMethod { get; set; } + + /// + /// match method index + /// + string v_TargetWindowIndex { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/Window/IWindowPositionProperties.cs b/taskt/Core/Automation/Commands/Window/IWindowPositionProperties.cs new file mode 100644 index 000000000..be4dc444a --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/IWindowPositionProperties.cs @@ -0,0 +1,9 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// window position properties + /// + public interface IWindowPositionProperties : ILPositionProperties + { + } +} diff --git a/taskt/Core/Automation/Commands/Window/IWindowSizeProperties.cs b/taskt/Core/Automation/Commands/Window/IWindowSizeProperties.cs new file mode 100644 index 000000000..90c6cd008 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/IWindowSizeProperties.cs @@ -0,0 +1,9 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// window size properties + /// + public interface IWindowSizeProperties : ILSizeProperties + { + } +} diff --git a/taskt/Core/Automation/Commands/Window/MoveWindowByWindowHandleCommand.cs b/taskt/Core/Automation/Commands/Window/MoveWindowByWindowHandleCommand.cs new file mode 100644 index 000000000..4aed8de17 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/MoveWindowByWindowHandleCommand.cs @@ -0,0 +1,114 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Window Handle Actions")] + [Attributes.ClassAttributes.CommandSettings("Move Window By Window Handle")] + [Attributes.ClassAttributes.Description("This command moves a window to a specified location on screen.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to move an existing window by name to a certain point on the screen.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class MoveWindowByWindowHandleCommand : AWindowHandleCommands, IWindowPositionProperties + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + [XmlAttribute] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + //[PropertyDescription("X horizontal coordinate (pixel) for the Window's Location")] + //[InputSpecification("X Window Location", true)] + //[PropertyDetailSampleUsageBehavior(MultiAttributesBehavior.Overwrite)] + //[PropertyDetailSampleUsage("**0**", "Specify X Top Position")] + //[PropertyDetailSampleUsage("**100**", PropertyDetailSampleUsage.ValueType.Value, "X Position")] + //[PropertyDetailSampleUsage("**{{{vXPos}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "X Position")] + //[PropertyDetailSampleUsage("**%kwd_current_position%**", "Specify Current Position for X Position")] + //[PropertyDetailSampleUsage("**%kwd_current_xposition%**", "Specify Current X Position for X Position", false)] + //[PropertyDetailSampleUsage("**%kwd_current_yposition%**", "Specify Current Y Position for X Position", false)] + //[Remarks("This number is the pixel location on screen. Maximum value should be the maximum value allowed by your resolution. For 1920x1080, the valid range could be 0-1920")] + //[PropertyValidationRule("X Position", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "X Position")] + //[PropertyIntermediateConvert(nameof(ApplicationSettings.EngineSettings.convertToIntermediateWindowPosition), nameof(ApplicationSettings.EngineSettings.convertToRawWindowPosition))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_InputXPosition))] + [PropertyParameterOrder(5500)] + public string v_XPosition { get; set; } + + [XmlAttribute] + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + //[PropertyDescription("Y vertical coordinate (pixel) for the Window's Location")] + //[InputSpecification("Y Window Location", true)] + //[PropertyDetailSampleUsageBehavior(MultiAttributesBehavior.Overwrite)] + //[PropertyDetailSampleUsage("**0**", "Specify Y Left Position")] + //[PropertyDetailSampleUsage("**100**", PropertyDetailSampleUsage.ValueType.Value, "Y Position")] + //[PropertyDetailSampleUsage("**{{{vYPos}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Y Position")] + //[PropertyDetailSampleUsage("**%kwd_current_position%**", "Specify Current Position for Y Position")] + //[PropertyDetailSampleUsage("**%kwd_current_xposition%**", "Specify Current X Position for Y Position", false)] + //[PropertyDetailSampleUsage("**%kwd_current_yposition%**", "Specify Current Y Position for Y Position", false)] + //[Remarks("This number is the pixel location on screen. Maximum value should be the maximum value allowed by your resolution. For 1920x1080, the valid range could be 0-1080")] + //[PropertyValidationRule("Y Position", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "Y Position")] + //[PropertyIntermediateConvert(nameof(ApplicationSettings.EngineSettings.convertToIntermediateWindowPosition), nameof(ApplicationSettings.EngineSettings.convertToRawWindowPosition))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_InputYPosition))] + [PropertyParameterOrder(5500)] + public string v_YPosition { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + public MoveWindowByWindowHandleCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + //var pos = WindowControls.GetWindowRect(whnd); + + //var variableXPosition = v_XPosition.ExpandValueOrUserVariable(engine); + //int xPos; + //if ((variableXPosition == engine.engineSettings.CurrentWindowPositionKeyword) || (variableXPosition == engine.engineSettings.CurrentWindowXPositionKeyword)) + //{ + // xPos = pos.left; + //} + //else if (variableXPosition == engine.engineSettings.CurrentWindowYPositionKeyword) + //{ + // xPos = pos.top; + //} + //else + //{ + // xPos = v_XPosition.ExpandValueOrUserVariableAsInteger("X Position", engine); + //} + + //var variableYPosition = v_YPosition.ExpandValueOrUserVariable(engine); + //int yPos; + //if ((variableYPosition == engine.engineSettings.CurrentWindowPositionKeyword) || (variableYPosition == engine.engineSettings.CurrentWindowYPositionKeyword)) + //{ + // yPos = pos.top; + //} + //else if (variableYPosition == engine.engineSettings.CurrentWindowXPositionKeyword) + //{ + // yPos = pos.left; + //} + //else + //{ + // yPos = v_YPosition.ExpandValueOrUserVariableAsInteger("Y Position", engine); + //} + + var xPos = this.ExpandValueOrVariableAsWindowXPosition(whnd, engine); + var yPos = this.ExpandValueOrVariableAsWindowYPosition(whnd, engine); + + WindowControls.SetWindowPosition(whnd, xPos, yPos); + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/MoveWindowCommand.cs b/taskt/Core/Automation/Commands/Window/MoveWindowCommand.cs index 4003ab198..b2abeb8a2 100644 --- a/taskt/Core/Automation/Commands/Window/MoveWindowCommand.cs +++ b/taskt/Core/Automation/Commands/Window/MoveWindowCommand.cs @@ -1,85 +1,88 @@ using System; -using System.Windows.Forms; using System.Xml.Serialization; -using taskt.UI.CustomControls; -using taskt.UI.Forms; +using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Window Commands")] + [Attributes.ClassAttributes.Group("Window")] [Attributes.ClassAttributes.SubGruop("Window Actions")] [Attributes.ClassAttributes.CommandSettings("Move Window")] [Attributes.ClassAttributes.Description("This command moves a window to a specified location on screen.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to move an existing window by name to a certain point on the screen.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class MoveWindowCommand : ScriptCommand + public sealed class MoveWindowCommand : AWindowNameCommands, IWindowPositionProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] - public string v_WindowName { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] - [PropertyDescription("X horizontal coordinate (pixel) for the Window's Location")] - [InputSpecification("X Window Location", true)] - [PropertyDetailSampleUsageBehavior(MultiAttributesBehavior.Overwrite)] - [PropertyDetailSampleUsage("**0**", "Specify X Top Position")] - [PropertyDetailSampleUsage("**100**", PropertyDetailSampleUsage.ValueType.Value, "X Position")] - [PropertyDetailSampleUsage("**{{{vXPos}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "X Position")] - [PropertyDetailSampleUsage("**%kwd_current_position%**", "Specify Current Position for X Position")] - [PropertyDetailSampleUsage("**%kwd_current_xposition%**", "Specify Current X Position for X Position", false)] - [PropertyDetailSampleUsage("**%kwd_current_yposition%**", "Specify Current Y Position for X Position", false)] - [Remarks("This number is the pixel location on screen. Maximum value should be the maximum value allowed by your resolution. For 1920x1080, the valid range could be 0-1920")] - [PropertyValidationRule("X Position", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "X Position")] - [PropertyIntermediateConvert(nameof(ApplicationSettings.EngineSettings.convertToIntermediateWindowPosition), nameof(ApplicationSettings.EngineSettings.convertToRawWindowPosition))] - public string v_XWindowPosition { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] - [PropertyDescription("Y vertical coordinate (pixel) for the Window's Location")] - [InputSpecification("Y Window Location", true)] - [PropertyDetailSampleUsageBehavior(MultiAttributesBehavior.Overwrite)] - [PropertyDetailSampleUsage("**0**", "Specify Y Left Position")] - [PropertyDetailSampleUsage("**100**", PropertyDetailSampleUsage.ValueType.Value, "Y Position")] - [PropertyDetailSampleUsage("**{{{vYPos}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Y Position")] - [PropertyDetailSampleUsage("**%kwd_current_position%**", "Specify Current Position for Y Position")] - [PropertyDetailSampleUsage("**%kwd_current_xposition%**", "Specify Current X Position for Y Position", false)] - [PropertyDetailSampleUsage("**%kwd_current_yposition%**", "Specify Current Y Position for Y Position", false)] - [Remarks("This number is the pixel location on screen. Maximum value should be the maximum value allowed by your resolution. For 1920x1080, the valid range could be 0-1080")] - [PropertyValidationRule("Y Position", PropertyValidationRule.ValidationRuleFlags.Empty)] - [PropertyDisplayText(true, "Y Position")] - [PropertyIntermediateConvert(nameof(ApplicationSettings.EngineSettings.convertToIntermediateWindowPosition), nameof(ApplicationSettings.EngineSettings.convertToRawWindowPosition))] - public string v_YWindowPosition { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod))] - [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] - public string v_MatchMethod { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] - public string v_TargetWindowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] - public string v_NameResult { get; set; } + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + //[PropertyDescription("X horizontal coordinate (pixel) for the Window's Location")] + //[InputSpecification("X Window Location", true)] + //[PropertyDetailSampleUsageBehavior(MultiAttributesBehavior.Overwrite)] + //[PropertyDetailSampleUsage("**0**", "Specify X Top Position")] + //[PropertyDetailSampleUsage("**100**", PropertyDetailSampleUsage.ValueType.Value, "X Position")] + //[PropertyDetailSampleUsage("**{{{vXPos}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "X Position")] + //[PropertyDetailSampleUsage("**%kwd_current_position%**", "Specify Current Position for X Position")] + //[PropertyDetailSampleUsage("**%kwd_current_xposition%**", "Specify Current X Position for X Position", false)] + //[PropertyDetailSampleUsage("**%kwd_current_yposition%**", "Specify Current Y Position for X Position", false)] + //[Remarks("This number is the pixel location on screen. Maximum value should be the maximum value allowed by your resolution. For 1920x1080, the valid range could be 0-1920")] + //[PropertyValidationRule("X Position", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "X Position")] + //[PropertyIntermediateConvert(nameof(ApplicationSettings.EngineSettings.convertToIntermediateWindowPosition), nameof(ApplicationSettings.EngineSettings.convertToRawWindowPosition))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_InputXPosition))] + [PropertyParameterOrder(6500)] + public string v_XPosition { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowHandleResult))] - public string v_HandleResult { get; set; } + //[PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_DisallowNewLine_OneLineTextBox))] + //[PropertyDescription("Y vertical coordinate (pixel) for the Window's Location")] + //[InputSpecification("Y Window Location", true)] + //[PropertyDetailSampleUsageBehavior(MultiAttributesBehavior.Overwrite)] + //[PropertyDetailSampleUsage("**0**", "Specify Y Left Position")] + //[PropertyDetailSampleUsage("**100**", PropertyDetailSampleUsage.ValueType.Value, "Y Position")] + //[PropertyDetailSampleUsage("**{{{vYPos}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Y Position")] + //[PropertyDetailSampleUsage("**%kwd_current_position%**", "Specify Current Position for Y Position")] + //[PropertyDetailSampleUsage("**%kwd_current_xposition%**", "Specify Current X Position for Y Position", false)] + //[PropertyDetailSampleUsage("**%kwd_current_yposition%**", "Specify Current Y Position for Y Position", false)] + //[Remarks("This number is the pixel location on screen. Maximum value should be the maximum value allowed by your resolution. For 1920x1080, the valid range could be 0-1080")] + //[PropertyValidationRule("Y Position", PropertyValidationRule.ValidationRuleFlags.Empty)] + //[PropertyDisplayText(true, "Y Position")] + //[PropertyIntermediateConvert(nameof(ApplicationSettings.EngineSettings.convertToIntermediateWindowPosition), nameof(ApplicationSettings.EngineSettings.convertToRawWindowPosition))] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_InputYPosition))] + [PropertyParameterOrder(6500)] + public string v_YPosition { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod))] + //[PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] + //public string v_MatchMethod { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + //public string v_TargetWindowIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } public MoveWindowCommand() { @@ -89,101 +92,64 @@ public MoveWindowCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - //var wins = WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitTime), engine); - - //foreach(var win in wins) - //{ - // var pos = WindowNameControls.GetWindowPosition(win.Item1); - - // var variableXPosition = v_XWindowPosition.ConvertToUserVariable(engine); - // int xPos; - // if ((variableXPosition == engine.engineSettings.CurrentWindowPositionKeyword) || (variableXPosition == engine.engineSettings.CurrentWindowXPositionKeyword)) - // { - // xPos = pos.left; - // } - // else if (variableXPosition == engine.engineSettings.CurrentWindowYPositionKeyword) - // { - // xPos = pos.top; - // } - // else - // { - // xPos = v_XWindowPosition.ConvertToUserVariableAsInteger("X Position", engine); - // } - - // var variableYPosition = v_YWindowPosition.ConvertToUserVariable(engine); - // int yPos; - // if ((variableYPosition == engine.engineSettings.CurrentWindowPositionKeyword) || (variableYPosition == engine.engineSettings.CurrentWindowYPositionKeyword)) - // { - // yPos = pos.top; - // } - // else if (variableYPosition == engine.engineSettings.CurrentWindowXPositionKeyword) - // { - // yPos = pos.left; - // } - // else - // { - // yPos = v_YWindowPosition.ConvertToUserVariableAsInteger("Y Position", engine); - // } - - // WindowNameControls.SetWindowPosition(win.Item1, xPos, yPos); - //} - - WindowNameControls.WindowAction(this, engine, - new Action>(wins => + WindowControls.WindowAction(this, engine, + new Action>(wins => { foreach (var win in wins) { - var pos = WindowNameControls.GetWindowPosition(win.Item1); - - var variableXPosition = v_XWindowPosition.ConvertToUserVariable(engine); - int xPos; - if ((variableXPosition == engine.engineSettings.CurrentWindowPositionKeyword) || (variableXPosition == engine.engineSettings.CurrentWindowXPositionKeyword)) - { - xPos = pos.left; - } - else if (variableXPosition == engine.engineSettings.CurrentWindowYPositionKeyword) - { - xPos = pos.top; - } - else - { - xPos = v_XWindowPosition.ConvertToUserVariableAsInteger("X Position", engine); - } - - var variableYPosition = v_YWindowPosition.ConvertToUserVariable(engine); - int yPos; - if ((variableYPosition == engine.engineSettings.CurrentWindowPositionKeyword) || (variableYPosition == engine.engineSettings.CurrentWindowYPositionKeyword)) - { - yPos = pos.top; - } - else if (variableYPosition == engine.engineSettings.CurrentWindowXPositionKeyword) - { - yPos = pos.left; - } - else - { - yPos = v_YWindowPosition.ConvertToUserVariableAsInteger("Y Position", engine); - } - - WindowNameControls.SetWindowPosition(win.Item1, xPos, yPos); + //var pos = WindowControls.GetWindowRect(win.Item1); + + //var variableXPosition = v_XPosition.ExpandValueOrUserVariable(engine); + //int xPos; + //if ((variableXPosition == engine.engineSettings.CurrentWindowPositionKeyword) || (variableXPosition == engine.engineSettings.CurrentWindowXPositionKeyword)) + //{ + // xPos = pos.left; + //} + //else if (variableXPosition == engine.engineSettings.CurrentWindowYPositionKeyword) + //{ + // xPos = pos.top; + //} + //else + //{ + // xPos = v_XPosition.ExpandValueOrUserVariableAsInteger("X Position", engine); + //} + + //var variableYPosition = v_YPosition.ExpandValueOrUserVariable(engine); + //int yPos; + //if ((variableYPosition == engine.engineSettings.CurrentWindowPositionKeyword) || (variableYPosition == engine.engineSettings.CurrentWindowYPositionKeyword)) + //{ + // yPos = pos.top; + //} + //else if (variableYPosition == engine.engineSettings.CurrentWindowXPositionKeyword) + //{ + // yPos = pos.left; + //} + //else + //{ + // yPos = v_YPosition.ExpandValueOrUserVariableAsInteger("Y Position", engine); + //} + + var whnd = win.Item1; + + var xPos = this.ExpandValueOrVariableAsWindowXPosition(whnd, engine); + var yPos = this.ExpandValueOrVariableAsWindowYPosition(whnd, engine); + + WindowControls.SetWindowPosition(win.Item1, xPos, yPos); } }) ); } - public override void Refresh(frmCommandEditor editor) - { - base.Refresh(); - ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); - } + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} - private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) - { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); - } + //private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + //{ + // WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/ResizeWindowByWindowHandleCommand.cs b/taskt/Core/Automation/Commands/Window/ResizeWindowByWindowHandleCommand.cs new file mode 100644 index 000000000..bf79cabae --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/ResizeWindowByWindowHandleCommand.cs @@ -0,0 +1,74 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Window Handle Actions")] + [Attributes.ClassAttributes.CommandSettings("Resize Window By Window Handle")] + [Attributes.ClassAttributes.Description("This command resizes a window to a specified size.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to reize a window by name to a specific size on screen.")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class ResizeWindowByWindowHandleCommand : AWindowHandleCommands, IWindowSizeProperties + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + [XmlAttribute] + //[PropertyDescription("Window Width (Pixcel)")] + //[InputSpecification("Window Width", true)] + //[PropertyDetailSampleUsage("**640**", PropertyDetailSampleUsage.ValueType.Value, "Width")] + //[PropertyDetailSampleUsage("**{{{vWidth}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Width")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyTextBoxSetting(1, false)] + //[PropertyValidationRule("Width", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] + //[PropertyDisplayText(true, "Width")] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_InputWidth))] + [PropertyParameterOrder(5500)] + public string v_Width { get; set; } + + [XmlAttribute] + //[PropertyDescription("Window Height (Pixcel)")] + //[InputSpecification("Window Height", true)] + //[PropertyDetailSampleUsage("**480**", PropertyDetailSampleUsage.ValueType.Value, "Height")] + //[PropertyDetailSampleUsage("**{{{vHeight}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Height")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyTextBoxSetting(1, false)] + //[PropertyValidationRule("Height", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] + //[PropertyDisplayText(true, "Height")] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_InputHeight))] + [PropertyParameterOrder(5500)] + public string v_Height { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + public ResizeWindowByWindowHandleCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + //var width = this.ExpandValueOrUserVariableAsInteger(nameof(v_Width), engine); + //var height = this.ExpandValueOrUserVariableAsInteger(nameof(v_Height), engine); + var width = this.ExpandValueOrVariableAsWindowWidth(whnd, engine); + var height = this.ExpandValueOrVariableAsWindowHeight(whnd, engine); + + WindowControls.SetWindowSize(whnd, width, height); + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/ResizeWindowCommand.cs b/taskt/Core/Automation/Commands/Window/ResizeWindowCommand.cs index 3d2648e6e..6ea0312b5 100644 --- a/taskt/Core/Automation/Commands/Window/ResizeWindowCommand.cs +++ b/taskt/Core/Automation/Commands/Window/ResizeWindowCommand.cs @@ -1,75 +1,79 @@ using System; -using System.Windows.Forms; using System.Xml.Serialization; -using taskt.UI.CustomControls; -using taskt.UI.Forms; +using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Window Commands")] + [Attributes.ClassAttributes.Group("Window")] [Attributes.ClassAttributes.SubGruop("Window Actions")] [Attributes.ClassAttributes.CommandSettings("Resize Window")] [Attributes.ClassAttributes.Description("This command resizes a window to a specified size.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to reize a window by name to a specific size on screen.")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class ResizeWindowCommand : ScriptCommand + public sealed class ResizeWindowCommand : AWindowNameCommands, IWindowSizeProperties { - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] - public string v_WindowName { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } - [XmlAttribute] - [PropertyDescription("Window Width (Pixcel)")] - [InputSpecification("Window Width", true)] - [PropertyDetailSampleUsage("**640**", PropertyDetailSampleUsage.ValueType.Value, "Width")] - [PropertyDetailSampleUsage("**{{{vWidth}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Width")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - [PropertyValidationRule("Width", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] - [PropertyDisplayText(true, "Width")] - public string v_XWindowSize { get; set; } - - [XmlAttribute] - [PropertyDescription("Window Height (Pixcel)")] - [InputSpecification("Window Height", true)] - [PropertyDetailSampleUsage("**480**", PropertyDetailSampleUsage.ValueType.Value, "Height")] - [PropertyDetailSampleUsage("**{{{vHeight}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Height")] - [Remarks("")] - [PropertyShowSampleUsageInDescription(true)] - [PropertyTextBoxSetting(1, false)] - [PropertyValidationRule("Height", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] - [PropertyDisplayText(true, "Height")] - public string v_YWindowSize { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod))] - [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] - public string v_MatchMethod { get; set; } + //[PropertyDescription("Window Width (Pixcel)")] + //[InputSpecification("Window Width", true)] + //[PropertyDetailSampleUsage("**640**", PropertyDetailSampleUsage.ValueType.Value, "Width")] + //[PropertyDetailSampleUsage("**{{{vWidth}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Width")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyTextBoxSetting(1, false)] + //[PropertyValidationRule("Width", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] + //[PropertyDisplayText(true, "Width")] + //[PropertyAvailableSystemVariable(Engine.SystemVariables.LimitedSystemVariableNames.Window_Size)] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_InputWidth))] + [PropertyParameterOrder(6500)] + public string v_Width { get; set; } [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] - public string v_TargetWindowIndex { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitTime { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] - public string v_NameResult { get; set; } - - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowHandleResult))] - public string v_HandleResult { get; set; } + //[PropertyDescription("Window Height (Pixcel)")] + //[InputSpecification("Window Height", true)] + //[PropertyDetailSampleUsage("**480**", PropertyDetailSampleUsage.ValueType.Value, "Height")] + //[PropertyDetailSampleUsage("**{{{vHeight}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Height")] + //[Remarks("")] + //[PropertyShowSampleUsageInDescription(true)] + //[PropertyTextBoxSetting(1, false)] + //[PropertyValidationRule("Height", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] + //[PropertyDisplayText(true, "Height")] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_InputHeight))] + [PropertyParameterOrder(6500)] + public string v_Height { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod))] + //[PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] + //public string v_MatchMethod { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + //public string v_TargetWindowIndex { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } public ResizeWindowCommand() { @@ -79,41 +83,35 @@ public ResizeWindowCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - //var wins = WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitTime), engine); - - //var width = this.ConvertToUserVariableAsInteger(nameof(v_XWindowSize), engine); - //var height = this.ConvertToUserVariableAsInteger(nameof(v_YWindowSize), engine); - //foreach (var win in wins) - //{ - // WindowNameControls.SetWindowSize(win.Item1, width, height); - //} - - WindowNameControls.WindowAction(this, engine, - new Action>(wins => + WindowControls.WindowAction(this, engine, + new Action>(wins => { - var width = this.ConvertToUserVariableAsInteger(nameof(v_XWindowSize), engine); - var height = this.ConvertToUserVariableAsInteger(nameof(v_YWindowSize), engine); + //var width = this.ExpandValueOrUserVariableAsInteger(nameof(v_Width), engine); + //var height = this.ExpandValueOrUserVariableAsInteger(nameof(v_Height), engine); + foreach (var win in wins) { - WindowNameControls.SetWindowSize(win.Item1, width, height); + var whnd = win.Item1; + + var width = this.ExpandValueOrVariableAsWindowWidth(whnd, engine); + var height = this.ExpandValueOrVariableAsWindowHeight(whnd, engine); + + WindowControls.SetWindowSize(whnd, width, height); } }) ); } - private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) - { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); - } + //private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + //{ + // WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + //} - public override void Refresh(frmCommandEditor editor) - { - base.Refresh(); - ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); - } + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/SetWindowStateByWindowHandleCommand.cs b/taskt/Core/Automation/Commands/Window/SetWindowStateByWindowHandleCommand.cs new file mode 100644 index 000000000..e5c261b64 --- /dev/null +++ b/taskt/Core/Automation/Commands/Window/SetWindowStateByWindowHandleCommand.cs @@ -0,0 +1,69 @@ +using System; +using System.Xml.Serialization; +using taskt.Core.Automation.Attributes.PropertyAttributes; + +namespace taskt.Core.Automation.Commands +{ + [Serializable] + [Attributes.ClassAttributes.Group("Window")] + [Attributes.ClassAttributes.SubGruop("Window Handle Actions")] + [Attributes.ClassAttributes.CommandSettings("Set Window State By Window Handle")] + [Attributes.ClassAttributes.Description("This command sets a target window's state.")] + [Attributes.ClassAttributes.UsesDescription("Use this command when you want to change a window's state to minimized, maximized, or restored state")] + [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] + [Attributes.ClassAttributes.EnableAutomateRender(true)] + [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] + public sealed class SetWindowStateByWindowHandleCommand : AWindowHandleCommands + { + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_InputWindowHandle))] + //public string v_WindowHandle { get; set; } + + [XmlAttribute] + [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] + [PropertyDescription("State of the Window")] + [PropertyUISelectionOption("Maximize")] + [PropertyUISelectionOption("Minimize")] + [PropertyUISelectionOption("Restore")] + [InputSpecification("", true)] + [PropertyValidationRule("Window State", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyDisplayText(true, "State")] + [PropertyParameterOrder(5500)] + public string v_WindowState { get; set; } + + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } + + public SetWindowStateByWindowHandleCommand() + { + } + + public override void RunCommand(Engine.AutomationEngineInstance engine) + { + WindowControls.WindowHandleAction(this, engine, + new Action(whnd => + { + var windowState = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WindowState), engine); + var state = WindowControls.WindowState.SW_RESTORE; + switch (windowState.ToLower()) + { + case "maximize": + state = WindowControls.WindowState.SW_MAXIMIZE; + break; + case "minimize": + state = WindowControls.WindowState.SW_MINIMIZE; + break; + } + + if (WindowControls.IsIconic(whnd) && (state != WindowControls.WindowState.SW_MINIMIZE)) + { + WindowControls.ShowIconicWindow(whnd); + } + WindowControls.SetWindowState(whnd, state); + }) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/SetWindowStateCommand.cs b/taskt/Core/Automation/Commands/Window/SetWindowStateCommand.cs index 37fc17a14..c23dbc52a 100644 --- a/taskt/Core/Automation/Commands/Window/SetWindowStateCommand.cs +++ b/taskt/Core/Automation/Commands/Window/SetWindowStateCommand.cs @@ -1,30 +1,29 @@ using System; -using System.Windows.Forms; using System.Xml.Serialization; -using taskt.UI.CustomControls; -using taskt.UI.Forms; +using System.Collections.Generic; using taskt.Core.Automation.Attributes.PropertyAttributes; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Window Commands")] + [Attributes.ClassAttributes.Group("Window")] [Attributes.ClassAttributes.SubGruop("Window Actions")] [Attributes.ClassAttributes.CommandSettings("Set Window State")] [Attributes.ClassAttributes.Description("This command sets a target window's state.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to change a window's state to minimized, maximized, or restored state")] [Attributes.ClassAttributes.ImplementationDescription("")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class SetWindowStateCommand : ScriptCommand + public sealed class SetWindowStateCommand : AWindowNameCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] - public string v_WindowName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } [XmlAttribute] [PropertyVirtualProperty(nameof(GeneralPropertyControls), nameof(GeneralPropertyControls.v_ComboBox))] @@ -35,28 +34,29 @@ public class SetWindowStateCommand : ScriptCommand [InputSpecification("", true)] [PropertyValidationRule("Window State", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "State")] + [PropertyParameterOrder(6500)] public string v_WindowState { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod))] - [PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] - public string v_MatchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_MatchMethod))] + //[PropertySelectionChangeEvent(nameof(MatchMethodComboBox_SelectionChangeCommitted))] + //public string v_MatchMethod { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] - public string v_TargetWindowIndex { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_TargetWindowIndex))] + //public string v_TargetWindowIndex { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_WaitTime { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public string v_WaitTime { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] - public string v_NameResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowHandleResult))] - public string v_HandleResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } public SetWindowStateCommand() { @@ -66,70 +66,44 @@ public SetWindowStateCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - //var windowState = this.GetUISelectionValue(nameof(v_WindowState), engine); - //var state = WindowNameControls.WindowState.SW_RESTORE; - //switch (windowState.ToLower()) - //{ - // case "maximize": - // state = WindowNameControls.WindowState.SW_MAXIMIZE; - // break; - // case "minimize": - // state = WindowNameControls.WindowState.SW_MINIMIZE; - // break; - //} - - //var wins = WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_MatchMethod), nameof(v_TargetWindowIndex), nameof(v_WaitTime), engine); - //foreach (var win in wins) - //{ - // var whnd = win.Item1; - // if (WindowNameControls.IsIconic(whnd) && (state != WindowNameControls.WindowState.SW_MINIMIZE)) - // { - // WindowNameControls.ShowIconicWindow(whnd); - // } - // WindowNameControls.SetWindowState(whnd, state); - //} - - WindowNameControls.WindowAction(this, engine, - new Action>(wins => + WindowControls.WindowAction(this, engine, + new Action>(wins => { - var windowState = this.GetUISelectionValue(nameof(v_WindowState), engine); - var state = WindowNameControls.WindowState.SW_RESTORE; + var windowState = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_WindowState), engine); + var state = WindowControls.WindowState.SW_RESTORE; switch (windowState.ToLower()) { case "maximize": - state = WindowNameControls.WindowState.SW_MAXIMIZE; + state = WindowControls.WindowState.SW_MAXIMIZE; break; case "minimize": - state = WindowNameControls.WindowState.SW_MINIMIZE; + state = WindowControls.WindowState.SW_MINIMIZE; break; } foreach (var win in wins) { var whnd = win.Item1; - if (WindowNameControls.IsIconic(whnd) && (state != WindowNameControls.WindowState.SW_MINIMIZE)) + if (WindowControls.IsIconic(whnd) && (state != WindowControls.WindowState.SW_MINIMIZE)) { - WindowNameControls.ShowIconicWindow(whnd); + WindowControls.ShowIconicWindow(whnd); } - WindowNameControls.SetWindowState(whnd, state); + WindowControls.SetWindowState(whnd, state); } }) ); } - private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) - { - WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); - } + //private void MatchMethodComboBox_SelectionChangeCommitted(object sender, EventArgs e) + //{ + // WindowNameControls.MatchMethodComboBox_SelectionChangeCommitted(ControlsList, (ComboBox)sender, nameof(v_TargetWindowIndex)); + //} - public override void Refresh(frmCommandEditor editor) - { - base.Refresh(); - ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); - } + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Window/WaitForWindowToExistsCommand.cs b/taskt/Core/Automation/Commands/Window/WaitForWindowToExistsCommand.cs index 52c99c6da..070a5ae61 100644 --- a/taskt/Core/Automation/Commands/Window/WaitForWindowToExistsCommand.cs +++ b/taskt/Core/Automation/Commands/Window/WaitForWindowToExistsCommand.cs @@ -1,42 +1,39 @@ using System; -using System.Windows.Forms; -using System.Xml.Serialization; -using taskt.UI.CustomControls; -using taskt.UI.Forms; -using taskt.Core.Automation.Attributes.PropertyAttributes; +using System.Collections.Generic; namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Window Commands")] + [Attributes.ClassAttributes.Group("Window")] [Attributes.ClassAttributes.SubGruop("Window Actions")] [Attributes.ClassAttributes.CommandSettings("Wait For Window To Exists")] [Attributes.ClassAttributes.Description("This command waits for a window to exist.")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to explicitly wait for a window to exist before continuing script execution.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements 'FindWindowNative', 'ShowWindow' from user32.dll to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_window))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WaitForWindowToExistsCommand : ScriptCommand + public sealed class WaitForWindowToExistsCommand : AAnyWindowNameCommands { - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] - public string v_WindowName { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowName))] + //public string v_WindowName { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] - public string v_SearchMethod { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_CompareMethod))] + //public string v_SearchMethod { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] - public string v_LengthToWait { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WaitTime))] + //public override string v_WaitTime { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] - public string v_NameResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowNameResult))] + //public string v_NameResult { get; set; } - [XmlAttribute] - [PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_WindowHandleResult))] - public string v_HandleResult { get; set; } + //[XmlAttribute] + //[PropertyVirtualProperty(nameof(WindowNameControls), nameof(WindowNameControls.v_OutputWindowHandle))] + //public string v_HandleResult { get; set; } //[XmlIgnore] //[NonSerialized] @@ -50,32 +47,20 @@ public WaitForWindowToExistsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - //try - //{ - // WindowNameControls.FindWindows(this, nameof(v_WindowName), nameof(v_SearchMethod), nameof(v_LengthToWait), engine); - //} - //catch (Exception ex) - //{ - // throw ex; - //} - - WindowNameControls.WindowAction(this, engine, - new Action>(wins => + WindowControls.WindowAction(this, engine, + new Action>(wins => { // nothing to do }) ); } - public override void Refresh(frmCommandEditor editor) - { - base.Refresh(); - //WindowNameControl.AddWindowNames(); - ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); - } + //public override void Refresh(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) + //{ + // //WindowNameControl.AddWindowNames(); + // ControlsList.GetPropertyControl(nameof(v_WindowName)).AddWindowNames(); + //} } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/WindowNameControls.cs b/taskt/Core/Automation/Commands/WindowControls.cs similarity index 51% rename from taskt/Core/Automation/Commands/WindowNameControls.cs rename to taskt/Core/Automation/Commands/WindowControls.cs index 89419131c..6c8d145a5 100644 --- a/taskt/Core/Automation/Commands/WindowNameControls.cs +++ b/taskt/Core/Automation/Commands/WindowControls.cs @@ -8,15 +8,60 @@ using System.Windows.Forms; using taskt.UI.CustomControls; using taskt.Core.Automation.Attributes.PropertyAttributes; +using taskt.Core.Automation.Engine; namespace taskt.Core.Automation.Commands { /// - /// for window name methods + /// for window methods /// - internal static class WindowNameControls + internal static class WindowControls { + #region fields + + /// + /// internal current window keyword + /// + public const string INTERNAL_CURRENT_WINDOW_KEYWORD = "%kwd_current_window%"; + /// + /// internal Desktop keyword + /// + public const string INTERNAL_DESKTOP_KEYWORD = "%kwd_desktop%"; + /// + /// internal all windows keyword + /// + public const string INTERNAL_ALL_WINDOWS_KEYWORD = "%kwd_all_windows%"; + /// + /// internal current window position keyword + /// + public const string INTERNAL_CURRENT_WINDOW_POSITION_KEYWORD = "%kwd_current_window_position%"; + /// + /// internal current window X position keyword + /// + public const string INTERNAL_CURRENT_WINDOW_X_POSITION_KEYWORD = "%kwd_current_window_xposition%"; + /// + /// internal current window Y position keyword + /// + public const string INTERNAL_CURRENT_WINDOW_Y_POSITION_KEYWORD = "%kwd_current_window_yposition%"; + /// + /// internal current window size keyword + /// + public const string INTERNAL_CURRENT_WINDOW_SIZE_KEYWORD = "%kwd_current_window_size%"; + /// + /// internal current window width keyword + /// + public const string INTERNAL_CURRENT_WINDOW_WIDTH_KEYWORD = "%kwd_current_window_width%"; + /// + /// internal current window height keyword + /// + public const string INTERNAL_CURRENT_WINDOW_HEIGHT_KEYWORD = "%kwd_current_window_height%"; + /// + /// internal current window handle keyword + /// + public const string INTERNAL_CURRENT_WINDOW_HANDLE_KEYWORD = "%kwd_current_window_handle%"; + #endregion + #region virtualproperty /// @@ -29,18 +74,18 @@ internal static class WindowNameControls [PropertyDetailSampleUsage("**{{{vWindow}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Window Name")] [Remarks("")] [PropertyIsWindowNamesList(true)] - [PropertyCustomUIHelper("Up-to-date", nameof(WindowNameControls) + "+" + nameof(WindowNameControls.lnkWindowNameUpToDate_Click))] + [PropertyCustomUIHelper("Up-to-date", nameof(WindowControls) + "+" + nameof(WindowControls.lnkWindowNameUpToDate_Click))] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyShowSampleUsageInDescription(true)] - [PropertyIntermediateConvert(nameof(ApplicationSettings.EngineSettings.convertToIntermediateWindowName), nameof(ApplicationSettings.EngineSettings.convertToRawWindowName))] [PropertyValidationRule("Window Name", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Name")] + [PropertyParameterOrder(5000)] public static string v_WindowName { get; } /// /// windows name compare(search) method /// - [PropertyDescription("Search Method for the Window Name")] + [PropertyDescription("Compare Method for the Window Name")] [InputSpecification("", true)] [PropertyUISelectionOption("Contains")] [PropertyUISelectionOption("Starts with")] @@ -49,7 +94,8 @@ internal static class WindowNameControls [Remarks("")] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyIsOptional(true, "Contains")] - [PropertyDisplayText(true, "Search Method")] + [PropertyDisplayText(true, "Compare Method")] + [PropertyParameterOrder(5000)] public static string v_CompareMethod { get; } /// @@ -68,6 +114,7 @@ internal static class WindowNameControls [Remarks("Specify when there are Multiple Matching Windows")] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyIsOptional(true, "First")] + [PropertyParameterOrder(5000)] public static string v_MatchMethod { get; } /// @@ -84,6 +131,7 @@ internal static class WindowNameControls [Remarks("Specify when there are Multiple Matching Windows")] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] [PropertyIsOptional(true, "First")] + [PropertyParameterOrder(5000)] public static string v_MatchMethod_Single { get; } /// @@ -99,6 +147,7 @@ internal static class WindowNameControls [PropertyTextBoxSetting(1, false)] [PropertyIsOptional(true, "0")] [PropertyFirstValue("0")] + [PropertyParameterOrder(5000)] public static string v_TargetWindowIndex { get; } /// @@ -113,6 +162,7 @@ internal static class WindowNameControls [PropertyTextBoxSetting(1, false)] [PropertyIsOptional(true, "60")] [PropertyFirstValue("60")] + [PropertyParameterOrder(5000)] public static string v_WaitTime { get; } /// @@ -130,10 +180,11 @@ internal static class WindowNameControls [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("Window Name Result", PropertyValidationRule.ValidationRuleFlags.None)] [PropertyDisplayText(false, "")] + [PropertyParameterOrder(5000)] public static string v_WindowNameResult { get; } /// - /// window handle result + /// output window handle result /// [PropertyDescription("Variable Name to Store Window Handle Result")] [InputSpecification("Variable Name", true)] @@ -144,10 +195,105 @@ internal static class WindowNameControls [PropertyIsVariablesList(true)] [PropertyIsOptional(true)] [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyInstanceType(PropertyInstanceType.InstanceType.WindowHandle, true)] [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Output)] [PropertyValidationRule("Window Handle Result", PropertyValidationRule.ValidationRuleFlags.None)] [PropertyDisplayText(false, "")] - public static string v_WindowHandleResult { get; } + [PropertyParameterOrder(5000)] + public static string v_OutputWindowHandle { get; } + + /// + /// input window handle result + /// + [PropertyDescription("Window Handle Variable Name")] + [InputSpecification("Variable Name", true)] + [PropertyDetailSampleUsage("**vHandle**", PropertyDetailSampleUsage.ValueType.VariableName)] + [PropertyDetailSampleUsage("**{{{vHandle}}}**", PropertyDetailSampleUsage.ValueType.VariableName)] + [Remarks("")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] + [PropertyInstanceType(PropertyInstanceType.InstanceType.WindowHandle, true)] + [PropertyParameterDirection(PropertyParameterDirection.ParameterDirection.Input)] + [PropertyValidationRule("Window Handle Result", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyDisplayText(true, "Window Handle")] + [PropertyParameterOrder(5000)] + public static string v_InputWindowHandle { get; } + + /// + /// input window width + /// + [PropertyDescription("Window Width (Pixcel)")] + [InputSpecification("Window Width", true)] + [PropertyDetailSampleUsage("**640**", PropertyDetailSampleUsage.ValueType.Value, "Width")] + [PropertyDetailSampleUsage("**{{{vWidth}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Width")] + [PropertyDetailSampleUsage("**%kwd_current_window_size%**", "Specify Current Window Width for Window Width")] + [PropertyDetailSampleUsage("**%kwd_current_window_width%**", "Specify Current Window Width for Window Width", false)] + [Remarks("")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyTextBoxSetting(1, false)] + [PropertyValidationRule("Width", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] + [PropertyDisplayText(true, "Width")] + [PropertyAvailableSystemVariable(SystemVariables.LimitedSystemVariableNames.Window_Size)] + [PropertyParameterOrder(5000)] + public static string v_InputWidth { get; } + + /// + /// input window height + /// + [PropertyDescription("Window Height (Pixcel)")] + [InputSpecification("Window Height", true)] + [PropertyDetailSampleUsage("**480**", PropertyDetailSampleUsage.ValueType.Value, "Height")] + [PropertyDetailSampleUsage("**{{{vHeight}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Height")] + [PropertyDetailSampleUsage("**%kwd_current_window_size%**", "Specify Current Window Height for Window Height")] + [PropertyDetailSampleUsage("**%kwd_current_window_height%**", "Specify Current Window Height for Window Height", false)] + [Remarks("")] + [PropertyShowSampleUsageInDescription(true)] + [PropertyTextBoxSetting(1, false)] + [PropertyValidationRule("Height", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] + [PropertyAvailableSystemVariable(SystemVariables.LimitedSystemVariableNames.Window_Size)] + [PropertyDisplayText(true, "Height")] + [PropertyParameterOrder(5000)] + public static string v_InputHeight { get; } + + /// + /// input window X position + /// + [PropertyDescription("X horizontal coordinate (pixel) for the Window's Location")] + [InputSpecification("X Window Location", true)] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage("**0**", "Specify X Top Position")] + [PropertyDetailSampleUsage("**100**", PropertyDetailSampleUsage.ValueType.Value, "X Position")] + [PropertyDetailSampleUsage("**{{{vXPos}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "X Position")] + [PropertyDetailSampleUsage("**%kwd_current_window_position%**", "Specify Current Position for X Position")] + [PropertyDetailSampleUsage("**%kwd_current_window_xposition%**", "Specify Current X Position for X Position", false)] + [PropertyDetailSampleUsage("**%kwd_current_window_yposition%**", "Specify Current Y Position for X Position", false)] + [Remarks("This number is the pixel location on screen. Maximum value should be the maximum value allowed by your resolution. For 1920x1080, the valid range could be 0-1920")] + [PropertyValidationRule("X Position", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyTextBoxSetting(1, false)] + [PropertyAvailableSystemVariable(SystemVariables.LimitedSystemVariableNames.Window_Position)] + [PropertyDisplayText(true, "X Position")] + [PropertyParameterOrder(5000)] + public static string v_InputXPosition { get; } + + /// + /// intpu window Y position + /// + [PropertyDescription("Y vertical coordinate (pixel) for the Window's Location")] + [InputSpecification("Y Window Location", true)] + [PropertyShowSampleUsageInDescription(true)] + [PropertyDetailSampleUsage("**0**", "Specify Y Left Position")] + [PropertyDetailSampleUsage("**100**", PropertyDetailSampleUsage.ValueType.Value, "Y Position")] + [PropertyDetailSampleUsage("**{{{vYPos}}}**", PropertyDetailSampleUsage.ValueType.VariableValue, "Y Position")] + [PropertyDetailSampleUsage("**%kwd_current_window_position%**", "Specify Current Position for Y Position")] + [PropertyDetailSampleUsage("**%kwd_current_window_xposition%**", "Specify Current X Position for Y Position", false)] + [PropertyDetailSampleUsage("**%kwd_current_window_yposition%**", "Specify Current Y Position for Y Position", false)] + [Remarks("This number is the pixel location on screen. Maximum value should be the maximum value allowed by your resolution. For 1920x1080, the valid range could be 0-1080")] + [PropertyValidationRule("Y Position", PropertyValidationRule.ValidationRuleFlags.Empty)] + [PropertyTextBoxSetting(1, false)] + [PropertyAvailableSystemVariable(SystemVariables.LimitedSystemVariableNames.Window_Position)] + [PropertyDisplayText(true, "Y Position")] + [PropertyParameterOrder(5000)] + public static string v_InputYPosition { get; } #endregion @@ -182,10 +328,16 @@ public enum WindowState SW_SHOWNORMAL = 1, } - public struct RECT - { - public int left, top, right, bottom; - } + ///// + ///// Window Rect + ///// + //public struct RECT + //{ + // public int left; + // public int top; + // public int right; + // public int bottom; + //} public struct WINDOWPLACEMENT { @@ -211,6 +363,9 @@ public struct WINDOWPLACEMENT [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr hWnd); + [DllImport("user32.dll")] + private static extern bool IsWindow(IntPtr hWnd); + [DllImport("user32.dll", CharSet = CharSet.Unicode)] private static extern int GetWindowTextLengthW(IntPtr hWnd); @@ -251,6 +406,10 @@ public struct WINDOWPLACEMENT [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)] private static extern IntPtr GetDesktopWindow(); + /// + /// get all window name and handle as Dictionary. Key is WindowHandle, Value is Window name + /// + /// public static List<(IntPtr, string)> GetAllWindowNamesAndHandles() { windowTitles = new List<(IntPtr, string)>(); @@ -260,6 +419,12 @@ public struct WINDOWPLACEMENT return new List<(IntPtr, string)>(windowTitles); } + /// + /// enum windows + /// + /// + /// + /// private static bool EnumerateWindow(IntPtr hWnd, IntPtr lParam) { int titleLengthA = GetWindowTextLengthW(hWnd); @@ -273,6 +438,11 @@ private static bool EnumerateWindow(IntPtr hWnd, IntPtr lParam) return true; } + /// + /// get window name from window handle + /// + /// + /// public static string GetWindowTitle(IntPtr hWnd) { int titleLengthA = GetWindowTextLengthW(hWnd); @@ -281,28 +451,50 @@ public static string GetWindowTitle(IntPtr hWnd) return title.ToString(); } + /// + /// get active window handlw + /// + /// public static IntPtr GetActiveWindowHandle() { return GetForegroundWindow(); } + /// + /// set window state + /// + /// + /// public static void SetWindowState(IntPtr hWnd, WindowState windowState) { ShowWindow(hWnd, (int)windowState); } - public static void SetForegroundWindow(IntPtr hWnd) + /// + /// set foreground to window + /// + /// + public static void SetToForegroundWindow(IntPtr hWnd) { SetForegroundWindowNative(hWnd); } - public static RECT GetWindowPosition(IntPtr hWnd) + /// + /// get window RECT + /// + /// + /// + public static RECT GetWindowRect(IntPtr hWnd) { - RECT clientArea = new RECT(); - GetWindowRect(hWnd, out clientArea); + GetWindowRect(hWnd, out RECT clientArea); return clientArea; } + /// + /// get window state + /// + /// + /// public static int GetWindowState(IntPtr hWnd) { var wInfo = new WINDOWPLACEMENT(); @@ -310,11 +502,22 @@ public static int GetWindowState(IntPtr hWnd) return wInfo.showCmd; } + /// + /// close window. send SendMessage + /// + /// public static void CloseWindow(IntPtr hWnd) { const UInt32 WM_CLOSE = 0x0010; SendMessage(hWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero); } + + /// + /// set window position + /// + /// + /// + /// public static void SetWindowPosition(IntPtr hWnd, int newXPosition, int newYPosition) { const short SWP_NOSIZE = 1; @@ -323,6 +526,13 @@ public static void SetWindowPosition(IntPtr hWnd, int newXPosition, int newYPosi SetWindowPos(hWnd, 0, newXPosition, newYPosition, 0, 0, SWP_NOZORDER | SWP_NOSIZE | SWP_SHOWWINDOW); } + + /// + /// set window size + /// + /// + /// + /// public static void SetWindowSize(IntPtr hWnd, int newXSize, int newYSize) { const short SWP_NOZORDER = 0X4; @@ -333,11 +543,19 @@ public static void SetWindowSize(IntPtr hWnd, int newXSize, int newYSize) SetWindowPos(hWnd, 0, windowRect.left, windowRect.top, newXSize, newYSize, SWP_NOZORDER | SWP_SHOWWINDOW); } + /// + /// ? + /// + /// public static void ShowIconicWindow(IntPtr hWind) { ShowWindowAsync(hWind, WindowState.SW_SHOWNORMAL); } + /// + /// get active window name (title) + /// + /// public static string GetActiveWindowTitle() { var whnd = GetActiveWindowHandle(); @@ -445,19 +663,16 @@ public static Func GetWindowNameCompareMethod(string compa /// private static Func> GetWindowSearchMethod(string window, string searchMethod, string matchType, int index, Engine.AutomationEngineInstance engine) { - if (window == engine.engineSettings.CurrentWindowKeyword) + if (window == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_Desktop.VariableName, engine)) { - // current window - - var whnd = GetActiveWindowHandle(); - var title = GetWindowTitle(whnd); - + // Desktop + var whnd = GetDesktopWindow(); return new Func>(() => { - return new List<(IntPtr, string)>() { (whnd, title) }; + return new List<(IntPtr, string)>() { (whnd, "") }; }); } - else if (window == engine.engineSettings.AllWindowsKeyword) + else if (window == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_AllWindows.VariableName, engine)) { // all windows & match-type return new Func>(() => @@ -496,9 +711,17 @@ public static string GetCurrentWindowName() return GetWindowTitle(whnd); } + /// + /// find window handle from specified from args + /// + /// + /// + /// + /// + /// public static IntPtr FindWindowHandle(string windowName, string searchMethod, Automation.Engine.AutomationEngineInstance engine) { - if (windowName == engine.engineSettings.CurrentWindowKeyword) + if (windowName == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentWindowName.VariableName, engine)) { return GetActiveWindowHandle(); } @@ -520,114 +743,153 @@ public static IntPtr FindWindowHandle(string windowName, string searchMethod, Au } } + /// + /// get all window titles + /// + /// public static List GetAllWindowTitles() { return GetAllWindowNamesAndHandles().Select(w => w.Item2).ToList(); } + /// + /// get all window handles + /// + /// public static List GetAllWindowHandles() { return GetAllWindowNamesAndHandles().Select(w => w.Item1).ToList(); } - public static void ActivateWindow(IntPtr handle) + /// + /// get all window names for frmCommandEditor ComboBox + /// + /// + /// + /// + /// + /// + public static List GetAllWindowTitles(ApplicationSettings settings, bool addCurrentWindow = true, bool addAllWindows = false, bool addDesktop = false) { - if (IsIconic(handle)) + var lst = new List(); + + if (addCurrentWindow) { - SetWindowState(handle, WindowState.SW_SHOWNORMAL); + lst.Add(VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentWindowName.VariableName, settings)); } - SetForegroundWindow(handle); - } - - public static Bitmap CaptureWindow(string windowName, Engine.AutomationEngineInstance engine) - { - IntPtr hWnd; - if (windowName == "Desktop") + + // TODO: use system variable like keyword + if (addAllWindows) { - hWnd = GetDesktopWindow(); + //lst.Add(settings?.EngineSettings.AllWindowsKeyword ?? "All Windows"); + lst.Add(VariableNameControls.GetWrappedVariableName(SystemVariables.Window_AllWindows.VariableName, settings)); } - else + + if (addDesktop) { - //hWnd = FindWindow(windowName); - var wins = FindWindows(windowName, "", "", 0, 60, engine); - hWnd = wins[0].Item1; - - SetWindowState(hWnd, WindowState.SW_RESTORE); - SetForegroundWindow(hWnd); + //lst.Add(settings?.EngineSettings.DesktopKeyword ?? "Desktop"); + lst.Add(VariableNameControls.GetWrappedVariableName(SystemVariables.Window_Desktop.VariableName, settings)); } - var rect = new RECT(); + lst.AddRange(GetAllWindowTitles()); - //sleep to allow repaint - System.Threading.Thread.Sleep(500); - - GetWindowRect(hWnd, out rect); - var bounds = new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); - var screenshot = new Bitmap(bounds.Width, bounds.Height); + return lst; + } - using (var graphics = Graphics.FromImage(screenshot)) + /// + /// Activate Window + /// + /// + public static void ActivateWindow(IntPtr handle) + { + if (IsIconic(handle)) { - graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); + SetWindowState(handle, WindowState.SW_SHOWNORMAL); } - - return screenshot; + SetToForegroundWindow(handle); } - public static string GetMatchedWindowName(string windowName, string searchMethod, Automation.Engine.AutomationEngineInstance engine) + /// + /// convert processId to Window Handle + /// + /// + /// + /// + public static IntPtr ConvertProcessIdToWindowHandle(int pid) { - if (windowName == engine.engineSettings.CurrentWindowKeyword) + var whnds = GetAllWindowHandles(); + foreach(var whnd in whnds) { - return GetCurrentWindowName(); - } - else - { - var wins = GetAllWindowNamesAndHandles(); - var method = GetWindowNameCompareMethod(searchMethod); - try - { - var win = wins.Where(w => method(w.Item2, windowName)).First(); - return win.Item2; - } - catch + int myPid; + GetWindowThreadProcessId(whnd, out myPid); + if (myPid == pid) { - // not found - throw new Exception("Window Name '" + windowName + "' not found"); + return whnd; } } + throw new Exception("ProcessID: " + pid + " does not found."); } + + //public static Bitmap CaptureWindow(string windowName, Engine.AutomationEngineInstance engine) + //{ + // IntPtr hWnd; + // if (windowName == "Desktop") + // { + // hWnd = GetDesktopWindow(); + // } + // else + // { + // //hWnd = FindWindow(windowName); + // var wins = FindWindows(windowName, "", "", 0, 60, engine); + // hWnd = wins[0].Item1; + + // SetWindowState(hWnd, WindowState.SW_RESTORE); + // SetToForegroundWindow(hWnd); + // } + + // var rect = new RECT(); + + // //sleep to allow repaint + // System.Threading.Thread.Sleep(500); + + // GetWindowRect(hWnd, out rect); + // var bounds = new Rectangle(rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top); + // var screenshot = new Bitmap(bounds.Width, bounds.Height); + + // using (var graphics = Graphics.FromImage(screenshot)) + // { + // graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); + // } + + // return screenshot; + //} /// - /// expand variable as Window Name + /// capture window /// - /// - /// + /// /// - private static string ConvertToUserVariableAsWindowName(this string value, Engine.AutomationEngineInstance engine) + /// + public static Bitmap CaptureWindow(IntPtr whnd) { - if ((value == engine.engineSettings.CurrentWindowKeyword) || (value == engine.engineSettings.AllWindowsKeyword)) + if (GetWindowRect(whnd, out RECT r)) { - return value; + var bounds = new Rectangle(r.left, r.top, r.right - r.left, r.bottom - r.top); + var screenshot = new Bitmap(bounds.Width, bounds.Height); + + using (var graphics = Graphics.FromImage(screenshot)) + { + graphics.CopyFromScreen(new Point(bounds.Left, bounds.Top), Point.Empty, bounds.Size); + } + + return screenshot; } else { - return value.ConvertToUserVariable(engine); + throw new Exception($"Fail Capture Window. WindowHandle: {whnd}"); } } - /// - /// expand specified property value as Window Name - /// - /// - /// - /// - /// - private static string ConvertToUserVariableAsWindowName(this ScriptCommand command, string windowName, Engine.AutomationEngineInstance engine) - { - var prop = command.GetProperty(windowName); - var value = prop.GetValue(command)?.ToString() ?? ""; - return value.ConvertToUserVariableAsWindowName(engine); - } - /// /// search & wait window name. this method use argument values, DON'T convert variable. /// @@ -688,11 +950,11 @@ private static string ConvertToUserVariableAsWindowName(this ScriptCommand comma /// public static List<(IntPtr, string)> FindWindows(ScriptCommand command, string windowName, string compareMethodName, string matchTypeName, string indexName, string waitName, Engine.AutomationEngineInstance engine) { - var window = command.ConvertToUserVariableAsWindowName(windowName, engine); - var compareMethod = command.GetUISelectionValue(compareMethodName, engine); - var matchType = command.GetUISelectionValue(matchTypeName, engine); - var index = command.ConvertToUserVariableAsInteger(indexName, engine); - var waitTime = command.ConvertToUserVariableAsInteger(waitName, engine); + var window = command.ExpandValueOrUserVariableAsWindowName(windowName, engine); + var compareMethod = command.ExpandValueOrUserVariableAsSelectionItem(compareMethodName, engine); + var matchType = command.ExpandValueOrUserVariableAsSelectionItem(matchTypeName, engine); + var index = command.ExpandValueOrUserVariableAsInteger(indexName, engine); + var waitTime = command.ExpandValueOrUserVariableAsInteger(waitName, engine); return FindWindows(window, compareMethod, matchType, index, waitTime, engine); } @@ -708,9 +970,9 @@ private static string ConvertToUserVariableAsWindowName(this ScriptCommand comma /// public static List<(IntPtr, string)> FindWindows(ScriptCommand command, string windowName, string compareMethodName, string waitName, Engine.AutomationEngineInstance engine) { - var window = command.ConvertToUserVariableAsWindowName(windowName, engine); - var compareMethod = command.GetUISelectionValue(compareMethodName, engine); - var waitTime = command.ConvertToUserVariableAsInteger(waitName, engine); + var window = command.ExpandValueOrUserVariableAsWindowName(windowName, engine); + var compareMethod = command.ExpandValueOrUserVariableAsSelectionItem(compareMethodName, engine); + var waitTime = command.ExpandValueOrUserVariableAsInteger(waitName, engine); return FindWindows(window, compareMethod, "All", 60, waitTime, engine); } @@ -737,7 +999,7 @@ private static void WindowAction(ScriptCommand command, string matchType, Func private static void WindowAction(ScriptCommand command, string windowName, string compareMethodName, string matchTypeName, string indexName, string waitName, Engine.AutomationEngineInstance engine, Action> actionFunc, string nameResultName = "", string handleResultName = "", Action errorFunc = null) { - var matchType = command.GetUISelectionValue(matchTypeName, engine); + var matchType = command.ExpandValueOrUserVariableAsSelectionItem(matchTypeName, engine); WindowAction(command, matchType, new Func>(() => { @@ -824,7 +1087,7 @@ private static void WindowAction(ScriptCommand command, string windowName, strin } /// - /// window general action. This method search window before execute actionFunc, and try store Found Window Name and Handle after execute actionFunc. This method specifies the parameter from the value of PropertyVirtualProperty + /// window general action. This method search window before execute actionFunc, and try store Found Window Name and Handle after execute actionFunc. This method specifies the parameter names from the value of PropertyVirtualProperty /// /// /// @@ -832,26 +1095,16 @@ private static void WindowAction(ScriptCommand command, string windowName, strin /// public static void WindowAction(ScriptCommand command, Engine.AutomationEngineInstance engine, Action> actionFunc, Action errorFunc = null) { - //var windowName = command.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_WindowName)))?.Name ?? ""; - //var compareMethod = command.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_CompareMethod)))?.Name ?? ""; - //var waitTime = command.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_WaitTime)))?.Name ?? ""; - //var nameResult = command.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_WindowNameResult)))?.Name ?? ""; - //var handleResult = command.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_WindowHandleResult)))?.Name ?? ""; - - //var matchType = command.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_MatchMethod)))?.Name ?? - // command.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_MatchMethod_Single)))?.Name ?? ""; - //var index = command.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_TargetWindowIndex)))?.Name ?? ""; - var props = command.GetParameterProperties(); - var windowName = props.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_WindowName)))?.Name ?? ""; - var compareMethod = props.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_CompareMethod)))?.Name ?? ""; - var waitTime = props.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_WaitTime)))?.Name ?? ""; - var nameResult = props.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_WindowNameResult)))?.Name ?? ""; - var handleResult = props.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_WindowHandleResult)))?.Name ?? ""; + var windowName = props.GetProperty(new PropertyVirtualProperty(nameof(WindowControls), nameof(v_WindowName)))?.Name ?? ""; + var compareMethod = props.GetProperty(new PropertyVirtualProperty(nameof(WindowControls), nameof(v_CompareMethod)))?.Name ?? ""; + var waitTime = props.GetProperty(new PropertyVirtualProperty(nameof(WindowControls), nameof(v_WaitTime)))?.Name ?? ""; + var nameResult = props.GetProperty(new PropertyVirtualProperty(nameof(WindowControls), nameof(v_WindowNameResult)))?.Name ?? ""; + var handleResult = props.GetProperty(new PropertyVirtualProperty(nameof(WindowControls), nameof(v_OutputWindowHandle)))?.Name ?? ""; - var matchType = props.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_MatchMethod)))?.Name ?? - props.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_MatchMethod_Single)))?.Name ?? ""; - var index = props.GetProperty(new PropertyVirtualProperty(nameof(WindowNameControls), nameof(v_TargetWindowIndex)))?.Name ?? ""; + var matchType = props.GetProperty(new PropertyVirtualProperty(nameof(WindowControls), nameof(v_MatchMethod)))?.Name ?? + props.GetProperty(new PropertyVirtualProperty(nameof(WindowControls), nameof(v_MatchMethod_Single)))?.Name ?? ""; + var index = props.GetProperty(new PropertyVirtualProperty(nameof(WindowControls), nameof(v_TargetWindowIndex)))?.Name ?? ""; if (matchType == "") { @@ -862,6 +1115,211 @@ public static void WindowAction(ScriptCommand command, Engine.AutomationEngineIn WindowAction(command, windowName, compareMethod, matchType, index, waitTime, engine, actionFunc, nameResult, handleResult, errorFunc); } } + + /// + /// window general action. This method search window before execute actionFunc, and try store Found Window Name and Handle after execute actionFunc. This method specifies the parameter names from interface + /// + /// + /// + /// + /// + public static void WindowAction(AWindowNameCommands command, Engine.AutomationEngineInstance engine, Action> actionFunc, Action errorFunc = null) + { + WindowAction(command, + nameof(command.v_WindowName), nameof(command.v_CompareMethod), nameof(command.v_MatchMethod), + nameof(command.v_TargetWindowIndex), nameof(command.v_WaitTimeForWindow), engine, actionFunc, + nameof(command.v_NameResult), nameof(command.v_HandleResult), errorFunc); + } + + /// + /// window general action. This method search window before execute actionFunc, and try store Found Window Name and Handle after execute actionFunc. This method specifies the parameter names from interface + /// + /// + /// + /// + /// + public static void WindowAction(AAnyWindowNameCommands command, Engine.AutomationEngineInstance engine, Action> actionFunc, Action errorFunc = null) + { + WindowAction(command, + nameof(command.v_WindowName), nameof(command.v_CompareMethod), nameof(command.v_WaitTimeForWindow), + engine, actionFunc, nameof(command.v_NameResult), nameof(command.v_HandleResult), errorFunc); + } + + /// + /// inner window handle action + /// + /// + /// + /// + /// + /// + private static void WindowHandleAction(string handleValue, int waitTime, Engine.AutomationEngineInstance engine, Action actionFunc, Action errorFunc = null) + { + try + { + var whnd = handleValue.ExpandUserVariableAsWindowHandle(engine); + + var obj = WaitControls.WaitProcess(waitTime, "Window Handle", new Func<(bool, object)>(() => + { + if (IsWindow(whnd)) + { + return (true, whnd); + } + else + { + return (false, null); + } + + }), engine); + + if (obj is IntPtr ptr) + { + actionFunc(ptr); + } + } + catch (Exception ex) + { + if (errorFunc != null) + { + errorFunc(ex); + } + else + { + throw ex; + } + } + } + + /// + /// window handle action. specified Window Handle, Wait Time parameter names + /// + /// + /// + /// + /// + /// + /// + public static void WindowHandleAction(ScriptCommand command, string handleName, string waitTimeName, Engine.AutomationEngineInstance engine, Action actionFunc, Action errorFunc = null) + { + //var handle = command.ExpandValueOrUserVariable(handleName, "Window Handle", engine); + var handle = command.GetRawPropertyValueAsString(handleName, "Window Handle"); + var waitTime = command.ExpandValueOrUserVariableAsInteger(waitTimeName, "Wait Time", engine); + WindowHandleAction(handle, waitTime, engine, actionFunc, errorFunc); + } + + /// + /// general window handle action. Infer parameter names from VirtualProperty + /// + /// + /// + /// + /// + public static void WindowHandleAction(ScriptCommand command, Engine.AutomationEngineInstance engine, Action actionFunc, Action errorFunc = null) + { + var props = command.GetParameterProperties(); + var handleName = props.GetProperty(new PropertyVirtualProperty(nameof(WindowControls), nameof(v_InputWindowHandle)))?.Name ?? ""; + var waitTimeName = props.GetProperty(new PropertyVirtualProperty(nameof(WindowControls), nameof(v_WaitTime)))?.Name ?? ""; + WindowHandleAction(command, handleName, waitTimeName, engine, actionFunc, errorFunc); + } + + + #endregion + + #region variable + + /// + /// expand variable as Window Name + /// + /// + /// + /// + private static string ExpandValueOrUserVariableAsWindowName(this string value, Engine.AutomationEngineInstance engine) + { + if ((value == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_AllWindows.VariableName, engine)) || + (value == VariableNameControls.GetWrappedVariableName(SystemVariables.Window_Desktop.VariableName, engine))) + { + return value; + } + else + { + return value.ExpandValueOrUserVariable(engine); + } + } + + /// + /// expand specified property value as Window Name + /// + /// + /// + /// + /// + private static string ExpandValueOrUserVariableAsWindowName(this ScriptCommand command, string windowName, Engine.AutomationEngineInstance engine) + { + var prop = command.GetProperty(windowName); + var value = prop.GetValue(command)?.ToString() ?? ""; + return value.ExpandValueOrUserVariableAsWindowName(engine); + } + + /// + /// expand variable as WindowHandle specified by parameter value + /// + /// + /// + /// + /// + public static IntPtr ExpandUserVariableAsWindowHandle(this string value, Engine.AutomationEngineInstance engine) + { + var v = value.GetRawVariable(engine); + var vv = v.VariableValue; + string handleStr; + if (vv is string str) + { + handleStr = str; + } + else if (vv is List lst) + { + handleStr = lst[v.CurrentPosition]; + } + else + { + throw new Exception($"Value '{value}' is not Window Handle value type."); + } + + if (int.TryParse(handleStr, out int whnd)) + { + return (IntPtr)whnd; + } + else + { + throw new Exception($"Value '{value}' is not Window Handle value type."); + } + } + + /// + /// expand variable as WindowHanle specified by parameter name + /// + /// + /// + /// + /// + public static IntPtr ExpandUserVariableAsWindowHandle(this ScriptCommand command, string windowName, Engine.AutomationEngineInstance engine) + { + var prop = command.GetProperty(windowName); + var value = prop.GetValue(command)?.ToString() ?? ""; + return value.ExpandUserVariableAsWindowHandle(engine); + } + + /// + /// store IntPtr In User Variable + /// + /// + /// + /// + public static void StoreInUserVariable(this IntPtr value, Engine.AutomationEngineInstance engine, string targetVariable) + { + ExtensionMethods.StoreInUserVariable(targetVariable, value.ToString(), engine, false); + } + #endregion #region Events @@ -876,10 +1334,6 @@ public static void lnkWindowNameUpToDate_Click(object sender, EventArgs e) var winList = GetAllWindowTitles(); - //foreach (var title in winList) - //{ - // cmb.Items.Add(title); - //} cmb.Items.AddRange(winList.ToArray()); cmb.EndUpdate(); @@ -893,9 +1347,52 @@ public static void lnkWindowNameUpToDate_Click(object sender, EventArgs e) public static void MatchMethodComboBox_SelectionChangeCommitted(Dictionary controlsList, ComboBox matchMethodComboBox, string indexParameterName) { string item = matchMethodComboBox.SelectedItem?.ToString().ToLower() ?? ""; - GeneralPropertyControls.SetVisibleParameterControlGroup(controlsList, indexParameterName, (item == "index")); + FormUIControls.SetVisibleParameterControlGroup(controlsList, indexParameterName, (item == "index")); + } + + #endregion + + #region convert internal keywords + + /// + /// Replace Internal Keywords to SystemVariable Names + /// + /// + /// + /// + public static string ReplaceKeywordsToSystemVariable(string txt, Engine.AutomationEngineInstance engine) + { + return txt.Replace(INTERNAL_CURRENT_WINDOW_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentWindowName.VariableName, engine)) + .Replace(INTERNAL_ALL_WINDOWS_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_AllWindows.VariableName, engine)) + .Replace(INTERNAL_DESKTOP_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_Desktop.VariableName, engine)) + .Replace(INTERNAL_CURRENT_WINDOW_SIZE_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentSize.VariableName, engine)) + .Replace(INTERNAL_CURRENT_WINDOW_WIDTH_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentWidth.VariableName, engine)) + .Replace(INTERNAL_CURRENT_WINDOW_HEIGHT_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentHeight.VariableName, engine)) + .Replace(INTERNAL_CURRENT_WINDOW_POSITION_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentPosition.VariableName, engine)) + .Replace(INTERNAL_CURRENT_WINDOW_X_POSITION_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentXPosition.VariableName, engine)) + .Replace(INTERNAL_CURRENT_WINDOW_Y_POSITION_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentYPosition.VariableName, engine)) + .Replace(INTERNAL_CURRENT_WINDOW_HANDLE_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentWindowHandle.VariableName, engine)); } + /// + /// Replace Internal Keywords to SystemVariable Names + /// + /// + /// + /// + public static string ReplaceKeywordsToSystemVariable(string txt, ApplicationSettings settings) + { + return txt.Replace(INTERNAL_CURRENT_WINDOW_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentWindowName.VariableName, settings)) + .Replace(INTERNAL_ALL_WINDOWS_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_AllWindows.VariableName, settings)) + .Replace(INTERNAL_DESKTOP_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_Desktop.VariableName, settings)) + .Replace(INTERNAL_CURRENT_WINDOW_SIZE_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentSize.VariableName, settings)) + .Replace(INTERNAL_CURRENT_WINDOW_WIDTH_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentWidth.VariableName, settings)) + .Replace(INTERNAL_CURRENT_WINDOW_HEIGHT_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentHeight.VariableName, settings)) + .Replace(INTERNAL_CURRENT_WINDOW_POSITION_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentPosition.VariableName, settings)) + .Replace(INTERNAL_CURRENT_WINDOW_X_POSITION_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentXPosition.VariableName, settings)) + .Replace(INTERNAL_CURRENT_WINDOW_Y_POSITION_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentYPosition.VariableName, settings)) + .Replace(INTERNAL_CURRENT_WINDOW_HANDLE_KEYWORD, VariableNameControls.GetWrappedVariableName(SystemVariables.Window_CurrentWindowHandle.VariableName, settings)); + } #endregion } } diff --git a/taskt/Core/Automation/Commands/Word/WordAddDocumentCommand.cs b/taskt/Core/Automation/Commands/Word/WordAddDocumentCommand.cs index adccdb157..810743a89 100644 --- a/taskt/Core/Automation/Commands/Word/WordAddDocumentCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordAddDocumentCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command adds a new Word Document.")] [Attributes.ClassAttributes.CommandSettings("Add Document")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a new document to a Word Instance")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordAddDocumentCommand : ScriptCommand + public sealed class WordAddDocumentCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -26,11 +27,9 @@ public WordAddDocumentCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var wordInstance = v_InstanceName.GetWordInstance(engine); + var wordInstance = v_InstanceName.ExpandValueOrUserVariableAsWordInstance(engine); wordInstance.Documents.Add(); } diff --git a/taskt/Core/Automation/Commands/Word/WordAppendDataTableCommand.cs b/taskt/Core/Automation/Commands/Word/WordAppendDataTableCommand.cs index dcd4b01da..f5a3f99ee 100644 --- a/taskt/Core/Automation/Commands/Word/WordAppendDataTableCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordAppendDataTableCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command appends a datatable to a word document.")] [Attributes.ClassAttributes.CommandSettings("Append DataTable")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to append a datatable to a specific document.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordAppendDataTableCommand : ScriptCommand + public sealed class WordAppendDataTableCommand : ScriptCommand, ICanHandleDataTable { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -31,26 +32,25 @@ public WordAppendDataTableCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + (var _, var wordDocument) = v_InstanceName.ExpandValueOrUserVariableAsWordInstanceAndDocument(engine); - (var _, var wordDocument) = v_InstanceName.GetWordInstanceAndDocument(engine); - - var dataTable = v_DataTableName.GetDataTableVariable(engine); + //var myDT = v_DataTableName.ExpandUserVariableAsDataTable(engine); + var myDT = this.ExpandUserVariableAsDataTable(nameof(v_DataTableName), engine); //converting System DataTable to Word DataTable - int RowCount = dataTable.Rows.Count; - int ColumnCount = dataTable.Columns.Count; + int RowCount = myDT.Rows.Count; + int ColumnCount = myDT.Columns.Count; Object[,] DataArray = new object[RowCount + 1, ColumnCount + 1]; int r = 0; for (int c = 0; c <= ColumnCount - 1; c++) { - DataArray[r, c] = dataTable.Columns[c].ColumnName; + DataArray[r, c] = myDT.Columns[c].ColumnName; for (r = 0; r <= RowCount - 1; r++) { - DataArray[r, c] = dataTable.Rows[r][c]; + DataArray[r, c] = myDT.Rows[r][c]; } //end row loop } //end column loop @@ -92,7 +92,7 @@ public override void RunCommand(object sender) //Adding header row manually for (int c = 0; c <= ColumnCount - 1; c++) { - wordDocument.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = dataTable.Columns[c].ColumnName; + wordDocument.Application.Selection.Tables[1].Cell(1, c + 1).Range.Text = myDT.Columns[c].ColumnName; } //Formatting header row diff --git a/taskt/Core/Automation/Commands/Word/WordAppendImageCommand.cs b/taskt/Core/Automation/Commands/Word/WordAppendImageCommand.cs index b874bb26a..dbf4941ce 100644 --- a/taskt/Core/Automation/Commands/Word/WordAppendImageCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordAppendImageCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command appends an image to a word document.")] [Attributes.ClassAttributes.CommandSettings("Append Image")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to append an image to a specific document.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordAppendImageCommand : ScriptCommand + public sealed class WordAppendImageCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -39,14 +40,12 @@ public WordAppendImageCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - (var _, var wordDocument) = v_InstanceName.GetWordInstanceAndDocument(engine); + (var _, var wordDocument) = v_InstanceName.ExpandValueOrUserVariableAsWordInstanceAndDocument(engine); //Appends image after text/images - var vImagePath = v_ImagePath.ConvertToUserVariable(engine); + var vImagePath = v_ImagePath.ExpandValueOrUserVariable(engine); object collapseEnd = WdCollapseDirection.wdCollapseEnd; Range imageRange = wordDocument.Content; imageRange.Collapse(ref collapseEnd); diff --git a/taskt/Core/Automation/Commands/Word/WordAppendTextCommand.cs b/taskt/Core/Automation/Commands/Word/WordAppendTextCommand.cs index 73848b03f..11c0283b3 100644 --- a/taskt/Core/Automation/Commands/Word/WordAppendTextCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordAppendTextCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command appends text to a word document.")] [Attributes.ClassAttributes.CommandSettings("Append Text")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to append text to a specific document.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordAppendTextCommand : ScriptCommand + public sealed class WordAppendTextCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -49,7 +50,7 @@ public class WordAppendTextCommand : ScriptCommand [InputSpecification("Font Size", true)] //[SampleUsage("Select **14**")] [PropertyFirstValue("11")] - [PropertyValidationRule("Font Size", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.GreaterThanZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] + [PropertyValidationRule("Font Size", PropertyValidationRule.ValidationRuleFlags.Empty | PropertyValidationRule.ValidationRuleFlags.EqualsZero | PropertyValidationRule.ValidationRuleFlags.LessThanZero)] [PropertyIsOptional(true, "11")] [PropertyDisplayText(false, "")] public string v_FontSize { get; set; } @@ -106,20 +107,18 @@ public WordAppendTextCommand() //this.v_FontUnderline = "No"; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; + (var _, var wordDocument) = v_InstanceName.ExpandValueOrUserVariableAsWordInstanceAndDocument(engine); - (var _, var wordDocument) = v_InstanceName.GetWordInstanceAndDocument(engine); - - var vText = v_TextToSet.ConvertToUserVariable(engine); + var vText = v_TextToSet.ExpandValueOrUserVariable(engine); Paragraph paragraph = wordDocument.Content.Paragraphs.Add(); paragraph.Range.Text = vText; paragraph.Range.Font.Name = v_FontName; paragraph.Range.Font.Size = float.Parse(v_FontSize); - if (this.GetUISelectionValue(nameof(v_FontBold), engine) == "yes") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_FontBold), engine) == "yes") { paragraph.Range.Font.Bold = 1; } @@ -127,7 +126,7 @@ public override void RunCommand(object sender) { paragraph.Range.Font.Bold = 0; } - if (this.GetUISelectionValue(nameof(v_FontItalic), engine) == "yes") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_FontItalic), engine) == "yes") { paragraph.Range.Font.Italic = 1; } @@ -135,7 +134,7 @@ public override void RunCommand(object sender) { paragraph.Range.Font.Italic = 0; } - if (this.GetUISelectionValue(nameof(v_FontUnderline), engine) == "yes") + if (this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_FontUnderline), engine) == "yes") { paragraph.Range.Font.Underline = WdUnderline.wdUnderlineSingle; } diff --git a/taskt/Core/Automation/Commands/Word/WordCheckWordInstanceExistsCommand.cs b/taskt/Core/Automation/Commands/Word/WordCheckWordInstanceExistsCommand.cs index c28566414..73dc80397 100644 --- a/taskt/Core/Automation/Commands/Word/WordCheckWordInstanceExistsCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordCheckWordInstanceExistsCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command returns existance of Word instance.")] [Attributes.ClassAttributes.CommandSettings("Check Word Instance Exists")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to check Word instance.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordCheckWordInstanceExistsCommand : ScriptCommand + public sealed class WordCheckWordInstanceExistsCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -33,13 +34,11 @@ public WordCheckWordInstanceExistsCommand() //this.v_InstanceName = ""; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - try { - var _ = v_InstanceName.GetWordInstance(engine); + var _ = v_InstanceName.ExpandValueOrUserVariableAsWordInstance(engine); true.StoreInUserVariable(engine, v_applyToVariableName); } catch diff --git a/taskt/Core/Automation/Commands/Word/WordCloseWordInstanceCommand.cs b/taskt/Core/Automation/Commands/Word/WordCloseWordInstanceCommand.cs index 8bdfddddf..93d5345ce 100644 --- a/taskt/Core/Automation/Commands/Word/WordCloseWordInstanceCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordCloseWordInstanceCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command allows you to close Word Instance.")] [Attributes.ClassAttributes.CommandSettings("Close Word Instance")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to close an open instance of Word.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordCloseWordInstanceCommand : ScriptCommand + public sealed class WordCloseWordInstanceCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -34,11 +35,9 @@ public WordCloseWordInstanceCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var vInstance = v_InstanceName.ConvertToUserVariable(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); var wordObject = engine.GetAppInstance(vInstance); var wordInstance = (Microsoft.Office.Interop.Word.Application)wordObject; @@ -47,7 +46,7 @@ public override void RunCommand(object sender) //check if document exists and save if (wordInstance.Documents.Count >= 1) { - var isSave = v_WordSaveOnExit.ConvertToUserVariableAsBool("Document should be saved", engine); + var isSave = v_WordSaveOnExit.ExpandValueOrUserVariableAsBool("Document should be saved", engine); wordInstance.ActiveDocument.Close(isSave); } diff --git a/taskt/Core/Automation/Commands/Word/WordCreateWordInstanceCommand.cs b/taskt/Core/Automation/Commands/Word/WordCreateWordInstanceCommand.cs index 2786c5fa6..9dc6524e1 100644 --- a/taskt/Core/Automation/Commands/Word/WordCreateWordInstanceCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordCreateWordInstanceCommand.cs @@ -1,4 +1,6 @@ using System; +using System.Diagnostics; +using System.Windows.Automation.Provider; using System.Xml.Serialization; using taskt.Core.Automation.Attributes.PropertyAttributes; @@ -6,14 +8,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command creates a Word Instance.")] [Attributes.ClassAttributes.CommandSettings("Create Word Instance")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to launch a new instance of Word.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordCreateWordInstanceCommand : ScriptCommand + public sealed class WordCreateWordInstanceCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -22,6 +25,10 @@ public class WordCreateWordInstanceCommand : ScriptCommand [PropertyTextBoxSetting(1, false)] public string v_InstanceName { get; set; } + [XmlAttribute] + [PropertyVirtualProperty(nameof(WindowControls), nameof(WindowControls.v_OutputWindowHandle))] + public string v_WindowHandle { get; set; } + public WordCreateWordInstanceCommand() { //this.CommandName = "WordCreateApplicationCommand"; @@ -30,17 +37,43 @@ public WordCreateWordInstanceCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var vInstance = v_InstanceName.ConvertToUserVariable(engine); + var vInstance = v_InstanceName.ExpandValueOrUserVariable(engine); var newWordSession = new Microsoft.Office.Interop.Word.Application { Visible = true }; engine.AddAppInstance(vInstance, newWordSession); + + if (!string.IsNullOrEmpty(v_WindowHandle)) + { + newWordSession.Activate(); + var currentCaption = newWordSession.Application.Caption; + + var rnd = new Random(); + + var newCaption = "rpa_word_" + rnd.Next() + "_" + rnd.Next(); + newWordSession.Application.Caption = newCaption; + + bool isFound = false; + foreach(var p in Process.GetProcessesByName("winword")) + { + if (p.MainWindowTitle == newCaption) + { + p.MainWindowHandle.StoreInUserVariable(engine, v_WindowHandle); + newWordSession.Application.Caption = currentCaption; + isFound = true; + break; + } + } + if (!isFound) + { + throw new Exception("Fail to Get Word Instance Window Handle"); + } + } + } } } \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/Word/WordExportToPDFCommand.cs b/taskt/Core/Automation/Commands/Word/WordExportToPDFCommand.cs index 87a5d4362..a05f6fbf5 100644 --- a/taskt/Core/Automation/Commands/Word/WordExportToPDFCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordExportToPDFCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command allows you to export a Word document to a PDF.")] [Attributes.ClassAttributes.CommandSettings("Export To PDF")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to save a document to a PDF.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordExportToPDFCommand : ScriptCommand + public sealed class WordExportToPDFCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -39,14 +40,11 @@ public WordExportToPDFCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get engine context - var engine = (Engine.AutomationEngineInstance)sender; + (var _, var wordDocument) = v_InstanceName.ExpandValueOrUserVariableAsWordInstanceAndDocument(engine); - (var _, var wordDocument) = v_InstanceName.GetWordInstanceAndDocument(engine); - - var fileName = v_FileName.ConvertToUserVariable(engine); + var fileName = v_FileName.ExpandValueOrUserVariable(engine); object fileFormat = WdSaveFormat.wdFormatPDF; wordDocument.SaveAs(fileName, ref fileFormat, Type.Missing, Type.Missing, diff --git a/taskt/Core/Automation/Commands/Word/WordOpenDocumentCommand.cs b/taskt/Core/Automation/Commands/Word/WordOpenDocumentCommand.cs index eba868b98..b9d8ccbef 100644 --- a/taskt/Core/Automation/Commands/Word/WordOpenDocumentCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordOpenDocumentCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command opens an Word Document.")] [Attributes.ClassAttributes.CommandSettings("Open Document")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to open an existing Word Document.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordOpenDocumentCommand : ScriptCommand + public sealed class WordOpenDocumentCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -36,11 +37,9 @@ public WordOpenDocumentCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - var engine = (Engine.AutomationEngineInstance)sender; - - var wordInstance = v_InstanceName.GetWordInstance(engine); + var wordInstance = v_InstanceName.ExpandValueOrUserVariableAsWordInstance(engine); //string vFilePath = FilePathControls.FormatFilePath_NoFileCounter(v_FilePath, engine, new List() { "docx", "docm", "doc", "odt", "rtf" }, true); var vFilePath = FilePathControls.WaitForFile(this, nameof(v_FilePath), nameof(v_WaitForFile), engine); diff --git a/taskt/Core/Automation/Commands/Word/WordReadDocumentCommand.cs b/taskt/Core/Automation/Commands/Word/WordReadDocumentCommand.cs index c748c5c68..1441a0508 100644 --- a/taskt/Core/Automation/Commands/Word/WordReadDocumentCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordReadDocumentCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command allows you to save a Word document.")] [Attributes.ClassAttributes.CommandSettings("Read Document")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to save changes to a document.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordReadDocumentCommand : ScriptCommand + public sealed class WordReadDocumentCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -30,12 +31,9 @@ public WordReadDocumentCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get engine context - var engine = (Engine.AutomationEngineInstance)sender; - - (var _, var wordDocument) = v_InstanceName.GetWordInstanceAndDocument(engine); + (var _, var wordDocument) = v_InstanceName.ExpandValueOrUserVariableAsWordInstanceAndDocument(engine); //store text in variable string textFromDocument = wordDocument.Content.Text; diff --git a/taskt/Core/Automation/Commands/Word/WordReplaceTextCommand.cs b/taskt/Core/Automation/Commands/Word/WordReplaceTextCommand.cs index 52584a7d7..0d46f9b42 100644 --- a/taskt/Core/Automation/Commands/Word/WordReplaceTextCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordReplaceTextCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command allows you to replace text in a Word document.")] [Attributes.ClassAttributes.CommandSettings("Replace Text")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to replace text in a document.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordReplaceTextCommand : ScriptCommand + public sealed class WordReplaceTextCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -47,15 +48,12 @@ public WordReplaceTextCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get engine context - var engine = (Engine.AutomationEngineInstance)sender; + (var _, var wordDocument) = v_InstanceName.ExpandValueOrUserVariableAsWordInstanceAndDocument(engine); - (var _, var wordDocument) = v_InstanceName.GetWordInstanceAndDocument(engine); - - var vFindText = v_FindText.ConvertToUserVariable(engine); - var vReplaceWithText = v_ReplaceWithText.ConvertToUserVariable(engine); + var vFindText = v_FindText.ExpandValueOrUserVariable(engine); + var vReplaceWithText = v_ReplaceWithText.ExpandValueOrUserVariable(engine); Range range = wordDocument.Content; diff --git a/taskt/Core/Automation/Commands/Word/WordSaveAsCommand.cs b/taskt/Core/Automation/Commands/Word/WordSaveAsCommand.cs index 650a67ea0..4a3800c5d 100644 --- a/taskt/Core/Automation/Commands/Word/WordSaveAsCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordSaveAsCommand.cs @@ -6,14 +6,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command allows you to save an Word document.")] [Attributes.ClassAttributes.CommandSettings("Save Document As")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to save a document to a file.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordSaveDocumentAsCommand : ScriptCommand + public sealed class WordSaveDocumentAsCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -32,11 +33,8 @@ public WordSaveDocumentAsCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get engine context - var engine = (Engine.AutomationEngineInstance)sender; - //string fileName; //if (FilePathControls.ContainsFileCounter(v_FileName, engine)) //{ @@ -46,9 +44,9 @@ public override void RunCommand(object sender) //{ // fileName = FilePathControls.FormatFilePath_NoFileCounter(v_FileName, engine, "docx"); //} - string fileName = this.ConvertToUserVariableAsFilePath(nameof(v_FileName), engine); + string fileName = this.ExpandValueOrUserVariableAsFilePath(nameof(v_FileName), engine); - var wordInstance = v_InstanceName.GetWordInstance(engine); + var wordInstance = v_InstanceName.ExpandValueOrUserVariableAsWordInstance(engine); //overwrite and save wordInstance.DisplayAlerts = WdAlertLevel.wdAlertsNone; diff --git a/taskt/Core/Automation/Commands/Word/WordSaveCommand.cs b/taskt/Core/Automation/Commands/Word/WordSaveCommand.cs index dcbf51551..2e9bf54fa 100644 --- a/taskt/Core/Automation/Commands/Word/WordSaveCommand.cs +++ b/taskt/Core/Automation/Commands/Word/WordSaveCommand.cs @@ -5,14 +5,15 @@ namespace taskt.Core.Automation.Commands { [Serializable] - [Attributes.ClassAttributes.Group("Word Commands")] + [Attributes.ClassAttributes.Group("Word")] [Attributes.ClassAttributes.Description("This command allows you to save a Word document.")] [Attributes.ClassAttributes.CommandSettings("Save Document")] [Attributes.ClassAttributes.UsesDescription("Use this command when you want to save changes to a document.")] [Attributes.ClassAttributes.ImplementationDescription("This command implements Word Interop to achieve automation.")] + [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] [Attributes.ClassAttributes.EnableAutomateRender(true)] [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] - public class WordSaveDocumentCommand : ScriptCommand + public sealed class WordSaveDocumentCommand : ScriptCommand { [XmlAttribute] [PropertyVirtualProperty(nameof(WordControls), nameof(WordControls.v_InstanceName))] @@ -26,12 +27,9 @@ public WordSaveDocumentCommand() //this.CustomRendering = true; } - public override void RunCommand(object sender) + public override void RunCommand(Engine.AutomationEngineInstance engine) { - //get engine context - var engine = (Engine.AutomationEngineInstance)sender; - - var wordInstance = v_InstanceName.GetWordInstance(engine); + var wordInstance = v_InstanceName.ExpandValueOrUserVariableAsWordInstance(engine); //save wordInstance.ActiveDocument.Save(); diff --git a/taskt/Core/Automation/Commands/WordControls.cs b/taskt/Core/Automation/Commands/WordControls.cs index 8ba84a94b..82d036490 100644 --- a/taskt/Core/Automation/Commands/WordControls.cs +++ b/taskt/Core/Automation/Commands/WordControls.cs @@ -24,6 +24,7 @@ internal static class WordControls [PropertyValidationRule("Instance", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Instance")] [PropertyFirstValue("%kwd_default_word_instance%")] + [PropertyParameterOrder(5000)] public static string v_InstanceName { get; } /// @@ -39,18 +40,19 @@ internal static class WordControls [PropertyTextBoxSetting(1, false)] [PropertyValidationRule("Path", PropertyValidationRule.ValidationRuleFlags.Empty)] [PropertyDisplayText(true, "Path")] + [PropertyParameterOrder(5000)] public static string v_FilePath { get; } /// - /// get word instace from value (specified argument) + /// expand value or user variable as Word Instance /// /// /// /// /// - public static Application GetWordInstance(this string instanceName, Engine.AutomationEngineInstance engine) + public static Application ExpandValueOrUserVariableAsWordInstance(this string instanceName, Engine.AutomationEngineInstance engine) { - var instance = instanceName.ConvertToUserVariable(engine); + var instance = instanceName.ExpandValueOrUserVariable(engine); var instanceObject = engine.GetAppInstance(instance); if (instanceObject is Application wd) { @@ -63,15 +65,15 @@ public static Application GetWordInstance(this string instanceName, Engine.Autom } /// - /// get word instance and ActiveDocument from value (specified argument) + /// expand value or user variable as Word Instance and Active Document /// /// /// /// /// - public static (Application, Document) GetWordInstanceAndDocument(this string instanceName, Engine.AutomationEngineInstance engine) + public static (Application, Document) ExpandValueOrUserVariableAsWordInstanceAndDocument(this string instanceName, Engine.AutomationEngineInstance engine) { - var ins = instanceName.GetWordInstance(engine); + var ins = instanceName.ExpandValueOrUserVariableAsWordInstance(engine); if (ins.Documents.Count > 0) { diff --git a/taskt/Core/Automation/Commands/_General/EM_CommandIDPropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/_General/EM_CommandIDPropertiesExtensionMethods.cs new file mode 100644 index 000000000..0dc4c0805 --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/EM_CommandIDPropertiesExtensionMethods.cs @@ -0,0 +1,17 @@ +using System; + +namespace taskt.Core.Automation.Commands +{ + public static class EM_CommandIDPropertiesExtensionMethods + { + /// + /// Generate CommandID + /// + /// + public static void GenerateID(this ICommandIDProperties command) + { + var id = Guid.NewGuid(); + command.CommandID = id.ToString(); + } + } +} diff --git a/taskt/Core/Automation/Commands/_General/EM_HaveDataTablePropertiesExtensionMethods.cs b/taskt/Core/Automation/Commands/_General/EM_HaveDataTablePropertiesExtensionMethods.cs new file mode 100644 index 000000000..9cb9fef9c --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/EM_HaveDataTablePropertiesExtensionMethods.cs @@ -0,0 +1,23 @@ +using System; +using System.Data; + +namespace taskt.Core.Automation.Commands._General +{ + public static class EM_HaveDataTablePropertiesExtensionMethods + { + // TODO: make it! + //public static DataTable GetDataTableFromParameterName(this IHaveDataTableElements command, string parameterName) + //{ + // var prop = command.GetProperty(parameterName); + // var value = prop?.GetValue(command) ?? null; + // if (value is DataTable tbl) + // { + // return tbl; + // } + // else + // { + // throw new Exception($"Parameter '{parameterName}' is not DataTable"); + // } + //} + } +} diff --git a/taskt/Core/Automation/Commands/_General/ICommandIDProperties.cs b/taskt/Core/Automation/Commands/_General/ICommandIDProperties.cs new file mode 100644 index 000000000..6d12e3ea6 --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/ICommandIDProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + public interface ICommandIDProperties + { + /// + /// Command ID (GUID) + /// + string CommandID { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/_General/IDelimitersOfStructuredCommands.cs b/taskt/Core/Automation/Commands/_General/IDelimitersOfStructuredCommands.cs new file mode 100644 index 000000000..490533bd0 --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/IDelimitersOfStructuredCommands.cs @@ -0,0 +1,9 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// this commands are Delimiters of Stuctured commands. Else, Catch, Finally, etc... + /// + public interface IDelimitersOfStructuredCommands + { + } +} diff --git a/taskt/Core/Automation/Commands/_General/IEndOfStacturedCommand.cs b/taskt/Core/Automation/Commands/_General/IEndOfStacturedCommand.cs new file mode 100644 index 000000000..dc7eae848 --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/IEndOfStacturedCommand.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// this commands is End of Structured command. End Loop, End If, etc + /// + public interface IEndOfStacturedCommand + { + // nothing + } +} diff --git a/taskt/Core/Automation/Commands/_General/IHaveAdditionalCommands.cs b/taskt/Core/Automation/Commands/_General/IHaveAdditionalCommands.cs new file mode 100644 index 000000000..f0a5b1b59 --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/IHaveAdditionalCommands.cs @@ -0,0 +1,9 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// this command has AdditionalCommands (but AcriptCommand Class) + /// + public interface IHaveAdditionalCommands + { + } +} diff --git a/taskt/Core/Automation/Commands/_General/IHaveDataTableElements.cs b/taskt/Core/Automation/Commands/_General/IHaveDataTableElements.cs new file mode 100644 index 000000000..9b1eb2cc7 --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/IHaveDataTableElements.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// has DataTable Elements (properties) command + /// + public interface IHaveDataTableElements + { + /// + /// Process before Validate ScriptCommand parameters + /// + void BeforeValidate(); + } +} diff --git a/taskt/Core/Automation/Commands/_General/ILExpandableProperties.cs b/taskt/Core/Automation/Commands/_General/ILExpandableProperties.cs new file mode 100644 index 000000000..d2352692d --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/ILExpandableProperties.cs @@ -0,0 +1,10 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// expandable properties (base of interfaces) + /// for future process changes + /// + public interface ILExpandableProperties + { + } +} diff --git a/taskt/Core/Automation/Commands/_General/ILFilterValueProperties.cs b/taskt/Core/Automation/Commands/_General/ILFilterValueProperties.cs new file mode 100644 index 000000000..4ed549acc --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/ILFilterValueProperties.cs @@ -0,0 +1,25 @@ +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + /// + /// Filter Value Properties + /// + public interface ILFilterValueProperties : ILExpandableProperties + { + /// + /// Value Type (Text or Number) + /// + string v_ValueType { get; set; } + + /// + /// Filter Action + /// + string v_FilterAction { get; set; } + + /// + /// Filter Action Parameters + /// + DataTable v_FilterActionParameterTable { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/_General/ILPositionProperties.cs b/taskt/Core/Automation/Commands/_General/ILPositionProperties.cs new file mode 100644 index 000000000..5ee3ef342 --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/ILPositionProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// general position properties + /// + public interface ILPositionProperties : ILExpandableProperties + { + /// + /// x position + /// + string v_XPosition { get; set; } + + /// + /// y position + /// + string v_YPosition { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/_General/ILReplaceValueProperties.cs b/taskt/Core/Automation/Commands/_General/ILReplaceValueProperties.cs new file mode 100644 index 000000000..d8dd58476 --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/ILReplaceValueProperties.cs @@ -0,0 +1,30 @@ +using System.Data; + +namespace taskt.Core.Automation.Commands +{ + /// + /// Replace value properties + /// + public interface ILReplaceValueProperties : ILExpandableProperties + { + /// + /// Value Type (Text or Number) + /// + string v_ValueType { get; set; } + + /// + /// Replace Action + /// + string v_ReplaceAction { get; set; } + + /// + /// Replace Action parameters + /// + DataTable v_ReplaceActionParameterTable { get; set; } + + /// + /// New Value to Replace + /// + string v_NewValue { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/_General/ILResultProperties.cs b/taskt/Core/Automation/Commands/_General/ILResultProperties.cs new file mode 100644 index 000000000..e5abfe50a --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/ILResultProperties.cs @@ -0,0 +1,13 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Result properties + /// + public interface ILResultProperties + { + /// + /// Variable Name to Store Result + /// + string v_Result { get; set; } + } +} diff --git a/taskt/Core/Automation/Commands/_General/ILSizeProperties.cs b/taskt/Core/Automation/Commands/_General/ILSizeProperties.cs new file mode 100644 index 000000000..5444ee11f --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/ILSizeProperties.cs @@ -0,0 +1,18 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// general size properties + /// + public interface ILSizeProperties : ILExpandableProperties + { + /// + /// width + /// + string v_Width { get; set; } + + /// + /// height + /// + string v_Height { get; set;} + } +} diff --git a/taskt/Core/Automation/Commands/_General/ILUIParameterProperties.cs b/taskt/Core/Automation/Commands/_General/ILUIParameterProperties.cs new file mode 100644 index 000000000..8241c33cb --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/ILUIParameterProperties.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using System.Windows.Forms; + +namespace taskt.Core.Automation.Commands +{ + /// + /// for search & use Control for ScriptCommand parameters + /// + public interface ILUIParameterProperties + { + Dictionary ControlsList { get; } + } +} diff --git a/taskt/Core/Automation/Commands/_General/RECT.cs b/taskt/Core/Automation/Commands/_General/RECT.cs new file mode 100644 index 000000000..7a67c96e7 --- /dev/null +++ b/taskt/Core/Automation/Commands/_General/RECT.cs @@ -0,0 +1,36 @@ +namespace taskt.Core.Automation.Commands +{ + /// + /// Rect Struct + /// + public struct RECT + { + public int left; + public int top; + public int right; + public int bottom; + + public int GetWidth() + { + return (right - left); + } + + public int GetHeight() + { + return (bottom - top); + } + + public (int, int) GetWidthAndHeight() + { + return (GetWidth(), GetHeight()); + } + + public (int, int) GetCenterPosition() + { + return ( + left + (GetWidth() / 2), + top + (GetHeight() / 2) + ); + } + } +} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/_RemovedCommands/AddDataRowCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/AddDataRowCommand.cs new file mode 100644 index 000000000..134643092 --- /dev/null +++ b/taskt/Core/Automation/Commands/_RemovedCommands/AddDataRowCommand.cs @@ -0,0 +1,157 @@ +//using System; +//using System.Linq; +//using System.Xml.Serialization; +//using System.Data; +//using System.Windows.Forms; +//using System.Collections.Generic; +//using taskt.UI.Forms; +//using taskt.UI.CustomControls; +//using taskt.Core.Automation.Attributes.PropertyAttributes; + +//namespace taskt.Core.Automation.Commands +//{ +// [Serializable] +// [Attributes.ClassAttributes.Group("DataTable Commands")] +// [Attributes.ClassAttributes.SubGruop("Other")] +// [Attributes.ClassAttributes.Description("This command allows you to add a datarow to a DataTable")] +// [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a datarow to a DataTable.")] +// [Attributes.ClassAttributes.ImplementationDescription("")] +// [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] +// public class AddDataRowCommand : ScriptCommand +// { +// [XmlAttribute] +// [PropertyDescription("Please indicate the DataTable Variable Name")] +// [InputSpecification("Enter a existing DataTable to add rows to.")] +// [SampleUsage("**myDataTable** or **{{{vMyDataTable}}}**")] +// [Remarks("")] +// [PropertyShowSampleUsageInDescription(true)] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] +// [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] +// public string v_DataTableName { get; set; } + +// [XmlElement] +// [PropertyDescription("Define Data")] +// [InputSpecification("Enter the Column Names required for each column of data")] +// [SampleUsage("")] +// [Remarks("")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.DataGridView)] +// [PropertyDataGridViewSetting(true, true, true)] +// [PropertyDataGridViewColumnSettings("Column Name", "Column Name", false)] +// [PropertyDataGridViewColumnSettings("Data", "Data", false)] +// [PropertyDataGridViewCellEditEvent("AddDataGridViewHelper_CellClick", PropertyDataGridViewCellEditEvent.DataGridViewCellEvent.CellClick)] +// [PropertyCustomUIHelper("Load Column Names From Existing Table", nameof(LoadSchemaControl_Click), "load_column")] +// public DataTable v_AddDataDataTable { get; set; } + +// [XmlIgnore] +// [NonSerialized] +// private List DataTableCreationCommands; + +// [XmlIgnore] +// [NonSerialized] +// private DataGridView AddDataGridViewHelper; + +// public AddDataRowCommand() +// { +// this.CommandName = "AddDataRowCommand"; +// this.SelectionName = "Add DataRow"; +// this.CommandEnabled = true; +// this.CustomRendering = true; +// } + +// public override void RunCommand(Engine.AutomationEngineInstance engine) +// { +// //DataTable dataTable = (DataTable)v_DataTableName.GetRawVariable(engine).VariableValue; +// DataTable dataTable = v_DataTableName.ExpandUserVariableAsDataTable(engine); + +// var newRow = dataTable.NewRow(); + +// foreach (DataRow rw in v_AddDataDataTable.Rows) +// { +// var columnName = rw.Field("Column Name").ExpandValueOrUserVariable(engine); +// var data = rw.Field("Data").ExpandValueOrUserVariable(engine); +// newRow.SetField(columnName, data); +// } + +// dataTable.Rows.Add(newRow); +// } + +// public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) +// { +// base.Render(editor); + + +// var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); +// RenderedControls.AddRange(ctrls); + +// //AddDataGridViewHelper = (DataGridView)ctrls.GetControlsByName("v_AddDataDataTable")[0]; + +// DataTableCreationCommands = editor.configuredCommands.Where(f => f is CreateDataTableCommand).Select(f => (CreateDataTableCommand)f).ToList(); + +// return RenderedControls; +// } + +// private void LoadSchemaControl_Click(object sender, EventArgs e) +// { +// var items = new List(); +// foreach (var item in DataTableCreationCommands) +// { +// items.Add(item.v_DataTableName); +// } +// var selectionForm = new UI.Forms.ScriptBuilder.CommandEditor.Supplemental.frmItemSelector(items, "Load Schema", "Select a table from the list"); + +// var result = selectionForm.ShowDialog(); + +// if (result == DialogResult.OK) +// { +// //var tableName = selectionForm.lstVariables.SelectedItem.ToString(); +// var tableName = selectionForm.selectedItem.ToString(); +// var schema = DataTableCreationCommands.Where(f => f.v_DataTableName == tableName).FirstOrDefault(); + +// v_AddDataDataTable.Rows.Clear(); + +// foreach (DataRow rw in schema.v_ColumnNameDataTable.Rows) +// { +// v_AddDataDataTable.Rows.Add(rw.Field("Column Name"), ""); +// } +// } +// } + +// public override string GetDisplayValue() +// { +// return base.GetDisplayValue() + $" [{v_AddDataDataTable.Rows.Count} Fields, apply to '{v_DataTableName}']"; +// } + +// private void AddDataGridViewHelper_CellClick(object sender, DataGridViewCellEventArgs e) +// { +// if (e.ColumnIndex >= 0) +// { +// AddDataGridViewHelper.BeginEdit(false); +// } +// else +// { +// AddDataGridViewHelper.EndEdit(); +// } +// } + +// public override void BeforeValidate() +// { +// base.BeforeValidate(); +// //if (AddDataGridViewHelper.IsCurrentCellDirty || AddDataGridViewHelper.IsCurrentRowDirty) +// //{ +// // AddDataGridViewHelper.CommitEdit(DataGridViewDataErrorContexts.Commit); +// // var newRow = v_AddDataDataTable.NewRow(); +// // v_AddDataDataTable.Rows.Add(newRow); +// // for (var i = v_AddDataDataTable.Rows.Count - 1; i >= 0; i--) +// // { +// // if (v_AddDataDataTable.Rows[i][0].ToString() == "" && v_AddDataDataTable.Rows[i][1].ToString() == "") +// // { +// // v_AddDataDataTable.Rows[i].Delete(); +// // } +// // } +// //} +// DataTableControls.BeforeValidate((DataGridView)ControlsList[nameof(v_AddDataDataTable)], v_AddDataDataTable); +// } +// } +//} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/AddDataTableColumnAndFillValuesByListCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/AddDataTableColumnAndFillValuesByListCommand.cs similarity index 100% rename from taskt/Core/Automation/Commands/AddDataTableColumnAndFillValuesByListCommand.cs rename to taskt/Core/Automation/Commands/_RemovedCommands/AddDataTableColumnAndFillValuesByListCommand.cs diff --git a/taskt/Core/Automation/Commands/AddDataTableColumnsAndFillValuesByDataTableCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/AddDataTableColumnsAndFillValuesByDataTableCommand.cs similarity index 100% rename from taskt/Core/Automation/Commands/AddDataTableColumnsAndFillValuesByDataTableCommand.cs rename to taskt/Core/Automation/Commands/_RemovedCommands/AddDataTableColumnsAndFillValuesByDataTableCommand.cs diff --git a/taskt/Core/Automation/Commands/BeginExcelDatasetLoopCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/BeginExcelDatasetLoopCommand.cs similarity index 100% rename from taskt/Core/Automation/Commands/BeginExcelDatasetLoopCommand.cs rename to taskt/Core/Automation/Commands/_RemovedCommands/BeginExcelDatasetLoopCommand.cs diff --git a/taskt/Core/Automation/Commands/DatabaseRunQueryCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/DatabaseRunQueryCommand.cs similarity index 100% rename from taskt/Core/Automation/Commands/DatabaseRunQueryCommand.cs rename to taskt/Core/Automation/Commands/_RemovedCommands/DatabaseRunQueryCommand.cs diff --git a/taskt/Core/Automation/Commands/_RemovedCommands/ExcelWriteRowCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/ExcelWriteRowCommand.cs new file mode 100644 index 000000000..03aa9f093 --- /dev/null +++ b/taskt/Core/Automation/Commands/_RemovedCommands/ExcelWriteRowCommand.cs @@ -0,0 +1,158 @@ +//using System; +//using System.Collections.Generic; +//using System.Windows.Forms; +//using System.Xml.Serialization; +//using taskt.UI.CustomControls; +//using System.Data; +//using System.Linq; +//using System.Text.RegularExpressions; +//using taskt.Core.Automation.Attributes.PropertyAttributes; + +//namespace taskt.Core.Automation.Commands +//{ +// [Serializable] +// [Attributes.ClassAttributes.Group("Excel Commands")] +// [Attributes.ClassAttributes.SubGruop("Row")] +// [Attributes.ClassAttributes.CommandSettings("Write Row")] +// [Attributes.ClassAttributes.Description("This command writes a DataRow to an excel sheet starting from the given cell address.")] +// [Attributes.ClassAttributes.UsesDescription("Use this command when you want to set a value to a specific cell.")] +// [Attributes.ClassAttributes.ImplementationDescription("This command implements Excel Interop to achieve automation.")] +// [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] +// public class ExcelWriteRowCommand : AExcelInstanceCommands +// { +// //[XmlAttribute] +// //[PropertyDescription("Please Enter the instance name")] +// //[InputSpecification("Enter the unique instance name that was specified in the **Create Excel** command")] +// //[SampleUsage("**myInstance** or **excelInstance**")] +// //[Remarks("Failure to enter the correct instance name or failure to first call **Create Excel** command will cause an error")] +// //[PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// //[PropertyInstanceType(PropertyInstanceType.InstanceType.Excel)] +// //[PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] +// //public string v_InstanceName { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please Enter the Row to Set")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Enter the text value that will be set (This could be a DataRow).")] +// [SampleUsage("Hello,World or {vText}")] +// [Remarks("")] +// [PropertyParameterOrder(6000)] +// public string v_DataRowToSet { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please Enter the Cell Location to start from (ex. A1 or B2)")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Enter the actual location of the cell.")] +// [SampleUsage("A1, B10, {vAddress}")] +// [Remarks("")] +// [PropertyParameterOrder(6001)] +// public string v_ExcelCellAddress { get; set; } + +// public ExcelWriteRowCommand() +// { +// //this.CommandName = "ExcelWriteRowCommand"; +// //this.SelectionName = "Write Row"; +// //this.CommandEnabled = true; +// //this.CustomRendering = true; + +// //this.v_InstanceName = ""; +// } + +// public override void RunCommand(Engine.AutomationEngineInstance engine) +// { +// //(var excelInstance, var excelSheet) = v_InstanceName.ExpandValueOrUserVariableAsExcelInstanceAndWorksheet(engine); +// (_, var excelSheet) = this.ExpandValueOrVariableAsExcelInstanceAndCurrentWorksheet(engine); + +// var dataRowVariable = LookupVariable(engine); +// var variableList = engine.VariableList; +// DataRow row; + +// //check in case of looping through datatable using BeginListLoopCommand +// if (dataRowVariable.VariableValue is DataTable && engine.VariableList.Exists(x => x.VariableName == "Loop.CurrentIndex")) +// { +// var loopIndexVariable = engine.VariableList.Where(x => x.VariableName == "Loop.CurrentIndex").FirstOrDefault(); +// int loopIndex = int.Parse(loopIndexVariable.VariableValue.ToString()); +// row = ((DataTable)dataRowVariable.VariableValue).Rows[loopIndex - 1]; +// } +// else +// { +// row = (DataRow)dataRowVariable.VariableValue; +// } + +// var targetAddress = v_ExcelCellAddress.ExpandValueOrUserVariable(engine); +// if (string.IsNullOrEmpty(targetAddress)) +// { +// throw new ArgumentNullException("columnName"); +// } + +// // parse range +// var numberOfRow = Regex.Match(targetAddress, @"\d+").Value; +// targetAddress = Regex.Replace(targetAddress, @"[\d-]", string.Empty); +// targetAddress = targetAddress.ToUpperInvariant(); + +// int sum = 0; +// for (int i = 0; i < targetAddress.Length; i++) +// { +// sum *= 26; +// sum += (targetAddress[i] - 'A' + 1); +// } + +// //Write row +// string cellValue; +// for (int j = 0; j < row.ItemArray.Length; j++) +// { +// if (row.ItemArray[j] == null) +// { +// cellValue = string.Empty; +// } +// else +// { +// cellValue = row.ItemArray[j].ToString(); +// } + +// excelSheet.Cells[Int32.Parse(numberOfRow), j + sum] = cellValue; +// } +// } + +// private Script.ScriptVariable LookupVariable(Engine.AutomationEngineInstance sendingInstance) +// { +// //search for the variable +// var requiredVariable = sendingInstance.VariableList.Where(var => var.VariableName == v_DataRowToSet).FirstOrDefault(); + +// //if variable was not found but it starts with variable naming pattern +// if ((requiredVariable == null) && (v_DataRowToSet.StartsWith(sendingInstance.engineSettings.VariableStartMarker)) && (v_DataRowToSet.EndsWith(sendingInstance.engineSettings.VariableEndMarker))) +// { +// //reformat and attempt +// var reformattedVariable = v_DataRowToSet.Replace(sendingInstance.engineSettings.VariableStartMarker, "").Replace(sendingInstance.engineSettings.VariableEndMarker, ""); +// requiredVariable = sendingInstance.VariableList.Where(var => var.VariableName == reformattedVariable).FirstOrDefault(); +// } + +// return requiredVariable; +// } + +// public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) +// { +// base.Render(editor); + +// //create standard group controls +// var instanceCtrls = CommandControls.CreateDefaultDropdownGroupFor("v_InstanceName", this, editor); +// CommandControls.AddInstanceNames((ComboBox)instanceCtrls.Where(t => (t.Name == "v_InstanceName")).FirstOrDefault(), editor, PropertyInstanceType.InstanceType.Excel); +// RenderedControls.AddRange(instanceCtrls); +// //RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_InstanceName", this, editor)); +// RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_DataRowToSet", this, editor)); +// RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_ExcelCellAddress", this, editor)); + +// if (editor.creationMode == UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor.CreationMode.Add) +// { +// this.v_InstanceName = editor.appSettings.ClientSettings.DefaultExcelInstanceName; +// } + +// return RenderedControls; +// } + +// public override string GetDisplayValue() +// { +// return base.GetDisplayValue() + " [Writing Cells starting from '" + v_ExcelCellAddress + "', Instance Name: '" + v_InstanceName + "']"; +// } +// } +//} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/_RemovedCommands/GetDataRowCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/GetDataRowCommand.cs new file mode 100644 index 000000000..005380471 --- /dev/null +++ b/taskt/Core/Automation/Commands/_RemovedCommands/GetDataRowCommand.cs @@ -0,0 +1,93 @@ +//using System; +//using System.Xml.Serialization; +//using System.Windows.Forms; +//using System.Collections.Generic; +//using taskt.UI.CustomControls; +//using taskt.Core.Automation.Attributes.PropertyAttributes; + +//namespace taskt.Core.Automation.Commands +//{ +// [Serializable] +// [Attributes.ClassAttributes.Group("DataTable Commands")] +// [Attributes.ClassAttributes.SubGruop("Other")] +// [Attributes.ClassAttributes.Description("This command allows you to get a DataRow from a DataTable")] +// [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a datarow to a DataTable.")] +// [Attributes.ClassAttributes.ImplementationDescription("")] +// [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] +// public class GetDataRowCommand : ScriptCommand +// { +// [XmlAttribute] +// [PropertyDescription("Please indicate the DataTable Variable Name")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Enter a existing DataTable to fet rows from.")] +// [SampleUsage("**myDataTable** or **{{{vMyDataTable}}}**")] +// [Remarks("")] +// [PropertyShowSampleUsageInDescription(true)] +// [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] +// [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] +// [PropertyIsVariablesList(true)] +// public string v_DataTableName { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please enter the index of the DataRow")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Enter a valid DataRow index value")] +// [SampleUsage("**0** or **{{{vRowIndex}}}**")] +// [Remarks("")] +// [PropertyShowSampleUsageInDescription(true)] +// [PropertyTextBoxSetting(1, false)] +// public string v_DataRowIndex { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please Specify the Variable Name To Assign The DataRow")] +// [InputSpecification("Select or provide a variable from the variable list")] +// [SampleUsage("**vSomeVariable**")] +// [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] +// [PropertyIsVariablesList(true)] +// public string v_UserVariableName { get; set; } + +// public GetDataRowCommand() +// { +// this.CommandName = "GetDataRowCommand"; +// this.SelectionName = "Get DataRow"; +// this.CommandEnabled = true; +// this.CustomRendering = true; + +// } + +// public override void RunCommand(Engine.AutomationEngineInstance engine) +// { +// //DataTable dataTable = (DataTable)v_DataTableName.GetRawVariable(engine).VariableValue; + +// //int index = int.Parse(v_DataRowIndex.ExpandValueOrUserVariable(engine)); + +// //DataRow row = dataTable.Rows[index]; + +// //row.StoreInUserVariable(engine, v_UserVariableName); +// var convertToDic = new ConvertDataTableRowToDictionaryCommand() +// { +// v_DataTableName = this.v_DataTableName, +// v_DataRowIndex = this.v_DataRowIndex, +// v_OutputVariableName = this.v_UserVariableName, +// }; +// convertToDic.RunCommand(engine); +// } + +// public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) +// { +// base.Render(editor); + +// var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); +// RenderedControls.AddRange(ctrls); + +// return RenderedControls; +// } + +// public override string GetDisplayValue() +// { +// return base.GetDisplayValue() + $" [Get DataRow '{v_DataRowIndex}' from '{v_DataTableName}', Store In: '{v_UserVariableName}']"; +// } +// } +//} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/_RemovedCommands/GetDataRowCountCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/GetDataRowCountCommand.cs new file mode 100644 index 000000000..d71ea4cb5 --- /dev/null +++ b/taskt/Core/Automation/Commands/_RemovedCommands/GetDataRowCountCommand.cs @@ -0,0 +1,72 @@ +//using System; +//using System.Xml.Serialization; +//using System.Data; +//using System.Windows.Forms; +//using System.Collections.Generic; +//using taskt.UI.CustomControls; +//using taskt.Core.Automation.Attributes.PropertyAttributes; + +//namespace taskt.Core.Automation.Commands +//{ +// [Serializable] +// [Attributes.ClassAttributes.Group("DataTable Commands")] +// [Attributes.ClassAttributes.SubGruop("Other")] +// [Attributes.ClassAttributes.Description("This command allows you to get the datarow count of a DataTable")] +// [Attributes.ClassAttributes.UsesDescription("Use this command when you want to get the datarow count of a DataTable.")] +// [Attributes.ClassAttributes.ImplementationDescription("")] +// [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] +// public class GetDataRowCountCommand : ScriptCommand +// { +// [XmlAttribute] +// [PropertyDescription("Please indicate the DataTable Variable Name")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Enter a existing DataTable.")] +// [SampleUsage("**myDataTable** or **{{{vMyDataTable}}}**")] +// [Remarks("")] +// [PropertyShowSampleUsageInDescription(true)] +// [PropertyInstanceType(PropertyInstanceType.InstanceType.DataTable)] +// [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] +// public string v_DataTableName { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please Specify the Variable Name To Assign the Result")] +// [InputSpecification("Select or provide a variable from the variable list")] +// [SampleUsage("**vSomeVariable**")] +// [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] +// [PropertyIsVariablesList(true)] +// public string v_UserVariableName { get; set; } + +// public GetDataRowCountCommand() +// { +// this.CommandName = "GetDataRowCountCommand"; +// this.SelectionName = "Get DataRow Count"; +// this.CommandEnabled = true; +// this.CustomRendering = true; +// } + +// public override void RunCommand(Engine.AutomationEngineInstance engine) +// { +// DataTable dataTable = (DataTable)v_DataTableName.GetRawVariable(engine).VariableValue; + +// var count = dataTable.Rows.Count.ToString(); + +// count.StoreInUserVariable(engine, v_UserVariableName); +// } + +// public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) +// { +// base.Render(editor); +// var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); +// RenderedControls.AddRange(ctrls); + +// return RenderedControls; +// } + +// public override string GetDisplayValue() +// { +// return base.GetDisplayValue() + $" [From '{v_DataTableName}', Store In: '{v_UserVariableName}']"; +// } +// } +//} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/_RemovedCommands/GetDataRowValueCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/GetDataRowValueCommand.cs new file mode 100644 index 000000000..9642735af --- /dev/null +++ b/taskt/Core/Automation/Commands/_RemovedCommands/GetDataRowValueCommand.cs @@ -0,0 +1,123 @@ +//using System; +//using System.Xml.Serialization; +//using System.Windows.Forms; +//using System.Collections.Generic; +//using taskt.UI.CustomControls; +//using taskt.Core.Automation.Attributes.PropertyAttributes; + +//namespace taskt.Core.Automation.Commands +//{ +// [Serializable] +// [Attributes.ClassAttributes.Group("DataTable Commands")] +// [Attributes.ClassAttributes.SubGruop("Other")] +// [Attributes.ClassAttributes.Description("This command allows you to get a DataRow Value from a DataTable")] +// [Attributes.ClassAttributes.UsesDescription("Use this command when you want to add a datarow to a DataTable.")] +// [Attributes.ClassAttributes.ImplementationDescription("")] +// [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] +// public class GetDataRowValueCommand : ScriptCommand +// { +// [XmlAttribute] +// [PropertyDescription("Please indicate the DataRow Variable Name")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Enter a existing DataRow to get Values from.")] +// [SampleUsage("**myDataRow** or **{{{vMyDataRow}}}**")] +// [Remarks("")] +// [PropertyShowSampleUsageInDescription(true)] +// [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] +// public string v_DataRowName { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Select value by Index or Column Name (Default is Index)")] +// [PropertyUISelectionOption("Index")] +// [PropertyUISelectionOption("Column Name")] +// [InputSpecification("Select whether the DataRow value should be found by index or column name")] +// [SampleUsage("Select from **Index** or **Column Name**")] +// [Remarks("")] +// [PropertyIsOptional(true)] +// public string v_Option { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please enter the index of the DataRow Value")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Enter a valid DataRow index value")] +// [SampleUsage("**0** or **ColName** or **{{{vIndex}}}**")] +// [Remarks("")] +// [PropertyShowSampleUsageInDescription(true)] +// [PropertyTextBoxSetting(1, false)] +// public string v_DataValueIndex { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please Specify the Variable to Assign the Value")] +// [InputSpecification("Select or provide a variable from the variable list")] +// [SampleUsage("**vSomeVariable**")] +// [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] +// [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] +// [PropertyIsVariablesList(true)] +// public string v_UserVariableName { get; set; } + +// public GetDataRowValueCommand() +// { +// this.CommandName = "GetDataRowValueCommand"; +// this.SelectionName = "Get DataRow Value"; +// this.CommandEnabled = true; +// this.CustomRendering = true; + +// this.v_Option = "Index"; +// } + +// public override void RunCommand(Engine.AutomationEngineInstance engine) +// { +// //DataRow dataRow = (DataRow)v_DataRowName.GetRawVariable(engine).VariableValue; + +// //var valueIndex = v_DataValueIndex.ExpandValueOrUserVariable(engine); + +// //if (String.IsNullOrEmpty(v_Option)) +// //{ +// // v_Option = "Index"; +// //} + +// //string value = ""; +// //if (v_Option == "Index") +// //{ +// // int index = int.Parse(valueIndex); +// // value = dataRow[index].ToString(); +// //} +// //else if (v_Option == "Column Name") +// //{ +// // string index = valueIndex; +// // value = dataRow.Field(index); +// //} + +// //value.StoreInUserVariable(engine, v_UserVariableName); + +// var t = this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_Option), "Type", engine); +// if (t == "column name") +// { +// v_Option = "Key"; +// } +// var getDic = new GetDictionaryValueCommand() +// { +// v_InputData = this.v_DataRowName, +// v_Key = this.v_DataValueIndex, +// v_OutputVariable = this.v_UserVariableName, +// v_KeyType = this.v_Option, +// }; +// getDic.RunCommand(engine); +// } + +// public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) +// { +// base.Render(editor); + +// var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); +// RenderedControls.AddRange(ctrls); + +// return RenderedControls; +// } + +// public override string GetDisplayValue() +// { +// return base.GetDisplayValue() + $" [Get Value '{v_DataValueIndex}' from '{v_DataRowName}', Store In: '{v_UserVariableName}']"; +// } +// } +//} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/_RemovedCommands/ParseDatasetRowCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/ParseDatasetRowCommand.cs new file mode 100644 index 000000000..ec129c77a --- /dev/null +++ b/taskt/Core/Automation/Commands/_RemovedCommands/ParseDatasetRowCommand.cs @@ -0,0 +1,166 @@ +//using System; +//using System.Collections.Generic; +//using System.Linq; +//using System.Xml.Serialization; +//using System.Data; +//using System.Windows.Forms; +//using taskt.UI.CustomControls; +//using taskt.Core.Automation.Attributes.PropertyAttributes; + +//namespace taskt.Core.Automation.Commands +//{ +// [Serializable] +// [Attributes.ClassAttributes.Group("DataTable Commands")] +// [Attributes.ClassAttributes.SubGruop("Other")] +// [Attributes.ClassAttributes.Description("This command allows you to parse a dataset row column into a variable.")] +// [Attributes.ClassAttributes.UsesDescription("Use this command when you want to extract data from a dataset variable")] +// [Attributes.ClassAttributes.ImplementationDescription("")] +// [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] +// public class ParseDatasetRowCommand : ScriptCommand +// { +// [XmlAttribute] +// [PropertyDescription("Supply the name of the variable containing the datasource")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Select or provide a variable")] +// [SampleUsage("**vSomeVariable**")] +// [Remarks("")] +// public string v_DatasetName { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please Select Column Parse Type")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [PropertyUISelectionOption("By Column Name")] +// [PropertyUISelectionOption("By Column Index")] +// [InputSpecification("")] +// [SampleUsage("")] +// [Remarks("")] +// public string v_ColumnParseType { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Specify Column Name or Index")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("")] +// [SampleUsage("")] +// [Remarks("")] +// public string v_ColumnParameter { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please select the variable to receive the extracted column data")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Select or provide a variable from the variable list")] +// [SampleUsage("**vSomeVariable**")] +// [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] +// public string v_applyToVariableName { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Optional - Specify Alternate Row Number")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("If not executing within a loop, select the applicable index of the row required")] +// [SampleUsage("**0** or **vRowNumber**")] +// [Remarks("")] +// public string v_SpecifiedRow { get; set; } + +// public ParseDatasetRowCommand() +// { +// this.CommandName = "ParseRowCommand"; +// this.SelectionName = "Parse Dataset Row"; +// this.CommandEnabled = true; +// this.CustomRendering = true; +// this.v_SpecifiedRow = "N/A"; +// this.v_ColumnParseType = "By Column Name"; +// } + +// public override void RunCommand(Engine.AutomationEngineInstance engine) +// { +// ////try to find dataset based on variable name +// //var dataSourceVariable = engine.VariableList.FirstOrDefault(f => engine.engineSettings.VariableStartMarker + f.VariableName + engine.engineSettings.VariableEndMarker == v_DatasetName); + +// //if (dataSourceVariable == null) +// //{ +// // //see if match is found without encasing +// // dataSourceVariable = engine.VariableList.FirstOrDefault(f => f.VariableName == v_DatasetName); + +// // //no match was found +// // if (dataSourceVariable == null) +// // { +// // throw new Exception($"Data Source {v_DatasetName} Not Found! Did you input the correct name?"); +// // } +// //} + +// //var columnName = v_ColumnParameter.ExpandValueOrUserVariable(engine); +// //var parseStrat = v_ColumnParseType.ExpandValueOrUserVariable(engine); +// ////get datatable +// //var dataTable = (DataTable)dataSourceVariable.VariableValue; + +// //int requiredRowNumber; +// //if (!int.TryParse(this.v_SpecifiedRow.ExpandValueOrUserVariable(engine), out requiredRowNumber)) +// //{ +// // requiredRowNumber = dataSourceVariable.CurrentPosition; +// //} + +// ////get required row +// //var requiredRow = dataTable.Rows[requiredRowNumber]; + +// ////parse column name based on requirement +// //object requiredColumn; +// //if (parseStrat == "By Column Index") +// //{ +// // requiredColumn = requiredRow[int.Parse(columnName)]; +// //} +// //else +// //{ +// // requiredColumn = requiredRow[columnName]; +// //} + +// ////store value in variable +// //requiredColumn.ToString().StoreInUserVariable(engine, v_applyToVariableName); + +// string colType = ""; +// switch(this.ExpandValueOrUserVariableAsSelectionItem(nameof(v_ColumnParseType), engine)) +// { +// case "by column name": +// colType = "Column Name"; +// break; +// case "by column index": +// colType = "Index"; +// break; +// } + +// var getTableValue = new GetDataTableValueCommand() +// { +// v_DataTableName = this.v_DatasetName, +// v_ColumnType = colType, +// v_ColumnIndex = this.v_ColumnParseType, +// v_RowIndex = this.v_SpecifiedRow, +// v_UserVariableName = this.v_applyToVariableName, +// }; +// getTableValue.RunCommand(engine); +// } + +// public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) +// { +// base.Render(editor); + +// //create standard group controls +// RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_DatasetName", this, editor)); + +// RenderedControls.AddRange(CommandControls.CreateDefaultDropdownGroupFor("v_ColumnParseType", this, editor)); +// RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_ColumnParameter", this, editor)); + +// RenderedControls.Add(CommandControls.CreateDefaultLabelFor("v_applyToVariableName", this)); +// var VariableNameControl = CommandControls.CreateStandardComboboxFor("v_applyToVariableName", this).AddVariableNames(editor); +// RenderedControls.AddRange(CommandControls.CreateDefaultUIHelpersFor("v_applyToVariableName", this, VariableNameControl, editor)); +// RenderedControls.Add(VariableNameControl); + +// RenderedControls.AddRange(CommandControls.CreateDefaultInputGroupFor("v_SpecifiedRow", this, editor)); + +// return RenderedControls; + +// } + +// public override string GetDisplayValue() +// { +// return $"{base.GetDisplayValue()} - [Select '{v_ColumnParameter}' {v_ColumnParseType} from '{v_DatasetName}', Apply Result(s) To Variable: {v_applyToVariableName}]"; +// } +// } +//} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/_RemovedCommands/ParseJSONArrayCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/ParseJSONArrayCommand.cs new file mode 100644 index 000000000..c081b8df7 --- /dev/null +++ b/taskt/Core/Automation/Commands/_RemovedCommands/ParseJSONArrayCommand.cs @@ -0,0 +1,79 @@ +//using System; +//using System.Collections.Generic; +//using System.Xml.Serialization; +//using taskt.Core.Automation.Attributes.PropertyAttributes; + +//namespace taskt.Core.Automation.Commands +//{ +// [Serializable] +// [Attributes.ClassAttributes.Group("JSON")] +// [Attributes.ClassAttributes.SubGruop("Convert")] +// [Attributes.ClassAttributes.Description("This command allows you to parse a JSON Array into a list.")] +// [Attributes.ClassAttributes.UsesDescription("Use this command when you want to extract data from a JSON object")] +// [Attributes.ClassAttributes.ImplementationDescription("")] +// [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_function))] +// [Attributes.ClassAttributes.EnableAutomateRender(true)] +// [Attributes.ClassAttributes.EnableAutomateDisplayText(true)] +// public sealed class ParseJSONArrayCommand : ScriptCommand, ICanHandleList +// { +// [XmlAttribute] +// [PropertyDescription("Supply the JSON Array or Variable")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Select or provide a variable or json array value")] +// [SampleUsage("**[1,2,3]** or **[{obj1},{obj2}]** or **{{{vArrayVariable}}}**")] +// [Remarks("")] +// [PropertyShowSampleUsageInDescription(true)] +// [PropertyValidationRule("JSON", PropertyValidationRule.ValidationRuleFlags.Empty)] +// [PropertyDisplayText(true, "JSON")] +// public string v_Json { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please select the variable to receive the List")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Select or provide a variable from the variable list")] +// [SampleUsage("**vSomeVariable**")] +// [Remarks("If you have enabled the setting **Create Missing Variables at Runtime** then you are not required to pre-define your variables, however, it is highly recommended.")] +// [PropertyRecommendedUIControl(PropertyRecommendedUIControl.RecommendeUIControlType.ComboBox)] +// [PropertyIsVariablesList(true)] +// [PropertyValidationRule("List", PropertyValidationRule.ValidationRuleFlags.Empty)] +// [PropertyDisplayText(true, "List")] +// public string v_Result { get; set; } + +// public ParseJSONArrayCommand() +// { +// this.CommandName = "ParseJSONArrayCommand"; +// this.SelectionName = "Parse JSON Array"; +// this.CommandEnabled = true; +// this.CustomRendering = true; +// } + +// public override void RunCommand(Engine.AutomationEngineInstance engine) +// { +// //get variablized input +// var variableInput = v_Json.ExpandValueOrUserVariable(engine); + +// //create objects +// Newtonsoft.Json.Linq.JArray arr; +// List resultList = new List(); + +// //parse json +// try +// { +// arr = Newtonsoft.Json.Linq.JArray.Parse(variableInput); +// } +// catch (Exception ex) +// { +// throw new Exception("Error Occured Selecting Tokens: " + ex.ToString()); +// } + +// //add results to result list since list is supported +// foreach (var result in arr) +// { +// resultList.Add(result.ToString()); +// } + +// //resultList.StoreInUserVariable(engine, v_applyToVariableName); +// this.StoreListInUserVariable(resultList, nameof(v_Result), engine); +// } +// } +//} \ No newline at end of file diff --git a/taskt/Core/Automation/Commands/ThickAppClickItemCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/ThickAppClickItemCommand.cs similarity index 100% rename from taskt/Core/Automation/Commands/ThickAppClickItemCommand.cs rename to taskt/Core/Automation/Commands/_RemovedCommands/ThickAppClickItemCommand.cs diff --git a/taskt/Core/Automation/Commands/ThickAppGetTextCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/ThickAppGetTextCommand.cs similarity index 100% rename from taskt/Core/Automation/Commands/ThickAppGetTextCommand.cs rename to taskt/Core/Automation/Commands/_RemovedCommands/ThickAppGetTextCommand.cs diff --git a/taskt/Core/Automation/Commands/_RemovedCommands/WriteDataRowValueCommand.cs b/taskt/Core/Automation/Commands/_RemovedCommands/WriteDataRowValueCommand.cs new file mode 100644 index 000000000..48bec7a0f --- /dev/null +++ b/taskt/Core/Automation/Commands/_RemovedCommands/WriteDataRowValueCommand.cs @@ -0,0 +1,107 @@ +//using System; +//using System.Xml.Serialization; +//using System.Data; +//using System.Windows.Forms; +//using System.Collections.Generic; +//using taskt.UI.CustomControls; +//using taskt.Core.Automation.Attributes.PropertyAttributes; + +//namespace taskt.Core.Automation.Commands +//{ +// [Serializable] +// [Attributes.ClassAttributes.Group("DataTable Commands")] +// [Attributes.ClassAttributes.SubGruop("Other")] +// [Attributes.ClassAttributes.Description("This command allows you to write a Value to a DataRow")] +// [Attributes.ClassAttributes.UsesDescription("Use this command when you want to write a Value to a DataRow.")] +// [Attributes.ClassAttributes.ImplementationDescription("")] +// [Attributes.ClassAttributes.CommandIcon(nameof(Properties.Resources.command_spreadsheet))] +// public class WriteDataRowValueCommand : ScriptCommand +// { +// [XmlAttribute] +// [PropertyDescription("Please indicate the DataRow Variable Name")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Enter a existing DataTable to add rows to.")] +// [SampleUsage("**myDataRow** or **{{{vMyDataRow}}}**")] +// [Remarks("")] +// public string v_DataRowName { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Select value by Index or Column Name (Default is Index)")] +// [PropertyUISelectionOption("Index")] +// [PropertyUISelectionOption("Column Name")] +// [InputSpecification("Select whether the DataRow value should be found by index or column name")] +// [SampleUsage("Select from **Index** or **Column Name**")] +// [Remarks("")] +// [PropertyIsOptional(true)] +// public string v_Option { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please enter the index of the DataRow Value")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Enter a valid DataRow index value")] +// [SampleUsage("**0** or **{{{vIndex}}}**")] +// [Remarks("")] +// [PropertyShowSampleUsageInDescription(true)] +// [PropertyTextBoxSetting(1, false)] +// public string v_DataValueIndex { get; set; } + +// [XmlAttribute] +// [PropertyDescription("Please enter the Value")] +// [PropertyUIHelper(PropertyUIHelper.UIAdditionalHelperType.ShowVariableHelper)] +// [InputSpecification("Enter the value to write to the DataRow cell")] +// [SampleUsage("**vSomeVariable**")] +// [Remarks("")] +// public string v_DataRowValue { get; set; } + +// public WriteDataRowValueCommand() +// { +// this.CommandName = "WriteDataRowValueCommand"; +// this.SelectionName = "Write DataRow Value"; +// this.CommandEnabled = true; +// this.CustomRendering = true; +// v_Option = "Index"; + +// } + +// public override void RunCommand(Engine.AutomationEngineInstance engine) +// { +// var dataRowValue = v_DataRowValue.ExpandValueOrUserVariable(engine); + +// DataRow dataRow = (DataRow)v_DataRowName.GetRawVariable(engine).VariableValue; + +// var valueIndex = v_DataValueIndex.ExpandValueOrUserVariable(engine); + +// if (String.IsNullOrEmpty(v_Option)) +// { +// v_Option = "Index"; +// } + +// if (v_Option == "Index") +// { +// int index = int.Parse(valueIndex); +// dataRow[index] = dataRowValue; + +// } +// else if (v_Option == "Column Name") +// { +// string index = valueIndex; +// dataRow.SetField(index, dataRowValue); +// } +// } + +// public override List Render(UI.Forms.ScriptBuilder.CommandEditor.frmCommandEditor editor) +// { +// base.Render(editor); + +// var ctrls = CommandControls.MultiCreateInferenceDefaultControlGroupFor(this, editor); +// RenderedControls.AddRange(ctrls); + +// return RenderedControls; +// } + +// public override string GetDisplayValue() +// { +// return base.GetDisplayValue() + $" [Write Value '{v_DataRowValue}' to '{v_DataValueIndex}' in '{v_DataRowName}']"; +// } +// } +//} \ No newline at end of file diff --git a/taskt/Core/Automation/Engine/AutomationEngineInstance.cs b/taskt/Core/Automation/Engine/AutomationEngineInstance.cs index 083b469e9..fb2a5a699 100644 --- a/taskt/Core/Automation/Engine/AutomationEngineInstance.cs +++ b/taskt/Core/Automation/Engine/AutomationEngineInstance.cs @@ -4,34 +4,42 @@ using System.Collections.Generic; using System.Data; using System.Linq; -using System.Text; using System.Threading; -using System.Threading.Tasks; +using System.Reflection; using taskt.Core.Server; +using taskt.Core.Automation.Commands; +using taskt.Core.Script; + namespace taskt.Core.Automation.Engine { - public class AutomationEngineInstance + public class AutomationEngineInstance : IAppInstancesProperties, IScriptVariableListProperties { - - //engine variables - public List VariableList { get; set; } + /// + /// script variable list + /// + public List VariableList { get; set; } + + /// + /// app instances list + /// public Dictionary AppInstances { get; set; } - public Dictionary PreloadedTasks { get; set; } - public Core.Automation.Commands.ErrorHandlingCommand ErrorHandler; + + public Dictionary PreloadedTasks { get; set; } + public ErrorHandlingCommand ErrorHandler; public List ErrorsOccured { get; set; } public bool IsCancellationPending { get; set; } public bool CurrentLoopCancelled { get; set; } public bool CurrentLoopContinuing { get; set; } private bool IsScriptPaused { get; set; } [JsonIgnore] - public UI.Forms.frmScriptEngine tasktEngineUI { get; set; } + public UI.Forms.ScriptEngine.frmScriptEngine tasktEngineUI { get; set; } private System.Diagnostics.Stopwatch sw { get; set; } public EngineStatus CurrentStatus { get; set; } public EngineSettings engineSettings { get; set; } public ServerSettings serverSettings { get; set; } public List DataTables { get; set; } public string FileName { get; set; } - public Core.Server.Task taskModel { get; set; } + public Task taskModel { get; set; } public bool serverExecution { get; set; } public List ServiceResponses { get; set; } //events @@ -44,7 +52,7 @@ public class AutomationEngineInstance private Serilog.Core.Logger engineLogger = null; - private const int INNER_VARIABLES = 4; + //private const int INNER_VARIABLES = 4; public AutomationEngineInstance(bool enableLog = true) { @@ -66,7 +74,7 @@ public AutomationEngineInstance(bool enableLog = true) engineSettings = settings.EngineSettings; serverSettings = settings.ServerSettings; - VariableList = new List(); + VariableList = new List(); if (PreloadedTasks is null) { @@ -81,7 +89,7 @@ public AutomationEngineInstance(bool enableLog = true) AutoCalculateVariables = engineSettings.AutoCalcVariables; } - public void ExecuteScriptAsync(UI.Forms.frmScriptEngine scriptEngine, string filePath, List variables = null, Dictionary preloadedTasks = null) + public void ExecuteScriptAsync(UI.Forms.ScriptEngine.frmScriptEngine scriptEngine, string filePath, List variables = null, Dictionary preloadedTasks = null) { WriteLog("Client requesting to execute script using frmEngine"); @@ -103,6 +111,7 @@ public void ExecuteScriptAsync(UI.Forms.frmScriptEngine scriptEngine, string fil ExecuteScript(filePath, true); }).Start(); } + public void ExecuteScriptAsync(string filePath) { WriteLog("Client requesting to execute script independently"); @@ -113,6 +122,7 @@ public void ExecuteScriptAsync(string filePath) ExecuteScript(filePath, true); }).Start(); } + public void ExecuteScriptXML(string xmlData) { WriteLog("Client requesting to execute script independently"); @@ -126,11 +136,10 @@ public void ExecuteScriptXML(string xmlData) public void ExecuteScript(string data, bool dataIsFile) { - Core.Client.EngineBusy = true; + Client.EngineBusy = true; try { - CurrentStatus = EngineStatus.Running; //create stopwatch for metrics tracking @@ -146,15 +155,15 @@ public void ExecuteScript(string data, bool dataIsFile) { preLoadedTask = PreloadedTasks.Any(f => f.Key == data); } - + //get automation script - Core.Script.Script automationScript; + Script.Script automationScript; if (dataIsFile && (!preLoadedTask)) { ReportProgress("Deserializing File"); WriteLog("Script Path: " + data); FileName = data; - automationScript = Core.Script.Script.DeserializeFile(data, engineSettings); + automationScript = Script.Script.DeserializeFile(data, engineSettings); } else if (dataIsFile && preLoadedTask) { @@ -166,7 +175,7 @@ public void ExecuteScript(string data, bool dataIsFile) else { ReportProgress("Deserializing XML"); - automationScript = Core.Script.Script.DeserializeXML(data); + automationScript = Script.Script.DeserializeXML(data); } if (serverSettings.ServerConnectionEnabled && taskModel == null) @@ -196,35 +205,34 @@ public void ExecuteScript(string data, bool dataIsFile) } } - VariableList = automationScript.Variables; - // add hidden inner variable - VariableList.AddRange( - new Script.ScriptVariable[] - { - new Script.ScriptVariable() - { - VariableName = "__INNER_0", - VariableValue = "" - }, - new Script.ScriptVariable() - { - VariableName = "__INNER_1", - VariableValue = "" - }, - new Script.ScriptVariable() - { - VariableName = "__INNER_2", - VariableValue = "" - }, - new Script.ScriptVariable() - { - VariableName = "__INNER_3", - VariableValue = "" - } - } - ); + //// add hidden inner variable + //VariableList.AddRange( + // new ScriptVariable[] + // { + // new ScriptVariable() + // { + // VariableName = "__INNER_0", + // VariableValue = "" + // }, + // new ScriptVariable() + // { + // VariableName = "__INNER_1", + // VariableValue = "" + // }, + // new ScriptVariable() + // { + // VariableName = "__INNER_2", + // VariableValue = "" + // }, + // new ScriptVariable() + // { + // VariableName = "__INNER_3", + // VariableValue = "" + // } + // } + //); ReportProgress("Creating App Instance Tracking List"); //create app instances and merge in global instances @@ -264,10 +272,11 @@ public void ExecuteScript(string data, bool dataIsFile) ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult.Error, ex.ToString()); } } - public void ExecuteCommand(Core.Script.ScriptAction command) + + public void ExecuteCommand(ScriptAction command) { //get command - Core.Automation.Commands.ScriptCommand parentCommand = command.ScriptCommand; + ScriptCommand parentCommand = command.ScriptCommand; //update execution line numbers LineNumberChanged(parentCommand.LineNumber); @@ -294,7 +303,7 @@ public void ExecuteCommand(Core.Script.ScriptAction command) } //wait - System.Threading.Thread.Sleep(2000); + Thread.Sleep(2000); } CurrentStatus = EngineStatus.Running; @@ -305,60 +314,39 @@ public void ExecuteCommand(Core.Script.ScriptAction command) return; } - //bypass comments - if (parentCommand is Core.Automation.Commands.CommentCommand || parentCommand.IsCommented) + if (parentCommand is CommentCommand || parentCommand.IsCommented) { - ReportProgress("Skipping Line " + parentCommand.LineNumber + ": " + parentCommand.GetDisplayValue().ConvertToUserVariable(this)); + ReportProgress("Skipping Line " + parentCommand.LineNumber + ": " + parentCommand.GetDisplayValue().ExpandValueOrUserVariable(this)); return; } //report intended execution ReportProgress("Running Line " + parentCommand.LineNumber + ": " + parentCommand.GetDisplayValue()); - //handle any errors try { - //determine type of command - if ((parentCommand is Core.Automation.Commands.BeginNumberOfTimesLoopCommand) || (parentCommand is Core.Automation.Commands.BeginContinousLoopCommand) || (parentCommand is Core.Automation.Commands.BeginListLoopCommand) || (parentCommand is Core.Automation.Commands.BeginIfCommand) || (parentCommand is Core.Automation.Commands.BeginMultiIfCommand) || (parentCommand is Commands.TryCommand) || (parentCommand is Core.Automation.Commands.BeginLoopCommand) || (parentCommand is Core.Automation.Commands.BeginMultiLoopCommand)) - { - //run the command and pass bgw/command as this command will recursively call this method for sub commands - parentCommand.RunCommand(this, command); - } - else if (parentCommand is Core.Automation.Commands.SequenceCommand) - { - // todo: execute runcommand - parentCommand.RunCommand(this, command); - } - //else if (parentCommand is Core.Automation.Commands.StopCurrentScriptFileCommand) + ////determine type of command + //if ((parentCommand is BeginNumberOfTimesLoopCommand) || (parentCommand is BeginContinousLoopCommand) || (parentCommand is BeginLoopForComplexDataTypesCommand) || (parentCommand is BeginIfCommand) || (parentCommand is BeginMultiIfCommand) || (parentCommand is TryCommand) || (parentCommand is BeginLoopCommand) || (parentCommand is BeginMultiLoopCommand)) //{ - // IsCancellationPending = true; - // return; + // //run the command and pass bgw/command as this command will recursively call this method for sub commands + // parentCommand.RunCommand(this, command); //} - //else if (parentCommand is Core.Automation.Commands.ExitLoopCommand) + //else if (parentCommand is SequenceCommand) //{ - // CurrentLoopCancelled = true; - //} - //else if (parentCommand is Core.Automation.Commands.NextLoopCommand) - //{ - // CurrentLoopContinuing = true; - //} - //else if(parentCommand is Core.Automation.Commands.SetEngineDelayCommand) - //{ - // //get variable - // var setEngineCommand = (Core.Automation.Commands.SetEngineDelayCommand)parentCommand; - // var engineDelay = setEngineCommand.v_EngineSpeed.ConvertToUserVariable(this); - // var delay = int.Parse(engineDelay); - - // //update delay setting - // this.engineSettings.DelayBetweenCommands = delay; + // // todo: execute runcommand + // parentCommand.RunCommand(this, command); //} + if (parentCommand is IHaveAdditionalCommands) + { + parentCommand.RunCommand(this, command); + } else { //sleep required time - System.Threading.Thread.Sleep(engineSettings.DelayBetweenCommands); - + Thread.Sleep(engineSettings.DelayBetweenCommands); + //run the command parentCommand.RunCommand(this); } @@ -378,174 +366,150 @@ public void ExecuteCommand(Core.Script.ScriptAction command) switch (ErrorHandler.v_ErrorHandlingAction) { case "Continue Processing": - ReportProgress("Error Occured at Line " + parentCommand.LineNumber + ":" + ex.ToString()); ReportProgress("Continuing Per Error Handling"); + break; - break; - - default: - + default: throw ex; } } else { - throw ex; } } finally { - ClearInnerVariables(); + //ClearInnerVariables(); } } - public void AddAppInstance(string instanceName, object appObject) { - - if (AppInstances.ContainsKey(instanceName) && engineSettings.OverrideExistingAppInstances) - { - ReportProgress("Overriding Existing Instance: " + instanceName); - AppInstances.Remove(instanceName); - } - else if (AppInstances.ContainsKey(instanceName) && !engineSettings.OverrideExistingAppInstances) - { - throw new Exception("App Instance already exists and override has been disabled in engine settings! Enable override existing app instances or use unique instance names!"); - } - try - { - this.AppInstances.Add(instanceName, appObject); - } - catch (Exception ex) - { - throw ex; - } - } - public object GetAppInstance(string instanceName) - { - try - { - if (AppInstances.TryGetValue(instanceName, out object appObject)) - { - return appObject; - } - else - { - throw new Exception("App Instance '" + instanceName + "' not found!"); - } - } - catch (Exception ex) - { - - throw ex; - } - - } - public void RemoveAppInstance(string instanceName) + /// + /// add App Instance in Engine List (wrapper) + /// + /// + /// + /// + public void AddAppInstance(string instanceName, object appObject) { - try - { - if (AppInstances.ContainsKey(instanceName)) - { - AppInstances.Remove(instanceName); - - } - else - { - throw new Exception("App Instance '" + instanceName + "' not found!"); - } - } - catch (Exception ex) - { - - throw ex; - } - + this.AddAppInstance(instanceName, appObject, this); } - public void AddVariable(string variableName, object variableValue) + /// + /// get App Instance from Engine List (wrapper) + /// + /// + /// + public object GetAppInstance(string instanceName) { - - if (VariableList.Any(f => f.VariableName == variableName)) - { - //update existing variable - var existingVariable = VariableList.FirstOrDefault(f => f.VariableName == variableName); - existingVariable.VariableName = variableName; - existingVariable.VariableValue = variableValue; - } - else if (VariableList.Any(f => "{" + f.VariableName + "}" == variableName)) - { - //update existing edge-case variable due to user error - var existingVariable = VariableList.FirstOrDefault(f => "{" + f.VariableName + "}" == variableName); - existingVariable.VariableName = variableName; - existingVariable.VariableValue = variableValue; - } - else - { - //add new variable - var newVariable = new Script.ScriptVariable(); - newVariable.VariableName = variableName; - newVariable.VariableValue = variableValue; - VariableList.Add(newVariable); - } - + return ((IAppInstancesProperties)this).GetAppInstance(instanceName); } - public void StoreComplexObjectInVariable(string variableName, object value) + /// + /// remove App Instance from Engine List (wrapper) + /// + /// + public void RemoveAppInstance(string instanceName) { - Script.ScriptVariable storeVariable = VariableList.Where(x => x.VariableName == variableName).FirstOrDefault(); - - if (storeVariable == null) - { - //create and set variable - VariableList.Add(new Script.ScriptVariable - { - VariableName = variableName, - VariableValue = value - }); - } - else - { - //set variable - storeVariable.VariableValue = value; - } + ((IAppInstancesProperties)this).RemoveAppInstance(instanceName); } - private void ClearInnerVariables() + /// + /// Get New App Instance name (wrapper) + /// + /// + /// + public string GetNewAppInstanceName(string prefixName = "") { - for (int i = 0; i < INNER_VARIABLES; i++) - { - Script.ScriptVariable v = VariableList.Where(x => x.VariableName == "__INNER_" + i.ToString()).FirstOrDefault(); - if (v != null) - { - v.VariableValue = ""; - } - } + return ((IAppInstancesProperties)this).GetNewInstanceName(prefixName); } + //public void AddVariable(string variableName, object variableValue) + //{ + // if (VariableList.Any(f => f.VariableName == variableName)) + // { + // //update existing variable + // var existingVariable = VariableList.FirstOrDefault(f => f.VariableName == variableName); + // existingVariable.VariableName = variableName; + // existingVariable.VariableValue = variableValue; + // } + // else if (VariableList.Any(f => "{" + f.VariableName + "}" == variableName)) + // { + // //update existing edge-case variable due to user error + // var existingVariable = VariableList.FirstOrDefault(f => "{" + f.VariableName + "}" == variableName); + // existingVariable.VariableName = variableName; + // existingVariable.VariableValue = variableValue; + // } + // else + // { + // //add new variable + // var newVariable = new ScriptVariable(); + // newVariable.VariableName = variableName; + // newVariable.VariableValue = variableValue; + // VariableList.Add(newVariable); + // } + //} + + //public void StoreComplexObjectInVariable(string variableName, object value) + //{ + // ScriptVariable storeVariable = VariableList.Where(x => x.VariableName == variableName).FirstOrDefault(); + + // if (storeVariable == null) + // { + // //create and set variable + // VariableList.Add(new ScriptVariable + // { + // VariableName = variableName, + // VariableValue = value + // }); + // } + // else + // { + // //set variable + // storeVariable.VariableValue = value; + // } + //} + + //private void ClearInnerVariables() + //{ + // for (int i = 0; i < INNER_VARIABLES; i++) + // { + // ScriptVariable v = VariableList.Where(x => x.VariableName == "__INNER_" + i.ToString()).FirstOrDefault(); + // if (v != null) + // { + // v.VariableValue = ""; + // } + // } + //} + public void CancelScript() { IsCancellationPending = true; } + public void PauseScript() { IsScriptPaused = true; } + public void ResumeScript() { IsScriptPaused = false; } + public virtual void ReportProgress(string progress) { WriteLog(progress); ReportProgressEventArgs args = new ReportProgressEventArgs(); args.ProgressUpdate = progress; //send log to server - Core.Server.SocketClient.SendExecutionLog(progress); + SocketClient.SendExecutionLog(progress); //invoke event ReportProgressEvent?.Invoke(this, args); } + public virtual void ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult result, string error = null) { WriteLog("Result Code: " + result.ToString()); @@ -556,13 +520,12 @@ public virtual void ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult //handle if variable is missing if (resultVar == null) { - resultVar = new Script.ScriptVariable() { VariableName = "taskt.Result", VariableValue = "" }; + resultVar = new ScriptVariable() { VariableName = "taskt.Result", VariableValue = "" }; } //check value var resultValue = resultVar.VariableValue.ToString(); - if (error == null) { WriteLog("Error: None"); @@ -580,9 +543,7 @@ public virtual void ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult { TasktResult = resultValue; } - } - else { WriteLog("Error: " + error); @@ -593,12 +554,10 @@ public virtual void ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult } TasktResult = error; - } engineLogger.Dispose(); - CurrentStatus = EngineStatus.Finished; ScriptFinishedEventArgs args = new ScriptFinishedEventArgs(); args.LoggedOn = DateTime.Now; @@ -607,12 +566,11 @@ public virtual void ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult args.ExecutionTime = sw.Elapsed; args.FileName = FileName; - Core.Server.SocketClient.SendExecutionLog("Result Code: " + result.ToString()); - Core.Server.SocketClient.SendExecutionLog("Total Execution Time: " + sw.Elapsed); - + SocketClient.SendExecutionLog("Result Code: " + result.ToString()); + SocketClient.SendExecutionLog("Total Execution Time: " + sw.Elapsed); //convert to json - var serializedArguments = Newtonsoft.Json.JsonConvert.SerializeObject(args); + var serializedArguments = JsonConvert.SerializeObject(args); //write execution metrics if ((engineSettings.TrackExecutionMetrics) && (FileName != null)) @@ -622,20 +580,16 @@ public virtual void ScriptFinished(ScriptFinishedEventArgs.ScriptFinishedResult summaryLogger.Dispose(); } - - Core.Client.EngineBusy = false; - + Client.EngineBusy = false; if (serverSettings.ServerConnectionEnabled) { HttpServerClient.CheckIn(); } - ScriptFinishedEvent?.Invoke(this, args); - - } + public virtual void LineNumberChanged(int lineNumber) { LineNumberChangedEventArgs args = new LineNumberChangedEventArgs(); @@ -668,12 +622,13 @@ public void WriteLog(string logText) engineLogger.Information(logText); } } - } + public class ReportProgressEventArgs : EventArgs { public string ProgressUpdate { get; set; } } + public class ScriptFinishedEventArgs : EventArgs { public DateTime LoggedOn { get; set; } @@ -686,17 +641,17 @@ public enum ScriptFinishedResult Successful, Error, Cancelled } } + public class LineNumberChangedEventArgs : EventArgs { public int CurrentLineNumber { get; set; } } + public class ScriptError { public int LineNumber { get; set; } public string StackTrace { get; set; } public string ErrorMessage { get; set; } } - - } diff --git a/taskt/Core/Automation/Engine/EM_AppInstancesPropertiesExtensionMethods.cs b/taskt/Core/Automation/Engine/EM_AppInstancesPropertiesExtensionMethods.cs new file mode 100644 index 000000000..2f0158f87 --- /dev/null +++ b/taskt/Core/Automation/Engine/EM_AppInstancesPropertiesExtensionMethods.cs @@ -0,0 +1,130 @@ +using System; + +namespace taskt.Core.Automation.Engine +{ + /// + /// AppInstance properties extension methods + /// + public static class EM_AppInstancesPropertiesExtensionMethods + { + /// + /// Add App Instance + /// + /// + /// + /// + /// + /// + public static void AddAppInstance(this IAppInstancesProperties me, string instanceName, object appInstance, AutomationEngineInstance engine) + { + //if (me.AppInstances.ContainsKey(instanceName) && engine.engineSettings.OverrideExistingAppInstances) + //{ + // engine.ReportProgress($"Overriding Existing Instance. Instance Name: '{instanceName}'"); + // me.AppInstances.Remove(instanceName); + //} + //else if (me.AppInstances.ContainsKey(instanceName) && !engineSettings.OverrideExistingAppInstances) + //{ + // throw new Exception("App Instance already exists and override has been disabled in engine settings! Enable override existing app instances or use unique instance names!"); + //} + + if (me.AppInstances.ContainsKey(instanceName)) + { + if (engine.engineSettings.OverrideExistingAppInstances) + { + engine.ReportProgress($"Overriding Existing Instance. Instance Name: '{instanceName}'"); + me.AppInstances.Remove(instanceName); + } + else + { + throw new Exception($"App Instance '{instanceName}' is already exists and override has been disabled in engine settings! Enable override existing app instances or use unique instance names!"); + } + } + + try + { + me.AppInstances.Add(instanceName, appInstance); + } + catch (Exception ex) + { + throw ex; + } + } + + /// + /// get app instance + /// + /// + /// + /// + public static object GetAppInstance(this IAppInstancesProperties me, string instanceName) + { + try + { + if (me.AppInstances.TryGetValue(instanceName, out object appObject)) + { + return appObject; + } + else + { + throw new Exception($"App Instance '{instanceName}' not found!"); + } + } + catch (Exception ex) + { + throw ex; + } + } + + /// + /// remove app instance + /// + /// + /// + public static void RemoveAppInstance(this IAppInstancesProperties me, string instanceName) + { + try + { + if (me.AppInstances.ContainsKey(instanceName)) + { + me.AppInstances.Remove(instanceName); + } + else + { + throw new Exception($"App Instance '{instanceName}' not found!"); + } + } + catch (Exception ex) + { + throw ex; + } + } + + /// + /// create new instance name (not dup) + /// + /// + /// + /// + /// + public static string GetNewInstanceName(this IAppInstancesProperties me, string prefixName = "") + { + if (string.IsNullOrEmpty(prefixName)) + { + prefixName = "AppInstance"; + } + + for (int i = 0; i < int.MaxValue; i++) + { + for (int j = 0; j < int.MaxValue; j++) + { + var checkInstanceName = $"{prefixName}_{i}_{j}"; + if (!me.AppInstances.ContainsKey(checkInstanceName)) + { + return (checkInstanceName); + } + } + } + throw new Exception($"Sorry, New Instance Name does not created. Prefix: '{prefixName}'"); + } + } +} diff --git a/taskt/Core/Automation/Engine/EM_ScriptVariablePropertiesExtensionMethods.cs b/taskt/Core/Automation/Engine/EM_ScriptVariablePropertiesExtensionMethods.cs new file mode 100644 index 000000000..bfeb26a2d --- /dev/null +++ b/taskt/Core/Automation/Engine/EM_ScriptVariablePropertiesExtensionMethods.cs @@ -0,0 +1,76 @@ +using System; +using System.Linq; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Engine +{ + public static class EM_ScriptVariablePropertiesExtensionMethods + { + /// + /// Try Get Script Variable + /// + /// + /// + /// ScritpVariable or Null + public static ScriptVariable TryGetScriptVariable(this IScriptVariableListProperties engine, string variableName) + { + return engine.VariableList.Where(var => var.VariableName == variableName).FirstOrDefault(); + } + + /// + /// Check ScriptVariable Exists + /// + /// + /// no wrapped variable marker + /// + /// + public static bool CheckScriptVariableExists(this IScriptVariableListProperties engine, string variableName, out ScriptVariable v) + { + v = engine.TryGetScriptVariable(variableName); + return (v != null); + } + + /// + /// Add ScriptVariable + /// + /// + /// + /// + public static void AddScriptVariable(this IScriptVariableListProperties engine, ScriptVariable variable, bool allowOverride = true) + { + if (engine.CheckScriptVariableExists(variable.VariableName, out ScriptVariable v)) + { + if (allowOverride) + { + engine.RemoveScriptVariable(v.VariableName); + engine.VariableList.Add(variable); + } + else + { + throw new Exception($"ScriptVariable '{v.VariableName}' is already Exists."); + } + } + else + { + engine.VariableList.Add(variable); + } + } + + /// + /// Remove ScriptVariable + /// + /// + /// + public static void RemoveScriptVariable(this IScriptVariableListProperties engine, string variableName) + { + if (engine.CheckScriptVariableExists(variableName, out ScriptVariable v)) + { + engine.VariableList.Remove(v); + } + else + { + throw new Exception($"ScriptVariable '{variableName}' does not Exsits."); + } + } + } +} diff --git a/taskt/Core/Automation/Engine/IAppInstancesProperties.cs b/taskt/Core/Automation/Engine/IAppInstancesProperties.cs new file mode 100644 index 000000000..a2c7273cc --- /dev/null +++ b/taskt/Core/Automation/Engine/IAppInstancesProperties.cs @@ -0,0 +1,15 @@ +using System.Collections.Generic; + +namespace taskt.Core.Automation.Engine +{ + /// + /// App Instances properties + /// + public interface IAppInstancesProperties + { + /// + /// App Instances + /// + Dictionary AppInstances { get; set; } + } +} diff --git a/taskt/Core/Automation/Engine/IScriptVariableListProperties.cs b/taskt/Core/Automation/Engine/IScriptVariableListProperties.cs new file mode 100644 index 000000000..abc4a4fac --- /dev/null +++ b/taskt/Core/Automation/Engine/IScriptVariableListProperties.cs @@ -0,0 +1,13 @@ +using System.Collections.Generic; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Engine +{ + public interface IScriptVariableListProperties + { + /// + /// Variable List + /// + List VariableList { get; set; } + } +} diff --git a/taskt/Core/Automation/Engine/SystemVariables.cs b/taskt/Core/Automation/Engine/SystemVariables.cs new file mode 100644 index 000000000..2ee71a8fa --- /dev/null +++ b/taskt/Core/Automation/Engine/SystemVariables.cs @@ -0,0 +1,287 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Windows.Forms; +using taskt.Core.Automation.Commands; +using taskt.Core.IO; +using taskt.Core.Script; + +namespace taskt.Core.Automation.Engine +{ + /// + /// system variables + /// + public static class SystemVariables + { + #region normal system variables + public static readonly ScriptVariable Folder_Desktop = new ScriptVariable { VariableName = "Folder.Desktop", VariableValue = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) }; + public static readonly ScriptVariable Folder_Documents = new ScriptVariable { VariableName = "Folder.Documents", VariableValue = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) }; + public static readonly ScriptVariable Folder_AppData = new ScriptVariable { VariableName = "Folder.AppData", VariableValue = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) }; + public static readonly ScriptVariable Folder_ScriptPath = new ScriptVariable { VariableName = "Folder.ScriptPath", VariableValue = Folders.GetScriptsFolderPath() }; + public static readonly ScriptVariable Folder_RootPath = new ScriptVariable { VariableName = "Folder.RootPath", VariableValue = Folders.GetRootFolderPath() }; + public static readonly ScriptVariable Folder_AttendedTasksPath = new ScriptVariable { VariableName = "Folder.AttendedTasksPath", VariableValue = Folders.GetAttendedTasksFolderPath() }; + public static readonly ScriptVariable Folder_ResoucesPath = new ScriptVariable { VariableName = "Folder.ResourcesPath", VariableValue = Folders.GetResourcesFolderPath() }; + public static readonly ScriptVariable Folder_SamplesPath = new ScriptVariable { VariableName = "Folder.SamplesPath", VariableValue = Folders.GetSamplesFolderPath() }; + + public static readonly ScriptVariable DateTime_Now = new ScriptVariable { VariableName = "DateTime.Now", VariableValue = "" }; + public static readonly ScriptVariable DateTime_Now_Month = new ScriptVariable { VariableName = "DateTime.Now.Month", VariableValue = "" }; + public static readonly ScriptVariable DateTime_Now_Day = new ScriptVariable { VariableName = "DateTime.Now.Day", VariableValue = "" }; + public static readonly ScriptVariable DateTime_Now_Year = new ScriptVariable { VariableName = "DateTime.Now.Year", VariableValue = "" }; + public static readonly ScriptVariable DateTime_Now_YearLong = new ScriptVariable { VariableName = "DateTime.Now.YearLong", VariableValue = "" }; + public static readonly ScriptVariable DateTime_Now_Hour = new ScriptVariable { VariableName = "DateTime.Now.Hour", VariableValue = "" }; + public static readonly ScriptVariable DateTime_Now_Minute = new ScriptVariable { VariableName = "DateTime.Now.Minute", VariableValue = "" }; + public static readonly ScriptVariable DateTime_Now_Second = new ScriptVariable { VariableName = "DateTime.Now.Second", VariableValue = "" }; + public static readonly ScriptVariable DateTime_Now_FileSafe = new ScriptVariable { VariableName = "DateTime.Now.FileSafe", VariableValue = "" }; + public static readonly ScriptVariable DateTime_Now_FileSafeLong = new ScriptVariable { VariableName = "DateTime.Now.FileSafeLong", VariableValue = "" }; + + public static readonly ScriptVariable System_InputLanguage = new ScriptVariable { VariableName = "System.InputLanguage", VariableValue = InputLanguage.CurrentInputLanguage.Culture.Name }; + public static readonly ScriptVariable System_KeyboardLayout = new ScriptVariable { VariableName = "System.KeyboardLayout", VariableValue = InputLanguage.CurrentInputLanguage.LayoutName }; + + public static readonly ScriptVariable Error_Message = new ScriptVariable { VariableName = "Error.Message", VariableValue = "" }; + public static readonly ScriptVariable Error_Line = new ScriptVariable { VariableName = "Error.Line", VariableValue = "" }; + public static readonly ScriptVariable Error_StackTrace = new ScriptVariable { VariableName = "Error.StackTrace", VariableValue = "" }; + + public static readonly ScriptVariable PC_MachineName = new ScriptVariable { VariableName = "PC.MachineName", VariableValue = Environment.MachineName }; + public static readonly ScriptVariable PC_UserName = new ScriptVariable { VariableName = "PC.UserName", VariableValue = Environment.UserName }; + public static readonly ScriptVariable PC_DomainName = new ScriptVariable { VariableName = "PC.DomainName", VariableValue = Environment.UserDomainName }; + + public static readonly ScriptVariable Env_ActiveWindowTitle = new ScriptVariable { VariableName = "Env.ActiveWindowTitle", VariableValue = "" }; + public static readonly ScriptVariable Window_CurrentWindowName = new ScriptVariable { VariableName = "Window.CurrentWindowName", VariableValue = "" }; + public static readonly ScriptVariable Window_CurrentWindowHandle = new ScriptVariable { VariableName = "Window.CurrentWindowHandle", VariableValue = "" }; + + public static readonly ScriptVariable Taskt_EngineContext = new ScriptVariable { VariableName = "taskt.EngineContext", VariableValue = "" }; // post expand + public static readonly ScriptVariable Taskt_Location = new ScriptVariable { VariableName = "taskt.Location", VariableValue = Assembly.GetEntryAssembly().Location }; + + public static readonly ScriptVariable Char_NewLine = new ScriptVariable { VariableName = "Char.NewLine", VariableValue = Environment.NewLine }; + public static readonly ScriptVariable Char_Cr = new ScriptVariable { VariableName = "Char.Cr", VariableValue = "\r" }; + public static readonly ScriptVariable Char_Lf = new ScriptVariable { VariableName = "Char.Lf", VariableValue = "\n" }; + public static readonly ScriptVariable Char_Tab = new ScriptVariable { VariableName = "Char.Tab", VariableValue = "\t" }; + public static readonly ScriptVariable Char_Space = new ScriptVariable { VariableName = "Char.Space", VariableValue = " " }; + + public static readonly ScriptVariable FileCounter_F0 = new ScriptVariable { VariableName = "FileCounter.F0", VariableValue = "1" }; + public static readonly ScriptVariable FileCounter_F00 = new ScriptVariable { VariableName = "FileCounter.F00", VariableValue = "01" }; + public static readonly ScriptVariable FileCounter_F000 = new ScriptVariable { VariableName = "FileCounter.F000", VariableValue = "001" }; + public static readonly ScriptVariable File_CurrentScriptPath = new ScriptVariable { VariableName = "File.CurrentScriptFile", VariableValue = "" }; + + public static readonly ScriptVariable Loop_CurrentIndex = new ScriptVariable { VariableName = "Loop.CurrentIndex", VariableValue = "0" }; + + public static readonly ScriptVariable Math_PI = new ScriptVariable { VariableName = "Math.PI", VariableValue = Math.PI.ToString() }; + public static readonly ScriptVariable Math_E = new ScriptVariable { VariableName = "Math.E", VariableValue = Math.E.ToString() }; + #endregion + + #region limited system variables + + /// + /// specify desktop + /// + public static readonly ScriptVariable Window_Desktop = new ScriptVariable { VariableName = "Window.Desktop", VariableValue = "" }; + + /// + /// specify all windows + /// + public static readonly ScriptVariable Window_AllWindows = new ScriptVariable { VariableName = "Window.AllWindows", VariableValue = "" }; + + /// + /// specify current window position + /// + public static readonly ScriptVariable Window_CurrentPosition = new ScriptVariable { VariableName = "Window.CurrentPosition", VariableValue = "" }; + /// + /// specify current window x position + /// + public static readonly ScriptVariable Window_CurrentXPosition = new ScriptVariable { VariableName = "Window.CurrentXPosition", VariableValue = "" }; + /// + /// specify current window y position + /// + public static readonly ScriptVariable Window_CurrentYPosition = new ScriptVariable { VariableName = "Window.CurrentYPosition", VariableValue = "" }; + + /// + /// specify current window size + /// + public static readonly ScriptVariable Window_CurrentSize = new ScriptVariable { VariableName = "Window.CurrentSize", VariableValue = "" }; + /// + /// specify current window width size + /// + public static readonly ScriptVariable Window_CurrentWidth = new ScriptVariable { VariableName = "Window.CurrentWidth", VariableValue = "" }; + /// + /// specify current window height size + /// + public static readonly ScriptVariable Window_CurrentHeight = new ScriptVariable { VariableName = "Window.CurrentHeight", VariableValue = "" }; + + /// + /// specify current worksheet + /// + public static readonly ScriptVariable Excel_CurrentWorkSheet = new ScriptVariable { VariableName = "Excel.CurrentWorksheet", VariableValue = "" }; + /// + /// specify next worksheet + /// + public static readonly ScriptVariable Excel_NextWorkSheet = new ScriptVariable { VariableName = "Excel.NextWorksheet", VariableValue = "" }; + /// + /// specify previous worksheet + /// + public static readonly ScriptVariable Excel_PreviousWorkSheet = new ScriptVariable { VariableName = "Excel.PreviousWorksheet", VariableValue = "" }; + #endregion + + #region Enum + + public enum LimitedSystemVariableNames + { + None, + Window_Desktop, + Window_AllWindows, + Window_Position, + Window_Size, + Excel_Worksheet, + }; + + #endregion + + private static readonly List systemVariables = new List() + { + // folders + Folder_Desktop, + Folder_Documents, + Folder_AppData, + Folder_ScriptPath, + Folder_RootPath, + Folder_AttendedTasksPath, + Folder_ResoucesPath, + Folder_SamplesPath, + + // datetime + DateTime_Now, + DateTime_Now_Month, + DateTime_Now_Day, + DateTime_Now_Year, + DateTime_Now_YearLong, + DateTime_Now_Hour, + DateTime_Now_Minute, + DateTime_Now_Second, + DateTime_Now_FileSafe, + DateTime_Now_FileSafeLong, + + // system + System_InputLanguage, + System_KeyboardLayout, + + // error + Error_Message, + Error_Line, + Error_StackTrace, + + // PC + PC_MachineName, + PC_UserName, + PC_DomainName, + + // Active Window Title (not recommended) + Env_ActiveWindowTitle, + // Window + Window_CurrentWindowName, + Window_CurrentWindowHandle, + + // taskt + Taskt_EngineContext, + Taskt_Location, + + // special chars + Char_NewLine, + Char_Cr, + Char_Lf, + Char_Tab, + Char_Space, + + // file + FileCounter_F0, + FileCounter_F00, + FileCounter_F000, + File_CurrentScriptPath, + + // loop + Loop_CurrentIndex, + + // math + Math_PI, + Math_E, + }; + + /// + /// update system variables value + /// + /// + private static void UpdateSystemVariables(AutomationEngineInstance engine) + { + DateTime_Now.VariableValue = DateTime.Now.ToString(); + DateTime_Now_Month.VariableValue = DateTime.Now.ToString("MM"); + DateTime_Now_Day.VariableValue = DateTime.Now.ToString("dd"); + DateTime_Now_Year.VariableValue = DateTime.Now.ToString("yy"); + DateTime_Now_YearLong.VariableValue = DateTime.Now.ToString("yyyy"); + DateTime_Now_Hour.VariableValue = DateTime.Now.ToString("HH"); + DateTime_Now_Minute.VariableValue = DateTime.Now.ToString("mm"); + DateTime_Now_Second.VariableValue = DateTime.Now.ToString("ss"); + DateTime_Now_FileSafe.VariableValue = DateTime.Now.ToString("MM-dd-yy HH.mm.ss"); + DateTime_Now_FileSafeLong.VariableValue = DateTime.Now.ToString("yyyy-MM-dd_HH.mm.ss"); + + Env_ActiveWindowTitle.VariableValue = WindowControls.GetActiveWindowTitle(); + + Window_CurrentWindowName.VariableValue = WindowControls.GetActiveWindowTitle(); + Window_CurrentWindowHandle.VariableValue = WindowControls.GetActiveWindowHandle().ToString(); + + // NOTE: Keep it commented out as this is where it slows down the script execution. + //Taskt_EngineContext.VariableValue = engine.GetEngineContext(); + + File_CurrentScriptPath.VariableValue = engine.FileName; + } + + /// + /// get system variables list + /// + /// + /// + public static List GetSystemVariables(AutomationEngineInstance engine) + { + UpdateSystemVariables(engine); + return systemVariables; + } + + /// + /// get system variable names + /// + /// + public static List GetSystemVariablesName() + { + return systemVariables.Select(t => t.VariableName).ToList(); + } + + // TODO: I want to do better with class inheritance, etc. + /// + /// update Loop.CurrentIndex value + /// + /// + public static void Update_LoopCurrentIndex(int value) + { + Loop_CurrentIndex.VariableValue = value.ToString(); + } + + /// + /// update Loop.CurrentIndex value + /// + /// + public static void Update_LoopCurrentIndex(decimal value) + { + Loop_CurrentIndex.VariableValue = value.ToString(); + } + + /// + /// update Error System variables + /// + /// + /// + public static void Update_ErrorCatch(ScriptCommand command, Exception ex) + { + Error_Line.VariableValue = command.LineNumber.ToString(); + Error_StackTrace.VariableValue = ex.StackTrace; + Error_Message.VariableValue = ex.Message; + } + } +} diff --git a/taskt/Core/Automation/User32/User32Functionas.cs b/taskt/Core/Automation/User32/User32Functionas.cs index d6f4b143d..2a3bf433f 100644 --- a/taskt/Core/Automation/User32/User32Functionas.cs +++ b/taskt/Core/Automation/User32/User32Functionas.cs @@ -461,8 +461,8 @@ private static void BuildWindowCommand(IntPtr hWinEventHook, SystemEvents @event Automation.Commands.MoveWindowCommand moveWindowCommand = new MoveWindowCommand { v_WindowName = windowName, - v_XWindowPosition = windowRect.left.ToString(), - v_YWindowPosition = windowRect.top.ToString(), + v_XPosition = windowRect.left.ToString(), + v_YPosition = windowRect.top.ToString(), v_Comment = "Generated by Screen Recorder @ " + DateTime.Now.ToString() }; @@ -476,8 +476,8 @@ private static void BuildWindowCommand(IntPtr hWinEventHook, SystemEvents @event Automation.Commands.MoveWindowCommand moveWindowCommand = new MoveWindowCommand { v_WindowName = windowName, - v_XWindowPosition = "0", - v_YWindowPosition = "0", + v_XPosition = "0", + v_YPosition = "0", v_Comment = "Generated by Screen Recorder @ " + DateTime.Now.ToString() }; @@ -501,8 +501,8 @@ private static void BuildWindowCommand(IntPtr hWinEventHook, SystemEvents @event Automation.Commands.ResizeWindowCommand reszWindowCommand = new ResizeWindowCommand { v_WindowName = windowName, - v_XWindowSize = width.ToString(), - v_YWindowSize = height.ToString(), + v_Width = width.ToString(), + v_Height = height.ToString(), v_Comment = "Generated by Screen Recorder @ " + DateTime.Now.ToString() }; diff --git a/taskt/Core/Client.cs b/taskt/Core/Client.cs index 2a88da599..0759d7e9a 100644 --- a/taskt/Core/Client.cs +++ b/taskt/Core/Client.cs @@ -1,15 +1,10 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace taskt.Core { + // TODO: why static ? public static class Client { - - private static bool engineBusy; public static bool EngineBusy { diff --git a/taskt/Core/Common.cs b/taskt/Core/Common.cs deleted file mode 100644 index e42e5e584..000000000 --- a/taskt/Core/Common.cs +++ /dev/null @@ -1,580 +0,0 @@ -//Copyright (c) 2019 Jason Bayldon -// -//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.Data; -using System.Drawing; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; -using System.Windows.Forms; -using taskt.Core.Automation.Commands; -using taskt.Core.IO; - -namespace taskt.Core -{ - public static class Common - { - /// - /// Creates a unique 'clone' of an item. Used to create unique clones of commands when changing/updating new parameters. - /// - public static T Clone(T source) - { - if (!typeof(T).IsSerializable) - { - throw new ArgumentException("The type must be serializable.", "source"); - } - - - if (source == null) - { - return default(T); - } - - - using (MemoryStream ms = new MemoryStream()) - { - BinaryFormatter formatter = new BinaryFormatter(); - formatter.Context = new StreamingContext(StreamingContextStates.Clone); - formatter.Serialize(ms, source); - ms.Position = 0; - return (T)formatter.Deserialize(ms); - } - - - - - ////output to xml file - //XmlSerializer serializer = new XmlSerializer(typeof(T)); - //var settings = new XmlWriterSettings - //{ - // NewLineHandling = NewLineHandling.Entitize, - // Indent = true - //}; - - //StringBuilder xml = new StringBuilder(); - //XmlWriter xmlWriter = XmlWriter.Create(xml); - - //serializer.Serialize(xmlWriter, source); - - - //using (TextReader reader = new StringReader(xml.ToString())) - //{ - // T deserializedData = (T)serializer.Deserialize(reader); - // return deserializedData; - //} - - //System.Runtime.Serialization.IFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); - //Stream stream = new MemoryStream(); - //using (stream) - //{ - // formatter.Serialize(stream, source); - // stream.Seek(0, SeekOrigin.Begin); - // return (T)formatter.Deserialize(stream); - //} - } - ///// - ///// Returns a path to the underlying Script folder where script file objects are loaded and saved. Used when saved or loading files. - ///// - //public static string GetScriptFolderPath() - //{ - // return GetAppFolderPath() + "My Scripts\\"; - //} - ///// - ///// Returns a path to the storage path for taskt objects. Used when accessing the base storage path. - ///// - //public static string GetAppFolderPath() - //{ - // return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\taskt\\"; - //} - ///// - ///// Returns a path to the storage path for log objects. Used when accessing the base storage path. - ///// - //public static string GetLogFolderPath() - //{ - // return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\taskt\\Logs"; - //} - - //public static string GetAppDataPath() - //{ - // return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\taskt\\"; - //} - - /// - /// Returns commands from the AutomationCommands.cs file grouped by Custom 'Group' attribute. - /// - public static List> GetGroupedCommands() - { - var groupedCommands = Assembly.GetExecutingAssembly().GetTypes() - .Where(t => t.Namespace == "taskt.Core.Automation.Commands") - .Where(t => t.Name != "ScriptCommand") - .Where(t => t.IsAbstract == false) - .Where(t => t.BaseType.Name == "ScriptCommand") - .Where(t => CommandEnabled(t)) - .GroupBy(t => t.GetCustomAttribute(typeof(Core.Automation.Attributes.ClassAttributes.Group))) - .ToList(); - - return groupedCommands; - } - /// - /// Returns boolean indicating if the current command is enabled for use in automation. - /// - private static bool CommandEnabled(Type cmd) - { - var scriptCommand = (Core.Automation.Commands.ScriptCommand)Activator.CreateInstance(cmd); - return scriptCommand.CommandEnabled; - } - /// - /// Returns a list of system-generated variables for use with automation. - /// - public static List GenerateSystemVariables() - { - List systemVariableList = new List(); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Folder.Desktop", VariableValue = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Folder.Documents", VariableValue = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Folder.AppData", VariableValue = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Folder.ScriptPath", VariableValue = Core.IO.Folders.GetFolder(Folders.FolderType.ScriptsFolder) }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Folder.RootPath", VariableValue = Core.IO.Folders.GetFolder(Folders.FolderType.RootFolder)}); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Folder.AttendedTasksPath", VariableValue = Core.IO.Folders.GetFolder(Folders.FolderType.AttendedTasksFolder) }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "DateTime.Now", VariableValue = DateTime.Now.ToString() }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "DateTime.Now.Month", VariableValue = DateTime.Now.ToString("MM")}); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "DateTime.Now.Day", VariableValue = DateTime.Now.ToString("dd") }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "DateTime.Now.Year", VariableValue = DateTime.Now.ToString("yy") }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "DateTime.Now.YearLong", VariableValue = DateTime.Now.ToString("yyyy") }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "DateTime.Now.Hour", VariableValue = DateTime.Now.ToString("HH") }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "DateTime.Now.Minute", VariableValue = DateTime.Now.ToString("mm") }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "DateTime.Now.Second", VariableValue = DateTime.Now.ToString("ss") }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "DateTime.Now.FileSafe", VariableValue = DateTime.Now.ToString("MM-dd-yy hh.mm.ss") }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "System.InputLanguage", VariableValue = InputLanguage.CurrentInputLanguage.Culture.Name }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "System.KeyboardLayout", VariableValue = InputLanguage.CurrentInputLanguage.LayoutName }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Error.Message", VariableValue = "An Error Occured!" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Error.Line", VariableValue = "1" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Error.StackTrace", VariableValue = "An Error Occured + StackTrace" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "PC.MachineName", VariableValue = Environment.MachineName }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "PC.UserName", VariableValue = Environment.UserName }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "PC.DomainName", VariableValue = Environment.UserDomainName }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Env.ActiveWindowTitle", VariableValue = WindowNameControls.GetActiveWindowTitle() }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "taskt.EngineContext", VariableValue = "{JsonContext}" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "taskt.Location", VariableValue = System.Reflection.Assembly.GetEntryAssembly().Location }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Char.NewLine", VariableValue = Environment.NewLine }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Char.Cr", VariableValue = "\r" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Char.Lf", VariableValue = "\n" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Char.Tab", VariableValue = "\t" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Char.Space", VariableValue = " " }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "FileCounter.F0", VariableValue = "1" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "FileCounter.F00", VariableValue = "01" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "FileCounter.F000", VariableValue = "001" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "File.CurrentScriptFile", VariableValue = "" }); - systemVariableList.Add(new Core.Script.ScriptVariable { VariableName = "Loop.CurrentIndex", VariableValue = "0" }); - return systemVariableList; - } - public static string ImageToBase64(Image image) - { - - using (MemoryStream m = new MemoryStream()) - { - image.Save(m, System.Drawing.Imaging.ImageFormat.Bmp); - byte[] imageBytes = m.ToArray(); - var base64String = Convert.ToBase64String(imageBytes); - return base64String; - } - - } - public static Image Base64ToImage(string base64String) - { - byte[] imageBytes = Convert.FromBase64String(base64String); - MemoryStream ms = new MemoryStream(imageBytes, 0, imageBytes.Length); - ms.Write(imageBytes, 0, imageBytes.Length); - System.Drawing.Image image = System.Drawing.Image.FromStream(ms, true); - return image; - } - - //public static List GetAvailableWindowNames() - //{ - // List windowList = new List(); - // //get all running processes - // Process[] processlist = Process.GetProcesses(); - // //pull the main window title for each - // foreach (Process process in processlist) - // { - // if (!String.IsNullOrEmpty(process.MainWindowTitle)) - // { - // //add to the control list of available windows - // windowList.Add(process.MainWindowTitle); - // } - // } - - - // SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows(); - - // foreach (SHDocVw.InternetExplorer window in shellWindows) - // { - // windowList.Add("Windows Explorer - " + window.LocationName); - // } - - - // windowList.Sort(); - - // return windowList; - //} - - private static string GetKeyDescription(Keys key) - { - switch (key) - { - //letters - case Keys.A: - case Keys.B: - case Keys.C: - case Keys.D: - case Keys.E: - case Keys.F: - case Keys.G: - case Keys.H: - case Keys.I: - case Keys.J: - case Keys.K: - case Keys.L: - case Keys.M: - case Keys.N: - case Keys.O: - case Keys.P: - case Keys.Q: - case Keys.R: - case Keys.S: - case Keys.T: - case Keys.U: - case Keys.V: - case Keys.W: - case Keys.X: - case Keys.Y: - case Keys.Z: - return Enum.GetName(typeof(Keys), key); - - //digits - case Keys.D0: - return "0"; - case Keys.NumPad0: - return "Number Pad 0"; - case Keys.D1: - return "1"; - case Keys.NumPad1: - return "Number Pad 1"; - case Keys.D2: - return "2"; - case Keys.NumPad2: - return "Number Pad 2"; - case Keys.D3: - return "3"; - case Keys.NumPad3: - return "Number Pad 3"; - case Keys.D4: - return "4"; - case Keys.NumPad4: - return "Number Pad 4"; - case Keys.D5: - return "5"; - case Keys.NumPad5: - return "Number Pad 5"; - case Keys.D6: - return "6"; - case Keys.NumPad6: - return "Number Pad 6"; - case Keys.D7: - return "7"; - case Keys.NumPad7: - return "Number Pad 7"; - case Keys.D8: - return "8"; - case Keys.NumPad8: - return "Number Pad 8"; - case Keys.D9: - return "9"; - case Keys.NumPad9: - return "Number Pad 9"; - - //punctuation - case Keys.Add: - return "Number Pad +"; - case Keys.Subtract: - return "Number Pad -"; - case Keys.Divide: - return "Number Pad /"; - case Keys.Multiply: - return "Number Pad *"; - case Keys.Space: - return "Spacebar"; - case Keys.Decimal: - return "Number Pad ."; - - //function - case Keys.F1: - case Keys.F2: - case Keys.F3: - case Keys.F4: - case Keys.F5: - case Keys.F6: - case Keys.F7: - case Keys.F8: - case Keys.F9: - case Keys.F10: - case Keys.F11: - case Keys.F12: - case Keys.F13: - case Keys.F14: - case Keys.F15: - case Keys.F16: - case Keys.F17: - case Keys.F18: - case Keys.F19: - case Keys.F20: - case Keys.F21: - case Keys.F22: - case Keys.F23: - case Keys.F24: - return Enum.GetName(typeof(Keys), key); - - //navigation - case Keys.Up: - return "Up Arrow"; - case Keys.Down: - return "Down Arrow"; - case Keys.Left: - return "Left Arrow"; - case Keys.Right: - return "Right Arrow"; - case Keys.Prior: - return "Page Up"; - case Keys.Next: - return "Page Down"; - case Keys.Home: - return "Home"; - case Keys.End: - return "End"; - - //control keys - case Keys.Back: - return "Backspace"; - case Keys.Tab: - return "Tab"; - case Keys.Escape: - return "Escape"; - case Keys.Enter: - return "Enter"; - case Keys.Shift: - case Keys.ShiftKey: - return "Shift"; - case Keys.LShiftKey: - return "Shift (Left)"; - case Keys.RShiftKey: - return "Shift (Right)"; - case Keys.Control: - case Keys.ControlKey: - return "Control"; - case Keys.LControlKey: - return "Control (Left)"; - case Keys.RControlKey: - return "Control (Right)"; - case Keys.Menu: - case Keys.Alt: - return "Alt"; - case Keys.LMenu: - return "Alt (Left)"; - case Keys.RMenu: - return "Alt (Right)"; - case Keys.Pause: - return "Pause"; - case Keys.CapsLock: - return "Caps Lock"; - case Keys.NumLock: - return "Num Lock"; - case Keys.Scroll: - return "Scroll Lock"; - case Keys.PrintScreen: - return "Print Screen"; - case Keys.Insert: - return "Insert"; - case Keys.Delete: - return "Delete"; - case Keys.Help: - return "Help"; - case Keys.LWin: - return "Windows (Left)"; - case Keys.RWin: - return "Windows (Right)"; - case Keys.Apps: - return "Context Menu"; - - //browser keys - case Keys.BrowserBack: - return "Browser Back"; - case Keys.BrowserFavorites: - return "Browser Favorites"; - case Keys.BrowserForward: - return "Browser Forward"; - case Keys.BrowserHome: - return "Browser Home"; - case Keys.BrowserRefresh: - return "Browser Refresh"; - case Keys.BrowserSearch: - return "Browser Search"; - case Keys.BrowserStop: - return "Browser Stop"; - - //media keys - case Keys.VolumeDown: - return "Volume Down"; - case Keys.VolumeMute: - return "Volume Mute"; - case Keys.VolumeUp: - return "Volume Up"; - case Keys.MediaNextTrack: - return "Next Track"; - case Keys.Play: - case Keys.MediaPlayPause: - return "Play"; - case Keys.MediaPreviousTrack: - return "Previous Track"; - case Keys.MediaStop: - return "Stop"; - case Keys.SelectMedia: - return "Select Media"; - - //IME keys - case Keys.HanjaMode: - case Keys.JunjaMode: - case Keys.HangulMode: - case Keys.FinalMode: //duplicate values: Hanguel, Kana, Kanji - case Keys.IMEAccept: - case Keys.IMEConvert: //duplicate: IMEAceept - case Keys.IMEModeChange: - case Keys.IMENonconvert: - return null; - - //special keys - case Keys.LaunchMail: - return "Launch Mail"; - case Keys.LaunchApplication1: - return "Launch Favorite Application 1"; - case Keys.LaunchApplication2: - return "Launch Favorite Application 2"; - case Keys.Zoom: - return "Zoom"; - - //oem keys - case Keys.OemSemicolon: //oem1 - return ";"; - case Keys.OemQuestion: //oem2 - return "?"; - case Keys.Oemtilde: //oem3 - return "~"; - case Keys.OemOpenBrackets: //oem4 - return "["; - case Keys.OemPipe: //oem5 - return "|"; - case Keys.OemCloseBrackets: //oem6 - return "]"; - case Keys.OemQuotes: //oem7 - return "'"; - case Keys.OemBackslash: //oem102 - return "/"; - case Keys.Oemplus: - return "+"; - case Keys.OemMinus: - return "-"; - case Keys.Oemcomma: - return ","; - case Keys.OemPeriod: - return "."; - - //unsupported oem keys - case Keys.Oem8: - case Keys.OemClear: - return null; - - //unsupported other keys - case Keys.None: - case Keys.LButton: - case Keys.RButton: - case Keys.MButton: - case Keys.XButton1: - case Keys.XButton2: - case Keys.Clear: - case Keys.Sleep: - case Keys.Cancel: - case Keys.LineFeed: - case Keys.Select: - case Keys.Print: - case Keys.Execute: - case Keys.Separator: - case Keys.ProcessKey: - case Keys.Packet: - case Keys.Attn: - case Keys.Crsel: - case Keys.Exsel: - case Keys.EraseEof: - case Keys.NoName: - case Keys.Pa1: - case Keys.KeyCode: - case Keys.Modifiers: - return null; - - default: - throw new NotSupportedException(Enum.GetName(typeof(Keys), key)); - } - } - - public static List GetAvailableKeys() - { - var keyDescriptionList = new List(); - - foreach (string name in Enum.GetNames(typeof(Keys))) - { - - object value = Enum.Parse(typeof(Keys), name); - - var keyValue = (Keys)value; - - - string description = Core.Common.GetKeyDescription((Keys)value); - - if (description != null) - { - keyDescriptionList.Add(string.Concat(description, " [", keyValue, "]")); - } - - } - - return keyDescriptionList; - } - - //public static string ConvertObjectToJson(object obj) - //{ - // //set json settings - // JsonSerializerSettings settings = new JsonSerializerSettings(); - // settings.Error = (serializer, err) => - // { - // err.ErrorContext.Handled = true; - // }; - - // settings.Formatting = Newtonsoft.Json.Formatting.Indented; - - // return JsonConvert.SerializeObject(obj, settings); - //} - - } -} - diff --git a/taskt/Core/CompilerServices.cs b/taskt/Core/CompilerServices.cs deleted file mode 100644 index f67597af7..000000000 --- a/taskt/Core/CompilerServices.cs +++ /dev/null @@ -1,33 +0,0 @@ -using System; -using System.CodeDom.Compiler; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace taskt.Core -{ - public class CompilerServices - { - public CompilerResults CompileInput(string codeInput) - { - - //define file output - string Output = "tasktOnTheFly.exe"; - - //create provider - CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp"); - - //create compile parameters - CompilerParameters parameters = new CompilerParameters(); - parameters.GenerateExecutable = true; - parameters.OutputAssembly = Output; - - //compile - CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, codeInput); - return results; - - } - } - - } diff --git a/taskt/Core/DocumentationGeneration.cs b/taskt/Core/DocumentationGeneration.cs index aa07ef72c..c7511bcb4 100644 --- a/taskt/Core/DocumentationGeneration.cs +++ b/taskt/Core/DocumentationGeneration.cs @@ -7,10 +7,8 @@ using taskt.Core.Automation.Commands; using taskt.Core.Automation.Attributes.PropertyAttributes; using taskt.UI.CustomControls; -using static taskt.Core.Automation.Commands.PropertyControls; using Markdig; -using Microsoft.Office.Core; -using taskt.Core.Automation.Engine; +using static taskt.Core.Automation.Commands.PropertyControls; namespace taskt.Core { @@ -52,12 +50,17 @@ public static string GenerateMarkdownFiles() } //get all commands - var commandClasses = Assembly.GetExecutingAssembly().GetTypes() - .Where(t => t.Namespace == "taskt.Core.Automation.Commands") - .Where(t => t.Name != "ScriptCommand") - .Where(t => t.IsAbstract == false) - .Where(t => t.BaseType.Name == "ScriptCommand") - .ToList(); + //var commandClasses = Assembly.GetExecutingAssembly().GetTypes() + // .Where(t => t.Namespace == "taskt.Core.Automation.Commands") + // .Where(t => t.Name != "ScriptCommand") + // .Where(t => t.IsAbstract == false) + // .Where(t => t.BaseType.Name == "ScriptCommand") + // .ToList(); + var commandClasses = Assembly.GetAssembly(typeof(ScriptCommand)).GetTypes() + .Where(t => + { + return t.IsSubclassOf(typeof(ScriptCommand)) && !t.IsAbstract; + }).ToList(); // load settings var settings = new ApplicationSettings().GetOrCreateApplicationSettings(); @@ -172,7 +175,8 @@ private static CommandMetaData GenerateMarkdownCommandFile(Type commandClass, Ap sb.AppendLine("## Command Parameters"); // get propertyLists - List propInfos = commandClass.GetProperties().Where(f => f.Name.StartsWith("v_")).ToList(); + //List propInfos = commandClass.GetProperties().Where(f => f.Name.StartsWith("v_")).ToList(); + var propInfos = PropertyControls.GetParameterProperties(command, true); // create Parameters List int maxCount = 0; @@ -315,9 +319,11 @@ private static CommandMetaData GenerateMarkdownCommandFile(Type commandClass, Ap { var searchKey = pInfo.searchKey.Replace("\t", " & "); var desc = pInfo.description; - var sample = settings.EngineSettings.replaceEngineKeyword(pInfo.sampleUsage); - var rmk = settings.EngineSettings.replaceEngineKeyword(pInfo.remarks); - sb.AppendLine("|" + searchKey + "|" + desc + "|" + sample + "|" + rmk + "|"); + //var sample = settings.EngineSettings.replaceEngineKeyword(pInfo.sampleUsage); + //var rmk = settings.EngineSettings.replaceEngineKeyword(pInfo.remarks); + var sample = InternalKeywordsControls.ReplaceKeywordsToSystemVariableAndInstanceName(pInfo.sampleUsage, settings); + var remark = InternalKeywordsControls.ReplaceKeywordsToSystemVariableAndInstanceName(pInfo.remarks, settings); + sb.AppendLine("|" + searchKey + "|" + desc + "|" + sample + "|" + remark + "|"); } } @@ -335,7 +341,19 @@ private static CommandMetaData GenerateMarkdownCommandFile(Type commandClass, Ap foreach(var s in sampleUsages) { - sb.AppendLine("| " + ConvertMDToHTML(settings.replaceApplicationKeyword(s.sampleUsage)) + " | " + GetSampleUsageMeansText(s, settings) + " |"); + //var smp = s.sampleUsage.Replace(WindowControls.INTERNAL_CURRENT_WINDOW_KEYWORD, VariableNameControls.GetWrappedVariableName(Automation.Engine.SystemVariables.Window_CurrentWindowName.VariableName, settings)) + // .Replace(WindowControls.INTERNAL_CURRENT_WINDOW_POSITION_KEYWORD, VariableNameControls.GetWrappedVariableName(Automation.Engine.SystemVariables.Window_CurrentPosition.VariableName, settings)) + // .Replace(WindowControls.INTERNAL_CURRENT_WINDOW_X_POSITION_KEYWORD, VariableNameControls.GetWrappedVariableName(Automation.Engine.SystemVariables.Window_CurrentXPosition.VariableName, settings)) + // .Replace(WindowControls.INTERNAL_CURRENT_WINDOW_Y_POSITION_KEYWORD, VariableNameControls.GetWrappedVariableName(Automation.Engine.SystemVariables.Window_CurrentYPosition.VariableName, settings)) + // .Replace(WindowControls.INTERNAL_CURRENT_WINDOW_SIZE_KEYWORD, VariableNameControls.GetWrappedVariableName(Automation.Engine.SystemVariables.Window_CurrentSize.VariableName, settings)) + // .Replace(WindowControls.INTERNAL_CURRENT_WINDOW_WIDTH_KEYWORD, VariableNameControls.GetWrappedVariableName(Automation.Engine.SystemVariables.Window_CurrentWidth.VariableName, settings)) + // .Replace(WindowControls.INTERNAL_CURRENT_WINDOW_HEIGHT_KEYWORD, VariableNameControls.GetWrappedVariableName(Automation.Engine.SystemVariables.Window_CurrentHeight.VariableName, settings)) + // .Replace(ExcelControls.INTERNAL_EXCEL_CURRENT_WORKSHEET_KEYWORD, VariableNameControls.GetWrappedVariableName(Automation.Engine.SystemVariables.Excel_CurrentWorkSheet.VariableName, settings)); + + var smp = s.sampleUsage; + + //sb.AppendLine("| " + ConvertMDToHTML(settings.replaceApplicationKeyword(smp)) + " | " + GetSampleUsageMeansText(s, settings) + " |"); + sb.AppendLine("| " + ConvertMDToHTML(InternalKeywordsControls.ReplaceKeywordsToSystemVariableAndInstanceName(smp, settings)) + " | " + GetSampleUsageMeansText(s, settings) + " |"); //sampleUsageTabe += "| " + ConvertMDToHTML(settings.replaceApplicationKeyword(s.sampleUsage)) + " | " + GetSampleUsageMeansText(s, settings) + " |\n"; } //sb.AppendLine(ConvertMDToHTML(sampleUsageTabe)); @@ -377,6 +395,10 @@ private static CommandMetaData GenerateMarkdownCommandFile(Type commandClass, Ap //create kebob destination and command file nmae var kebobDestination = groupName.Replace(" ", "-").Replace("/", "-").ToLower(); + if (!kebobDestination.EndsWith("-commands")) + { + kebobDestination += "-commands"; + } var kebobFileName = commandName.Replace(" ", "-").Replace("/", "-").ToLower() + "-command.md"; //create directory if required @@ -402,7 +424,8 @@ private static string GetInputSpecification(PropertyInfo propInfo, PropertyInfo if (attrInput != null) { - var txt = settings.EngineSettings.replaceEngineKeyword(attrInput.inputSpecification); + //var txt = settings.EngineSettings.replaceEngineKeyword(attrInput.inputSpecification); + var txt = InternalKeywordsControls.ReplaceKeywordsToSystemVariableAndInstanceName(attrInput.inputSpecification, settings); if (attrInput.autoGenerate) { if (txt == "") @@ -502,12 +525,14 @@ private static string GetSampleUsageMeansText(PropertyDetailSampleUsage smp, App break; case PropertyDetailSampleUsage.ValueType.VariableValue: - string vName = settings.replaceApplicationKeyword(smp.sampleUsage).Replace(settings.EngineSettings.VariableStartMarker, "").Replace(settings.EngineSettings.VariableEndMarker, ""); + //string vName = settings.replaceApplicationKeyword(smp.sampleUsage).Replace(settings.EngineSettings.VariableStartMarker, "").Replace(settings.EngineSettings.VariableEndMarker, ""); + string vName = InternalKeywordsControls.ReplaceKeywordsToSystemVariableAndInstanceName(smp.sampleUsage, settings).Replace(settings.EngineSettings.VariableStartMarker, "").Replace(settings.EngineSettings.VariableEndMarker, ""); ret = "Specify Value of Variable " + vName; break; case PropertyDetailSampleUsage.ValueType.VariableName: - string vName2 = settings.replaceApplicationKeyword(smp.sampleUsage).Replace(settings.EngineSettings.VariableStartMarker, "").Replace(settings.EngineSettings.VariableEndMarker, ""); + //string vName2 = settings.replaceApplicationKeyword(smp.sampleUsage).Replace(settings.EngineSettings.VariableStartMarker, "").Replace(settings.EngineSettings.VariableEndMarker, ""); + string vName2 = InternalKeywordsControls.ReplaceKeywordsToSystemVariableAndInstanceName(smp.sampleUsage, settings).Replace(settings.EngineSettings.VariableStartMarker, "").Replace(settings.EngineSettings.VariableEndMarker, ""); ret = "Specify Variable Name " + vName2; break; } @@ -582,7 +607,8 @@ private static string GetErrorValidation(PropertyInfo propInfo, PropertyInfo vir private static string GetRemarksText(PropertyInfo propInfo, PropertyInfo virtualPropInfo, ApplicationSettings settings) { - string rm = settings.ClientSettings.replaceClientKeyword(GetCustomAttributeWithVirtual(propInfo, virtualPropInfo)?.remarks ?? ""); + //string rm = settings.ClientSettings.replaceClientKeyword(GetCustomAttributeWithVirtual(propInfo, virtualPropInfo)?.remarks ?? ""); + string rm = InternalKeywordsControls.ReplaceKeywordsToSystemVariableAndInstanceName(GetCustomAttributeWithVirtual(propInfo, virtualPropInfo)?.remarks ?? "", settings); // is optional var isOpt = GetCustomAttributeWithVirtual(propInfo, virtualPropInfo) ?? new PropertyIsOptional(); diff --git a/taskt/Core/EncryptionServices.cs b/taskt/Core/EncryptionServices.cs index f25dc6ffe..e59996ccd 100644 --- a/taskt/Core/EncryptionServices.cs +++ b/taskt/Core/EncryptionServices.cs @@ -1,10 +1,7 @@ using System; -using System.Collections.Generic; using System.IO; -using System.Linq; using System.Security.Cryptography; using System.Text; -using System.Threading.Tasks; namespace taskt.Core { @@ -15,6 +12,7 @@ public static class EncryptionServices private const string initVector = "kPcmAhmtL4ofXSMJ"; // This constant is used to determine the keysize of the encryption algorithm private const int keysize = 256; + //Encrypt public static string EncryptString(string plainText, string passPhrase) { diff --git a/taskt/Core/ExtensionMethods.cs b/taskt/Core/ExtensionMethods.cs index f82052d8b..5c56e607a 100644 --- a/taskt/Core/ExtensionMethods.cs +++ b/taskt/Core/ExtensionMethods.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using System.Data; using System.Linq; -using System.Text; using taskt.Core.Automation.Commands; namespace taskt.Core @@ -63,7 +62,15 @@ public static class ExtensionMethods '\n', '\r', '\t' }; - public static string GetRawPropertyString(this ScriptCommand command, string propertyName, string propertyDescription) + /// + /// get raw property value as string + /// + /// + /// + /// + /// + /// value is not string + public static string GetRawPropertyValueAsString(this ScriptCommand command, string propertyName, string propertyDescription) { var propInfo = command.GetType().GetProperty(propertyName) ?? throw new Exception(propertyDescription + " (name: '" + propertyName + "') does not exists."); object propValue = propInfo.GetValue(command); @@ -78,44 +85,60 @@ public static string GetRawPropertyString(this ScriptCommand command, string pro } } - public static string ConvertToUserVariable(this ScriptCommand command, string propertyName, string propertyDescription, Automation.Engine.AutomationEngineInstance engine) + /// + /// expand value or user variable as string + /// + /// + /// + /// + /// + /// + public static string ExpandValueOrUserVariable(this ScriptCommand command, string propertyName, string propertyDescription, Automation.Engine.AutomationEngineInstance engine) { - return GetRawPropertyString(command, propertyName, propertyDescription).ConvertToUserVariable(engine); + return GetRawPropertyValueAsString(command, propertyName, propertyDescription).ExpandValueOrUserVariable(engine); } /// - /// Replaces variable placeholders ([variable]) with variable text. + /// expand value or user variable as string /// - /// The script engine instance (frmScriptEngine) which contains session variables. - public static string ConvertToUserVariable(this String str, object sender) + /// + /// + /// + public static string ExpandValueOrUserVariable(this string str, Automation.Engine.AutomationEngineInstance engine) { - if (((Core.Automation.Engine.AutomationEngineInstance)sender).engineSettings.UseNewParser) + if (engine.engineSettings.UseNewParser) { - return str.ConvertToUserVariable_Unofficial(sender); + return str.ExpandValueOrUserVariable_new2022(engine); } else { - return str.ConvertToUserVariable_Official(sender); + return str.ExpandValueOrUserVariable_Official(engine); } } - public static string ConvertToUserVariable_Unofficial(this String str, object sender) + /// + /// new expand method 2022 + /// + /// + /// + /// + public static string ExpandValueOrUserVariable_new2022(this string str, Automation.Engine.AutomationEngineInstance engine) { if (str == null) { return string.Empty; } - if (sender == null) + if (engine == null) { return str; } - var engine = (Core.Automation.Engine.AutomationEngineInstance)sender; var variableList = engine.VariableList; - var systemVariables = Core.Common.GenerateSystemVariables(); + //var systemVariables = Core.Common.GenerateSystemVariables(); + var systemVariables = Automation.Engine.SystemVariables.GetSystemVariables(engine); - var searchList = new List(); + var searchList = new List(); searchList.AddRange(variableList); searchList.AddRange(systemVariables); @@ -144,11 +167,6 @@ public static string ConvertToUserVariable_Unofficial(this String str, object se } } - //if ((searchVariableCount == 0) && (convertedStr == "") && (str != convertedStr)) - //{ - // // not converted variable, result is empty string, but 'str' is not equals result - //} - if (!engine.AutoCalculateVariables) { return convertedStr; @@ -182,14 +200,14 @@ private static string AutoCalucationVariable(string targetString) } /// - /// + /// search user variable /// /// /// /// /// /// ret[0]: expands variable value, ret[1]: left string - private static string[] SearchVariable(string str, List variables, Core.Automation.Engine.AutomationEngineInstance engine) + private static string[] SearchVariable(string str, List variables, Automation.Engine.AutomationEngineInstance engine) { int state = 1; string variableName = ""; @@ -282,11 +300,19 @@ private static string[] SearchVariable(string str, List variables, Core.Automation.Engine.AutomationEngineInstance engine, out string result) + /// + /// expand user variable + /// + /// + /// + /// + /// + /// + private static bool ExpandVariable(string variableName, List variables, Automation.Engine.AutomationEngineInstance engine, out string result) { variableName = variableName.Trim(); result = null; - if (isExpandJSON(variableName, engine)) // => + if (IsExpandJSON(variableName, engine)) // => { bool ret = ExpandVariableJSON(variableName, variables, engine, out result); if (ret) @@ -294,7 +320,7 @@ private static bool ExpandVariable(string variableName, List variables, out string result) + private static bool ExpandVariableNormal(string variableName, List variables, out string result) { foreach(var trg in variables) { @@ -327,7 +353,7 @@ private static bool ExpandVariableNormal(string variableName, List variables, out Core.Script.ScriptVariable result) + private static bool ExpandVariableScriptVariable(string variableName, List variables, out Script.ScriptVariable result) { foreach (var trg in variables) { @@ -341,13 +367,13 @@ private static bool ExpandVariableScriptVariable(string variableName, List' is engine settings return (variableName.Split(new string[] { "=>" }, StringSplitOptions.None).Length >= 2); } - public static bool ExpandVariableJSON(string variableName, List variables, Core.Automation.Engine.AutomationEngineInstance engine, out string result) + public static bool ExpandVariableJSON(string variableName, List variables, Automation.Engine.AutomationEngineInstance engine, out string result) { var elements = variableName.Split(new string[] { "=>" }, StringSplitOptions.None); var newVariableName = elements[0].Trim(); @@ -388,13 +414,13 @@ public static bool ExpandVariableJSON(string variableName, List variables, Core.Automation.Engine.AutomationEngineInstance engine, out string result) + private static bool ExpandVariableListIndex(string variableName, List variables, Automation.Engine.AutomationEngineInstance engine, out string result) { int startPos = variableName.IndexOf('['); string newVariableName = variableName.Substring(0, startPos).Trim(); @@ -407,7 +433,7 @@ private static bool ExpandVariableListIndex(string variableName, List variables, Core.Automation.Engine.AutomationEngineInstance engine, out string result) + private static bool ExpandVariableDotProperty(string variableName, List variables, Automation.Engine.AutomationEngineInstance engine, out string result) { //if (variableName == "taskt.EngineContext") //{ @@ -452,9 +478,9 @@ private static bool ExpandVariableDotProperty(string variableName, List + /// convert user variable to Intermediate Notation (change wrap marker) + /// + /// + /// + /// + public static string ConvertUserVariableToIntermediateNotation(this string str, Automation.Engine.AutomationEngineInstance engine) { if (str == null) { @@ -505,9 +537,10 @@ public static string ConvertToUserVariable_Intermediate(this String str, Core.Au } var variableList = engine.VariableList; - var systemVariables = Core.Common.GenerateSystemVariables(); + //var systemVariables = Core.Common.GenerateSystemVariables(); + var systemVariables = Automation.Engine.SystemVariables.GetSystemVariables(engine); - var searchList = new List(); + var searchList = new List(); searchList.AddRange(variableList); searchList.AddRange(systemVariables); @@ -535,7 +568,7 @@ public static string ConvertToUserVariable_Intermediate(this String str, Core.Au return convertedStr; } - private static string[] SearchVariable_Intermediate(string str, List variables, Core.Automation.Engine.AutomationEngineInstance engine) + private static string[] SearchVariable_Intermediate(string str, List variables, Automation.Engine.AutomationEngineInstance engine) { int state = 1; string variableName = ""; @@ -573,7 +606,8 @@ private static string[] SearchVariable_Intermediate(string str, List(); + var searchList = new List(); searchList.AddRange(variableList); searchList.AddRange(systemVariables); @@ -777,8 +811,10 @@ public static string ConvertToUserVariable_Official(this String str, object send varCheck.VariableValue = engine.GetEngineContext(); break; - case "File.CurrentScriptFile": - varCheck.VariableValue = engine.FileName; + //case "File.CurrentScriptFile": + // varCheck.VariableValue = engine.FileName; + // break; + default: break; } @@ -881,15 +917,17 @@ public static string ConvertToUserVariable_Official(this String str, object send else { //track math chars - var mathChars = new List(); - mathChars.Add('*'); - mathChars.Add('+'); - mathChars.Add('-'); - mathChars.Add('='); - mathChars.Add('/'); - mathChars.Add('\r'); - mathChars.Add('\n'); - mathChars.Add('\t'); + var mathChars = new List + { + '*', + '+', + '-', + '=', + '/', + '\r', + '\n', + '\t' + }; //if the string matches the char then return //as the user does not want to do math @@ -924,9 +962,9 @@ public static string ConvertToUserVariable_Official(this String str, object send /// /// The script engine instance (frmScriptEngine) which contains session variables. /// the name of the user-defined variable to override with new value - public static void StoreInUserVariable(this String str, object sender, string targetVariable) + public static void StoreInUserVariable(this string str, Automation.Engine.AutomationEngineInstance engine, string targetVariable) { - StoreInUserVariable(targetVariable, str, (Core.Automation.Engine.AutomationEngineInstance)sender, true); + StoreInUserVariable(targetVariable, str, engine, true); } /// @@ -934,39 +972,42 @@ public static void StoreInUserVariable(this String str, object sender, string ta /// /// The script engine instance (frmScriptEngine) which contains session variables. /// the name of the user-defined variable to override with new value - public static void StoreRawDataInUserVariable(this String str, object sender, string targetVariable) + public static void StoreRawDataInUserVariable(this string str, Automation.Engine.AutomationEngineInstance engine, string targetVariable) { - StoreInUserVariable(targetVariable, str, (Core.Automation.Engine.AutomationEngineInstance)sender, false); + StoreInUserVariable(targetVariable, str, engine, false); } - public static void StoreInUserVariable(this DataRow value, Core.Automation.Engine.AutomationEngineInstance sender, string targetVariable) - { - StoreInUserVariable(targetVariable, value, sender, false); - } + //public static void StoreInUserVariable(this DataRow value, Automation.Engine.AutomationEngineInstance engine, string targetVariable) + //{ + // StoreInUserVariable(targetVariable, value, engine, false); + //} /// /// Formats item as a variable (enclosing brackets)s /// /// The string to be wrapped as a variable - public static string ApplyVariableFormatting(this String str, Core.Automation.Engine.AutomationEngineInstance engine) + public static string ApplyVariableFormatting(this string str, Automation.Engine.AutomationEngineInstance engine) { //var settings = new ApplicationSettings().GetOrCreateApplicationSettings(); //return str.Insert(0, settings.EngineSettings.VariableStartMarker).Insert(str.Length + 1, settings.EngineSettings.VariableEndMarker); - return engine.engineSettings.wrapVariableMarker(str); + //return engine.engineSettings.wrapVariableMarker(str); + + return VariableNameControls.GetWrappedVariableName(str, engine); } - public static void StoreInUserVariable(string userVariable, object variableValue, Core.Automation.Engine.AutomationEngineInstance engine, bool parseValue = true) + public static void StoreInUserVariable(string userVariable, object variableValue, Automation.Engine.AutomationEngineInstance engine, bool parseValue = true) { - userVariable = parseVariableName(userVariable, engine); + //userVariable = parseVariableName(userVariable, engine); + userVariable = VariableNameControls.GetVariableName(userVariable, engine); - var requiredVariable = lookupVariable(userVariable, engine); + var requiredVariable = LookupVariable(userVariable, engine); //if still not found and user has elected option, create variable at runtime if ((requiredVariable == null) && (engine.engineSettings.CreateMissingVariablesDuringExecution)) { engine.VariableList.Add(new Script.ScriptVariable() { VariableName = userVariable }); - requiredVariable = lookupVariable(userVariable, engine); + requiredVariable = LookupVariable(userVariable, engine); } if (requiredVariable == null) @@ -975,9 +1016,9 @@ public static void StoreInUserVariable(string userVariable, object variableValue } else { - if (parseValue && (variableValue is string)) + if (parseValue && (variableValue is string str)) { - requiredVariable.VariableValue = ((string)variableValue).ConvertToUserVariable(engine); + requiredVariable.VariableValue = str.ExpandValueOrUserVariable(engine); } else { @@ -987,11 +1028,22 @@ public static void StoreInUserVariable(string userVariable, object variableValue } } - public static Script.ScriptVariable GetRawVariable(this string variableName, Core.Automation.Engine.AutomationEngineInstance engine) + /// + /// get raw user variable value + /// + /// + /// + /// + /// + public static Script.ScriptVariable GetRawVariable(this string variableName, Automation.Engine.AutomationEngineInstance engine) { - string newName = parseVariableName(variableName, engine); - newName = newName.ConvertToUserVariable(engine); - Script.ScriptVariable searchedVaiable = lookupVariable(newName, engine); + //string newName = parseVariableName(variableName, engine); + var newName = VariableNameControls.GetVariableName(variableName, engine); + if (newName != variableName) + { + newName = newName.ExpandValueOrUserVariable(engine); + } + Script.ScriptVariable searchedVaiable = LookupVariable(newName, engine); if (searchedVaiable == null) { throw new Exception("Variable " + variableName + " does not exists."); @@ -1002,7 +1054,13 @@ public static Script.ScriptVariable GetRawVariable(this string variableName, Cor } } - private static Script.ScriptVariable lookupVariable(string variableName, Core.Automation.Engine.AutomationEngineInstance engine) + /// + /// search and return variable that specified name + /// + /// + /// + /// + private static Script.ScriptVariable LookupVariable(string variableName, Automation.Engine.AutomationEngineInstance engine) { //search for the variable var requiredVariable = engine.VariableList.Where(var => var.VariableName == variableName).FirstOrDefault(); @@ -1010,60 +1068,60 @@ private static Script.ScriptVariable lookupVariable(string variableName, Core.Au return requiredVariable; } - public static string parseVariableName(string variableName, Core.Automation.Engine.AutomationEngineInstance engine) - { - var settings = engine.engineSettings; - if (variableName.StartsWith(settings.VariableStartMarker) && variableName.EndsWith(settings.VariableEndMarker)) - { - if (engine.engineSettings.IgnoreFirstVariableMarkerInOutputParameter) - { - variableName = variableName.Substring(settings.VariableStartMarker.Length, variableName.Length - settings.VariableStartMarker.Length - settings.VariableEndMarker.Length); - } - } - if (variableName.Contains(settings.VariableStartMarker) && variableName.Contains(settings.VariableEndMarker)) - { - variableName = variableName.ConvertToUserVariable(engine); - } - - return variableName; - } - - public static string ToBase64(this string text) - { - return ToBase64(text, Encoding.UTF8); - } - - public static string ToBase64(this string text, Encoding encoding) - { - byte[] textAsBytes = encoding.GetBytes(text); - return Convert.ToBase64String(textAsBytes); - } - - public static bool TryParseBase64(this string text, out string decodedText) - { - return TryParseBase64(text, Encoding.UTF8, out decodedText); - } - - public static bool TryParseBase64(this string text, Encoding encoding, out string decodedText) - { - if (string.IsNullOrEmpty(text)) - { - decodedText = text; - return false; - } - - try - { - byte[] textAsBytes = Convert.FromBase64String(text); - decodedText = encoding.GetString(textAsBytes); - return true; - } - catch (Exception) - { - decodedText = null; - return false; - } - } + //public static string parseVariableName(string variableName, Core.Automation.Engine.AutomationEngineInstance engine) + //{ + // var settings = engine.engineSettings; + // if (variableName.StartsWith(settings.VariableStartMarker) && variableName.EndsWith(settings.VariableEndMarker)) + // { + // if (engine.engineSettings.IgnoreFirstVariableMarkerInOutputParameter) + // { + // variableName = variableName.Substring(settings.VariableStartMarker.Length, variableName.Length - settings.VariableStartMarker.Length - settings.VariableEndMarker.Length); + // } + // } + // if (variableName.Contains(settings.VariableStartMarker) && variableName.Contains(settings.VariableEndMarker)) + // { + // variableName = variableName.ExpandValueOrUserVariable(engine); + // } + + // return variableName; + //} + + //public static string ToBase64(this string text) + //{ + // return ToBase64(text, Encoding.UTF8); + //} + + //public static string ToBase64(this string text, Encoding encoding) + //{ + // byte[] textAsBytes = encoding.GetBytes(text); + // return Convert.ToBase64String(textAsBytes); + //} + + //public static bool TryParseBase64(this string text, out string decodedText) + //{ + // return TryParseBase64(text, Encoding.UTF8, out decodedText); + //} + + //public static bool TryParseBase64(this string text, Encoding encoding, out string decodedText) + //{ + // if (string.IsNullOrEmpty(text)) + // { + // decodedText = text; + // return false; + // } + + // try + // { + // byte[] textAsBytes = Convert.FromBase64String(text); + // decodedText = encoding.GetString(textAsBytes); + // return true; + // } + // catch (Exception) + // { + // decodedText = null; + // return false; + // } + //} } } diff --git a/taskt/Core/GlobalAppInstances.cs b/taskt/Core/GlobalAppInstances.cs index 14076a0e7..f4df73f03 100644 --- a/taskt/Core/GlobalAppInstances.cs +++ b/taskt/Core/GlobalAppInstances.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Collections.Generic; namespace taskt.Core { diff --git a/taskt/Core/IO/Folders.cs b/taskt/Core/IO/Folders.cs index 1340dac1d..757da58b4 100644 --- a/taskt/Core/IO/Folders.cs +++ b/taskt/Core/IO/Folders.cs @@ -1,56 +1,225 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.IO; +using System.Reflection; namespace taskt.Core.IO { public static class Folders { - public static string GetFolder(FolderType folderType) - { - - switch (folderType) - { - case FolderType.RootFolder: - //return root folder from settings - var rootSettings = new Core.ApplicationSettings().GetOrCreateApplicationSettings(); - var rootFolder = rootSettings.ClientSettings.RootFolder; - return rootFolder; - case FolderType.AttendedTasksFolder: - //return attended tasks folder from settings - var attendedSettings = new Core.ApplicationSettings().GetOrCreateApplicationSettings(); - var attentedTasksFolder = attendedSettings.ClientSettings.AttendedTasksFolder; - return attentedTasksFolder; - case FolderType.SettingsFolder: - //return app data taskt folder - return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\taskt\\"; - case FolderType.ScriptsFolder: - //return scripts folder - return System.IO.Path.Combine(GetFolder(FolderType.RootFolder), "My Scripts\\"); - case FolderType.LogFolder: - //return logs folder - return System.IO.Path.Combine(GetFolder(FolderType.RootFolder), "Logs\\"); - case FolderType.TempFolder: - //return temp folder - return System.IO.Path.GetTempPath() + "\\taskt\\"; - default: - //enum is not implemented - throw new NotImplementedException("FolderType " + folderType.ToString() + " Not Supported"); - } - - } - - - public enum FolderType - { - RootFolder, - SettingsFolder, - ScriptsFolder, - LogFolder, - TempFolder, - AttendedTasksFolder + /// + /// taskt excecute file path + /// + private readonly static string TASKT_EXECUTE_FOLDER_PATH = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); + /// + /// scripts folder name + /// + private const string SCRIPTS_FOLDER_NAME = "My Scripts"; + /// + /// logs folder name + /// + private const string LOGS_FOLDER_NAME = "Logs"; + /// + /// taskt settings folder name + /// + private const string SETTINGS_FOLDER_NAME = "taskt"; + /// + /// taskt temp folder name + /// + private const string TEMP_FOLDER_NAME = "taskt"; + /// + /// Resouces folder name + /// + public const string RESOURCES_FOLDER_NAME = "Resources"; + /// + /// Samples folder name + /// + public const string SAMPLES_FOLDER_NAME = "Samples"; + /// + /// AutoSave folder name + /// + public const string AUTOSAVE_FOLDER_NAME = "AutoSave"; + /// + /// RunWithoutSaving folder name + /// + public const string RUN_WITHOUT_SAVING_FOLDER_NAME = "RunWithoutSaving"; + /// + /// BeforeConverted folder name + /// + public const string BEFORE_CONVERTED_FOLDER_NAME = "BeforeConverted"; + /// + /// taskt update working folder name + /// + public const string UPDATE_FOLDER_NAME = "temp"; + + //public enum FolderType + //{ + // RootFolder, + // SettingsFolder, + // ScriptsFolder, + // LogFolder, + // TempFolder, + // AttendedTasksFolder + //} + + ///// + ///// get some taskt folders path + ///// + ///// + ///// + ///// + //public static string GetFolder(FolderType folderType) + //{ + // // TODO: eventually stop using + // switch (folderType) + // { + // case FolderType.RootFolder: + // //return root folder from settings + // //var rootSettings = new Core.ApplicationSettings().GetOrCreateApplicationSettings(); + // //var rootFolder = rootSettings.ClientSettings.RootFolder; + // //return rootFolder; + // return GetRootFolderPath(); + + // case FolderType.AttendedTasksFolder: + // //return attended tasks folder from settings + // //var attendedSettings = new Core.ApplicationSettings().GetOrCreateApplicationSettings(); + // //var attentedTasksFolder = attendedSettings.ClientSettings.AttendedTasksFolder; + // //return attentedTasksFolder; + // return GetAttendedTasksFolderPath(); + + // case FolderType.SettingsFolder: + // //return app data taskt folder + // //return Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\taskt\\"; + // return GetSettingsFolderPath(); + + // case FolderType.ScriptsFolder: + // //return scripts folder + // //return System.IO.Path.Combine(GetFolder(FolderType.RootFolder), "My Scripts\\"); + // return GetScriptsFolderPath(); + + // case FolderType.LogFolder: + // //return logs folder + // //return System.IO.Path.Combine(GetFolder(FolderType.RootFolder), "Logs\\"); + // return GetLogsFolderPath(); + + // case FolderType.TempFolder: + // //return temp folder + // //return System.IO.Path.GetTempPath() + "\\taskt\\"; + // return GetTempFolderPath(); + + // default: + // //enum is not implemented + // throw new NotImplementedException("FolderType " + folderType.ToString() + " Not Supported"); + // } + //} + + /// + /// get taskt root folder in Documents + /// + /// + public static string GetRootFolderPath() + { + var rootSettings = new Core.ApplicationSettings().GetOrCreateApplicationSettings(); + return rootSettings.ClientSettings.RootFolder; + } + + /// + /// get taskt scripts folder in Documents + /// + /// + public static string GetAttendedTasksFolderPath() + { + var attendedSettings = new ApplicationSettings().GetOrCreateApplicationSettings(); + return attendedSettings.ClientSettings.AttendedTasksFolder; + } + + /// + /// get taskt settings folder in Users\%username%\... + /// + /// + public static string GetSettingsFolderPath() + { + return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), $"{SETTINGS_FOLDER_NAME}\\"); + } + + /// + /// get scripts folder path + /// + /// + public static string GetScriptsFolderPath() + { + return Path.Combine(GetRootFolderPath(), $"{SCRIPTS_FOLDER_NAME}\\"); + } + + /// + /// get logs folder path + /// + /// + public static string GetLogsFolderPath() + { + return Path.Combine(GetRootFolderPath(), $"{LOGS_FOLDER_NAME}\\"); + } + + /// + /// get temp folder path + /// + /// + public static string GetTempFolderPath() + { + return Path.Combine(Path.GetTempPath(), $"{TEMP_FOLDER_NAME}\\"); + } + + /// + /// get Resouces folder path in taskt excecution file folder + /// + /// + public static string GetResourcesFolderPath() + { + return Path.Combine(TASKT_EXECUTE_FOLDER_PATH, $"{RESOURCES_FOLDER_NAME}\\"); + } + + /// + /// get Samples folder path in taskt excecution file folder + /// + /// + public static string GetSamplesFolderPath() + { + return Path.Combine(TASKT_EXECUTE_FOLDER_PATH, $"{SAMPLES_FOLDER_NAME}\\"); + } + + /// + /// get AutoSave folder path in taskt execution file folder + /// + /// + public static string GetAutoSaveFolderPath() + { + return Path.Combine(TASKT_EXECUTE_FOLDER_PATH, $"{AUTOSAVE_FOLDER_NAME}\\"); + } + + /// + /// get RunWithoutSaving folder path in taskt execution file folder + /// + /// + public static string GetRunWithoutSavingFolderPath() + { + return Path.Combine(TASKT_EXECUTE_FOLDER_PATH, $"{RUN_WITHOUT_SAVING_FOLDER_NAME}\\"); + } + + /// + /// get BeforeConverted folder path in taskt execution file folder + /// + /// + public static string GetBeforeConvertedFolderPath() + { + return Path.Combine(TASKT_EXECUTE_FOLDER_PATH, $"{BEFORE_CONVERTED_FOLDER_NAME}\\"); + } + + /// + /// get update working folder name + /// + /// + public static string GetUpdateWorkingFolderPath() + { + return Path.Combine(TASKT_EXECUTE_FOLDER_PATH, $"{UPDATE_FOLDER_NAME}\\"); } } } diff --git a/taskt/Core/IO/JavaInterface.cs b/taskt/Core/IO/JavaInterface.cs index cc35bae3c..331c7ecb0 100644 --- a/taskt/Core/IO/JavaInterface.cs +++ b/taskt/Core/IO/JavaInterface.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace taskt.Core.IO +namespace taskt.Core.IO { public class JavaInterface { @@ -17,7 +11,6 @@ private System.Diagnostics.Process Create(string jarName, string args) throw new System.IO.FileNotFoundException("JAR Library was not found at " + jarLibary); } - System.Diagnostics.Process javaProc = new System.Diagnostics.Process(); javaProc.StartInfo.FileName = "java"; javaProc.StartInfo.Arguments = string.Join(" ", "-jar", "\"" + jarLibary + "\"", args); @@ -30,7 +23,6 @@ private System.Diagnostics.Process Create(string jarName, string args) public string ExtractPDFText(string pdfFilePath) { - //create pdf path var pdfPath = "\"" + pdfFilePath + "\""; @@ -54,14 +46,6 @@ public string ExtractPDFText(string pdfFilePath) //return data return output; - - } - - - - - - } } diff --git a/taskt/Core/InstanceCounter.cs b/taskt/Core/InstanceCounter.cs index 18fd42eb2..6b45c94c1 100644 --- a/taskt/Core/InstanceCounter.cs +++ b/taskt/Core/InstanceCounter.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using taskt.Core.Automation.Commands; +using static taskt.Core.Automation.Attributes.PropertyAttributes.PropertyInstanceType; namespace taskt.Core { @@ -74,7 +76,7 @@ public class InstanceCounter { "created", new Dictionary() }, { "used", new Dictionary() } }; - private Dictionary> automationElementInstance = new Dictionary> + private Dictionary> uiElementInstance = new Dictionary> { { "created", new Dictionary() }, { "used", new Dictionary() } @@ -99,6 +101,16 @@ public class InstanceCounter { "created", new Dictionary() }, { "used", new Dictionary() } }; + private Dictionary> windowHandleInstance = new Dictionary> + { + { "created", new Dictionary() }, + { "used", new Dictionary() } + }; + private Dictionary> numericInstance = new Dictionary> + { + { "created", new Dictionary() }, + { "used", new Dictionary() } + }; public InstanceCounter(ApplicationSettings settings) { @@ -109,7 +121,7 @@ public void addInstance(string instanceName, Automation.Attributes.PropertyAttri { Dictionary targetDic = decideDictionary(instanceType.instanceType, isUsed); - if (String.IsNullOrEmpty(instanceName)) + if (string.IsNullOrEmpty(instanceName)) { instanceName = ""; } @@ -119,9 +131,12 @@ public void addInstance(string instanceName, Automation.Attributes.PropertyAttri return; } - if ((instanceType.autoWrapVariableMarker) && !(this.appSettings.EngineSettings.isWrappedVariableMarker(instanceName))) + //if ((instanceType.autoWrapVariableMarker) && !(this.appSettings.EngineSettings.isWrappedVariableMarker(instanceName))) + if ((instanceType.autoWrapVariableMarker) && + !(VariableNameControls.IsWrappedVariableMarker(instanceName, appSettings))) { - instanceName = this.appSettings.EngineSettings.wrapVariableMarker(instanceName); + //instanceName = this.appSettings.EngineSettings.wrapVariableMarker(instanceName); + instanceName = VariableNameControls.GetWrappedVariableName(instanceName, appSettings); } if (targetDic.ContainsKey(instanceName)) @@ -138,7 +153,7 @@ public void removeInstance(string instanceName, Automation.Attributes.PropertyAt { Dictionary targetDic = decideDictionary(instanceType.instanceType, isUsed); - if (String.IsNullOrEmpty(instanceName)) + if (string.IsNullOrEmpty(instanceName)) { instanceName = ""; } @@ -148,9 +163,12 @@ public void removeInstance(string instanceName, Automation.Attributes.PropertyAt return; } - if ((instanceType.autoWrapVariableMarker) && !(this.appSettings.EngineSettings.isWrappedVariableMarker(instanceName))) + //if ((instanceType.autoWrapVariableMarker) && !(this.appSettings.EngineSettings.isWrappedVariableMarker(instanceName))) + if ((instanceType.autoWrapVariableMarker) && + !(VariableNameControls.IsWrappedVariableMarker(instanceName, appSettings))) { - instanceName = this.appSettings.EngineSettings.wrapVariableMarker(instanceName); + //instanceName = this.appSettings.EngineSettings.wrapVariableMarker(instanceName); + instanceName = VariableNameControls.GetWrappedVariableName(instanceName, appSettings); } if (targetDic.ContainsKey(instanceName)) @@ -166,70 +184,76 @@ public void removeInstance(string instanceName, Automation.Attributes.PropertyAt } } - public Dictionary getInstanceClone(Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType instanceType, bool isUsed = false) + public Dictionary getInstanceClone(InstanceType instanceType, bool isUsed = false) { Dictionary targetDic = decideDictionary(instanceType, isUsed); return new Dictionary(targetDic); } - private Dictionary decideDictionary(Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType instanceType, bool isUsed = false) + private Dictionary decideDictionary(InstanceType instanceType, bool isUsed = false) { Dictionary> targetDic; switch (instanceType) { - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.UIElement: - targetDic = automationElementInstance; - break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Boolean: + case InstanceType.Boolean: targetDic = booleanInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Color: + case InstanceType.Color: targetDic = colorInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.DataBase: + case InstanceType.DataBase: targetDic = databaseInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.DataTable: + case InstanceType.DataTable: targetDic = dataTableInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.DateTime: + case InstanceType.DateTime: targetDic = dateTimeInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Dictionary: + case InstanceType.Dictionary: targetDic = dictionaryInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Excel: + case InstanceType.Excel: targetDic = excelInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.IE: + case InstanceType.IE: targetDic = ieInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.JSON: + case InstanceType.JSON: targetDic = jsonInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.List: + case InstanceType.List: targetDic = listInstance; ; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.MailKitEMail: + case InstanceType.MailKitEMail: targetDic = mailkitEMailInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.MailKitEMailList: + case InstanceType.MailKitEMailList: targetDic = mailkitEMailListInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.NLG: + case InstanceType.NLG: targetDic = nlgInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.StopWatch: + case InstanceType.Numeric: + targetDic = numericInstance; + break; + case InstanceType.StopWatch: targetDic = stopWatchInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.WebBrowser: + case InstanceType.UIElement: + targetDic = uiElementInstance; + break; + case InstanceType.WebBrowser: targetDic = webBrowserInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.WebElement: + case InstanceType.WebElement: targetDic = webElementInstance; break; - case Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Word: + case InstanceType.WindowHandle: + targetDic = windowHandleInstance; + break; + case InstanceType.Word: targetDic = wordInstance; break; default: @@ -238,47 +262,51 @@ private Dictionary decideDictionary(Automation.Attributes.PropertyA return (isUsed) ? targetDic["used"] : targetDic["created"]; } - public static Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType GetInstanceType(string instanceType) + public static InstanceType GetInstanceType(string instanceType) { switch (instanceType.ToLower()) { - case "automationelement": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.UIElement; case "boolean": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Boolean; + return InstanceType.Boolean; case "color": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Color; + return InstanceType.Color; case "database": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.DataBase; + return InstanceType.DataBase; case "datatable": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.DataTable; + return InstanceType.DataTable; case "datetime": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.DateTime; + return InstanceType.DateTime; case "dictionary": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Dictionary; + return InstanceType.Dictionary; case "excel": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Excel; + return InstanceType.Excel; case "ie": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.IE; + return InstanceType.IE; case "json": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.JSON; + return InstanceType.JSON; case "list": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.List; + return InstanceType.List; case "mailkitemail": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.MailKitEMail; + return InstanceType.MailKitEMail; case "mailkitemaillist": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.MailKitEMailList; + return InstanceType.MailKitEMailList; + case "numeric": + return InstanceType.Numeric; case "stopwatch": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.StopWatch; + return InstanceType.StopWatch; + case "uielement": + return InstanceType.UIElement; case "web browser": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.WebBrowser; + return InstanceType.WebBrowser; case "webelement": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.WebElement; + return InstanceType.WebElement; + case "windowhandle": + return InstanceType.WindowHandle; case "word": - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.Word; + return InstanceType.Word; case "none": default: - return Automation.Attributes.PropertyAttributes.PropertyInstanceType.InstanceType.none; + return InstanceType.none; } } } diff --git a/taskt/Core/Logging.cs b/taskt/Core/Logging.cs index 3f3080468..3151b0f29 100644 --- a/taskt/Core/Logging.cs +++ b/taskt/Core/Logging.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using Serilog; +using Serilog; using Serilog.Formatting.Compact; using taskt.Core.IO; @@ -17,18 +12,17 @@ public class Logging public Serilog.Core.Logger CreateLogger(string componentName, RollingInterval logInterval) { return new LoggerConfiguration() - .WriteTo.File(Folders.GetFolder(Core.IO.Folders.FolderType.LogFolder) + "\\taskt " + componentName + " Logs.txt", rollingInterval: logInterval) - .CreateLogger(); - + //.WriteTo.File(Folders.GetFolder(Core.IO.Folders.FolderType.LogFolder) + "\\taskt " + componentName + " Logs.txt", rollingInterval: logInterval) + .WriteTo.File(Folders.GetLogsFolderPath() + "\\taskt " + componentName + " Logs.txt", rollingInterval: logInterval) + .CreateLogger(); } + public Serilog.Core.Logger CreateJsonLogger(string componentName, RollingInterval logInterval) { return new LoggerConfiguration() - .WriteTo.File(new CompactJsonFormatter(), Folders.GetFolder(Core.IO.Folders.FolderType.LogFolder) + "\\taskt " + componentName + " Logs.txt", rollingInterval: logInterval) - .CreateLogger(); - + //.WriteTo.File(new CompactJsonFormatter(), Folders.GetFolder(Core.IO.Folders.FolderType.LogFolder) + "\\taskt " + componentName + " Logs.txt", rollingInterval: logInterval) + .WriteTo.File(new CompactJsonFormatter(), Folders.GetLogsFolderPath() + "\\taskt " + componentName + " Logs.txt", rollingInterval: logInterval) + .CreateLogger(); } - } - } diff --git a/taskt/Core/Metrics.cs b/taskt/Core/Metrics.cs index 5ccb224f8..0bf333a12 100644 --- a/taskt/Core/Metrics.cs +++ b/taskt/Core/Metrics.cs @@ -2,8 +2,6 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using System.Text; -using System.Threading.Tasks; namespace taskt.Core { @@ -12,19 +10,20 @@ public class Metrics public List ExecutionMetricsSummary() { //create execution file path - var filePath = System.IO.Path.Combine(Core.IO.Folders.GetFolder(Core.IO.Folders.FolderType.LogFolder), "taskt Execution Summary Logs.txt"); + //var filePath = Path.Combine(IO.Folders.GetFolder(IO.Folders.FolderType.LogFolder), "taskt Execution Summary Logs.txt"); + var filePath = Path.Combine(IO.Folders.GetLogsFolderPath(), "taskt Execution Summary Logs.txt"); //throw if file doesnt exist - if (!System.IO.File.Exists(filePath)) + if (!File.Exists(filePath)) { - throw new System.IO.FileNotFoundException("Execution Summary Log does not exist!"); + throw new FileNotFoundException("Execution Summary Log does not exist!"); } //create list for sorting data - var scriptsFinishedArgs = new List(); + var scriptsFinishedArgs = new List(); //get all text from log file - var logFileLines = System.IO.File.ReadAllLines(filePath); + var logFileLines = File.ReadAllLines(filePath); //loop each line from log file foreach (var line in logFileLines) @@ -35,7 +34,7 @@ public List ExecutionMetricsSummary() var deserializedLine = Newtonsoft.Json.JsonConvert.DeserializeObject(line) as Newtonsoft.Json.Linq.JToken; //convert the logged data json - var scriptArgs = Newtonsoft.Json.JsonConvert.DeserializeObject(deserializedLine["@mt"].ToString()); + var scriptArgs = Newtonsoft.Json.JsonConvert.DeserializeObject(deserializedLine["@mt"].ToString()); //add to tracking list scriptsFinishedArgs.Add(scriptArgs); @@ -49,16 +48,9 @@ public List ExecutionMetricsSummary() //create list to return var executionMetrics = new List(); - //group by file name and create execution time average - var groupedTasks = scriptsFinishedArgs - .GroupBy(f => f.FileName); + var groupedTasks = scriptsFinishedArgs.GroupBy(f => f.FileName); - - - - - //loop through each group foreach (var task in groupedTasks) { @@ -70,7 +62,7 @@ public List ExecutionMetricsSummary() //get info around file var fullFileName = task.FirstOrDefault().FileName; string parentFolder = new DirectoryInfo(fullFileName).Parent.Name; - string fileName = new System.IO.FileInfo(fullFileName).Name; + string fileName = new FileInfo(fullFileName).Name; //create metric var metric = new ExecutionMetric() @@ -82,26 +74,22 @@ public List ExecutionMetricsSummary() //add metric to list executionMetrics.Add(metric); - } catch (Exception) { //do nothing } - - - } //return metric return executionMetrics; - } public void ClearExecutionMetrics() { - var filePath = System.IO.Path.Combine(Core.IO.Folders.GetFolder(Core.IO.Folders.FolderType.LogFolder), "taskt Execution Summary Logs.txt"); - System.IO.File.WriteAllText(filePath, string.Empty); + //var filePath = Path.Combine(IO.Folders.GetFolder(IO.Folders.FolderType.LogFolder), "taskt Execution Summary Logs.txt"); + var filePath = Path.Combine(IO.Folders.GetLogsFolderPath(), "taskt Execution Summary Logs.txt"); + File.WriteAllText(filePath, string.Empty); } } @@ -109,7 +97,6 @@ public class ExecutionMetric { public string FileName { get; set; } public TimeSpan AverageExecutionTime { get; set; } - public List ExecutionData { get; set; } - + public List ExecutionData { get; set; } } } diff --git a/taskt/Core/MyURLs.cs b/taskt/Core/MyURLs.cs index c3f463653..13056029d 100644 --- a/taskt/Core/MyURLs.cs +++ b/taskt/Core/MyURLs.cs @@ -10,9 +10,9 @@ public class MyURLs public const string GitterURL = "https://gitter.im/taskt-rpa/Lobby"; public const string WikiBaseURL = "https://github.com/saucepleez/taskt-wiki/blob/master/"; - public const string LatestJSONURL = "http://www.taskt.net/updates/latest.json"; + public const string LatestJSONURL = "https://raw.githubusercontent.com/saucepleez/taskt/development-branch/taskt/latest.json"; - public const string ChromeDriverURL = "https://chromedriver.chromium.org/downloads"; + public const string ChromeDriverURL = "https://googlechromelabs.github.io/chrome-for-testing/"; public const string EdgeDriverURL = "https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/"; public const string GeckoDriverURL = "https://github.com/mozilla/geckodriver/releases/"; public const string IEDriverURL = "https://www.selenium.dev/downloads/"; @@ -24,11 +24,38 @@ public class MyURLs public const string DateTimeFormatURL1 = "https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings"; public const string DateTimeFormatURL2 = "https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings"; + // NuGets, etc + public const string BouncyCastleURL = "https://www.bouncycastle.org/csharp/"; + public const string HTMLAgilityPackURL = "https://www.nuget.org/packages/HtmlAgilityPack/"; + public const string IMAPXURL = "https://github.com/azanov/imapx"; + public const string JetBrainAnnotationsURL = "https://www.nuget.org/packages/JetBrains.Annotations/"; + public const string Log4NetURL = ""; //? + public const string MailKitURL = "http://www.mimekit.net/"; + public const string MarkddigURL = "https://github.com/xoofx/markdig"; + public const string MimeKitURL = "http://www.mimekit.net/"; + public const string NewtonSoftJSONURL = "https://www.nuget.org/packages/newtonsoft.json/"; + public const string OneNoteOCRURL = "https://github.com/ignatandrei/OneNoteOCR"; + public const string RestSharpURL = "https://restsharp.dev/"; + public const string SeleniumURL = "https://github.com/SeleniumHQ/selenium"; + public const string SelilogURL = "https://serilog.net/"; + public const string SelilogFormattingCompactURL = "https://github.com/serilog/serilog-formatting-compact"; + public const string SelilogSinksFileURL = "https://serilog.net/"; + public const string SharpCompressURL = "https://github.com/adamhathcock/sharpcompress"; + public const string SharpSimpleNLGURL = "https://github.com/nickhodge/SharpSimpleNLG"; + public const string SuperSocketClientEngineURL = "https://github.com/kerryjiang/SuperSocket.ClientEngine"; + public const string TaskSchedulerURL = "https://github.com/dahall/TaskScheduler"; + public const string WebSocket4NetURL = "https://github.com/kerryjiang/WebSocket4Net"; + public const string ZstdSharpPortURL = "https://github.com/oleg-st/ZstdSharp"; public static string GetWikiURL(string commandName, string groupName) { string page = commandName.ToLower().Replace(" ", "-").Replace("/", "-") + "-command.md"; - string parent = groupName.ToLower().Replace(" ", "-").Replace("/", "-"); + groupName = groupName.ToLower(); + if (!groupName.EndsWith("-commands")) + { + groupName += "-commands"; + } + string parent = groupName.Replace(" ", "-").Replace("/", "-"); return WikiBaseURL + parent + "/" + page; } } diff --git a/taskt/Core/Script/InnerScriptVariable.cs b/taskt/Core/Script/InnerScriptVariable.cs new file mode 100644 index 000000000..876ac1d3e --- /dev/null +++ b/taskt/Core/Script/InnerScriptVariable.cs @@ -0,0 +1,57 @@ +using System; +using taskt.Core.Automation.Commands; +using taskt.Core.Automation.Engine; + +namespace taskt.Core.Script +{ + /// + /// Inner Script Variable + /// + public class InnerScriptVariable : ScriptVariable, IDisposable + { + private readonly AutomationEngineInstance engine; + + public InnerScriptVariable(AutomationEngineInstance engine) + { + this.engine = engine; + + var variableList = engine.VariableList; + int i = 0; + while (true) + { + if (variableList.Exists(v => (v.VariableName == VariableNameControls.INNER_VARIABLE_PREFIX + i.ToString()))) + { + i++; + } + else + { + break; + } + } + this.VariableName = VariableNameControls.INNER_VARIABLE_PREFIX + i.ToString(); + variableList.Add(this); + } + + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + protected virtual void Dispose(bool disposing) + { + var variableLists = engine.VariableList; + + var idx = variableLists.IndexOf(this); + if (idx >= 0) + { + variableLists.RemoveAt(idx); + } + } + + ~InnerScriptVariable() + { + Dispose(false); + } + } +} diff --git a/taskt/Core/Script/Script.cs b/taskt/Core/Script/Script.cs index b72e8a073..20e2e9e22 100644 --- a/taskt/Core/Script/Script.cs +++ b/taskt/Core/Script/Script.cs @@ -13,13 +13,17 @@ //limitations under the License. using System; using System.Collections.Generic; +using System.Data; +using System.IO; using System.Linq; -using System.Xml.Serialization; +using System.Reflection; +using System.Text.RegularExpressions; using System.Windows.Forms; using System.Xml; using System.Xml.Linq; -using System.Data; +using System.Xml.Serialization; using taskt.Core.Automation.Commands; +using taskt.Core.Automation.Engine; namespace taskt.Core.Script { @@ -79,7 +83,8 @@ public static Script SerializeScript(ListView.ListViewItemCollection scriptComma var command = srcCommand.Clone(); command.LineNumber = lineNumber; - if ((command is BeginNumberOfTimesLoopCommand) || (command is BeginContinousLoopCommand) || (command is BeginListLoopCommand) || (command is BeginIfCommand) || (command is BeginMultiIfCommand) || (command is TryCommand) || (command is BeginLoopCommand) || (command is BeginMultiLoopCommand)) + //if ((command is BeginNumberOfTimesLoopCommand) || (command is BeginContinousLoopCommand) || (command is BeginLoopForComplexDataTypesCommand) || (command is BeginIfCommand) || (command is BeginMultiIfCommand) || (command is TryCommand) || (command is BeginLoopCommand) || (command is BeginMultiLoopCommand)) + if ((command is IHaveErrorAdditionalCommands) || (command is IHaveIfAdditionalCommands) || (command is IHaveLoopAdditionalCommands)) { if (subCommands.Count == 0) //if this is the first loop { @@ -98,7 +103,8 @@ public static Script SerializeScript(ListView.ListViewItemCollection scriptComma subCommands.Add(nextNodeParent); } } - else if ((command is EndLoopCommand) || (command is EndIfCommand) || (command is EndTryCommand)) //if current loop scenario is ending + //else if ((command is EndLoopCommand) || (command is EndIfCommand) || (command is EndTryCommand)) //if current loop scenario is ending + else if (command is IEndOfStacturedCommand) { //get reference to previous node var parentCommand = subCommands[subCommands.Count - 1]; @@ -146,7 +152,7 @@ public static Script SerializeScript(ListView.ListViewItemCollection scriptComma if (scriptFilePath != "") { //write to file - using (System.IO.FileStream fs = System.IO.File.Create(scriptFilePath)) + using (System.IO.FileStream fs = File.Create(scriptFilePath)) { using (XmlWriter writer = XmlWriter.Create(fs, settings)) { @@ -163,10 +169,16 @@ public static Script SerializeScript(ListView.ListViewItemCollection scriptComma /// public static Script DeserializeFile(string scriptFilePath, EngineSettings engineSettings, XmlSerializer serializer = null) { + // backup before converted + var fileName = $"bc-{Path.GetFileNameWithoutExtension(scriptFilePath)}-{DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")}.xml"; + //var bkFile = Path.Combine(GetBeforeConvertedFolderPath(), fileName); + var bkFile = Path.Combine(IO.Folders.GetBeforeConvertedFolderPath(), fileName); + File.Copy(scriptFilePath, bkFile); + XDocument xmlScript = XDocument.Load(scriptFilePath); // pre-convert - convertOldScript(xmlScript); + convertOldScript(xmlScript, engineSettings); using (var reader = xmlScript.Root.CreateReader()) { @@ -251,23 +263,110 @@ public static Script DeserializeScript(string scriptXML, XmlSerializer serialize /// public static XmlSerializer CreateSerializer() { - var subClasses = System.Reflection.Assembly.GetAssembly(typeof(ScriptCommand)) + var subClasses = Assembly.GetAssembly(typeof(ScriptCommand)) .GetTypes() .Where(x => x.IsSubclassOf(typeof(ScriptCommand)) && !x.IsAbstract) + //.Where(x => x.IsSubclassOf(typeof(ScriptCommand))) .ToArray(); return new XmlSerializer(typeof(Script), subClasses); } + ///// + ///// get AutoSave Folder Path + ///// + ///// + //public static string GetAutoSaveFolderPath() + //{ + // var tasktExePath = Assembly.GetEntryAssembly().Location; + // return Path.Combine(Path.GetDirectoryName(tasktExePath), "AutoSave"); + //} + + /// + /// get autosave script file path + /// + /// + public static (string path, string timeStump) GetAutoSaveScriptFilePath() + { + //var savePath = GetAutoSaveFolderPath(); + var savePath = IO.Folders.GetAutoSaveFolderPath(); + var saveTime = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"); + + return (Path.Combine(savePath, "autosave-") + saveTime + ".xml", saveTime); + } + + ///// + ///// get RunWithoutSaving Folder Path + ///// + ///// + //public static string GetRunWithoutSavingFolderPath() + //{ + // var tasktExePath = Assembly.GetEntryAssembly().Location; + // return Path.Combine(Path.GetDirectoryName(tasktExePath), "RunWithoutSaving"); + //} + + ///// + ///// get BeforeConverted Folder Path + ///// + ///// + //public static string GetBeforeConvertedFolderPath() + //{ + // var tasktExePath = Assembly.GetEntryAssembly().Location; + // return Path.Combine(Path.GetDirectoryName(tasktExePath), "BeforeConverted"); + //} + + /// + /// get file path when use 'Run Without Saving' + /// + /// + public static string GetRunWithoutSavingScriptFilePath() + { + //var runPath = GetRunWithoutSavingFolderPath(); + var runPath = IO.Folders.GetRunWithoutSavingFolderPath(); + var saveTime = DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss"); + return Path.Combine(runPath, "run-") + saveTime + ".xml"; + } + + /// + /// ReGenerate all commandID + /// + public void ReGenerateCommandID() + { + foreach(var command in this.Commands) + { + ReGenerateCommandIDProcess(command); + } + } + + /// + /// ReGenerate commands ID process + /// + /// + public static void ReGenerateCommandIDProcess(ScriptAction script) + { + script.ScriptCommand.GenerateID(); + if ((script.AdditionalScriptCommands?.Count ?? 0) > 0) + { + foreach(var command in script.AdditionalScriptCommands) + { + ReGenerateCommandIDProcess(command); + } + } + } + /// /// script xml converter /// /// /// - private static XDocument convertOldScript(XDocument doc) + private static XDocument convertOldScript(XDocument doc, EngineSettings engine) { // very important! // ** DO NOT USE nameof to change command name ** + + fixDataTableSchemaPosition(doc); + fixToSameCommandNames(doc); + convertTo3_5_0_45(doc); convertTo3_5_0_46(doc); convertTo3_5_0_47(doc); @@ -280,7 +379,7 @@ private static XDocument convertOldScript(XDocument doc) convertTo3_5_0_73(doc); convertTo3_5_0_74(doc); convertTo3_5_0_78(doc); - fixUIAutomationGroupEnableParameterValue(doc); + fixUIAutomationSearchEnableParameterValue(doc); convertTo3_5_0_83(doc); convertTo3_5_1_16(doc); convertTo3_5_1_30(doc); @@ -291,7 +390,7 @@ private static XDocument convertOldScript(XDocument doc) convertTo3_5_1_36(doc); convertTo3_5_1_38(doc); convertTo3_5_1_39(doc); - fixUIAutomationGroupEnableParameterValue_3_5_1_39(doc); + fixUIAutomationSearchEnableParameterValue_3_5_1_39(doc); convertTo3_5_1_40(doc); convertTo3_5_1_41(doc); convertTo3_5_1_42(doc); @@ -304,15 +403,119 @@ private static XDocument convertOldScript(XDocument doc) convertTo3_5_1_51(doc); convertTo3_5_1_52(doc); convertTo3_5_1_54(doc); - + fixUIAutomationSearchEnableParameterValue_v3_5_1_56(doc); + convertTo3_5_1_56(doc); + convertTo3_5_1_58(doc); + convertTo3_5_1_62(doc); + convertTo3_5_1_72(doc); + convertTo3_5_1_74(doc); + convertTo3_5_1_75(doc, engine); + convertTo3_5_1_77(doc, engine); + convertTo3_5_1_79(doc, engine); + convertTo3_5_1_80(doc); + convertTo3_5_1_81(doc, engine); + convertTo3_5_1_83(doc); + convertTo3_5_1_84(doc); + convertTo3_5_1_86(doc); + convertTo3_5_1_87(doc); + convertTo3_5_1_88(doc); + convertTo3_5_1_89(doc); + convertTo3_5_1_91(doc); + convertTo3_5_1_92(doc); + convertTo3_5_1_93(doc); + convertTo3_5_1_96(doc); + convertTo3_5_1_98(doc); + convertTo3_5_2_0(doc); + convertTo3_5_2_1(doc); return doc; } - private static XDocument convertTo3_5_0_45(XDocument doc) + + private static void fixDataTableSchemaPosition(XDocument doc) + { + // add v3.5.1.55 + + /* before + + + + + + + + + + + + + + + + + + */ + /* after + + + + + + + + + + + + + + + + + */ + + XNamespace nsXs = "http://www.w3.org/2001/XMLSchema"; + var schemas = doc.Descendants(nsXs + "schema"); // get all datatable schema elements () + foreach (var schema in schemas) + { + var elements = schema.Elements(nsXs + "element").ToList(); + // target datatable has two child elements in + if (elements.Count() != 2) + { + continue; + } + var fe = elements[0]; // first remove from parent + fe.Remove(); + + var se = elements[1]; + var choice = se.Element(nsXs + "complexType").Element(nsXs + "choice"); + choice.Element(nsXs + "element").Remove(); // second has . this node is removed + choice.Add(fe); // insert first + } + } + + private static void fixToSameCommandNames(XDocument doc) + { + // add v3.5.1.56 + + XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance"; + + var commands = doc.Descendants("ScriptCommand"); + foreach(var cmd in commands) + { + var commandName = cmd.Attribute("CommandName"); + var xsiType = cmd.Attribute(ns + "type"); + if (commandName.Value != xsiType.Value) + { + xsiType.SetValue(commandName.Value); + } + } + } + + private static void convertTo3_5_0_45(XDocument doc) { // change "Start with" -> "Starts with", "End with" -> "Ends with" ChangeAttributeValue(doc, new Func( el => { - switch (el.Attribute("CommandName").Value) + switch (GetCommandName(el)) { case "ActivateWindowCommand": case "CheckWindowNameExistsCommand": @@ -346,11 +549,9 @@ private static XDocument convertTo3_5_0_45(XDocument doc) // ExcelCreateDataset -> LoadDataTable ChangeCommandName(doc, "ExcelCreateDatasetCommand", "LoadDataTableCommand", "Load DataTable"); - - return doc; } - private static XDocument convertTo3_5_0_46(XDocument doc) + private static void convertTo3_5_0_46(XDocument doc) { // AddToVariable -> AddListItem ChangeCommandName(doc, "AddToVariableCommand", "AddListItemCommand", "Add List Item"); @@ -358,15 +559,14 @@ private static XDocument convertTo3_5_0_46(XDocument doc) // SetVariableIndex -> SetListIndex // stop v3.5.1.40 //ChangeCommandName(doc, "SetVariableIndexCommand", "SetListIndexCommand", "Set List Index"); - - return doc; } - private static XDocument convertTo3_5_0_47(XDocument doc) + + private static void convertTo3_5_0_47(XDocument doc) { // AddListItem.v_userVariableName, SetListIndex.v_userVariableName -> *.v_ListName ChangeAttributeName(doc, new Func(el => { - switch (el.Attribute("CommandName").Value) + switch (GetCommandName(el)) { case "AddListItemCommand": case "SetListIndexCommand": @@ -375,31 +575,29 @@ private static XDocument convertTo3_5_0_47(XDocument doc) return false; } }), "v_userVariableName", "v_ListName"); - - return doc; } - private static XDocument convertTo3_5_0_50(XDocument doc) + + private static void convertTo3_5_0_50(XDocument doc) { // ParseJSONArray -> ConvertJSONToList ChangeCommandName(doc, "ParseJSONArrayCommand", "ConvertJSONToListCommand", "Convert JSON To List"); - return doc; } - private static XDocument convertTo3_5_0_51(XDocument doc) + + private static void convertTo3_5_0_51(XDocument doc) { // GetDataCountRowCommand -> GetDataTableRowCountCommand ChangeCommandName(doc, "GetDataRowCountCommand", "GetDataTableRowCountCommand", "Get DataTable Row Count"); // AddDataRow -> AddDataTableRow ChangeCommandName(doc, "AddDataRowCommand", "AddDataTableRowCommand", "Add DataTable Row"); - - return doc; } - private static XDocument convertTo3_5_0_52(XDocument doc) + + private static void convertTo3_5_0_52(XDocument doc) { // change "Start with" -> "Starts with", "End with" -> "Ends with" ChangeAttributeValue(doc, new Func(el => { - switch(el.Attribute("CommandName").Value) + switch(GetCommandName(el)) { case "GetFilesCommand": case "GetFoldersCommand": @@ -419,9 +617,9 @@ private static XDocument convertTo3_5_0_52(XDocument doc) break; } })); - return doc; } - private static XDocument convertTo3_5_0_57(XDocument doc) + + private static void convertTo3_5_0_57(XDocument doc) { // StringCheckTextCommand -> CheckTextCommand ChangeCommandName(doc, "CheckStringCommand", "CheckTextCommand", "Check Text"); @@ -429,7 +627,7 @@ private static XDocument convertTo3_5_0_57(XDocument doc) // ModifyVariableCommand -> ModifyTextCommand ChangeCommandName(doc, new Func( el => { - switch (el.Attribute("CommandName").Value) + switch (GetCommandName(el)) { case "ModifyVariableCommand": case "StringCaseCommand": @@ -453,11 +651,9 @@ private static XDocument convertTo3_5_0_57(XDocument doc) // TextExtractorCommand -> ExtractionTextCommand ChangeCommandName(doc, "TextExtractorCommand", "ExtractionTextCommand", "Extraction Text"); - - return doc; } - private static XDocument convertTo3_5_0_67(XDocument doc) + private static void convertTo3_5_0_67(XDocument doc) { // GetAElement -> GetAnElement ChangeCommandName(doc, "SeleniumBrowserGetAElementValuesAsListCommand", "SeleniumBrowserGetAnElementValuesAsListCommand", "Get An Element Values As List"); @@ -465,16 +661,14 @@ private static XDocument convertTo3_5_0_67(XDocument doc) ChangeCommandName(doc, "SeleniumBrowserGetAElementValuesAsDictionaryCommand", "SeleniumBrowserGetAnElementValuesAsDictionaryCommand", "Get An Element Values As Dictionary"); ChangeCommandName(doc, "SeleniumBrowserGetAElementValuesAsDataTableCommand", "SeleniumBrowserGetAnElementValuesAsDataTableCommand", "Get An Element Values As DataTable"); - - return doc; } - private static XDocument fixUIAutomationCommandEnableParameterValue(XDocument doc) + private static void fixUIAutomationCommandEnableParameterValue(XDocument doc) { // UI Automation Boolean Fix ChangeTableCellValue(doc, "UIAutomationCommand", "v_UIASearchParameters", "Enabled", new Action(c => { - switch(c.Value.ToLower() ?? "") + switch (c.Value.ToLower()) { case "true": case "false": @@ -483,12 +677,10 @@ private static XDocument fixUIAutomationCommandEnableParameterValue(XDocument do c.SetValue("False"); break; } - })); - - return doc; + }), "False"); } - private static XDocument convertTo3_5_0_73(XDocument doc) + private static void convertTo3_5_0_73(XDocument doc) { var changeFunc = new Action(c => { @@ -502,24 +694,22 @@ private static XDocument convertTo3_5_0_73(XDocument doc) ChangeTableCellValue(doc, new Func(el => { return ( - (el.Attribute("CommandName").Value == "BeginIfCommand") && + (GetCommandName(el) == "BeginIfCommand") && ((el.Attribute("v_IfActionType")?.Value ?? "") == "Web Element Exists") ); - }), "v_IfActionParameterTable", "Parameter_x0020_Name", changeFunc); + }), "v_IfActionParameterTable", "Parameter_x0020_Name", changeFunc, "WebBrowser Instance Name"); // BeginLoop Selenium -> WebBrowser ChangeTableCellValue(doc, new Func(el => { return ( - (el.Attribute("CommandName").Value == "BeginLoopCommand") && + (GetCommandName(el) == "BeginLoopCommand") && ((el.Attribute("v_LoopActionType")?.Value ?? "") == "Web Element Exists") ); - }), "v_LoopActionParameterTable", "Parameter_x0020_Name", changeFunc); - - return doc; + }), "v_LoopActionParameterTable", "Parameter_x0020_Name", changeFunc, "WebBrowser Instance Name"); } - private static XDocument convertTo3_5_0_74(XDocument doc) + private static void convertTo3_5_0_74(XDocument doc) { var changeFunc = new Action(attr => { @@ -539,10 +729,9 @@ private static XDocument convertTo3_5_0_74(XDocument doc) // BeginLoop Value, Variable Compare -> Numeric Compare, Text Compare ChangeAttributeValue(doc, "BeginLoopCommand", "v_LoopActionType", changeFunc); - - return doc; } - private static XDocument convertTo3_5_0_78(XDocument doc) + + private static void convertTo3_5_0_78(XDocument doc) { var modFunc = new Action, string>((table, before, rows, rowName) => { @@ -562,7 +751,7 @@ private static XDocument convertTo3_5_0_78(XDocument doc) // BeginIf add Window Search Method cell parameter ModifyTable(doc, new Func(el => { - if (el.Attribute("CommandName").Value == "BeginIfCommand") + if (GetCommandName(el) == "BeginIfCommand") { switch (el.Attribute("v_IfActionType")?.Value.ToLower() ?? "") { @@ -582,7 +771,7 @@ private static XDocument convertTo3_5_0_78(XDocument doc) // BeginLoop add Window Search Method parameter ModifyTable(doc, new Func(el => { - if (el.Attribute("CommandName").Value == "BeginLoopCommand") + if (GetCommandName(el) == "BeginLoopCommand") { switch (el.Attribute("v_LoopActionType")?.Value.ToLower() ?? "") { @@ -598,16 +787,14 @@ private static XDocument convertTo3_5_0_78(XDocument doc) return false; } }), "v_LoopActionParameterTable", modFunc); - - - return doc; } - private static XDocument fixUIAutomationGroupEnableParameterValue(XDocument doc) + + private static void fixUIAutomationSearchEnableParameterValue(XDocument doc) { // UI Automation Boolean Fix ChangeTableCellValue(doc, new Func(el => { - switch (el.Attribute("CommandName").Value) + switch (GetCommandName(el)) { case "UIAutomationGetChidrenElementsInformationCommand": case "UIAutomationGetChildElementCommand": @@ -618,7 +805,7 @@ private static XDocument fixUIAutomationGroupEnableParameterValue(XDocument doc) } }), "v_SearchParameters", "Enabled", new Action(c => { - switch (c.Value.ToLower()) + switch (c.Value?.ToLower() ?? "") { case "true": case "false": @@ -627,31 +814,25 @@ private static XDocument fixUIAutomationGroupEnableParameterValue(XDocument doc) c.SetValue("False"); break; } - })); - - return doc; + }), "False"); } - private static XDocument convertTo3_5_0_83(XDocument doc) + private static void convertTo3_5_0_83(XDocument doc) { // SMTPSendEmail -> MailKitSendEmail ChangeCommandName(doc, "SMTPCommand", "MailKitSendEmailCommand", "Send Email"); - - return doc; } - private static XDocument convertTo3_5_1_16(XDocument doc) + private static void convertTo3_5_1_16(XDocument doc) { // Parse Json -> Get JSON Value List ChangeCommandName(doc, "ParseJsonCommand", "GetJSONValueListCommand", "Get JSON Value List"); // Parse Json Model -> Get Multi JSON Value List ChangeCommandName(doc, "ParseJsonModelCommand", "GetMultiJSONValueListCommand", "Get Multi JSON Value List"); - - return doc; } - private static XDocument convertTo3_5_1_30(XDocument doc) + private static void convertTo3_5_1_30(XDocument doc) { // AddDataTableRowByDataTableCommand -> AddDataTableRowsByDataTableCommand ChangeCommandName(doc, "AddDataTableRowByDataTableCommand", "AddDataTableRowsByDataTableCommand", "Add DataTable Rows By DataTable"); @@ -673,11 +854,9 @@ private static XDocument convertTo3_5_1_30(XDocument doc) // MailKitGetEMailFromMailListCommand -> MailKitGetEMailFromEMailListCommand ChangeCommandName(doc, "MailKitGetEMailFromMailListCommand", "MailKitGetEMailFromEMailListCommand", "Get EMail From EMailList"); - - return doc; } - private static XDocument convertTo3_5_1_31(XDocument doc) + private static void convertTo3_5_1_31(XDocument doc) { // AddJSONArrayItem -> AddJSONArrayItemCommand ChangeCommandName(doc, "AddJSONArrayItem", "AddJSONArrayItemCommand", "Add JSON Array Item"); @@ -723,33 +902,27 @@ private static XDocument convertTo3_5_1_31(XDocument doc) // ExcelWorksheetInfoCommand -> ExcelGetWorksheetInfoCommand ChangeCommandName(doc, "ExcelWorksheetInfoCommand", "ExcelGetWorksheetInfoCommand", "Get Worksheet Info"); - - return doc; } - private static XDocument convertTo3_5_1_33(XDocument doc) + private static void convertTo3_5_1_33(XDocument doc) { // AddVariableCommand -> NewVariableCommand ChangeCommandName(doc, "AddVariableCommand", "NewVariableCommand", "New Variable"); // VariableCommand -> SetVariableValueCommand ChangeCommandName(doc, "VariableCommand", "SetVariableValueCommand", "Set Variable Value"); - - return doc; } - private static XDocument convertTo3_5_1_34(XDocument doc) + private static void convertTo3_5_1_34(XDocument doc) { // GetLengthCommand -> GetWordLengthCommand ChangeCommandName(doc, "GetLengthCommand", "GetWordLengthCommand", "Get Word Length"); // CreateNumberVariableCommand -> CreateNumericalVariableCommand ChangeCommandName(doc, "CreateNumberVariableCommand", "CreateNumericalVariableCommand", "Create Numerical Variable"); - - return doc; } - private static XDocument convertTo3_5_1_35(XDocument doc) + private static void convertTo3_5_1_35(XDocument doc) { // EnvironmentVariableCommand -> GetEnvironmentVariableCommand ChangeCommandName(doc, "EnvironmentVariableCommand", "GetEnvironmentVariableCommand", "Get Environment Variable"); @@ -785,11 +958,9 @@ private static XDocument convertTo3_5_1_35(XDocument doc) // UnloadTaskCommand -> UnloadScriptFileCommand ChangeCommandName(doc, "UnloadTaskCommand", "UnloadScriptFileCommand", "Unload Script File"); - - return doc; } - private static XDocument convertTo3_5_1_36(XDocument doc) + private static void convertTo3_5_1_36(XDocument doc) { // RunCustomCodeCommand -> RunCSharpCodeCommand ChangeCommandName(doc, "RunCustomCodeCommand", "RunCSharpCodeCommand", "Run CSharp Code"); @@ -829,11 +1000,9 @@ private static XDocument convertTo3_5_1_36(XDocument doc) // SequenceCommand (Display text only) ChangeCommandName(doc, "SequenceCommand", "SequenceCommand", "Sequence"); - - return doc; } - private static XDocument convertTo3_5_1_38(XDocument doc) + private static void convertTo3_5_1_38(XDocument doc) { // GetDataCommand -> GetBotStoreDataCommand ChangeCommandName(doc, "GetDataCommand", "GetBotStoreDataCommand", "Get BotStore Data"); @@ -849,23 +1018,19 @@ private static XDocument convertTo3_5_1_38(XDocument doc) // ExtractFileCommand -> ExtractZipFileCommand ChangeCommandName(doc, "ExtractFileCommand", "ExtractZipFileCommand", "Extract Zip File"); - - return doc; } - private static XDocument convertTo3_5_1_39(XDocument doc) + private static void convertTo3_5_1_39(XDocument doc) { // Format Folder PathCommand -> FormatFolderPathCommand ChangeCommandName(doc, "Format Folder PathCommand", "FormatFolderPathCommand", "Format Folder Path"); - - return doc; } - private static XDocument fixUIAutomationGroupEnableParameterValue_3_5_1_39(XDocument doc) + private static void fixUIAutomationSearchEnableParameterValue_3_5_1_39(XDocument doc) { ChangeTableCellValue(doc, new Func(el => { - switch (el.Attribute("CommandName").Value) + switch (GetCommandName(el)) { case "UIAutomationCheckElementExistCommand": case "UIAutomationWaitForElementExistCommand": @@ -884,11 +1049,10 @@ private static XDocument fixUIAutomationGroupEnableParameterValue_3_5_1_39(XDocu c.SetValue("False"); break; } - })); - return doc; + }), "False"); } - private static XDocument convertTo3_5_1_40(XDocument doc) + private static void convertTo3_5_1_40(XDocument doc) { // OCRCommand -> ExecuteOCR ChangeCommandName(doc, "OCRCommand", "ExecuteOCRCommand", "Execute OCR"); @@ -916,11 +1080,9 @@ private static XDocument convertTo3_5_1_40(XDocument doc) // SendMouseMoveCommand -> MoveMouseCommand ChangeCommandName(doc, "SendMouseMoveCommand", "MoveMouseCommand", "Move Mouse"); - - return doc; } - private static XDocument convertTo3_5_1_41(XDocument doc) + private static void convertTo3_5_1_41(XDocument doc) { // UserInputCommand -> ShowUserInputDialogCommand ChangeCommandName(doc, "UserInputCommand", "ShowUserInputDialogCommand", "Show User Input Dialog"); @@ -954,11 +1116,9 @@ private static XDocument convertTo3_5_1_41(XDocument doc) // NLGSetParameterCommand -> NLGSetNLGParameterCommand ChangeCommandName(doc, "NLGSetParameterCommand", "NLGSetNLGParameterCommand", "Set NLG Parameter"); - - return doc; } - private static XDocument convertTo3_5_1_42(XDocument doc) + private static void convertTo3_5_1_42(XDocument doc) { // HTTPRequestQueryCommand -> HTMLGetHTMLTextByXPath ChangeCommandName(doc, "HTTPRequestQueryCommand", "HTMLGetHTMLTextByXPath", "Get HTML Text By XPath"); @@ -968,11 +1128,9 @@ private static XDocument convertTo3_5_1_42(XDocument doc) // RESTCommand -> HTTPExecuteRESTAPICommand ChangeCommandName(doc, "RESTCommand", "HTTPExecuteRESTAPICommand", "Execute REST API"); - - return doc; } - private static XDocument convertTo3_5_1_44(XDocument doc) + private static void convertTo3_5_1_44(XDocument doc) { // Move/Copy File command -> Move File, Copy File command //var commands = doc.Descendants("ScriptCommand").Where(el => { @@ -981,13 +1139,13 @@ private static XDocument convertTo3_5_1_44(XDocument doc) //}); var commands = GetCommands(doc, new Func(el => { - return (el.Attribute("CommandName").Value == "MoveFileCommand") && + return (GetCommandName(el) == "MoveFileCommand") && (el.Attribute("v_OperationType") != null); })); var moveCommands = commands.Where(el => (el.Attribute("v_OperationType").Value.ToLower() != "copy file")).ToList(); var copyCommands = commands.Where(el => (el.Attribute("v_OperationType").Value.ToLower() == "copy file")).ToList(); - ChangeCommandName(moveCommands, "MoveFileCommand", "Move File"); - ChangeCommandName(copyCommands, "CopyFileCommand", "Copy File"); + ChangeCommandNameProcess(moveCommands, "MoveFileCommand", "Move File"); + ChangeCommandNameProcess(copyCommands, "CopyFileCommand", "Copy File"); foreach(var cmd in commands) { cmd.Attribute("v_OperationType").Remove(); @@ -1005,13 +1163,13 @@ private static XDocument convertTo3_5_1_44(XDocument doc) //}); commands = GetCommands(doc, new Func(el => { - return (el.Attribute("CommandName").Value == "MoveFolderCommand") && + return (GetCommandName(el) == "MoveFolderCommand") && (el.Attribute("v_OperationType") != null); })); moveCommands = commands.Where(el => (el.Attribute("v_OperationType").Value.ToLower() != "copy folder")).ToList(); copyCommands = commands.Where(el => (el.Attribute("v_OperationType").Value.ToLower() == "copy folder")).ToList(); - ChangeCommandName(moveCommands, "MoveFolderCommand", "Move Folder"); - ChangeCommandName(copyCommands, "CopyFolderCommand", "Copy Folder"); + ChangeCommandNameProcess(moveCommands, "MoveFolderCommand", "Move Folder"); + ChangeCommandNameProcess(copyCommands, "CopyFolderCommand", "Copy Folder"); foreach (var cmd in commands) { cmd.Attribute("v_OperationType").Remove(); @@ -1019,17 +1177,15 @@ private static XDocument convertTo3_5_1_44(XDocument doc) // UIAutomationSearchElementFromWindowByXPathCommand -> UIAutomationSearchElementAndWindowByXPathCommand ChangeCommandName(doc, "UIAutomationSearchElementFromWindowByXPathCommand", "UIAutomationSearchElementAndWindowByXPathCommand", "Search Element And Window By XPath"); - - return doc; } - private static XDocument convertTo3_5_1_45(XDocument doc) + private static void convertTo3_5_1_45(XDocument doc) { // FormatFilePathCommand -> ExtractionFilePathCommand ChangeCommandName(doc, "FormatFilePathCommand", "ExtractionFilePathCommand", "Extraction File Path"); - // FormatFolderPathCommnad -> ExtractionFolderPathCommand - ChangeCommandName(doc, "FormatFolderPathCommnad", "ExtractionFolderPathCommand", "Extraction Folder Path"); + // FormatFolderPathCommand -> ExtractionFolderPathCommand + ChangeCommandName(doc, "FormatFolderPathCommand", "ExtractionFolderPathCommand", "Extraction Folder Path"); // FormatColorCommand -> ConvertColorCommand ChangeCommandName(doc, "FormatColorCommand", "ConvertColorCommand", "Convert Color"); @@ -1042,7 +1198,7 @@ private static XDocument convertTo3_5_1_45(XDocument doc) //}); var commands = GetCommands(doc, new Func(el => { - return ((el.Attribute("CommandName").Value == "UIAutomationClickElementCommand") && + return ((GetCommandName(el) == "UIAutomationClickElementCommand") && (el.Attribute("v_ClickType") == null)); })); XNamespace ns = "urn:schemas-microsoft-com:xml-diffgram-v1"; @@ -1090,19 +1246,15 @@ private static XDocument convertTo3_5_1_45(XDocument doc) xpath.Remove(); } } - - return doc; } - private static XDocument convertTo3_5_1_46(XDocument doc) + private static void convertTo3_5_1_46(XDocument doc) { // MoveFolderCommand change dipslay command name ChangeCommandName(doc, "MoveFolderCommand", "MoveFolderCommand", "Move Folder"); - - return doc; } - private static XDocument convertTo3_5_1_48(XDocument doc) + private static void convertTo3_5_1_48(XDocument doc) { // SeleniumBrowserGetAnElementValuesAsDataTableCommand -> SeleniumBrowserGetAnWebElementValuesAsDataTableCommand ChangeCommandName(doc, "SeleniumBrowserGetAnElementValuesAsDataTableCommand", "SeleniumBrowserGetAnWebElementValuesAsDataTableCommand", "Get An WebElement Values As DataTable"); @@ -1124,11 +1276,9 @@ private static XDocument convertTo3_5_1_48(XDocument doc) // SeleniumBrowserGetElementsValuesAsDataTableCommand -> SeleniumBrowserGetWebElementsValuesAsDataTableCommand ChangeCommandName(doc, "SeleniumBrowserGetElementsValuesAsDataTableCommand", "SeleniumBrowserGetWebElementsValuesAsDataTableCommand", "Get WebElements Values As DataTable"); - - return doc; } - private static XDocument convertTo3_5_1_49(XDocument doc) + private static void convertTo3_5_1_49(XDocument doc) { // SeleniumBrowserElementActionCommand -> SeleniumBrowserWebElementActionCommand ChangeCommandName(doc, "SeleniumBrowserElementActionCommand", "SeleniumBrowserWebElementActionCommand", "WebElement Action"); @@ -1198,7 +1348,10 @@ private static XDocument convertTo3_5_1_49(XDocument doc) y = rows[i].Element("Parameter_x0020_Value").Value; } rows[i].Remove(); - beforeRows[i].Remove(); + if (i < beforeRows.Count) // rare case diffgram:before is null + { + beforeRows[i].Remove(); + } } string click = ""; switch (act) @@ -1253,7 +1406,10 @@ private static XDocument convertTo3_5_1_49(XDocument doc) { cmd.SetAttributeValue("v_WaitTime", rows[i].Element("Parameter_x0020_Value").Value); rows[i].Remove(); - beforeRows[i].Remove(); + if (i < beforeRows.Count) // rare case diffgram:before is null + { + beforeRows[i].Remove(); + } break; } } @@ -1262,17 +1418,15 @@ private static XDocument convertTo3_5_1_49(XDocument doc) if (currentRows == 0) { table.Remove(); - before.Remove(); + before?.Remove(); // rare case diffgram:before is null } break; } } - - return doc; } - private static XDocument convertTo3_5_1_50(XDocument doc) + private static void convertTo3_5_1_50(XDocument doc) { // WebElement Action: Wait For WebElement To Exists // WebElement Action: fix parameter table @@ -1293,11 +1447,9 @@ private static XDocument convertTo3_5_1_50(XDocument doc) before.Remove(); } } - - return doc; } - private static XDocument convertTo3_5_1_51(XDocument doc) + private static void convertTo3_5_1_51(XDocument doc) { // UIAutomationCheckElementExistByXPathCommand -> UIAutomationCheckUIElementExistByXPathCommand ChangeCommandName(doc, "UIAutomationCheckElementExistByXPathCommand", "UIAutomationCheckUIElementExistByXPathCommand", "Check UIElement Exist By XPath"); @@ -1374,7 +1526,7 @@ private static XDocument convertTo3_5_1_51(XDocument doc) // UIAutomationCommand -> UIAutomationUIElementActionCommand ChangeCommandName(doc, "UIAutomationCommand", "UIAutomationUIElementActionCommand", "UIElement Action"); - // UIAutomationUIElementActionCommand : UIElement Action name + // UIAutomationUIElementActionCommand : UIElement Action name, v_WindowName to Attribute var cmds = GetCommands(doc, "UIAutomationUIElementActionCommand"); foreach(var cmd in cmds) { @@ -1423,12 +1575,19 @@ private static XDocument convertTo3_5_1_51(XDocument doc) { cmd.SetAttributeValue("v_AutomationType", newAct); } + + var winNameElem = cmd.Element("v_WindowName"); + if (winNameElem != null) + { + cmd.SetAttributeValue("v_WindowName", winNameElem.Value); + winNameElem.Remove(); + } } // WebElementAction: Set Text (Encrypted Text param) cmds = GetCommands(doc, new Func((el) => { - return (el.Attribute("CommandName").Value == "SeleniumBrowserWebElementActionCommand") && + return (GetCommandName(el) == "SeleniumBrowserWebElementActionCommand") && (el.Attribute("v_SeleniumElementAction").Value.ToLower() == "set text"); })); foreach(var cmd in cmds) @@ -1456,11 +1615,9 @@ private static XDocument convertTo3_5_1_51(XDocument doc) } } } - - return doc; } - private static XDocument convertTo3_5_1_52(XDocument doc) + private static void convertTo3_5_1_52(XDocument doc) { // SeleniumBrowserWaitForWebElementExistCommand -> SeleniumBrowserWaitForWebElementToExistsCommand ChangeCommandName(doc, "SeleniumBrowserWaitForWebElementExistCommand", "SeleniumBrowserWaitForWebElementToExistsCommand", "Wait For WebElement To Exists"); @@ -1481,7 +1638,7 @@ private static XDocument convertTo3_5_1_52(XDocument doc) //ChangeCommandName(doc, "ExcelCreateApplicationCommand", "ExcelCreateExcelInstanceCommand", "Create Excel Instance"); ChangeCommandName(doc, new Func((el) => { - switch (el.Attribute("CommandName").Value) + switch (GetCommandName(el)) { case "ExcelCreateApplicationCommand": case "ExcelOpenApplicationCommand": @@ -1530,7 +1687,7 @@ private static XDocument convertTo3_5_1_52(XDocument doc) // UIAutomationUIElementAction: Get Value From UIElement -> Get Property Value From UIElement ChangeAttributeValue(doc, new Func((el) => { - return (el.Attribute("CommandName").Value == "UIAutomationUIElementActionCommand") && + return (GetCommandName(el) == "UIAutomationUIElementActionCommand") && (el.Attribute("v_AutomationType").Value.ToLower() == "get value from uielement"); }), "v_AutomationType", new Action((attr) => { @@ -1541,7 +1698,7 @@ private static XDocument convertTo3_5_1_52(XDocument doc) // UIAutomationUIElementAction: Get Property Value From UIElement parameter var cmds = GetCommands(doc, new Func((el) => { - return (el.Attribute("CommandName").Value == "UIAutomationUIElementActionCommand") && + return (GetCommandName(el) == "UIAutomationUIElementActionCommand") && (el.Attribute("v_AutomationType").Value.ToLower() == "get property value from uielement"); })); foreach (var cmd in cmds) @@ -1561,7 +1718,7 @@ private static XDocument convertTo3_5_1_52(XDocument doc) // UIAutomationUIElementAction: Click UIElement cmds = GetCommands(doc, new Func((el) => { - return (el.Attribute("CommandName").Value == "UIAutomationUIElementActionCommand") && + return (GetCommandName(el) == "UIAutomationUIElementActionCommand") && (el.Attribute("v_AutomationType").Value.ToLower() == "click uielement"); })); foreach (var cmd in cmds) @@ -1580,11 +1737,9 @@ private static XDocument convertTo3_5_1_52(XDocument doc) } } } - - return doc; } - private static XDocument convertTo3_5_1_54(XDocument doc) + private static void convertTo3_5_1_54(XDocument doc) { // UIAutomationUIElementActionCommand : tablename ChangeTableColumnNames(doc, "UIAutomationUIElementActionCommand", "v_UIASearchParameters", @@ -1592,125 +1747,1833 @@ private static XDocument convertTo3_5_1_54(XDocument doc) { ("Parameter_x0020_Name", "ParameterName"), ("Parameter_x0020_Value", "ParameterValue"), - }); - - return doc; + } + ); } - - /// - /// get specfied commands - /// - /// - /// - /// - private static IEnumerable GetCommands(XDocument doc, Func searchFunc) + private static void fixUIAutomationSearchEnableParameterValue_v3_5_1_56(XDocument doc) { - return doc.Descendants("ScriptCommand").Where(searchFunc); + var changeFunc = new Action(e => + { + switch (e.Value.ToLower()) + { + case "true": + case "false": + break; + default: + e.SetValue("False"); + break; + } + }); + + ChangeTableCellValue(doc, new Func(el => + { + switch (GetCommandName(el)) + { + case "UIAutomationCheckUIElementExistCommand": + case "UIAutomationGetChildrenUIElementsInformationCommand": + case "UIAutomationSearchChildUIElementCommand": + case "UIAutomationSearchUIElementAndWindowCommand": + case "UIAutomationSearchUIElementFromUIElementCommand": + case "UIAutomationWaitForUIElementToExistsCommand": + return true; + default: + return false; + } + }), "v_SearchParameters", "Enabled", changeFunc, "False"); + + ChangeTableCellValue(doc, "UIAutomationUIElementActionCommand", "v_UIASearchParameters", "Enabled", changeFunc, "False"); } - /// - /// get specified commands - /// - /// - /// - /// - private static IEnumerable GetCommands(XDocument doc, string commandName) + private static void convertTo3_5_1_56(XDocument doc) { - return GetCommands(doc, new Func(el => el.Attribute("CommandName").Value == commandName)); + // WordOpenApplicationCommand -> WordCreateWordInstanceCommand + ChangeCommandName(doc, "WordOpenApplicationCommand", "WordCreateWordInstanceCommand", "Create Word Insntance"); } - /// - /// change command name to specified commands - /// - /// - /// - /// - private static void ChangeCommandName(IEnumerable commands, string newName, string newSelectioName) + private static void convertTo3_5_1_58(XDocument doc) { - XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance"; - foreach (var cmd in commands) - { - cmd.SetAttributeValue("CommandName", newName); - cmd.SetAttributeValue(ns + "type", newName); - cmd.SetAttributeValue("SelectionName", newSelectioName); - } + // MailKitGetEmailAttachmentsNameCommand -> MailKitGetEMailAttachmentsNameCommand + ChangeCommandName(doc, "MailKitGetEmailAttachmentsNameCommand", "MailKitGetEMailAttachmentsNameCommand", "Get EMail Attachments Name"); + + // MailKitLoadEmailCommand -> MailKitLoadEMailCommand + ChangeCommandName(doc, "MailKitLoadEmailCommand", "MailKitLoadEMailCommand", "Load EMail"); + + // MailKitRecieveEmailListUsingIMAPCommand -> MailKitRecieveEMailListUsingIMAPCommand + ChangeCommandName(doc, "MailKitRecieveEmailListUsingIMAPCommand", "MailKitRecieveEMailListUsingIMAPCommand", "Recieve EMailList Using IMAP"); + + // MailKitRecieveEmailListUsingPOPCommand -> MailKitRecieveEMailListUsingPOPCommand + ChangeCommandName(doc, "MailKitRecieveEmailListUsingPOPCommand", "MailKitRecieveEMailListUsingPOPCommand", "Recieve EMailList Using POP"); + + // MailKitSaveEmailAttachmentsCommand -> MailKitSaveEMailAttachmentsCommand + ChangeCommandName(doc, "MailKitSaveEmailAttachmentsCommand", "MailKitSaveEMailAttachmentsCommand", "Save EMail Attachments"); + + // MailKitSaveEmailCommand -> MailKitSaveEMailCommand + ChangeCommandName(doc, "MailKitSaveEmailCommand", "MailKitSaveEMailCommand", "Save EMail"); + + // MailKitSendEmailCommand -> MailKitSendEMailCommand + ChangeCommandName(doc, "MailKitSendEmailCommand", "MailKitSendEMailCommand", "Send EMail"); } - /// - /// change command name. target commands are searched by specified Func<> - /// - /// - /// - /// - /// - /// - private static XDocument ChangeCommandName(XDocument doc, Func searchFunc, string newName, string newSelectioName) + private static void convertTo3_5_1_62(XDocument doc) { - IEnumerable commands = doc.Descendants("ScriptCommand").Where(searchFunc); - //XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance"; - //foreach (var cmd in commands) - //{ - // cmd.SetAttributeValue("CommandName", newName); - // cmd.SetAttributeValue(ns + "type", newName); - // cmd.SetAttributeValue("SelectionName", newSelectioName); - //} - ChangeCommandName(commands, newName, newSelectioName); - return doc; + // CreateTextVariable -> CreateTextVariableCommand + ChangeCommandName(doc, "CreateTextVariable", "CreateTextVariableCommand", "Create Text Variable"); } - /// - /// change command name. a target command is specified command name. - /// - /// - /// - /// - /// - /// - private static XDocument ChangeCommandName(XDocument doc, string targetName, string newName, string newSelectioName) + private static void convertTo3_5_1_72(XDocument doc) { - return ChangeCommandName(doc, new Func(el => + var macroCommands = new List(); + var cmds = GetCommands(doc, "ExcelAddWorkbookCommand"); + foreach (var cmd in cmds) { - return (el.Attribute("CommandName").Value == targetName); - }), newName, newSelectioName); - } + var vMacro = cmd.Attribute("v_MacroName"); + if (vMacro != null) + { + macroCommands.Add(cmd); + } + } - /// - /// change attribute value. target commands are searched by specified Func<> - /// - /// - /// - /// - /// - /// - private static XDocument ChangeAttributeValue(XDocument doc, Func searchFunc, string targetAttribute, Action changeFunc) - { - IEnumerable commands = doc.Descendants("ScriptCommand") - .Where(searchFunc); - foreach(var cmd in commands) + if (cmds.Count() > 0) { - changeFunc(cmd.Attribute(targetAttribute)); + ChangeCommandNameProcess(macroCommands, "ExcelRunMacroCommand", "Run Macro"); } - return doc; } - /// - /// change attribute value. target commands are specified command name - /// - /// - /// - /// - /// - /// - private static XDocument ChangeAttributeValue(XDocument doc, string targetCommand, string targetAttribute, Action changeFunc) + private static void convertTo3_5_1_74(XDocument doc) { - return ChangeAttributeValue(doc, new Func(el => - { - return (el.Attribute("CommandName").Value == targetCommand); - }), targetAttribute, changeFunc); - } + ChangeAttributeName(doc, "WaitForWindowToExistsCommand", "v_LengthToWait", "v_WaitTime"); + ChangeAttributeName(doc, "GetWindowHandleFromWindowNameCommand", "v_WindowHandle", "v_HandleResult"); - /// + //var getWinPositionCommandsSearch = new Func(el => + //{ + // switch (el.Attribute("CommandName").Value) + // { + // case "GetWindowPositionCommand": + // case "GetWindowPositionFromWindowHandleCommand": + // return true; + // default: + // return false; + // } + //}); + //ChangeAttributeName(doc, getWinPositionCommandsSearch, "v_VariablePositionX", "v_XPosition"); + //ChangeAttributeName(doc, getWinPositionCommandsSearch, "v_VariablePositionY", "v_YPosition"); + + ChangeMultiAttributeNames(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "GetWindowPositionCommand": + case "GetWindowPositionFromWindowHandleCommand": + return true; + default: + return false; + } + }), + new List<(string, string)>() + { + ("v_VariablePositionX", "v_XPosition"), + ("v_VariablePositionY", "v_YPosition"), + } + ); + + ChangeAttributeName(doc, "GetWindowSizeCommand", "v_With", "v_Width"); + + //var moveWinPositionCommandsSearch = new Func(el => + //{ + // switch (el.Attribute("CommandName").Value) + // { + // case "MoveWindowCommand": + // case "MoveWindowByWindowHandleCommand": + // return true; + // default: + // return false; + // } + //}); + //ChangeAttributeName(doc, moveWinPositionCommandsSearch, "v_XWindowPosition", "v_XPosition"); + //ChangeAttributeName(doc, moveWinPositionCommandsSearch, "v_YWindowPosition", "v_YPosition"); + + ChangeMultiAttributeNames(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "MoveWindowCommand": + case "MoveWindowByWindowHandleCommand": + return true; + default: + return false; + } + }), + new List<(string, string)>() + { + ("v_XWindowPosition", "v_XPosition"), + ("v_YWindowPosition", "v_YPosition"), + } + ); + + //var resizeWinPositionCommandsSearch = new Func(el => + //{ + // switch (el.Attribute("CommandName").Value) + // { + // case "ResizeWindowCommand": + // case "ResizeWindowByWindowHandleCommand": + // return true; + // default: + // return false; + // } + //}); + //ChangeAttributeName(doc, resizeWinPositionCommandsSearch, "v_XWindowSize", "v_Width"); + //ChangeAttributeName(doc, resizeWinPositionCommandsSearch, "v_YWindowSize", "v_Height"); + + ChangeMultiAttributeNames(doc, new Func(el => + { + switch (GetCommandName(el)) + { + case "ResizeWindowCommand": + case "ResizeWindowByWindowHandleCommand": + return true; + default: + return false; + } + }), + new List<(string, string)>() + { + ("v_XWindowSize", "v_Width"), + ("v_YWindowSize", "v_Height"), + } + ); + + ChangeAttributeName(doc, "GetWindowStateCommand", "v_UserVariableName", "v_WindowState"); + ChangeAttributeName(doc, "GetWindowStateFromWindowHandleCommand", "v_Result", "v_WindowState"); + } + + private static void convertTo3_5_1_75(XDocument doc, EngineSettings engine) + { + //string oldKW; + //string newKW; + //if (engine.ExportIntermediateXML) + //{ + // oldKW = IntermediateControls.GetWrappedIntermediateKeyword("%kwd_current_window%"); + // newKW = IntermediateControls.GetWrappedIntermediateVariable(SystemVariables.Window_CurrentWindowName.VariableName); + //} + //else + //{ + // oldKW = engine.CurrentWindowKeyword; + // newKW = string.Concat(engine.VariableStartMarker, SystemVariables.Window_CurrentWindowName.VariableValue, engine.VariableEndMarker); + //} + (var oldKW, var newKW) = GetOldNewCurrentWindow(engine); + + // keyword "Current Window" -> {Window.CurrentWindowName} + ChangeAttributeValue(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ActivateWindowCommand": + case "CheckWindowNameExistsCommand": + case "CloseWindowCommand": + case "GetProcessNameFromWindowNameCommand": + case "GetWindowNamesCommand": + case "GetWindowPositionCommand": + case "GetWindowSizeCommand": + case "GetWindowStateCommand": + case "MoveWindowCommand": + case "ResizeWindowCommand": + case "SetWindowStateCommand": + case "WaitForWindowToExistsCommand": + return true; + default: + return false; + } + }), "v_WindowName", + new Action(attr => + { + if (attr.Value == oldKW) + { + attr.SetValue(newKW); + } + }) + ); + + // SendAdvancedKeyStrokesCommand strange element "v_KeyUpDefault" + var cmds = GetCommands(doc, "SendAdvancedKeyStrokesCommand"); + foreach(var cmd in cmds) + { + var elem = cmd.Element("v_KeyUpDefault"); + var attr = cmd.Attribute("v_KeyUpDefault"); + + // attribute v_KeyUpDefault not exists + if (attr == null) + { + //if (elem != null) + //{ + // cmd.SetAttributeValue("v_KeyUpDefault", elem.Value ?? ""); + //} + //else + //{ + // cmd.SetAttributeValue("v_KeyUpDefault", ""); + //} + cmd.SetAttributeValue("v_KeyUpDefault", elem?.Value ?? ""); + } + + elem?.Remove(); + } + + // TakeScreenShot attr v_ScreenshotWindowName -> v_WindowName + ChangeAttributeName(doc, "TakeScreenshotCommand", "v_ScreenshotWindowName", "v_WindowName"); + } + + private static void convertTo3_5_1_77(XDocument doc, EngineSettings engine) + { + //var oldKW = IntermediateControls.GetWrappedIntermediateKeyword("%kwd_current_window%"); + //var newKW = IntermediateControls.GetWrappedIntermediateVariable(SystemVariables.Window_CurrentWindowName.VariableName); + (var oldKW, var newKW) = GetOldNewCurrentWindow(engine); + + // keyword "Current Window" -> {Window.CurrentWindowName} + ChangeAttributeValue(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "TakeScreenshotCommand": + case "EnterKeysCommand": + case "EnterShortcutKeyCommand": + case "SendAdvancedKeyStrokesCommand": + case "UIAutomationSearchUIElementAndWindowByXPathCommand": + case "UIAutomationSearchUIElementAndWindowCommand": + case "UIAutomationSearchUIElementFromWindowCommand": + case "UIAutomationUIElementActionByXPathCommand": + case "UIAutomationUIElementActionCommand": + return true; + default: + return false; + } + }), "v_WindowName", + new Action(attr => + { + if (attr.Value == oldKW) + { + attr.SetValue(newKW); + } + }) + ); + + // v_WaitTime -> v_WaitTimeForWindow (Window Commands group) + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ActivateWindowByWindowHandleCommand": + case "ActivateWindowCommand": + case "CheckWindowHandleExistsCommand": + case "CheckWindowNameExistsCommand": + case "CloseWindowByWindowHandle": + case "CloseWindowCommand": + case "GetProcessNameFromWindowHandleCommand": + case "GetProcessNameFromWindowNameCommand": + case "GetWindowHandleFromWindowNameCommand": + case "GetWindowNameFromWindowHandleCommand": + case "GetWindowNamesCommand": + case "GetWindowPositionCommand": + case "GetWindowPositionFromWindowHandleCommand": + case "GetWindowSizeCommand": + case "GetWindowSizeFromWindowHandleCommand": + case "GetWindowStateCommand": + case "GetWindowStateFromWindowHandleCommand": + case "MoveWindowByWindowHandleCommand": + case "MoveWindowCommand": + case "ResizeWindowByWindowHandleCommand": + case "ResizeWindowCommand": + case "SetWindowStateByWindowHandleCommand": + case "SetWindowStateCommand": + case "WaitForWindowToExistsCommand": + return true; + default: + return false; + } + }), "v_WaitTime", "v_WaitTimeForWindow" + ); + + // v_WaitForWindow -> v_WaitTimeForWindow (KeyMouse, Image) + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + // Image + case "TakeScreenshotCommand": + // KeyMouse + case "EnterKeysCommand": + case "EnterShortcutKeyCommand": + case "SendAdvancedKeyStrokesCommand": + return true; + default: + return false; + } + }), "v_WaitForWindow", "v_WaitTimeForWindow" + ); + + // v_WindowWaitTime -> v_WaitForWindow (UIAutomation) + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "UIAutomationSearchUIElementAndWindowByXPathCommand": + case "UIAutomationSearchUIElementAndWindowCommand": + case "UIAutomationSearchUIElementFromWindowCommand": + case "UIAutomationUIElementActionByXPathCommand": + case "UIAutomationUIElementActionCommand": + return true; + default: + return false; + } + }), "v_WindowWaitTime", "v_WaitTimeForWindow" + ); + + // v_SearchMethod -> v_CompareMethod (Window, Image, KeyMouse, UIAutomation) + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + // Window + case "ActivateWindowCommand": + case "CheckWindowNameExistsCommand": + case "CloseWindowCommand": + case "GetProcessNameFromWindowNameCommand": + case "GetWindowHandleFromWindowNameCommand": + case "GetWindowNamesCommand": + case "GetWindowPositionCommand": + case "GetWindowSizeCommand": + case "GetWindowStateCommand": + case "MoveWindowCommand": + case "ResizeWindowCommand": + case "SetWindowStateCommand": + case "WaitForWindowToExistsCommand": + // Image + case "TakeScreenshotCommand": + // KeyMouse + case "EnterKeysCommand": + case "EnterShortcutKeyCommand": + case "SendAdvancedKeyStrokesCommand": + // UIAutomation + case "UIAutomationSearchUIElementAndWindowByXPathCommand": + case "UIAutomationSearchUIElementAndWindowCommand": + case "UIAutomationSearchUIElementFromWindowCommand": + case "UIAutomationUIElementActionByXPathCommand": + case "UIAutomationUIElementActionCommand": + return true; + default: + return false; + } + }), "v_SearchMethod", "v_CompareMethod" + ); + } + + private static void convertTo3_5_1_79(XDocument doc, EngineSettings engine) + { + // change v_XPosition, v_YPosition keyword + //var oldPosition = IntermediateControls.GetWrappedIntermediateKeyword("%kwd_current_position%"); + //var newPosition = IntermediateControls.GetWrappedIntermediateVariable(SystemVariables.Window_CurrentPosition.VariableName); + (var oldPosition, var newPosition) = GetOldNewKeyword("%kwd_current_position%", engine.CurrentWindowPositionKeyword, SystemVariables.Window_CurrentPosition, engine); + + //var oldXPosition = IntermediateControls.GetWrappedIntermediateKeyword("%kwd_current_xposition%"); + //var newXPosition = IntermediateControls.GetWrappedIntermediateVariable(SystemVariables.Window_CurrentXPosition.VariableName); + (var oldXPosition, var newXPosition) = GetOldNewKeyword("%kwd_current_xposition%", engine.CurrentWindowXPositionKeyword, SystemVariables.Window_CurrentXPosition, engine); + + //var oldYPosition = IntermediateControls.GetWrappedIntermediateKeyword("%kwd_current_yposition%"); + //var newYPosition = IntermediateControls.GetWrappedIntermediateVariable(SystemVariables.Window_CurrentYPosition.VariableName); + (var oldYPosition, var newYPosition) = GetOldNewKeyword("%kwd_current_yposition%", engine.CurrentWindowYPositionKeyword, SystemVariables.Window_CurrentYPosition, engine); + + var changeAction = new Action(attr => + { + var v = attr.Value; + if (v == oldPosition) + { + attr.SetValue(newPosition); + } + else if (v == oldXPosition) + { + attr.SetValue(newXPosition); + } + else if (v == oldYPosition) + { + attr.SetValue(newYPosition); + } + }); + + ChangeAttributeValue(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "MoveWindowCommand": + case "MoveWindowByWindowHandleCommand": + return true; + default: + return false; + } + }), "v_XPosition", changeAction + ); + + ChangeAttributeValue(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "MoveWindowCommand": + case "MoveWindowByWindowHandleCommand": + return true; + default: + return false; + } + }), "v_YPosition", changeAction + ); + } + + private static void convertTo3_5_1_80(XDocument doc) + { + // Copy Worksheet + //ChangeAttributeName(doc, "ExcelCopyWorksheetCommand", "v_sourceSheet", "v_TargetSheetName"); + //ChangeAttributeName(doc, "ExcelCopyWorksheetCommand", "v_newSheetName", "v_NewSheetName"); + ChangeMultiAttributeNames(doc, "ExcelCopyWorksheetCommand", + new List<(string, string)>() + { + ("v_sourceSheet", "v_TargetSheetName"), + ("v_newSheetName", "v_NewSheetName"), + } + ); + + // Rename Worksheet + //ChangeAttributeName(doc, "ExcelRenameWorksheetCommand", "v_sourceSheet", "v_TargetSheetName"); + //ChangeAttributeName(doc, "ExcelRenameWorksheetCommand", "v_newName", "v_NewSheetName"); + ChangeMultiAttributeNames(doc, "ExcelRenameWorksheetCommand", + new List<(string, string)>() + { + ("v_sourceSheet", "v_TargetSheetName"), + ("v_newName", "v_NewSheetName"), + } + ); + + // Activate Sheet -> Activate Worksheet + ChangeCommandName(doc, "ExcelActivateSheetCommand", "ExcelActivateWorksheetCommand", "Activate Worksheet"); + + // ExcelGetWorksheetsCommand v_SearchMethod -> v_CompareMethod + ChangeAttributeName(doc, "ExcelGetWorksheetsCommand", "v_SearchMethod", "v_CompareMethod"); + // change v_CompareMethod value + ChangeAttributeValue(doc, "ExcelGetWorksheetsCommand", "v_CompareMethod", + new Action(attr => + { + var v = attr.Value.ToLower(); + switch (v) + { + case "start with": + attr.SetValue("Starts with"); + break; + case "end with": + attr.SetValue("Ends with"); + break; + } + }) + ); + } + + private static void convertTo3_5_1_81(XDocument doc, EngineSettings engine) + { + //var oldCurrent = IntermediateControls.GetWrappedIntermediateKeyword("%kwd_current_worksheet%"); + //var newCurrent = IntermediateControls.GetWrappedIntermediateVariable(SystemVariables.Excel_CurrentWorkSheet.VariableName); + (var oldCurrent, var newCurrent) = GetOldNewKeyword("%kwd_current_worksheet%", engine.CurrentWorksheetKeyword, SystemVariables.Excel_CurrentWorkSheet, engine); + + //var oldNext = IntermediateControls.GetWrappedIntermediateKeyword("%kwd_next_worksheet%"); + //var newNext = IntermediateControls.GetWrappedIntermediateVariable(SystemVariables.Excel_NextWorkSheet.VariableName); + (var oldNext, var newNext) = GetOldNewKeyword("%kwd_next_worksheet%", engine.NextWorksheetKeyword, SystemVariables.Excel_NextWorkSheet, engine); + + //var oldPrevious = IntermediateControls.GetWrappedIntermediateKeyword("%kwd_previous_worksheet%"); + //var newPrevious = IntermediateControls.GetWrappedIntermediateVariable(SystemVariables.Excel_PreviousWorkSheet.VariableName); + (var oldPrevious, var newPrevious) = GetOldNewKeyword("%kwd_previous_worksheet%", engine.PreviousWorksheetKeyword, SystemVariables.Excel_PreviousWorkSheet, engine); + + var changeAction = new Action(attr => + { + var v = attr.Value; + if (v == oldCurrent) + { + attr.SetValue(newCurrent); + } + else if (v == oldNext) + { + attr.SetValue(newNext); + } + else if (v == oldPrevious) + { + attr.SetValue(newPrevious); + } + }); + + // ExcelActivateWorksheetCommand + ChangeAttributeValue(doc, "ExcelActivateWorksheetCommand", "v_SheetName", changeAction); + + ChangeAttributeValue(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ExcelCopyWorksheetCommand": + case "ExcelRenameWorksheetCommand": + return true; + default: + return false; + } + }), "v_TargetSheetName", changeAction + ); + + // Add Worksheet command v_SheetName + ChangeAttributeName(doc, "ExcelAddWorksheetCommand", "v_NewSheetName", "v_SheetName"); + + // change attribute v_applyToVariable -> v_Result + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ExcelCheckWorksheetExistsCommand": + case "ExcelGetCurrentWorksheetCommand": + case "ExcelGetExcelInfoCommand": + case "ExcelGetWorksheetInfoCommand": + case "ExcelGetWorksheetsCommand": + return true; + default: + return false; + } + }), + "v_applyToVariable", "v_Result" + ); + + // change attribute v_applyToVariableName -> v_Result + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ExcelCheckExcelInstanceExistsCommand": + case "ExcelGetLastRowCommand": + return true; + default: + return false; + } + }), + "v_applyToVariableName", "v_Result" + ); + + // change attribute v_userVariableName -> v_Result + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ExcelCheckCellValueExistsCommand": + case "ExcelCheckCellValueExistsRCCommand": + case "ExcelGetCellCommand": + case "ExcelGetCellRCCommand": + case "ExcelGetColumnValuesAsDataTableCommand": + case "ExcelGetColumnValuesAsDictionaryCommand": + case "ExcelGetColumnValuesAsListCommand": + case "ExcelGetRangeValuesAsDataTableCommand": + case "ExcelGetRowValuesAsDataTableCommand": + case "ExcelGetRowValuesAsDictionaryCommand": + case "ExcelGetRowValuesAsListCommand": + return true; + default: + return false; + } + }), + "v_userVariableName", "v_Result" + ); + + // change attribute v_ExcelCellAddress -> v_CellLocation + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ExcelCheckCellValueExistsCommand": + case "ExcelGetCellCommand": + case "ExcelSetCellCommand": + return true; + default: + return false; + } + }), + "v_ExcelCellAddress", "v_CellLocation" + ); + + // ExcelGetCellRCCommand, ExcelSetCellRCCommand attributes v_CellRow, v_CellColumn + //var searchFunc = new Func(el => + //{ + // switch (el.Attribute("CommandName").Value) + // { + // case "ExcelGetCellRCCommand": + // case "ExcelSetCellRCCommand": + // return true; + // default: + // return false; + // } + //}); + //ChangeAttributeName(doc, searchFunc, "v_ExcelCellRow", "v_CellRow"); + //ChangeAttributeName(doc, searchFunc, "v_ExcelCellColumn", "v_CellColumn"); + ChangeMultiAttributeNames(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ExcelGetCellRCCommand": + case "ExcelSetCellRCCommand": + return true; + default: + return false; + } + }), + new List<(string, string)>() + { + ("v_ExcelCellRow", "v_CellRow"), + ("v_ExcelCellColumn", "v_CellColumn"), + } + ); + } + + private static void convertTo3_5_1_83(XDocument doc) + { + // ExcelSetRowValuesFromDataTableCommand, ExcelSetColumnValuesFromDataTableCommand v_WhenItemNotEnough + ChangeAttributeName(doc, + new Func(el => { + switch (GetCommandName(el)) + { + case "ExcelSetRowValuesFromDataTableCommand": + case "ExcelSetColumnValuesFromDataTableCommand": + return true; + default: + return false; + } + + }), "v_IfDataTableNotEnough", "v_WhenItemNotEnough"); + + // ExcelSetRowValuesFromDictionaryCommand, ExcelSetColumnValuesFromDictionaryCommand v_WhenItemNotEnough + ChangeAttributeName(doc, + new Func(el => { + switch (GetCommandName(el)) + { + case "ExcelSetRowValuesFromDictionaryCommand": + case "ExcelSetColumnValuesFromDictionaryCommand": + return true; + default: + return false; + } + }), "v_IfDictionaryNotEnough", "v_WhenItemNotEnough"); + + // ExcelSetRowValuesFromListCommand, ExcelSetColumnValuesFromListCommand v_WhenItemNotEnough + ChangeAttributeName(doc, + new Func(el => { + switch (GetCommandName(el)) + { + case "ExcelSetRowValuesFromListCommand": + case "ExcelSetColumnValuesFromListCommand": + return true; + default: + return false; + } + }), "v_IfListNotEnough", "v_WhenItemNotEnough"); + + // ExcelSetRowValuesFromDataTableCommand v_RowIndex + ChangeAttributeName(doc, "ExcelSetRowValuesFromDataTableCommand", "v_ExcelRowIndex", "v_RowIndex"); + + // ExcelSetColumnValuesFromDataTableCommand v_ColumnIndex + ChangeAttributeName(doc, "ExcelSetColumnValuesFromDataTableCommand", "v_ExcelColumnIndex", "v_ColumnIndex"); + + // ExcelDeleteCellCommand v_CellLocation + ChangeAttributeName(doc, "ExcelDeleteCellCommand", "v_Range", "v_CellLocation"); + + // ExcelDeleteRowCommand v_RowIndex + ChangeAttributeName(doc, "ExcelDeleteRowCommand", "v_RowNumber", "v_RowIndex"); + + // ExcelDeleteCellCommand, ExcelDeleteRowCommand v_Shift + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ExcelDeleteCellCommand": + case "ExcelDeleteRowCommand": + return true; + default: + return false; + } + }), "v_ShiftUp", "v_Shift"); + + // ExcelGetLastRowCommand v_ColumnIndex + ChangeAttributeName(doc, "ExcelGetLastRowCommand", "v_ColumnLetter", "v_ColumnIndex"); + } + + private static void convertTo3_5_1_84(XDocument doc) + { + // ConvertDateTimeToExcelSerialCommand v_Result + ChangeAttributeName(doc, "ConvertDateTimeToExcelSerialCommand", "v_Serial", "v_Result"); + + // GetDataRowCommand -> ConvertDataTableRowToDictioanryCommand + ChangeToOtherCommand(doc, "GetDataRowCommand", "ConvertDataTableRowToDictionaryCommand", "Convert DataTable Row To Dictionary", + new List<(string, string)>() + { + ("v_UserVariableName", "v_OutputVariableName"), + } + ); + + // GetDataRowValueCommand + // GetDataRowValueCommand attribute v_Option value + // GetDataRowValueCommand -> GetDictionaryValueCommand + ChangeToOtherCommand(doc, "GetDataRowValueCommand", "GetDictionaryValueCommand", "Get Dictionary Value", + new List<(string, string)>() + { + ("v_DataRowName", "v_InputData"), + ("v_Option", "v_KeyType"), + ("v_DataValueIndex", "v_Key"), + ("v_UserVariableName", "v_OutputVariable"), + }, + new List<(string, Action)>() + { + ( + "v_Option", + new Action(attr => + { + if (attr.Value.ToLower() == "column name") + { + attr.SetValue("Key"); + } + }) + ) + } + ); + + // RemoveDataRowCommand -> SearchAndDeleteDataTableRowsCommand + ChangeCommandName(doc, "RemoveDataRowCommand", "SearchAndDeleteDataTableRowsCommand", "Search And Delete DataTable Rows"); + + // WriteDataRowValueCommand -> SetDataTableValueCommand + ChangeToOtherCommand(doc, "WriteDataRowValueCommand", "SetDataTableValueCommand", "Set DataTable Value", + new List<(string, string)>() + { + ("v_DataRowName", "v_DataTableName"), + ("v_Option", "v_ColumnType"), + ("v_DataValueIndex", "v_ColumnIndex"), + ("v_DataRowValue", "v_NewValue"), + }, + new List<(string, Action)>() + { + ( + "v_Comment", + new Action(attr => + { + if (!attr.Value.StartsWith("Please specify Row Index. Converted by taskt.")) + { + string c = attr.Value; + attr.SetValue($"Please specify Row Index. Converted by taskt. {c}"); + } + }) + ) + } + ); + + // ExcelWriteRowCommand -> ExcelSetRowValuesFromDictionaryCommand + ChangeToOtherCommand(doc, "ExcelWriteRowCommand", "ExcelSetRowValuesFromDictionaryCommand", "Set Row Values From Dictionary", + new List<(string, string)>() + { + ("v_DataRowToSet", "v_DictionaryVariable"), + }, + new List<(string, Action)>() + { + ( + "v_ExcelCellAddress", + new Action(attr => + { + var rg = attr.Value; + var rowIndex = Regex.Match(rg, @"\d+").Value; + var columnName = Regex.Replace(rg, @"[\d-]", string.Empty); + + var elem = attr.Parent; + elem.SetAttributeValue("v_RowIndex", rowIndex); + elem.SetAttributeValue("v_ColumnStart", columnName); + attr.Remove(); + }) + ) + } + ); + + // ParseDatasetRowCommand (ParseRowCommand) -> GetDataTableValueCommand + ChangeToOtherCommand(doc, "ParseRowCommand", "GetDataTableValueCommand", "Get DataTable Value", + new List<(string, string)>() + { + ("v_DatasetName", "v_DataTableName"), + ("v_ColumnParseType", "v_ColumnType"), + ("v_ColumnParameter", "v_ColumnIndex"), + ("v_applyToVariableName", "v_UserVariableName"), + ("v_SpecifiedRow", "v_RowIndex"), + }, + new List<(string, Action)>() + { + ( + "v_ColumnParseType", + new Action(attr => + { + switch (attr.Value.ToLower()) + { + case "by column name": + attr.SetValue("Column Name"); + break; + case "by column index": + attr.SetValue("Index"); + break; + } + }) + ), + } + ); + } + + private static void convertTo3_5_1_86(XDocument doc) + { + // LoadDataTableCommand -> ExcelCreateDataTableFromExcelFile + ChangeToOtherCommand(doc, "LoadDataTableCommand", "ExcelCreateDataTableFromExcelFile", "Create DataTable From Excel File", + new List<(string, string)>() + { + ("v_DataSetName", "v_DataTableName"), + ("v_ContainsHeaderRow", "v_FirstRowAsColumnName"), + } + ); + + // LoadDictionaryCommand -> CreateDictionaryFromExcelFile + ChangeCommandName(doc, "LoadDictionaryCommand", "CreateDictionaryFromExcelFile", "Create Dictionary From Excel File"); + + // SetEnginePreferenceCommand + ChangeAttributeValue(doc, + new Func(el => + { + return (GetCommandName(el) == "SetEnginePreferenceCommand") && + (el.Attribute("v_PreferenceType").Value.ToLower() == "current window keyword"); + }), + "v_Comment", + new Action(attr => + { + var v = attr.Value; + if (!v.StartsWith("'Current Window Keyword' will eventually become unavailable.")) + { + attr.SetValue($"'Current Window Keyword' will eventually become unavailable. {v}"); + } + }) + ); + } + + private static void convertTo3_5_1_87(XDocument doc) + { + // Dictionary commands v_InputData -> v_Dictionary + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "CheckDictionaryKeyExistsCommand": + case "ConvertDictionaryToDataTableCommand": + case "ConvertDictionaryToJSONCommand": + case "ConvertDictionaryToListCommand": + case "CreateDictionaryCommand": + case "GetDictionaryKeyFromValueCommand": + case "GetDictionaryKeysListCommand": + case "GetDictionaryValueCommand": + case "RemoveDictionaryItemCommand": + case "ReplaceDictionaryCommand": + case "SetDictionaryValueCommand": + return true; + default: + return false; + } + }), "v_InputData", "v_Dictionary"); + + // AddDictionaryItemCommand, CreateDictionaryCommand v_DictionaryName -> v_Dictionary + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "AddDictionaryItemCommand": + case "CreateDictionaryCommand": + return true; + default: + return false; + } + }), "v_DictionaryName", "v_Dictionary"); + + // CopyDictionaryCommand v_InputData -> v_TargetDictionary + ChangeAttributeName(doc, "CopyDictionaryCommand", "v_InputData", "v_TargetDictionary"); + + // FilterDictionaryCommand v_InputDictionary -> v_TargetDictionary + ChangeAttributeName(doc, "FilterDictionaryCommand", "v_InputDictionary", "v_TargetDictionary"); + + // ReplaceDictionaryCommand v_TargetDictionary -> v_Dictionary + ChangeAttributeName(doc, "ReplaceDictionaryCommand", "v_TargetDictionary", "v_Dictionary"); + + // CheckDictionaryKeyExistsCommand v_applyToVariable -> v_Result + ChangeAttributeName(doc, "CheckDictionaryKeyExistsCommand", "v_applyToVariable", "v_Result"); + + // ConcatenateDictionaryCommand attributes + ChangeMultiAttributeNames(doc, "ConcatenateDictionaryCommand", + new List<(string, string)>() + { + ("v_InputDataA", "v_DictionaryA"), + ("v_InputDataB", "v_DictionaryB"), + ("v_OutputName", "v_NewDictionary"), + } + ); + + // Dictioanry commands v_OutputVariable -> v_Result + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ConvertDictionaryToDataTableCommand": + case "ConvertDictionaryToJSONCommand": + case "ConvertDictionaryToListCommand": + case "GetDictionaryKeyFromValueCommand": + case "GetDictionaryKeysListCommand": + case "GetDictionaryValueCommand": + return true; + default: + return false; + } + }), + "v_OutputVariable", "v_Result" + ); + + // CopyDictionaryCommand v_OutputName -> v_NewDictionary + ChangeAttributeName(doc, "CopyDictionaryCommand", "v_OutputName", "v_NewDictionary"); + + // FilterDictionaryCommand v_OutputDictionary -> v_NewDictionary + ChangeAttributeName(doc, "FilterDictionaryCommand", "v_OutputDictionary", "v_NewDictionary"); + + // CreateDictionaryFromExcelFile -> ExcelCreateDictionaryFromExcelFile + ChangeCommandName(doc, "CreateDictionaryFromExcelFile", "ExcelCreateDictionaryFromExcelFile", "Create Dictionary From Excel File"); + } + + private static void convertTo3_5_1_88(XDocument doc) + { + // GetDictionaryValueCommand, RemoveDictionaryItemCommand, SetDictionaryValueCommand v_WhenKeyDoesNotExists + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "GetDictionaryValueCommand": + case "RemoveDictionaryItemCommand": + case "SetDictionaryValueCommand": + return true; + default: + return false; + } + }), "v_IfKeyDoesNotExists", "v_WhenKeyDoesNotExists" + ); + + // DataTableCommand v_DataTableName -> v_DataTable + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "AddDataTableColumnCommand": + case "AddDataTableRowByDictionaryCommand": + case "AddDataTableRowCommand": + case "AddDataTableRowsByDataTableCommand": + case "CheckDataTableColumnExistsCommand": + case "ConvertDataTableColumnToDataTableCommand": + case "ConvertDataTableColumnToDictionaryCommand": + case "ConvertDataTableColumnToJSONCommand": + case "ConvertDataTableColumnToListCommand": + case "ConvertDataTableRowToDataTableCommand": + case "ConvertDataTableRowToDictionaryCommand": + case "ConvertDataTableRowToJSONCommand": + case "ConvertDataTableRowToListCommand": + case "ConvertDataTableToJSONCommand": + case "CreateDataTableCommand": + case "DeleteDataTableColumnCommand": + case "DeleteDataTableRowCommand": + case "GetDataTableColumnCountCommand": + case "GetDataTableColumnListCommand": + case "GetDataTableRowCountCommand": + case "GetDataTableValueCommand": + case "SearchAndDeleteDataTableRowsCommand": + case "SetDataTableColumnValuesByDataTableCommand": + case "SetDataTableColumnValuesByListCommand": + case "SetDataTableRowValuesByDataTableCommand": + case "SetDataTableRowValuesByDictionaryCommand": + case "SetDataTableValueCommand": + return true; + default: + return false; + } + }), "v_DataTableName", "v_DataTable" + ); + + // FilterDataTable commands v_InputDataTable -> v_TargetDataTable + // v_OutputDataTable -> v_NewDataTable + ChangeMultiAttributeNames(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "FilterDataTableColumnByRowValueCommand": + case "FilterDataTableRowByColumnValueCommand": + return true; + default: + return false; + } + }), + new List<(string, string)>() + { + ("v_InputDataTable", "v_TargetDataTable"), + ("v_OutputDataTable", "v_NewDataTable"), + } + ); + ChangeMultiAttributeNames(doc, "FilterDataTableCommand", + new List<(string, string)>() + { + ("v_DataTableName", "v_TargetDataTable"), + ("v_OutputDTName", "v_NewDataTable"), + } + ); + + // ReplaceDataTable commands v_InputDataTable -> v_DataTable + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ReplaceDataTableColumnValueCommand": + case "ReplaceDataTableRowValueCommand": + case "ReplaceDataTableValueCommand": + return true; + default: + return false; + } + }), "v_InputDataTable", "v_DataTable" + ); + + // DataTableCommands v_OutputVariableName -> v_Result + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "CheckDataTableColumnExistsCommand": + case "ConvertDataTableColumnToDataTableCommand": + case "ConvertDataTableColumnToDictionaryCommand": + case "ConvertDataTableColumnToJSONCommand": + case "ConvertDataTableColumnToListCommand": + case "ConvertDataTableRowToDataTableCommand": + case "ConvertDataTableRowToDictionaryCommand": + case "ConvertDataTableRowToJSONCommand": + case "ConvertDataTableRowToListCommand": + case "ConvertDataTableToJSONCommand": + case "GetDataTableColumnCountCommand": + return true; + default: + return false; + } + }), "v_OutputVariableName", "v_Result" + ); + + // DataTableCommands v_UserVariableName -> v_Result + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "GetDataTableRowCountCommand": + case "GetDataTableValueCommand": + return true; + default: + return false; + } + }), "v_UserVariableName", "v_Result" + ); + + // GetDataTableColumnListCommand v_OutputList -> v_Result + ChangeAttributeName(doc, "GetDataTableColumnListCommand", "v_OutputList", "v_Result"); + + // CopyDataTableCommand v_DatTableName -> v_TargetDataTable + ChangeMultiAttributeNames(doc, "CopyDataTableCommand", + new List<(string, string)>() + { + ("v_DataTableName", "v_TargetDataTable"), + ("v_OutputVariableName", "v_NewDataTable"), + } + ); + } + + private static void convertTo3_5_1_89(XDocument doc) + { + // List commands v_ListName -> v_List + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "AddListItemCommand": + case "CheckListItemExistsCommand": + case "CreateListCommand": + case "GetListCountCommand": + case "GetListIndexCommand": + case "GetListIndexFromValueCommand": + case "GetListItemCommand": + case "SetListIndexCommand": + case "SetListItemCommand": + return true; + default: + return false; + } + }), "v_ListName", "v_List" + ); + + // List commands v_InputList -> v_List + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ConvertListToDataTableCommand": + case "ConvertListToDictionaryCommand": + case "ConvertListToJSONCommand": + case "GetAverageFromListCommand": + case "GetMaxFromListCommand": + case "GetMedianFromListCommand": + case "GetMinFromListCommand": + case "GetSumFromListCommand": + case "GetVarianceFromListCommand": + return true; + default: + return false; + } + }), "v_InputList", "v_List" + ); + + // ReplaceListCommand v_TargetList -> v_List + ChangeAttributeName(doc, "ReplaceListCommand", "v_TargetList", "v_List"); + + // List commands v_InputList -> v_TargetList, v_OutputList -> v_NewList + ChangeMultiAttributeNames(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "CopyListCommand": + case "FilterListCommand": + case "ReverseListCommand": + case "SortListCommand": + return true; + default: + return false; + } + }), + new List<(string, string)>() + { + ("v_InputList", "v_TargetList"), + ("v_OutputList", "v_NewList"), + } + ); + + // ConcatenateListsCommand + ChangeMultiAttributeNames(doc, "ConcatenateListsCommand", + new List<(string, string)>() + { + ("v_InputListA", "v_ListA"), + ("v_InputListB", "v_ListB"), + ("v_OutputList", "v_NewList"), + } + ); + + // List Convert commands v_applyToVariableName -> v_Result + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ConvertListToDataTableCommand": + case "ConvertListToDictionaryCommand": + case "ConvertListToJSONCommand": + return true; + default: + return false; + } + }), "v_applyToVariableName", "v_Result" + ); + + // List Convert commands v_UserVariableName -> v_Result + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "GetListCountCommand": + case "GetListItemCommand": + return true; + default: + return false; + } + }), "v_UserVariableName", "v_Result" + ); + } + + private static void convertTo3_5_1_91(XDocument doc) + { + // SeleniumBrowserWebElementActionCommand, v_SeleniumElementAction + ChangeAttributeValue(doc, "SeleniumBrowserWebElementActionCommand", "v_SeleniumElementAction", + new Action(attr => + { + if (attr.Value.ToLower() == "clear webelement") + { + attr.SetValue("Clear Text"); + } + }) + ); + + // ConvertDataTable v_RowIndex + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ConvertDataTableRowToListCommand": + case "ConvertDataTableRowToJSONCommand": + case "ConvertDataTableRowToDictionaryCommand": + case "ConvertDataTableRowToDataTableCommand": + return true; + default: + return false; + } + }), + "v_DataRowIndex", "v_RowIndex" + ); + + // Filter/ReplaceDataTable v_RowIndex + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "FilterDataTableColumnByRowValueCommand": + case "ReplaceDataTableRowValueCommand": + return true; + default: + return false; + } + }), + "v_TargetRowIndex", "v_RowIndex" + ); + + // Filter/ReplaceDataTable v_ColumnIndex + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "FilterDataTableRowByColumnValueCommand": + case "ReplaceDataTableColumnValueCommand": + return true; + default: + return false; + } + }), + "v_TargetColumnIndex", "v_ColumnIndex" + ); + + // Filter/ReplaceDataTable,Dictionary,List v_ValueType + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "FilterDataTableColumnByRowValueCommand": + case "FilterDataTableRowByColumnValueCommand": + case "ReplaceDataTableColumnValueCommand": + case "ReplaceDataTableRowValueCommand": + case "FilterDictionaryCommand": + case "ReplaceDictionaryCommand": + case "FilterListCommand": + case "ReplaceListCommand": + return true; + default: + return false; + } + }), + "v_TargetType", "v_ValueType" + ); + + // ConvertDataTable v_ColumnIndex + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ConvertDataTableColumnToDataTableCommand": + case "ConvertDataTableColumnToDictionaryCommand": + case "ConvertDataTableColumnToJSONCommand": + case "ConvertDataTableColumnToListCommand": + return true; + default: + return false; + } + }), + "v_DataColumnIndex", "v_ColumnIndex" + ); + + // DeleteDataTableColumnCommand v_ColumnIndex + ChangeAttributeName(doc, "DeleteDataTableColumnCommand", "v_DeleteColumnName", "v_ColumnIndex"); + + // SetDataTableColumn v_ColumnIndex + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "SetDataTableColumnValuesByDataTableCommand": + case "SetDataTableColumnValuesByListCommand": + return true; + default: + return false; + } + }), + "v_SetColumnName", "v_ColumnIndex" + ); + + // DataTableCommands v_WhenKeyNotExists + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "AddDataTableRowByDictionaryCommand": + case "AddDataTableRowsByDataTableCommand": + case "SetDataTableRowValuesByDataTableCommand": + case "SetDataTableRowValuesByDictionaryCommand": + return true; + default: + return false; + } + }), + "v_NotExistsKey", "v_WhenColumnNotExists" + ); + + // ListCommands v_Index + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "GetListItemCommand": + case "SetListItemCommand": + return true; + default: + return false; + } + }), + "v_ItemIndex", "v_Index" + ); + + // ListCommands v_WhenValueIsNotNumeric + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "GetAverageFromListCommand": + case "GetMaxFromListCommand": + case "GetMedianFromListCommand": + case "GetMinFromListCommand": + case "GetSumFromListCommand": + case "GetVarianceFromListCommand": + return true; + default: + return false; + } + }), + "v_IfValueIsNotNumeric", "v_WhenValueIsNotNumeric" + ); + } + + private static void convertTo3_5_1_92(XDocument doc) + { + // ReplaceDataTableValueCommand v_ValueType + ChangeAttributeName(doc, "ReplaceDataTableValueCommand", "v_TargetType", "v_ValueType"); + + // ReplaceDictionaryCommand, ReplaceListCommand v_NewValue + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ReplaceDictionaryCommand": + case "ReplaceListCommand": + return true; + default: + return false; + } + }), "v_ReplaceValue", "v_NewValue" + ); + } + + private static void convertTo3_5_1_93(XDocument doc) + { + // CheckDataTableColumnExistsCommand v_ColumnIndex + ChangeAttributeName(doc, "CheckDataTableColumnExistsCommand", "v_ColumnName", "v_ColumnIndex"); + + // CheckListItemExistsCommand, GetListIndexFromValueCommand v_Value + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "CheckListItemExistsCommand": + case "GetListIndexFromValueCommand": + return true; + default: + return false; + } + }), + "v_SearchItem", "v_Value" + ); + } + + private static void convertTo3_5_1_96(XDocument doc) + { + // JSON v_applyToVariableName -> v_Result + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "ConvertJSONToDataTableCommand": + case "ConvertJSONToDictionaryCommand": + case "ConvertJSONToListCommand": + case "GetJSONValueListCommand": + case "GetMultiJSONValueListCommand": + case "ParseJSONArrayCommand": + return true; + default: + return false; + } + }), + "v_applyToVariableName", "v_Result" + ); + + // ReadJSONFileCommand v_userVariableName -> v_Result + ChangeAttributeName(doc, "ReadJSONFileCommand", "v_userVariableName", "v_Result"); + + // JSON v_InputValue -> v_Json + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "AddJSONArrayItemCommand": + case "AddJSONObjectPropertyCommand": + case "ConvertJSONToDataTableCommand": + case "ConvertJSONToDictionaryCommand": + case "ConvertJSONToListCommand": + case "GetJSONValueListCommand": + case "GetMultiJSONValueListCommand": + case "InsertJSONArrayItemCommand": + case "InsertJSONObjectPropertyCommand": + case "ParseJSONArrayCommand": + case "RemoveJSONArrayItemCommand": + case "RemoveJSONPropertyCommand": + case "SetJSONValueCommand": + return true; + default: + return false; + } + }), + "v_InputValue", "v_Json" + ); + + // CreateJsonVariableCommand v_JsonVariable -> v_Json + ChangeAttributeName(doc, "CreateJSONVariableCommand", "v_JsonVariable", "v_Json"); + + // JSON v_***Value -> v_Value + ChangeAttributeName(doc, "AddJSONArrayItemCommand", "v_ArrayItem", "v_Value"); + ChangeAttributeName(doc, "CreateJSONVariableCommand", "v_JsonValue", "v_Value"); + ChangeAttributeName(doc, "InsertJSONArrayItemCommand", "v_InsertItem", "v_Value"); + ChangeAttributeName(doc, "SetJSONValueCommand", "v_ValueToSet", "v_Value"); + + ChangeAttributeName(doc, + new Func(el => + { + switch (GetCommandName(el)) + { + case "AddJSONObjectPropertyCommand": + case "InsertJSONObjectPropertyCommand": + return true; + default: + return false; + } + }), + "v_PropertyValue", "v_Value" + ); + + // JSON array index -> v_Index + ChangeAttributeName(doc, "InsertJSONArrayItemCommand", "v_InsertIndex", "v_Index"); + ChangeAttributeName(doc, "RemoveJSONArrayItemCommand", "v_RemoveIndex", "v_Index"); + + // BeginListLoopCommand -> BeginLoopForComplexDataTypesCommand + ChangeCommandName(doc, "BeginListLoopCommand", "BeginLoopForComplexDataTypesCommand", "Loop Complex Data Types"); + } + + private static void convertTo3_5_1_98(XDocument doc) + { + // RemoveJSONProperty -> RemoveJSONObjectProperty + ChangeCommandName(doc, "RemoveJSONPropertyCommand", "RemoveJSONObjectPropertyCommand", "Remove JSON Object Property"); + + // stop v3.5.2.1 + // GetJSONValueList -> ConvertJSONToList + //ChangeCommandName(doc, "GetJSONValueListCommand", "ConvertJSONToListCommand", "Convert JSON To List"); + + // separate JSONPath + var rmv = GetCommands(doc, "RemoveJSONObjectPropertyCommand"); + foreach(var c in rmv) + { + var attrPath = c.Attribute("v_JsonExtractor"); + var attrProp = c.Attribute("v_PropertyName"); + var path = attrPath?.Value ?? ""; + var prop = attrProp?.Value ?? ""; + + if (string.IsNullOrEmpty(prop) && !string.IsNullOrEmpty(path)) + { + var idx = path.LastIndexOf('.'); + var newProp = path.Substring(idx + 1); + var newPath = path.Substring(0, idx); + + if (attrProp != null) + { + attrProp.SetValue(newProp); + } + else + { + c.Add(new XAttribute("v_PropertyName", newProp)); + } + if (attrPath != null) + { + attrPath.SetValue(newPath); + } + else + { + c.Add(new XAttribute("v_JsonExtractor", newPath)); + } + } + } + } + + private static void convertTo3_5_2_0(XDocument doc) + { + var htmlCommands = GetCommands(doc, "ShowHTMLInputDialogCommand"); + foreach(var cmd in htmlCommands) + { + var html = cmd.Attribute("v_InputHTML").Value; + html = html.Replace("window.external.Ok()", "chrome.webview.hostObjects.fm.OK()") + .Replace("window.external.Cancel()", "chrome.webview.hostObjects.fm.Cancel()"); + + cmd.SetAttributeValue("v_InputHTML", html); + + // MEMO: i want to remove form tags, but i don't know how to do it. + } + } + + private static void convertTo3_5_2_1(XDocument doc) + { + // GetJSONValueListCommand -> GetJSONValuesAsListCommand + ChangeCommandName(doc, "GetJSONValueListCommand", "GetJSONValuesAsListCommand", "Get JSON Values As List"); + } + + /// + /// get old, new current window keyword + /// + /// + /// + private static (string oldKeyword, string newKeyword) GetOldNewCurrentWindow(EngineSettings engine) + { + return GetOldNewKeyword("%kwd_current_window%", engine.CurrentWindowKeyword, SystemVariables.Window_CurrentWindowName, engine); + } + + /// + /// get old new keyword + /// + /// + /// + /// + /// + /// + private static (string oldKeyword, string newKeyword) GetOldNewKeyword(string intermediateKeyword, string rawKeyword, ScriptVariable systemVariable, EngineSettings engine) + { + string oldKW; + string newKW; + if (engine.ExportIntermediateXML) + { + oldKW = IntermediateControls.GetWrappedIntermediateKeyword(intermediateKeyword); + newKW = IntermediateControls.GetWrappedIntermediateVariable(systemVariable.VariableName); + } + else + { + oldKW = rawKeyword; + newKW = string.Concat(engine.VariableStartMarker, systemVariable.VariableName, engine.VariableEndMarker); + } + return (oldKW, newKW); + } + + /// + /// get command name + /// + /// + /// + private static string GetCommandName(XElement elem) + { + return elem.Attribute("CommandName").Value; + } + + /// + /// get specfied commands + /// + /// + /// + /// + private static IEnumerable GetCommands(XDocument doc, Func searchFunc) + { + return doc.Descendants("ScriptCommand").Where(searchFunc); + } + + /// + /// get command search Func. targetCommand is string (command name) + /// + /// + /// + private static Func GetSearchCommandsFunc(string targetCommand) + { + return new Func(el => + { + return (GetCommandName(el) == targetCommand); + }); + } + + /// + /// get specified commands + /// + /// + /// + /// + private static IEnumerable GetCommands(XDocument doc, string commandName) + { + return GetCommands(doc, new Func(el => GetCommandName(el) == commandName)); + } + + /// + /// change command name to specified commands + /// + /// + /// + /// + private static void ChangeCommandNameProcess(List commands, string newName, string newSelectioName) + { + XNamespace ns = "http://www.w3.org/2001/XMLSchema-instance"; + foreach (var cmd in commands) + { + cmd.SetAttributeValue("CommandName", newName); + cmd.SetAttributeValue(ns + "type", newName); + cmd.SetAttributeValue("SelectionName", newSelectioName); + } + } + + /// + /// change command name. target commands are searched by specified Func<> + /// + /// + /// + /// + /// + /// + private static XDocument ChangeCommandName(XDocument doc, Func searchFunc, string newName, string newSelectioName) + { + var commands = doc.Descendants("ScriptCommand").Where(searchFunc).ToList(); + ChangeCommandNameProcess(commands, newName, newSelectioName); + return doc; + } + + /// + /// change command name. a target command is specified command name. + /// + /// + /// + /// + /// + /// + private static XDocument ChangeCommandName(XDocument doc, string targetName, string newName, string newSelectioName) + { + return ChangeCommandName(doc, GetSearchCommandsFunc(targetName), newName, newSelectioName); + } + + /// + /// change attribute value process + /// + /// + /// + /// + private static void ChangeAttributeValueProcess(List commands, string targetAttribute, Action changeFunc) + { + foreach (var cmd in commands) + { + var attr = cmd.Attribute(targetAttribute); + if (attr == null) + { + cmd.SetAttributeValue(targetAttribute, ""); + attr = cmd.Attribute(targetAttribute); + } + changeFunc(attr); + } + } + + /// + /// change attribute value. target commands are searched by specified Func<> + /// + /// + /// + /// + /// + /// + private static XDocument ChangeAttributeValue(XDocument doc, Func searchFunc, string targetAttribute, Action changeFunc) + { + var commands = doc.Descendants("ScriptCommand") + .Where(searchFunc).ToList(); + ChangeAttributeValueProcess(commands, targetAttribute, changeFunc); + return doc; + } + + /// + /// change attribute value. target commands are specified command name + /// + /// + /// + /// + /// + /// + private static XDocument ChangeAttributeValue(XDocument doc, string targetCommand, string targetAttribute, Action changeFunc) + { + return ChangeAttributeValue(doc, GetSearchCommandsFunc(targetCommand), targetAttribute, changeFunc); + } + + /// /// change table cell value. target commands are specified Func<> /// /// @@ -1718,10 +3581,11 @@ private static XDocument ChangeAttributeValue(XDocument doc, string targetComman /// /// /// + /// /// - private static XDocument ChangeTableCellValue(XDocument doc, Func searchFunc, string tableParameterName, string tableCellName, Action changeFunc) + private static XDocument ChangeTableCellValue(XDocument doc, Func searchFunc, string tableParameterName, string tableCellName, Action changeFunc, string defaultCellValue) { - IEnumerable commands = doc.Descendants("ScriptCommand").Where(searchFunc); + var commands = doc.Descendants("ScriptCommand").Where(searchFunc).ToList(); XNamespace ns = "urn:schemas-microsoft-com:xml-diffgram-v1"; foreach (var cmd in commands) @@ -1731,7 +3595,14 @@ private static XDocument ChangeTableCellValue(XDocument doc, Func /// /// + /// /// - private static XDocument ChangeTableCellValue(XDocument doc, string commandName, string tableParameterName, string tableCellName, Action changeFunc) + private static XDocument ChangeTableCellValue(XDocument doc, string commandName, string tableParameterName, string tableCellName, Action changeFunc, string defaultCellValue) { - ChangeTableCellValue(doc, new Func(el => - { - return el.Attribute("CommandName").Value == commandName; - }), tableParameterName, tableCellName, changeFunc); - return doc; + return ChangeTableCellValue(doc, GetSearchCommandsFunc(commandName), tableParameterName, tableCellName, changeFunc, defaultCellValue); } /// @@ -1802,9 +3670,9 @@ private static (XElement, XElement, string, XElement, List) GetTable(X /// private static XDocument ModifyTable(XDocument doc, Func searchFunc, string tableParameterName, Action, string> modifyFunc) { - IEnumerable commands = doc.Descendants("ScriptCommand").Where(searchFunc); + var commands = doc.Descendants("ScriptCommand").Where(searchFunc).ToList(); - XNamespace ns = "urn:schemas-microsoft-com:xml-diffgram-v1"; + //XNamespace ns = "urn:schemas-microsoft-com:xml-diffgram-v1"; foreach (var cmd in commands) { //XElement tableParams = cmd.Element(tableParameterName).Element(ns + "diffgram").Element("DocumentElement"); @@ -1828,11 +3696,7 @@ private static XDocument ModifyTable(XDocument doc, Func searchF /// private static XDocument ModifyTable(XDocument doc, string targetCommand, string tableParameterName, Action, string> modifyFunc) { - ModifyTable(doc, new Func(el => - { - return el.Attribute("CommandName").Value == targetCommand; - }), tableParameterName, modifyFunc); - return doc; + return ModifyTable(doc, GetSearchCommandsFunc(targetCommand), tableParameterName, modifyFunc); } /// @@ -1845,6 +3709,11 @@ private static XDocument ModifyTable(XDocument doc, string targetCommand, string /// private static void AddTableRow(XElement table, Dictionary cols, string rowName, int currentMaxRows, bool addModified = true) { + if (table == null) + { + return; + } + XNamespace diffNs = "urn:schemas-microsoft-com:xml-diffgram-v1"; XNamespace msNs = "urn:schemas-microsoft-com:xml-msdata"; @@ -1877,6 +3746,11 @@ private static void AddTableRow(XElement table, Dictionary cols, /// private static void AddTableRows(XElement table, List> cols, string rowName, int currentMaxRows, bool addModified = true) { + if (table == null) + { + return; + } + XNamespace diffNs = "urn:schemas-microsoft-com:xml-diffgram-v1"; XNamespace msNs = "urn:schemas-microsoft-com:xml-msdata"; @@ -1966,19 +3840,14 @@ private static void ChangeTableColumnNames(XDocument doc, string commandName, st } /// - /// change attribute name. target command is specified Func<> + /// change attribute name process /// - /// - /// + /// /// /// - /// - private static XDocument ChangeAttributeName(XDocument doc, Func searchFunc, string targetAttribute, string newAttribute) + private static void ChangeAttributeNameProcess(List commands, string targetAttribute, string newAttribute) { - IEnumerable commands = doc.Descendants("ScriptCommand") - .Where(searchFunc); - - foreach(var cmd in commands) + foreach (var cmd in commands) { var trgAttr = cmd.Attribute(targetAttribute); var newAttr = cmd.Attribute(newAttribute); @@ -1991,6 +3860,22 @@ private static XDocument ChangeAttributeName(XDocument doc, Func trgAttr.Remove(); } } + } + + /// + /// change attribute name. target command is specified Func<> + /// + /// + /// + /// + /// + /// + private static XDocument ChangeAttributeName(XDocument doc, Func searchFunc, string targetAttribute, string newAttribute) + { + var commands = doc.Descendants("ScriptCommand") + .Where(searchFunc).ToList(); + + ChangeAttributeNameProcess(commands, targetAttribute, newAttribute); return doc; } @@ -2005,10 +3890,104 @@ private static XDocument ChangeAttributeName(XDocument doc, Func /// private static XDocument ChangeAttributeName(XDocument doc, string targetCommand, string targetAttribute, string newAttribute) { - return ChangeAttributeName(doc, new Func(el => + return ChangeAttributeName(doc, GetSearchCommandsFunc(targetCommand), targetAttribute, newAttribute); + } + + /// + /// Change multi attribute names process + /// + /// + /// (targetAttributeName, newAttributeName) + private static void ChangeMultiAttributeNamesProcess(List commands, List<(string, string)> attributePairs) + { + foreach((var targetAttribute, var newAttribute) in attributePairs) + { + ChangeAttributeNameProcess(commands, targetAttribute, newAttribute); + } + } + + /// + /// change multi attribute names + /// + /// + /// + /// (targetAttributeName, newAttributeName) + /// + private static XDocument ChangeMultiAttributeNames(XDocument doc, Func searchFunc, List<(string, string)> attributePairs) + { + var commands = doc.Descendants("ScriptCommand") + .Where(searchFunc).ToList(); + ChangeMultiAttributeNamesProcess(commands, attributePairs); + return doc; + } + + /// + /// change multi attribute name + /// + /// + /// + /// (targetAttributeName, newAttributeName) + /// + private static XDocument ChangeMultiAttributeNames(XDocument doc, string targetCommand, List<(string, string)> attributePairs) + { + return ChangeMultiAttributeNames(doc, GetSearchCommandsFunc(targetCommand), attributePairs); + } + + /// + /// change to other command + /// + /// + /// + /// + /// (targetAttribute, newAttributeName) + /// (attribute name, change action) + private static void ChangeToOtherCommandProcess(List commands, string newCommand, string newSelectionName, List<(string, string)> attributePairs, List<(string, Action)> preAttributeFunc = null) + { + // attribute values + if (preAttributeFunc != null) { - return el.Attribute("CommandName").Value == targetAttribute; - }), targetAttribute, newAttribute); + foreach((var attr, var func) in preAttributeFunc) + { + ChangeAttributeValueProcess(commands, attr, func); + } + } + // command name + ChangeCommandNameProcess(commands, newCommand, newSelectionName); + // attribute names + ChangeMultiAttributeNamesProcess(commands, attributePairs); + } + + /// + /// change to other command, specified commands search Func + /// + /// + /// + /// + /// + /// (targetAttribute, newAttributeName) + /// (attribute name, change action) + /// + private static XDocument ChangeToOtherCommand(XDocument doc, Func searchFunc, string newCommand, string newSelectionName, List<(string, string)> attributePairs, List<(string, Action)> preAttributeFunc = null) + { + var commands = doc.Descendants("ScriptCommand") + .Where(searchFunc).ToList(); + ChangeToOtherCommandProcess(commands, newCommand, newSelectionName, attributePairs, preAttributeFunc); + return doc; + } + + /// + /// change to other command, specified command name + /// + /// + /// + /// + /// + /// (targetAttribute, newAttributeName) + /// (attribute name, change action) + /// + private static XDocument ChangeToOtherCommand(XDocument doc, string targetCommand, string newCommand, string newSelectionName, List<(string, string)> attributePairs, List<(string, Action)> preAttributeFunc = null) + { + return ChangeToOtherCommand(doc, GetSearchCommandsFunc(targetCommand), newCommand, newSelectionName, attributePairs, preAttributeFunc); } } } \ No newline at end of file diff --git a/taskt/Core/Script/ScriptInformation.cs b/taskt/Core/Script/ScriptInformation.cs index d22029b63..dbd04af10 100644 --- a/taskt/Core/Script/ScriptInformation.cs +++ b/taskt/Core/Script/ScriptInformation.cs @@ -8,7 +8,8 @@ public class ScriptInformation public string TasktVersion { get; set; } public string Author { get; set; } public DateTime LastRunTime { get; set; } - public int RunTimes { get; set; } + public uint RunTimes { get; set; } + public uint Revision { get; set; } public string ScriptVersion { get; set; } public string Description { get; set; } public ScriptInformation() @@ -17,6 +18,7 @@ public ScriptInformation() this.Author = ""; this.LastRunTime = DateTime.Parse("1990-01-01T00:00:00"); this.RunTimes = 0; + this.Revision = 0; this.ScriptVersion = "0.0.0"; this.Description = ""; } diff --git a/taskt/Core/Server/HttpServerClient.cs b/taskt/Core/Server/HttpServerClient.cs index daf62eec2..5ab1ac62d 100644 --- a/taskt/Core/Server/HttpServerClient.cs +++ b/taskt/Core/Server/HttpServerClient.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Net; -using System.Text; -using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; @@ -14,7 +10,7 @@ namespace taskt.Core.Server /// public static class HttpServerClient { - public static UI.Forms.frmScriptBuilder associatedBuilder; + public static UI.Forms.ScriptBuilder.frmScriptBuilder associatedBuilder; private static Serilog.Core.Logger httpLogger; private static System.Timers.Timer heartbeatTimer { get; set; } private static ApplicationSettings appSettings { get; set; } @@ -35,7 +31,6 @@ public static void Initialize() if (appSettings.ServerSettings.ServerConnectionEnabled) { - //handle for reinitialization if (heartbeatTimer != null) { @@ -72,9 +67,8 @@ private static void Heartbeat_Elapsed(object sender, ElapsedEventArgs e) { httpLogger.Information("Heartbeat Error:" + ex.ToString()); } - - } + /// /// Attempts to retrieve a GUID from tasktServer. /// @@ -85,14 +79,12 @@ public static bool GetGuid(bool overrideExisting = false) try { if (!(appSettings.ServerSettings.ServerConnectionEnabled)) + { return false; + } httpLogger.Information("Client attempting to retrieve a GUID from the server, override " + overrideExisting); - - - - if (appSettings.ServerSettings.HTTPGuid == Guid.Empty || overrideExisting) { httpLogger.Information("Requesting GUID from the application server"); @@ -121,6 +113,7 @@ public static bool GetGuid(bool overrideExisting = false) return false; } } + /// /// Checks in the client with the server /// @@ -130,11 +123,12 @@ public static bool CheckIn() try { if (!(appSettings.ServerSettings.ServerConnectionEnabled) || associatedBuilder == null) + { return false; + } httpLogger.Information("Client is attempting to check in with the server"); - var workerID = appSettings.ServerSettings.HTTPGuid; if (workerID != Guid.Empty) @@ -147,33 +141,25 @@ public static bool CheckIn() if (deserialized.ScheduledTask != null) { - associatedBuilder.Invoke(new MethodInvoker(delegate () { - - if (deserialized.ScheduledTask.ExecutionType == "Local") { - UI.Forms.frmScriptEngine newEngine = new UI.Forms.frmScriptEngine(deserialized.PublishedScript.ScriptData, null); + var newEngine = new UI.Forms.ScriptEngine.frmScriptEngine(deserialized.PublishedScript.ScriptData, null); newEngine.remoteTask = deserialized.ScheduledTask; newEngine.serverExecution = true; newEngine.Show(); } else { - UI.Forms.frmScriptEngine newEngine = new UI.Forms.frmScriptEngine(); + var newEngine = new UI.Forms.ScriptEngine.frmScriptEngine(); newEngine.xmlData = deserialized.PublishedScript.ScriptData; newEngine.remoteTask = deserialized.ScheduledTask; newEngine.serverExecution = true; newEngine.Show(); } - - })); - } - - return true; } else @@ -187,8 +173,8 @@ public static bool CheckIn() httpLogger.Information("Error Checking In: " + ex.ToString()); return false; } - } + /// /// Used to test the connection to the API ensuring provided credentials were correct /// @@ -199,11 +185,12 @@ public static bool TestConnection(string HTTPServerURL) try { if (!(appSettings.ServerSettings.ServerConnectionEnabled)) + { return false; + } httpLogger.Information("Client is testing connection to server"); - var client = new WebClient(); var content = client.DownloadString(HTTPServerURL + "/api/Test"); @@ -221,8 +208,8 @@ public static bool TestConnection(string HTTPServerURL) httpLogger.Information("Error Testing Connection: " + ex.ToString()); return false; } - } + /// /// Adds a new Task to the server /// @@ -233,12 +220,12 @@ public static Task AddTask(string taskName) try { if (!(appSettings.ServerSettings.ServerConnectionEnabled)) + { return null; - + } + httpLogger.Information("Client is attempting to add task data to server"); - - var workerID = appSettings.ServerSettings.HTTPGuid; var userName = Environment.UserName; @@ -257,8 +244,8 @@ public static Task AddTask(string taskName) httpLogger.Information("Error Adding Task: " + ex.ToString()); return null; } - } + /// /// Updates an existing task on the server /// @@ -270,7 +257,9 @@ public static Task UpdateTask(Guid taskID, string status, string remark) try { if (!(appSettings.ServerSettings.ServerConnectionEnabled)) + { return null; + } httpLogger.Information("Client is update a previously added task to server"); @@ -291,8 +280,6 @@ public static Task UpdateTask(Guid taskID, string status, string remark) httpLogger.Information("Error Updating Task: " + ex.ToString()); return null; } - - } public static void PublishScript(string scriptPath, PublishedScript.PublishType publishType) @@ -300,18 +287,17 @@ public static void PublishScript(string scriptPath, PublishedScript.PublishType try { if (!(appSettings.ServerSettings.ServerConnectionEnabled)) + { return; + } httpLogger.Information("Client is publishing a script to the server"); - var script = new PublishedScript(); script.WorkerID = appSettings.ServerSettings.HTTPGuid; script.ScriptType = publishType; script.FriendlyName = new System.IO.FileInfo(scriptPath).Name; - - WebClient webClient = new WebClient(); var content = webClient.DownloadString(appSettings.ServerSettings.HTTPServerURL + "/api/Scripts/Exists?workerID=" + script.WorkerID + "&friendlyName=" + script.FriendlyName); @@ -328,15 +314,13 @@ public static void PublishScript(string scriptPath, PublishedScript.PublishType else { script.OverwriteExisting = false; - } - + } } else { script.OverwriteExisting = false; } - //based on publish type upload local reference or whole task if (publishType == PublishedScript.PublishType.ClientReference) { @@ -359,20 +343,17 @@ public static void PublishScript(string scriptPath, PublishedScript.PublishType webClient.UploadStringAsync(api, "POST", scriptJson); - return; - } catch (Exception ex) { httpLogger.Information("Publish Error: " + ex.ToString()); MessageBox.Show("Publish Error: " + ex.ToString()); } + } - - } private static void PublishTaskCompleted(object sender, UploadStringCompletedEventArgs e) - { + { try { var result = Newtonsoft.Json.JsonConvert.DeserializeObject(e.Result); @@ -382,7 +363,6 @@ private static void PublishTaskCompleted(object sender, UploadStringCompletedEve catch (Exception ex) { MessageBox.Show(ex.ToString(), "Publish Error", MessageBoxButtons.OK, MessageBoxIcon.Error); - } } @@ -404,8 +384,8 @@ public static string UploadData(string key, string value) var api = new Uri(appSettings.ServerSettings.HTTPServerURL + "/api/BotStore/Add"); return webClient.UploadString(api, "POST", scriptJson); - } + public static string GetData(string key, BotStoreRequest.RequestType requestType) { var botStoreRequest = new BotStoreRequest(); @@ -421,12 +401,7 @@ public static string GetData(string key, BotStoreRequest.RequestType requestType var api = new Uri(appSettings.ServerSettings.HTTPServerURL + "/api/BotStore/Get"); return webClient.UploadString(api, "POST", scriptJson); - - - } - - } #region tasktServer Models diff --git a/taskt/Core/Server/LocalTCPListener.cs b/taskt/Core/Server/LocalTCPListener.cs index 08cace7e7..1b14a8295 100644 --- a/taskt/Core/Server/LocalTCPListener.cs +++ b/taskt/Core/Server/LocalTCPListener.cs @@ -1,14 +1,13 @@ using System; -using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; -using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using RestSharp; +using static taskt.Core.Automation.Commands.TextControls; namespace taskt.Core.Server { @@ -22,20 +21,21 @@ public static class LocalTCPListener private static Serilog.Core.Logger automationLogger; public static TcpListener automationListener; private static LocalListenerSettings listenerSettings; - public static UI.Forms.frmScriptBuilder associatedBuilder; + public static UI.Forms.ScriptBuilder.frmScriptBuilder associatedBuilder; public static int Port; public static bool IsListening { get; set; } public static string TasktResult { get; set; } public static event EventHandler ListeningStarted; public static event EventHandler ListeningStopped; + static LocalTCPListener() { automationLogger = new Core.Logging().CreateLogger("Automation Client", Serilog.RollingInterval.Day); ExecuteCommandEngine = new Automation.Engine.AutomationEngineInstance(); } - public static void Initialize(UI.Forms.frmScriptBuilder builder) + public static void Initialize(UI.Forms.ScriptBuilder.frmScriptBuilder builder) { associatedBuilder = builder; automationLogger.Information("Automation Listener Initializing"); @@ -66,13 +66,11 @@ public static void Initialize(UI.Forms.frmScriptBuilder builder) automationLogger.Information("Listening Service is not Enabled! Unable to Automatically Start Listening!"); } - automationLogger.Information("Automation Listener Finished Initializing"); - } + public static void StartListening(int port) { - if (!listenerSettings.LocalListeningEnabled) { automationLogger.Information("Listening Service is not Enabled! Unable to Start Listening!"); @@ -84,8 +82,8 @@ public static void StartListening(int port) Thread.CurrentThread.IsBackground = true; StartAutomationListener(port); }).Start(); - } + public static void StartAutomationListener(int port) { try @@ -153,15 +151,12 @@ public static void StartAutomationListener(int port) SendResponse(ResponseCode.Unauthorized, $"Unauthorized", stream); return; } - } else { automationLogger.Information($"Listener does not require IP Verification"); } - - if (listenerSettings.RequireListenerAuthenticationKey) { string authKey = ""; @@ -228,9 +223,9 @@ public static void StartAutomationListener(int port) ListeningStopped?.Invoke(null, null); } } + private static void ProcessRequest(string data, string[] messageContent, NetworkStream stream) { - if ((data.StartsWith("POST /ExecuteScript")) || (data.StartsWith("POST /AwaitScript"))) { automationLogger.Information($"Client Requests Script Execution"); @@ -249,14 +244,12 @@ private static void ProcessRequest(string data, string[] messageContent, Network break; } - else if (item.StartsWith("ScriptLocation: ")) { dataParameter = item.Replace("ScriptLocation: ", ""); isFileLocation = true; break; } - } //check to see if nothing was provided @@ -266,7 +259,6 @@ private static void ProcessRequest(string data, string[] messageContent, Network return; } - if (dataParameter.TryParseBase64(out var base64SourceString)) { automationLogger.Information($"Client Passed Base64 String: {base64SourceString}"); @@ -277,7 +269,6 @@ private static void ProcessRequest(string data, string[] messageContent, Network automationLogger.Information($"Client Did Not Pass Base64 String"); } - //check if data parameter references file location if (isFileLocation) { @@ -286,10 +277,12 @@ private static void ProcessRequest(string data, string[] messageContent, Network //file was found at path provided dataParameter = File.ReadAllText(dataParameter); } - else if (File.Exists(Path.Combine(IO.Folders.GetFolder(IO.Folders.FolderType.ScriptsFolder), dataParameter))) + //else if (File.Exists(Path.Combine(IO.Folders.GetFolder(IO.Folders.FolderType.ScriptsFolder), dataParameter))) + else if (File.Exists(Path.Combine(IO.Folders.GetScriptsFolderPath(), dataParameter))) { //file was found at fallback to scripts folder - dataParameter = Path.Combine(IO.Folders.GetFolder(IO.Folders.FolderType.ScriptsFolder), dataParameter); + //dataParameter = Path.Combine(IO.Folders.GetFolder(IO.Folders.FolderType.ScriptsFolder), dataParameter); + dataParameter = Path.Combine(IO.Folders.GetScriptsFolderPath(), dataParameter); dataParameter = File.ReadAllText(dataParameter); } else @@ -305,18 +298,16 @@ private static void ProcessRequest(string data, string[] messageContent, Network //log execution automationLogger.Information($"Executing Script: {dataParameter}"); - //invoke builder and pass it script data to execute associatedBuilder.Invoke(new MethodInvoker(delegate () { - UI.Forms.frmScriptEngine newEngine = new UI.Forms.frmScriptEngine(); + var newEngine = new UI.Forms.ScriptEngine.frmScriptEngine(); newEngine.xmlData = dataParameter; newEngine.callBackForm = null; //instance = newEngine.engineInstance; newEngine.Show(); })); - if (data.StartsWith("POST /AwaitScript")) { //reset result value @@ -333,16 +324,12 @@ private static void ProcessRequest(string data, string[] messageContent, Network //send response back to client SendResponse(ResponseCode.OK, automationInstance.TasktResult, stream); - } else { //return success immediately SendResponse(ResponseCode.OK, "Script Launched Successfully", stream); } - - - } else if (data.StartsWith("POST /ExecuteCommand")) { @@ -368,7 +355,6 @@ private static void ProcessRequest(string data, string[] messageContent, Network return; } - if (dataParameter.TryParseBase64(out var base64SourceString)) { automationLogger.Information($"Client Passed Base64 String: {base64SourceString}"); @@ -400,10 +386,7 @@ private static void ProcessRequest(string data, string[] messageContent, Network { SendResponse(ResponseCode.InternalServerError, $"An error occured: {ex.ToString()}", stream); } - - } - else if (data.StartsWith("POST /EngineStatus")) { automationLogger.Information($"Returning Engine Status: {Client.ClientStatus}"); @@ -465,6 +448,7 @@ public static void StopAutomationListener() { automationListener.Stop(); } + public static string SendAutomationTask(string endpoint, string parameterType, string timeout, string scriptData = "", string awaitPreference = "") { @@ -485,12 +469,10 @@ public static string SendAutomationTask(string endpoint, string parameterType, s } //check type of execution needed - if (parameterType == "Run Raw Script Data") + if (parameterType == "run raw script data") { - - //handle await preference - if (awaitPreference == "Await For Result") + if (awaitPreference == "await for result") { request.Resource = "/AwaitScript"; } @@ -500,13 +482,12 @@ public static string SendAutomationTask(string endpoint, string parameterType, s } //add script data - request.AddParameter("ScriptData", scriptData.ToBase64(), RestSharp.ParameterType.HttpHeader); + request.AddParameter("ScriptData", scriptData.ConvertToBase64(), RestSharp.ParameterType.HttpHeader); } - else if (parameterType == "Run Local File") + else if (parameterType == "run local file") { - //handle await preference - if (awaitPreference == "Await For Result") + if (awaitPreference == "await for result") { request.Resource = "/AwaitScript"; } @@ -520,10 +501,12 @@ public static string SendAutomationTask(string endpoint, string parameterType, s //file was found at path provided scriptData = File.ReadAllText(scriptData); } - else if (File.Exists(Path.Combine(IO.Folders.GetFolder(IO.Folders.FolderType.ScriptsFolder), scriptData))) + //else if (File.Exists(Path.Combine(IO.Folders.GetFolder(IO.Folders.FolderType.ScriptsFolder), scriptData))) + else if (File.Exists(Path.Combine(IO.Folders.GetScriptsFolderPath(), scriptData))) { //file was found at fallback to scripts folder - scriptData = Path.Combine(IO.Folders.GetFolder(IO.Folders.FolderType.ScriptsFolder), scriptData); + //scriptData = Path.Combine(IO.Folders.GetFolder(IO.Folders.FolderType.ScriptsFolder), scriptData); + scriptData = Path.Combine(IO.Folders.GetScriptsFolderPath(), scriptData); scriptData = File.ReadAllText(scriptData); } else @@ -532,14 +515,12 @@ public static string SendAutomationTask(string endpoint, string parameterType, s } //add script data - request.AddParameter("ScriptData", scriptData.ToBase64(), RestSharp.ParameterType.HttpHeader); - + request.AddParameter("ScriptData", scriptData.ConvertToBase64(), RestSharp.ParameterType.HttpHeader); } - else if (parameterType == "Run Remote File") + else if (parameterType == "run remote file") { - //handle await preference - if (awaitPreference == "Await For Result") + if (awaitPreference == "await for result") { request.Resource = "/AwaitScript"; } @@ -551,28 +532,42 @@ public static string SendAutomationTask(string endpoint, string parameterType, s //add script parameter request.AddParameter("ScriptLocation", scriptData, RestSharp.ParameterType.HttpHeader); } - else if (parameterType == "Run Command Json") + else if (parameterType == "run command json") { - request.Resource = "/ExecuteCommand"; //add script data - request.AddParameter("CommandData", scriptData.ToBase64(), RestSharp.ParameterType.HttpHeader); - + request.AddParameter("CommandData", scriptData.ConvertToBase64(), RestSharp.ParameterType.HttpHeader); } - else if (parameterType == "Get Engine Status") + else if (parameterType == "get engine status") { request.Resource = "/EngineStatus"; } - else if (parameterType == "Restart taskt") + else if (parameterType == "restart taskt") { request.Resource = "/RestartTaskt"; } - request.Timeout = int.Parse(timeout); + request.Timeout = new TimeSpan(int.Parse(timeout)); + + var resp = client.Execute(request); + + //var resp = await client.ExecuteAsync(request); - var resp = client.Execute(request); + //var stopDateTime = DateTime.Now.AddMilliseconds(int.Parse(timeout)); + //while (true) + //{ + // if (resp.ErrorMessage != null) + // { + // break; + // } + // else if (DateTime.Now > stopDateTime) + // { + // break; + // } + // Thread.Sleep(500); // wait 500 ms + //} string content; if (resp.ErrorMessage is null) diff --git a/taskt/Core/Server/WebSocketClient.cs b/taskt/Core/Server/WebSocketClient.cs index 55f462d51..58f4c23fc 100644 --- a/taskt/Core/Server/WebSocketClient.cs +++ b/taskt/Core/Server/WebSocketClient.cs @@ -1,21 +1,16 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Net; using System.Text; -using System.Threading; -using System.Threading.Tasks; using System.Windows.Forms; -using System.Windows.Threading; namespace taskt.Core.Server { /// /// taskt SocketClient wraps WebSocket4Net and manages local client connection to taskt Server /// - public static class SocketClient + public static class SocketClient { - public static UI.Forms.frmScriptBuilder associatedBuilder; + public static UI.Forms.ScriptBuilder.frmScriptBuilder associatedBuilder; private static string publicKey; private static string serverURI; private static DateTime connectionOpened; @@ -25,10 +20,12 @@ public static class SocketClient private static System.Timers.Timer reconnectTimer; private static bool bypassCertificationValidation; public static Serilog.Core.Logger socketLogger; + static SocketClient() { socketLogger = new Core.Logging().CreateLogger("Socket", Serilog.RollingInterval.Day); } + /// /// Initializes the Socket Client /// @@ -38,12 +35,12 @@ public static void Initialize() //socketLogger.Information("Socket Client Initialized"); //LoadSettings(); } + /// /// Loads Settings used for the Socket Client /// public static void LoadSettings() { - socketLogger.Information("Socket Client Loading Settings"); //setup heartbeat to the server @@ -62,16 +59,12 @@ public static void LoadSettings() publicKey = serverSettings.ServerPublicKey; bypassCertificationValidation = serverSettings.BypassCertificateValidation; - //try to connect to server if ((serverSettings.ServerConnectionEnabled) && (serverSettings.ConnectToServerOnStartup)) { socketLogger.Information("Socket Client Connecting on Startup"); Connect(serverSettings.ServerURL); } - - - } /// @@ -82,9 +75,6 @@ public static void Connect(string serverUri) { try { - - - if (bypassCertificationValidation) { socketLogger.Information("Socket Client Bypasses SSL Validation"); @@ -95,7 +85,6 @@ public static void Connect(string serverUri) //reset connection exception connectionException = string.Empty; - //handle if insecure or invalid connection is defined if (!serverUri.ToLower().StartsWith("wss://")) { @@ -112,7 +101,6 @@ public static void Connect(string serverUri) socketLogger.Information("Socket Client Opening Connection To: " + serverUri); webSocket.Open(); - } catch (Exception ex) { @@ -137,9 +125,7 @@ private static void ConnectionOpened(object sender, EventArgs e) socketLogger.Information("Socket Client Sending Connection Opened Successfully"); connectionOpened = DateTime.Now; SendMessage("CONN_REQUEST"); - reconnectTimer.Enabled = true; - - + reconnectTimer.Enabled = true; } private static void ReconnectTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) @@ -156,16 +142,13 @@ private static void ReconnectTimer_Elapsed(object sender, System.Timers.ElapsedE private static void ConnectionClosed(object sender, EventArgs e) { socketLogger.Information("Socket Client Connection Closed"); - - if (retryOnFail) { reconnectTimer.Enabled = true; } - - } + /// /// Occurs when a connection error happens. This can fire if taskt server is down or not responding. /// @@ -173,7 +156,6 @@ private static void ConnectionClosed(object sender, EventArgs e) /// private static void ConnectionError(object sender, SuperSocket.ClientEngine.ErrorEventArgs e) { - connectionException = e.Exception.Message; socketLogger.Information("Socket Client Connection Error: " + connectionException); @@ -182,6 +164,7 @@ private static void ConnectionError(object sender, SuperSocket.ClientEngine.Erro reconnectTimer.Enabled = true; } } + /// /// Occurs when a message is received from taskt server. /// @@ -189,7 +172,6 @@ private static void ConnectionError(object sender, SuperSocket.ClientEngine.Erro /// private static void MessageReceived(object sender, WebSocket4Net.MessageReceivedEventArgs e) { - socketLogger.Information("Socket Message Received: " + e.Message); //server responded with script @@ -216,13 +198,9 @@ private static void MessageReceived(object sender, WebSocket4Net.MessageReceived appSettings.ServerSettings.ServerPublicKey = authPublicKey; appSettings.Save(appSettings); - - } - - - } + public static void SendExecutionLog(string executionLog) { //new Thread(() => @@ -232,8 +210,9 @@ public static void SendExecutionLog(string executionLog) try { if (SocketClient.webSocket is null) + { return; - + } if (SocketClient.webSocket.State == WebSocket4Net.WebSocketState.Open) { @@ -241,7 +220,6 @@ public static void SendExecutionLog(string executionLog) { try { - client.QueryString.Add("ClientName", SocketClient.publicKey); client.QueryString.Add("LogData", executionLog); @@ -249,7 +227,6 @@ public static void SendExecutionLog(string executionLog) var apiUri = SocketClient.serverURI; apiUri = apiUri.Replace("wss://", "https://").Replace("/ws", "/api/WriteLog"); - byte[] responsebytes = client.UploadValues(apiUri, "POST", client.QueryString); string responsebody = Encoding.UTF8.GetString(responsebytes); } @@ -265,17 +242,11 @@ public static void SendExecutionLog(string executionLog) //throw; } - - - - //}).Start(); - } public static void SendMessage(string message) { - if (webSocket == null) { return; @@ -287,8 +258,6 @@ public static void SendMessage(string message) return; } - - //create message package var socketPkg = new SocketPackage(); socketPkg.PUBLIC_KEY = publicKey; @@ -334,20 +303,16 @@ public static string GetSocketState() private static void RunXMLScript(string scriptData) { - - associatedBuilder.Invoke(new MethodInvoker(delegate () { - UI.Forms.frmScriptEngine newEngine = new UI.Forms.frmScriptEngine(); + var newEngine = new UI.Forms.ScriptEngine.frmScriptEngine(); newEngine.xmlData = scriptData; newEngine.callBackForm = null; newEngine.Show(); })); - } } - /// /// Model for sending data to taskt Server /// @@ -358,6 +323,7 @@ public class SocketPackage public string USER_NAME { get; set; } public string MESSAGE { get; set; } } + /// /// Exception defines Invalid Socket URI passed by user /// diff --git a/taskt/Core/Update/ApplicationUpdate.cs b/taskt/Core/Update/ApplicationUpdate.cs index 733ca7219..30e2e3981 100644 --- a/taskt/Core/Update/ApplicationUpdate.cs +++ b/taskt/Core/Update/ApplicationUpdate.cs @@ -61,7 +61,7 @@ private static UpdateManifest CheckUpdateAvailable(UpdateManifest manifest) /// public static void ShowUpdateResultSync(bool skipBeta, bool silent = true) { - ApplicationUpdate.SkipBeta = skipBeta; + SkipBeta = skipBeta; UpdateManifest manifest; try @@ -74,7 +74,7 @@ public static void ShowUpdateResultSync(bool skipBeta, bool silent = true) { if (!silent) { - using (var fm = new taskt.UI.Forms.Supplemental.frmDialog("Error getting manifest: " + ex.ToString(), "Error", taskt.UI.Forms.Supplemental.frmDialog.DialogType.OkOnly, 0)) + using (var fm = new UI.Forms.General.frmDialog("Error getting manifest: " + ex.ToString(), "Error", UI.Forms.General.frmDialog.DialogType.OkOnly, 0)) { fm.ShowDialog(); } @@ -92,7 +92,7 @@ public static void ShowUpdateResultSync(bool skipBeta, bool silent = true) { if (!silent) { - using (var fm = new taskt.UI.Forms.Supplemental.frmDialog("taskt is currently up-to-date!", "No Updates Available", taskt.UI.Forms.Supplemental.frmDialog.DialogType.OkOnly, 0)) + using (var fm = new UI.Forms.General.frmDialog("taskt is currently up-to-date!", "No Updates Available", UI.Forms.General.frmDialog.DialogType.OkOnly, 0)) { fm.ShowDialog(); } @@ -105,7 +105,7 @@ public static void ShowUpdateResultSync(bool skipBeta, bool silent = true) /// public static void ShowUpdateResultAsync(bool skipBeta) { - ApplicationUpdate.SkipBeta = skipBeta; + SkipBeta = skipBeta; //get manifest try @@ -158,7 +158,7 @@ private static void CompleteDownloadUpdateManifest(object sender, DownloadString /// private static void ShowUpdateForm(UpdateManifest manifestConfig) { - using (var frmUpdate = new taskt.UI.Forms.Supplement_Forms.frmUpdate(manifestConfig)) + using (var frmUpdate = new UI.Forms.ScriptBuilder.Supplemental.frmUpdate(manifestConfig)) { if (frmUpdate.ShowDialog() == DialogResult.OK) { @@ -168,7 +168,7 @@ private static void ShowUpdateForm(UpdateManifest manifestConfig) if (!System.IO.File.Exists(updaterExecutionResources)) { - using (var fm = new taskt.UI.Forms.Supplemental.frmDialog("taskt-updater.exe not found in Resources folder!", "Error", taskt.UI.Forms.Supplemental.frmDialog.DialogType.OkOnly, 0)) + using (var fm = new UI.Forms.General.frmDialog("taskt-updater.exe not found in Resources folder!", "Error", UI.Forms.General.frmDialog.DialogType.OkOnly, 0)) { fm.ShowDialog(); } diff --git a/taskt/Program.cs b/taskt/Program.cs index 24ba77696..bc1edc809 100644 --- a/taskt/Program.cs +++ b/taskt/Program.cs @@ -90,16 +90,16 @@ static void Main(string[] args) if (type == "run") { - Application.Run(new UI.Forms.frmScriptEngine(filePath, null, null, true)); + Application.Run(new UI.Forms.ScriptEngine.frmScriptEngine(filePath, null, null, true)); } else { - SplashForm = new UI.Forms.Supplemental.frmSplash(); + SplashForm = new UI.Forms.Splash.frmSplash(); SplashForm.Show(); Application.DoEvents(); - Application.Run(new UI.Forms.frmScriptBuilder(filePath)); + Application.Run(new UI.Forms.ScriptBuilder.frmScriptBuilder(filePath)); } } else @@ -112,12 +112,12 @@ static void Main(string[] args) System.IO.File.Delete(updaterExecutableDestination); } - SplashForm = new UI.Forms.Supplemental.frmSplash(); + SplashForm = new UI.Forms.Splash.frmSplash(); SplashForm.Show(); Application.DoEvents(); - Application.Run(new UI.Forms.frmScriptBuilder()); + Application.Run(new UI.Forms.ScriptBuilder.frmScriptBuilder()); } } [System.Runtime.InteropServices.DllImport("user32.dll")] @@ -128,8 +128,6 @@ static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEv MessageBox.Show("An unhandled exception occured: " + (e.ExceptionObject as Exception).ToString(), "Oops"); } - public static UI.Forms.Supplemental.frmSplash SplashForm { get; set; } - - + public static UI.Forms.Splash.frmSplash SplashForm { get; set; } } } \ No newline at end of file diff --git a/taskt/Properties/AssemblyInfo.cs b/taskt/Properties/AssemblyInfo.cs index f5657e661..63fc104d1 100644 --- a/taskt/Properties/AssemblyInfo.cs +++ b/taskt/Properties/AssemblyInfo.cs @@ -23,7 +23,7 @@ [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("taskt")] -[assembly: AssemblyCopyright("Copyright ©2022")] +[assembly: AssemblyCopyright("Copyright ©2023")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] diff --git a/taskt/Resources/IEDriverServer.exe b/taskt/Resources/IEDriverServer.exe index 501fe4a54..c8fa95242 100644 Binary files a/taskt/Resources/IEDriverServer.exe and b/taskt/Resources/IEDriverServer.exe differ diff --git a/taskt/Resources/chromedriver.exe b/taskt/Resources/chromedriver.exe index 5a609b97e..8e205f72d 100644 Binary files a/taskt/Resources/chromedriver.exe and b/taskt/Resources/chromedriver.exe differ diff --git a/taskt/Resources/geckodriver.exe b/taskt/Resources/geckodriver.exe index 8b0f1032e..c1e43c861 100644 Binary files a/taskt/Resources/geckodriver.exe and b/taskt/Resources/geckodriver.exe differ diff --git a/taskt/Resources/msedgedriver.exe b/taskt/Resources/msedgedriver.exe index df3dbf16b..1efdd43b5 100644 Binary files a/taskt/Resources/msedgedriver.exe and b/taskt/Resources/msedgedriver.exe differ diff --git a/taskt/Resources/sample_ocr_image.png b/taskt/Resources/sample_ocr_image.png new file mode 100644 index 000000000..af846b50a Binary files /dev/null and b/taskt/Resources/sample_ocr_image.png differ diff --git a/taskt/Resources/taskt-updater.exe b/taskt/Resources/taskt-updater.exe index 18d2e72ba..a3dc4c69e 100644 Binary files a/taskt/Resources/taskt-updater.exe and b/taskt/Resources/taskt-updater.exe differ diff --git a/taskt/Samples/Application_Script_Commands/Execute_Notepad_Start_Application.xml b/taskt/Samples/Application_Script_Commands/Execute_Notepad_Start_Application.xml new file mode 100644 index 000000000..5811e09f4 --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Execute_Notepad_Start_Application.xml @@ -0,0 +1,48 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Run_Batch_Script_File.xml b/taskt/Samples/Application_Script_Commands/Run_Batch_Script_File.xml new file mode 100644 index 000000000..caa7dd373 --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Run_Batch_Script_File.xml @@ -0,0 +1,21 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Run_By_Run_Script_File.xml b/taskt/Samples/Application_Script_Commands/Run_By_Run_Script_File.xml new file mode 100644 index 000000000..d28247037 --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Run_By_Run_Script_File.xml @@ -0,0 +1,21 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Run_By_Run_Script_File_Assign_Variable.xml b/taskt/Samples/Application_Script_Commands/Run_By_Run_Script_File_Assign_Variable.xml new file mode 100644 index 000000000..6b69b3f9b --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Run_By_Run_Script_File_Assign_Variable.xml @@ -0,0 +1,29 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Run_CSharp_Code.xml b/taskt/Samples/Application_Script_Commands/Run_CSharp_Code.xml new file mode 100644 index 000000000..1b66df55f --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Run_CSharp_Code.xml @@ -0,0 +1,21 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Run_CSharp_Code_Return_Value.xml b/taskt/Samples/Application_Script_Commands/Run_CSharp_Code_Return_Value.xml new file mode 100644 index 000000000..63e131c6e --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Run_CSharp_Code_Return_Value.xml @@ -0,0 +1,29 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Run_CSharp_Code_with_Arguments.xml b/taskt/Samples/Application_Script_Commands/Run_CSharp_Code_with_Arguments.xml new file mode 100644 index 000000000..f9b103b1d --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Run_CSharp_Code_with_Arguments.xml @@ -0,0 +1,38 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Run_JavaScript_File_Return_Value.xml b/taskt/Samples/Application_Script_Commands/Run_JavaScript_File_Return_Value.xml new file mode 100644 index 000000000..20ba0a9f5 --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Run_JavaScript_File_Return_Value.xml @@ -0,0 +1,32 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Run_JavaScript_File_Send_Argument.xml b/taskt/Samples/Application_Script_Commands/Run_JavaScript_File_Send_Argument.xml new file mode 100644 index 000000000..a4a47a911 --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Run_JavaScript_File_Send_Argument.xml @@ -0,0 +1,29 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Run_Script_File.xml b/taskt/Samples/Application_Script_Commands/Run_Script_File.xml new file mode 100644 index 000000000..283db3c67 --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Run_Script_File.xml @@ -0,0 +1,50 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Run_Script_File_Assing_Variable.xml b/taskt/Samples/Application_Script_Commands/Run_Script_File_Assing_Variable.xml new file mode 100644 index 000000000..b783ffaa3 --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Run_Script_File_Assing_Variable.xml @@ -0,0 +1,72 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Start_Application.xml b/taskt/Samples/Application_Script_Commands/Start_Application.xml new file mode 100644 index 000000000..fee2a8587 --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Start_Application.xml @@ -0,0 +1,42 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Application_Script_Commands/Start_Application_Stop_Application.xml b/taskt/Samples/Application_Script_Commands/Start_Application_Stop_Application.xml new file mode 100644 index 000000000..31153da54 --- /dev/null +++ b/taskt/Samples/Application_Script_Commands/Start_Application_Stop_Application.xml @@ -0,0 +1,41 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Color_Commands/Convert_Color_From_Excel_Color.xml b/taskt/Samples/Color_Commands/Convert_Color_From_Excel_Color.xml new file mode 100644 index 000000000..3e8158ce9 --- /dev/null +++ b/taskt/Samples/Color_Commands/Convert_Color_From_Excel_Color.xml @@ -0,0 +1,36 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Color_Commands/Convert_Color_From_HEX.xml b/taskt/Samples/Color_Commands/Convert_Color_From_HEX.xml new file mode 100644 index 000000000..912fde036 --- /dev/null +++ b/taskt/Samples/Color_Commands/Convert_Color_From_HEX.xml @@ -0,0 +1,36 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Color_Commands/Create_Color_Convert_Color.xml b/taskt/Samples/Color_Commands/Create_Color_Convert_Color.xml new file mode 100644 index 000000000..e32fbe246 --- /dev/null +++ b/taskt/Samples/Color_Commands/Create_Color_Convert_Color.xml @@ -0,0 +1,92 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Color_Commands/Create_Color_Format_Color.xml b/taskt/Samples/Color_Commands/Create_Color_Format_Color.xml deleted file mode 100644 index b96a4fe63..000000000 --- a/taskt/Samples/Color_Commands/Create_Color_Format_Color.xml +++ /dev/null @@ -1,91 +0,0 @@ - - \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Add_DataTable_Column.xml b/taskt/Samples/DataTable_Commands/Add_DataTable_Column.xml index dee1dfd18..53a051aa2 100644 --- a/taskt/Samples/DataTable_Commands/Add_DataTable_Column.xml +++ b/taskt/Samples/DataTable_Commands/Add_DataTable_Column.xml @@ -2,13 +2,13 @@ \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Add_DataTable_Row_By_DataTable.xml b/taskt/Samples/DataTable_Commands/Add_DataTable_Row_By_DataTable.xml index 273afdc21..41c4e48c8 100644 --- a/taskt/Samples/DataTable_Commands/Add_DataTable_Row_By_DataTable.xml +++ b/taskt/Samples/DataTable_Commands/Add_DataTable_Row_By_DataTable.xml @@ -2,19 +2,19 @@ \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Convert_DataTable_Column_To_List.xml b/taskt/Samples/DataTable_Commands/Convert_DataTable_Column_To_List.xml index 523028c96..cbcb38200 100644 --- a/taskt/Samples/DataTable_Commands/Convert_DataTable_Column_To_List.xml +++ b/taskt/Samples/DataTable_Commands/Convert_DataTable_Column_To_List.xml @@ -2,26 +2,25 @@ \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Convert_DataTable_Row_To_DataTable.xml b/taskt/Samples/DataTable_Commands/Convert_DataTable_Row_To_DataTable.xml index fd6376915..e3af511c3 100644 --- a/taskt/Samples/DataTable_Commands/Convert_DataTable_Row_To_DataTable.xml +++ b/taskt/Samples/DataTable_Commands/Convert_DataTable_Row_To_DataTable.xml @@ -2,26 +2,25 @@ \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Convert_DataTable_To_Text.xml b/taskt/Samples/DataTable_Commands/Convert_DataTable_To_Text.xml new file mode 100644 index 000000000..a662ac4f9 --- /dev/null +++ b/taskt/Samples/DataTable_Commands/Convert_DataTable_To_Text.xml @@ -0,0 +1,166 @@ + + \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Copy_DataTable.xml b/taskt/Samples/DataTable_Commands/Copy_DataTable.xml index bf63cbb9a..464d9d102 100644 --- a/taskt/Samples/DataTable_Commands/Copy_DataTable.xml +++ b/taskt/Samples/DataTable_Commands/Copy_DataTable.xml @@ -2,13 +2,13 @@ \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Delete_DataTable_Column.xml b/taskt/Samples/DataTable_Commands/Delete_DataTable_Column.xml index 44c8932dd..8c4ada410 100644 --- a/taskt/Samples/DataTable_Commands/Delete_DataTable_Column.xml +++ b/taskt/Samples/DataTable_Commands/Delete_DataTable_Column.xml @@ -2,26 +2,25 @@ \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Export_DataTable__Column_As_Text.xml b/taskt/Samples/DataTable_Commands/Export_DataTable__Column_As_Text.xml new file mode 100644 index 000000000..21dc9cc06 --- /dev/null +++ b/taskt/Samples/DataTable_Commands/Export_DataTable__Column_As_Text.xml @@ -0,0 +1,159 @@ + + \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Export_DataTable__Row_As_Text.xml b/taskt/Samples/DataTable_Commands/Export_DataTable__Row_As_Text.xml new file mode 100644 index 000000000..0362fe0ac --- /dev/null +++ b/taskt/Samples/DataTable_Commands/Export_DataTable__Row_As_Text.xml @@ -0,0 +1,159 @@ + + \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Filter_DataTable_Column_By_Row_Value.xml b/taskt/Samples/DataTable_Commands/Filter_DataTable_Column_By_Row_Value.xml new file mode 100644 index 000000000..271d9e9d5 --- /dev/null +++ b/taskt/Samples/DataTable_Commands/Filter_DataTable_Column_By_Row_Value.xml @@ -0,0 +1,300 @@ + + \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Filter_DataTable_Row_By_Column_Value.xml b/taskt/Samples/DataTable_Commands/Filter_DataTable_Row_By_Column_Value.xml index 42c3e4c00..0e4fe900f 100644 --- a/taskt/Samples/DataTable_Commands/Filter_DataTable_Row_By_Column_Value.xml +++ b/taskt/Samples/DataTable_Commands/Filter_DataTable_Row_By_Column_Value.xml @@ -2,13 +2,13 @@ \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Join_DataTable_Column_As_List.xml b/taskt/Samples/DataTable_Commands/Join_DataTable_Column_As_List.xml new file mode 100644 index 000000000..de0515470 --- /dev/null +++ b/taskt/Samples/DataTable_Commands/Join_DataTable_Column_As_List.xml @@ -0,0 +1,166 @@ + + \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Join_DataTable_Row_As_Text.xml b/taskt/Samples/DataTable_Commands/Join_DataTable_Row_As_Text.xml new file mode 100644 index 000000000..5d9c902e9 --- /dev/null +++ b/taskt/Samples/DataTable_Commands/Join_DataTable_Row_As_Text.xml @@ -0,0 +1,166 @@ + + \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Replace_DataTable_Column_By_Row_Value.xml b/taskt/Samples/DataTable_Commands/Replace_DataTable_Column_By_Row_Value.xml new file mode 100644 index 000000000..71407c33f --- /dev/null +++ b/taskt/Samples/DataTable_Commands/Replace_DataTable_Column_By_Row_Value.xml @@ -0,0 +1,296 @@ + + \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Replace_DataTable_Column_Value.xml b/taskt/Samples/DataTable_Commands/Replace_DataTable_Column_Value.xml index 69e1e51bb..af00fd708 100644 --- a/taskt/Samples/DataTable_Commands/Replace_DataTable_Column_Value.xml +++ b/taskt/Samples/DataTable_Commands/Replace_DataTable_Column_Value.xml @@ -2,13 +2,13 @@ \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Set_DataTable_Column_By_DataTable.xml b/taskt/Samples/DataTable_Commands/Set_DataTable_Column_By_DataTable.xml index cf6da4613..a51915f39 100644 --- a/taskt/Samples/DataTable_Commands/Set_DataTable_Column_By_DataTable.xml +++ b/taskt/Samples/DataTable_Commands/Set_DataTable_Column_By_DataTable.xml @@ -2,26 +2,25 @@ \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Set_DataTable_Column_Values_By_List.xml b/taskt/Samples/DataTable_Commands/Set_DataTable_Column_Values_By_List.xml new file mode 100644 index 000000000..9a4467a92 --- /dev/null +++ b/taskt/Samples/DataTable_Commands/Set_DataTable_Column_Values_By_List.xml @@ -0,0 +1,236 @@ + + \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Set_DataTable_Row_By_DataTable.xml b/taskt/Samples/DataTable_Commands/Set_DataTable_Row_By_DataTable.xml index 39bda93a0..d04d3c281 100644 --- a/taskt/Samples/DataTable_Commands/Set_DataTable_Row_By_DataTable.xml +++ b/taskt/Samples/DataTable_Commands/Set_DataTable_Row_By_DataTable.xml @@ -2,13 +2,13 @@ \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Show_All_DataTable_Items_Column_First_Loop.xml b/taskt/Samples/DataTable_Commands/Show_All_DataTable_Items_Column_First_Loop.xml new file mode 100644 index 000000000..de08b29e8 --- /dev/null +++ b/taskt/Samples/DataTable_Commands/Show_All_DataTable_Items_Column_First_Loop.xml @@ -0,0 +1,194 @@ + + \ No newline at end of file diff --git a/taskt/Samples/DataTable_Commands/Show_All_DataTable_Items_columns.xml b/taskt/Samples/DataTable_Commands/Show_All_DataTable_Items_Row_Column_Index.xml similarity index 60% rename from taskt/Samples/DataTable_Commands/Show_All_DataTable_Items_columns.xml rename to taskt/Samples/DataTable_Commands/Show_All_DataTable_Items_Row_Column_Index.xml index 9f92c7ee4..4e026c7b4 100644 --- a/taskt/Samples/DataTable_Commands/Show_All_DataTable_Items_columns.xml +++ b/taskt/Samples/DataTable_Commands/Show_All_DataTable_Items_Row_Column_Index.xml @@ -2,26 +2,25 @@ \ No newline at end of file diff --git a/taskt/Samples/DateTime_Commands/Convert_DateTime_To_Excel_Serial.xml b/taskt/Samples/DateTime_Commands/Convert_DateTime_To_Excel_Serial.xml new file mode 100644 index 000000000..421346b84 --- /dev/null +++ b/taskt/Samples/DateTime_Commands/Convert_DateTime_To_Excel_Serial.xml @@ -0,0 +1,45 @@ + + \ No newline at end of file diff --git a/taskt/Samples/DateTime_Commands/Create_DateTime_Format_DateTime_Calculate_DateTime.xml b/taskt/Samples/DateTime_Commands/Create_DateTime_Format_DateTime_Calculate_DateTime.xml index 63bad15b0..74ac076da 100644 --- a/taskt/Samples/DateTime_Commands/Create_DateTime_Format_DateTime_Calculate_DateTime.xml +++ b/taskt/Samples/DateTime_Commands/Create_DateTime_Format_DateTime_Calculate_DateTime.xml @@ -2,47 +2,48 @@ \ No newline at end of file diff --git a/taskt/Samples/DateTime_Commands/Create_DateTime_From_Text.xml b/taskt/Samples/DateTime_Commands/Create_DateTime_From_Text.xml new file mode 100644 index 000000000..8e2779309 --- /dev/null +++ b/taskt/Samples/DateTime_Commands/Create_DateTime_From_Text.xml @@ -0,0 +1,60 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Input_Commands/Open_File_Dialog.xml b/taskt/Samples/Dialog_Message_Commands/Open_File_Dialog_Show_File_Dialog.xml similarity index 72% rename from taskt/Samples/Input_Commands/Open_File_Dialog.xml rename to taskt/Samples/Dialog_Message_Commands/Open_File_Dialog_Show_File_Dialog.xml index d82a1cbd4..9f4241f5c 100644 --- a/taskt/Samples/Input_Commands/Open_File_Dialog.xml +++ b/taskt/Samples/Dialog_Message_Commands/Open_File_Dialog_Show_File_Dialog.xml @@ -2,16 +2,16 @@ \ No newline at end of file diff --git a/taskt/Samples/Dialog_Message_Commands/Show_HTML_Input_Dialog_2.xml b/taskt/Samples/Dialog_Message_Commands/Show_HTML_Input_Dialog_2.xml new file mode 100644 index 000000000..ba2bd625b --- /dev/null +++ b/taskt/Samples/Dialog_Message_Commands/Show_HTML_Input_Dialog_2.xml @@ -0,0 +1,61 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Dialog_Message_Commands/Show_Message.xml b/taskt/Samples/Dialog_Message_Commands/Show_Message.xml new file mode 100644 index 000000000..f3c5aef46 --- /dev/null +++ b/taskt/Samples/Dialog_Message_Commands/Show_Message.xml @@ -0,0 +1,29 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Dialog_Message_Commands/Show_Message_2.xml b/taskt/Samples/Dialog_Message_Commands/Show_Message_2.xml new file mode 100644 index 000000000..80338401c --- /dev/null +++ b/taskt/Samples/Dialog_Message_Commands/Show_Message_2.xml @@ -0,0 +1,24 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Input_Commands/UserInput.xml b/taskt/Samples/Dialog_Message_Commands/Show_User_Input_Dialog.xml similarity index 72% rename from taskt/Samples/Input_Commands/UserInput.xml rename to taskt/Samples/Dialog_Message_Commands/Show_User_Input_Dialog.xml index 4586dfdb3..954208636 100644 --- a/taskt/Samples/Input_Commands/UserInput.xml +++ b/taskt/Samples/Dialog_Message_Commands/Show_User_Input_Dialog.xml @@ -2,31 +2,30 @@ \ No newline at end of file diff --git a/taskt/Samples/Dictionary_Commands/Copy_Dictionary.xml b/taskt/Samples/Dictionary_Commands/Copy_Dictionary.xml index cc77ece90..33fd560b0 100644 --- a/taskt/Samples/Dictionary_Commands/Copy_Dictionary.xml +++ b/taskt/Samples/Dictionary_Commands/Copy_Dictionary.xml @@ -2,27 +2,26 @@ \ No newline at end of file diff --git a/taskt/Samples/Dictionary_Commands/Export_Dictionary_As_Text_File.xml b/taskt/Samples/Dictionary_Commands/Export_Dictionary_As_Text_File.xml new file mode 100644 index 000000000..61189365a --- /dev/null +++ b/taskt/Samples/Dictionary_Commands/Export_Dictionary_As_Text_File.xml @@ -0,0 +1,84 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Dictionary_Commands/Filter_Dictionary.xml b/taskt/Samples/Dictionary_Commands/Filter_Dictionary.xml index 8d053dcf3..b809551c7 100644 --- a/taskt/Samples/Dictionary_Commands/Filter_Dictionary.xml +++ b/taskt/Samples/Dictionary_Commands/Filter_Dictionary.xml @@ -2,13 +2,13 @@ \ No newline at end of file diff --git a/taskt/Samples/Dictionary_Commands/Show_All_Dictionary_Items.xml b/taskt/Samples/Dictionary_Commands/Show_All_Dictionary_Items.xml index 0292fefac..cb2da607f 100644 --- a/taskt/Samples/Dictionary_Commands/Show_All_Dictionary_Items.xml +++ b/taskt/Samples/Dictionary_Commands/Show_All_Dictionary_Items.xml @@ -2,13 +2,13 @@ \ No newline at end of file diff --git a/taskt/Samples/Error_Handling/If_Error_Occured.xml b/taskt/Samples/Error_Handling/Error_Handling_If_Error_Occured.xml similarity index 61% rename from taskt/Samples/Error_Handling/If_Error_Occured.xml rename to taskt/Samples/Error_Handling/Error_Handling_If_Error_Occured.xml index 4f8515d05..e9edaa9f7 100644 --- a/taskt/Samples/Error_Handling/If_Error_Occured.xml +++ b/taskt/Samples/Error_Handling/Error_Handling_If_Error_Occured.xml @@ -2,36 +2,35 @@ \ No newline at end of file diff --git a/taskt/Samples/Error_Handling/Try_Catch_error_handling.xml b/taskt/Samples/Error_Handling/Try_Catch_Exeption_Finally_End_Try.xml similarity index 62% rename from taskt/Samples/Error_Handling/Try_Catch_error_handling.xml rename to taskt/Samples/Error_Handling/Try_Catch_Exeption_Finally_End_Try.xml index 59210bccf..5fd62d6cc 100644 --- a/taskt/Samples/Error_Handling/Try_Catch_error_handling.xml +++ b/taskt/Samples/Error_Handling/Try_Catch_Exeption_Finally_End_Try.xml @@ -2,51 +2,51 @@ \ No newline at end of file diff --git a/taskt/Samples/File_Operation_Commands/Copy_File.xml b/taskt/Samples/File_Operation_Commands/Copy_File.xml new file mode 100644 index 000000000..64b30c405 --- /dev/null +++ b/taskt/Samples/File_Operation_Commands/Copy_File.xml @@ -0,0 +1,27 @@ + + \ No newline at end of file diff --git a/taskt/Samples/File_Operation_Commands/Delete_File.xml b/taskt/Samples/File_Operation_Commands/Delete_File.xml new file mode 100644 index 000000000..adc43af11 --- /dev/null +++ b/taskt/Samples/File_Operation_Commands/Delete_File.xml @@ -0,0 +1,30 @@ + + \ No newline at end of file diff --git a/taskt/Samples/File_Operation_Commands/Delete_File_Move_To_Recycle_Bin.xml b/taskt/Samples/File_Operation_Commands/Delete_File_Move_To_Recycle_Bin.xml new file mode 100644 index 000000000..2ec525ed5 --- /dev/null +++ b/taskt/Samples/File_Operation_Commands/Delete_File_Move_To_Recycle_Bin.xml @@ -0,0 +1,30 @@ + + \ No newline at end of file diff --git a/taskt/Samples/File_Operation_Commands/Extract_Zip_File_Wait_For_File_To_Exists.xml b/taskt/Samples/File_Operation_Commands/Extract_Zip_File_Wait_For_File_To_Exists.xml new file mode 100644 index 000000000..e95dcf4df --- /dev/null +++ b/taskt/Samples/File_Operation_Commands/Extract_Zip_File_Wait_For_File_To_Exists.xml @@ -0,0 +1,45 @@ + + \ No newline at end of file diff --git a/taskt/Samples/File_Operation_Commands/Extraction_File_Path.xml b/taskt/Samples/File_Operation_Commands/Extraction_File_Path.xml new file mode 100644 index 000000000..a413ff8be --- /dev/null +++ b/taskt/Samples/File_Operation_Commands/Extraction_File_Path.xml @@ -0,0 +1,47 @@ + + \ No newline at end of file diff --git a/taskt/Samples/File_Operation_Commands/Get_File_Info.xml b/taskt/Samples/File_Operation_Commands/Get_File_Info.xml new file mode 100644 index 000000000..00cbe3321 --- /dev/null +++ b/taskt/Samples/File_Operation_Commands/Get_File_Info.xml @@ -0,0 +1,53 @@ + + \ No newline at end of file diff --git a/taskt/Samples/File_Operation_Commands/Get_Files.xml b/taskt/Samples/File_Operation_Commands/Get_Files.xml index 57252c9e6..bbb731cd2 100644 --- a/taskt/Samples/File_Operation_Commands/Get_Files.xml +++ b/taskt/Samples/File_Operation_Commands/Get_Files.xml @@ -2,41 +2,61 @@ \ No newline at end of file diff --git a/taskt/Samples/File_Operation_Commands/Rename_File.xml b/taskt/Samples/File_Operation_Commands/Rename_File.xml new file mode 100644 index 000000000..93ac83364 --- /dev/null +++ b/taskt/Samples/File_Operation_Commands/Rename_File.xml @@ -0,0 +1,30 @@ + + \ No newline at end of file diff --git a/taskt/Samples/File_Operation_Commands/Rename_File_Change_Extention.xml b/taskt/Samples/File_Operation_Commands/Rename_File_Change_Extention.xml new file mode 100644 index 000000000..23318e384 --- /dev/null +++ b/taskt/Samples/File_Operation_Commands/Rename_File_Change_Extention.xml @@ -0,0 +1,33 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Folder_Operation_Commands/Check_Folder_Exists.xml b/taskt/Samples/Folder_Operation_Commands/Check_Folder_Exists.xml new file mode 100644 index 000000000..6ccf0c919 --- /dev/null +++ b/taskt/Samples/Folder_Operation_Commands/Check_Folder_Exists.xml @@ -0,0 +1,41 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Folder_Operation_Commands/Copy_Folder.xml b/taskt/Samples/Folder_Operation_Commands/Copy_Folder.xml new file mode 100644 index 000000000..49ccab6f3 --- /dev/null +++ b/taskt/Samples/Folder_Operation_Commands/Copy_Folder.xml @@ -0,0 +1,30 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Folder_Operation_Commands/Delete_Folder.xml b/taskt/Samples/Folder_Operation_Commands/Delete_Folder.xml new file mode 100644 index 000000000..be1ea9664 --- /dev/null +++ b/taskt/Samples/Folder_Operation_Commands/Delete_Folder.xml @@ -0,0 +1,36 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Folder_Operation_Commands/Delete_Folder_to_Recycle_Bin.xml b/taskt/Samples/Folder_Operation_Commands/Delete_Folder_to_Recycle_Bin.xml new file mode 100644 index 000000000..16b448fc0 --- /dev/null +++ b/taskt/Samples/Folder_Operation_Commands/Delete_Folder_to_Recycle_Bin.xml @@ -0,0 +1,36 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Folder_Operation_Commands/Extraction_Folder_Path.xml b/taskt/Samples/Folder_Operation_Commands/Extraction_Folder_Path.xml new file mode 100644 index 000000000..4e8bb3455 --- /dev/null +++ b/taskt/Samples/Folder_Operation_Commands/Extraction_Folder_Path.xml @@ -0,0 +1,41 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Folder_Operation_Commands/Get_Folders.xml b/taskt/Samples/Folder_Operation_Commands/Get_Folders.xml index 3adee5479..dd97d5ddf 100644 --- a/taskt/Samples/Folder_Operation_Commands/Get_Folders.xml +++ b/taskt/Samples/Folder_Operation_Commands/Get_Folders.xml @@ -2,35 +2,39 @@ \ No newline at end of file diff --git a/taskt/Samples/Folder_Operation_Commands/Move_Folder.xml b/taskt/Samples/Folder_Operation_Commands/Move_Folder.xml new file mode 100644 index 000000000..f3b445955 --- /dev/null +++ b/taskt/Samples/Folder_Operation_Commands/Move_Folder.xml @@ -0,0 +1,36 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Folder_Operation_Commands/Rename_Folder.xml b/taskt/Samples/Folder_Operation_Commands/Rename_Folder.xml new file mode 100644 index 000000000..cc9efeae4 --- /dev/null +++ b/taskt/Samples/Folder_Operation_Commands/Rename_Folder.xml @@ -0,0 +1,36 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Folder_Operation_Commands/Wait_For_Folder_To_Exists.xml b/taskt/Samples/Folder_Operation_Commands/Wait_For_Folder_To_Exists.xml new file mode 100644 index 000000000..6c20f5393 --- /dev/null +++ b/taskt/Samples/Folder_Operation_Commands/Wait_For_Folder_To_Exists.xml @@ -0,0 +1,27 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Image_Commands/Execute_OCR.xml b/taskt/Samples/Image_Commands/Execute_OCR.xml new file mode 100644 index 000000000..cfc80415b --- /dev/null +++ b/taskt/Samples/Image_Commands/Execute_OCR.xml @@ -0,0 +1,35 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Image_Commands/Image_Recognition.xml b/taskt/Samples/Image_Commands/Image_Recognition.xml index 540d99526..4002135f6 100644 --- a/taskt/Samples/Image_Commands/Image_Recognition.xml +++ b/taskt/Samples/Image_Commands/Image_Recognition.xml @@ -2,37 +2,41 @@ \ No newline at end of file diff --git a/taskt/Samples/Key_Mouse_Commands/Enter_Shortcut_Key.xml b/taskt/Samples/Key_Mouse_Commands/Enter_Shortcut_Key.xml new file mode 100644 index 000000000..69dfbbfa4 --- /dev/null +++ b/taskt/Samples/Key_Mouse_Commands/Enter_Shortcut_Key.xml @@ -0,0 +1,48 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Key_Mouse_Commands/Mouse_Move_Click_Drag_Move_Mouse_Click_Mouse.xml b/taskt/Samples/Key_Mouse_Commands/Mouse_Move_Click_Drag_Move_Mouse_Click_Mouse.xml new file mode 100644 index 000000000..4cd12d320 --- /dev/null +++ b/taskt/Samples/Key_Mouse_Commands/Mouse_Move_Click_Drag_Move_Mouse_Click_Mouse.xml @@ -0,0 +1,63 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Key_Mouse_Commands/Send_Advanced_Keystrokes.xml b/taskt/Samples/Key_Mouse_Commands/Send_Advanced_Keystrokes.xml new file mode 100644 index 000000000..ce6275415 --- /dev/null +++ b/taskt/Samples/Key_Mouse_Commands/Send_Advanced_Keystrokes.xml @@ -0,0 +1,122 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Key_Mouse_Commands/Send_Advanced_Keystrokes_Alt_Tab.xml b/taskt/Samples/Key_Mouse_Commands/Send_Advanced_Keystrokes_Alt_Tab.xml new file mode 100644 index 000000000..a3e5ddbd8 --- /dev/null +++ b/taskt/Samples/Key_Mouse_Commands/Send_Advanced_Keystrokes_Alt_Tab.xml @@ -0,0 +1,158 @@ + + \ No newline at end of file diff --git a/taskt/Samples/List_Commands/Add_List_Item.xml b/taskt/Samples/List_Commands/Add_List_Item.xml index de2c17d38..fd49bedbd 100644 --- a/taskt/Samples/List_Commands/Add_List_Item.xml +++ b/taskt/Samples/List_Commands/Add_List_Item.xml @@ -2,26 +2,25 @@ \ No newline at end of file diff --git a/taskt/Samples/List_Commands/Convert_To_Text.xml b/taskt/Samples/List_Commands/Convert_To_Text.xml new file mode 100644 index 000000000..09d785943 --- /dev/null +++ b/taskt/Samples/List_Commands/Convert_To_Text.xml @@ -0,0 +1,84 @@ + + \ No newline at end of file diff --git a/taskt/Samples/List_Commands/Copy_List.xml b/taskt/Samples/List_Commands/Copy_List.xml index bc49a1aef..078b634ea 100644 --- a/taskt/Samples/List_Commands/Copy_List.xml +++ b/taskt/Samples/List_Commands/Copy_List.xml @@ -2,26 +2,25 @@ \ No newline at end of file diff --git a/taskt/Samples/List_Commands/Export_List_As_Text_File.xml b/taskt/Samples/List_Commands/Export_List_As_Text_File.xml new file mode 100644 index 000000000..2732ad62f --- /dev/null +++ b/taskt/Samples/List_Commands/Export_List_As_Text_File.xml @@ -0,0 +1,77 @@ + + \ No newline at end of file diff --git a/taskt/Samples/List_Commands/Filter_List.xml b/taskt/Samples/List_Commands/Filter_List.xml index 39ba7341b..6d927f936 100644 --- a/taskt/Samples/List_Commands/Filter_List.xml +++ b/taskt/Samples/List_Commands/Filter_List.xml @@ -2,13 +2,13 @@ \ No newline at end of file diff --git a/taskt/Samples/List_Commands/Replace_List.xml b/taskt/Samples/List_Commands/Replace_List.xml index 65a0db5b8..59aacf591 100644 --- a/taskt/Samples/List_Commands/Replace_List.xml +++ b/taskt/Samples/List_Commands/Replace_List.xml @@ -2,13 +2,13 @@ \ No newline at end of file diff --git a/taskt/Samples/Loop_Commands/Exit_Loop.xml b/taskt/Samples/Loop_Commands/Exit_Loop.xml new file mode 100644 index 000000000..078385ef4 --- /dev/null +++ b/taskt/Samples/Loop_Commands/Exit_Loop.xml @@ -0,0 +1,96 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Loop_Commands/Loop_Continuously_Loop_End_Loop.xml b/taskt/Samples/Loop_Commands/Loop_Continuously_Loop_End_Loop.xml new file mode 100644 index 000000000..390285fa2 --- /dev/null +++ b/taskt/Samples/Loop_Commands/Loop_Continuously_Loop_End_Loop.xml @@ -0,0 +1,105 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Loop_Commands/Loop_For_DataTable_Column_As_DataTable.xml b/taskt/Samples/Loop_Commands/Loop_For_DataTable_Column_As_DataTable.xml new file mode 100644 index 000000000..852e7ae1e --- /dev/null +++ b/taskt/Samples/Loop_Commands/Loop_For_DataTable_Column_As_DataTable.xml @@ -0,0 +1,184 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Loop_Commands/Loop_For_DataTable_Column_As_List.xml b/taskt/Samples/Loop_Commands/Loop_For_DataTable_Column_As_List.xml new file mode 100644 index 000000000..2a1b7a480 --- /dev/null +++ b/taskt/Samples/Loop_Commands/Loop_For_DataTable_Column_As_List.xml @@ -0,0 +1,184 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Loop_Commands/Loop_For_DataTable_Row_As_DataTable.xml b/taskt/Samples/Loop_Commands/Loop_For_DataTable_Row_As_DataTable.xml new file mode 100644 index 000000000..9adedd0f8 --- /dev/null +++ b/taskt/Samples/Loop_Commands/Loop_For_DataTable_Row_As_DataTable.xml @@ -0,0 +1,180 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Loop_Commands/Loop_For_DataTable_Row_As_Dictionary.xml b/taskt/Samples/Loop_Commands/Loop_For_DataTable_Row_As_Dictionary.xml new file mode 100644 index 000000000..917ba3447 --- /dev/null +++ b/taskt/Samples/Loop_Commands/Loop_For_DataTable_Row_As_Dictionary.xml @@ -0,0 +1,180 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Dictionary_Commands/Show_All_Dictionary_Items_used_by_Loop.xml b/taskt/Samples/Loop_Commands/Loop_For_Dictionary.xml similarity index 69% rename from taskt/Samples/Dictionary_Commands/Show_All_Dictionary_Items_used_by_Loop.xml rename to taskt/Samples/Loop_Commands/Loop_For_Dictionary.xml index 630624642..2aad695fa 100644 --- a/taskt/Samples/Dictionary_Commands/Show_All_Dictionary_Items_used_by_Loop.xml +++ b/taskt/Samples/Loop_Commands/Loop_For_Dictionary.xml @@ -2,13 +2,13 @@ \ No newline at end of file diff --git a/taskt/Samples/Loop_Commands/Loop_Number_Of_Times_End_Loop.xml b/taskt/Samples/Loop_Commands/Loop_Number_Of_Times_End_Loop.xml new file mode 100644 index 000000000..dbf46c5ed --- /dev/null +++ b/taskt/Samples/Loop_Commands/Loop_Number_Of_Times_End_Loop.xml @@ -0,0 +1,39 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Loop_Commands/Next_Loop.xml b/taskt/Samples/Loop_Commands/Next_Loop.xml new file mode 100644 index 000000000..293b99b34 --- /dev/null +++ b/taskt/Samples/Loop_Commands/Next_Loop.xml @@ -0,0 +1,102 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Misc_Commands/Show_Message_Command.xml b/taskt/Samples/Misc_Commands/Show_Message_Command.xml deleted file mode 100644 index 116850a70..000000000 --- a/taskt/Samples/Misc_Commands/Show_Message_Command.xml +++ /dev/null @@ -1,29 +0,0 @@ - - \ No newline at end of file diff --git a/taskt/Samples/Mouse/Mouse_Move_Click_Drag.xml b/taskt/Samples/Mouse/Mouse_Move_Click_Drag.xml deleted file mode 100644 index c07827094..000000000 --- a/taskt/Samples/Mouse/Mouse_Move_Click_Drag.xml +++ /dev/null @@ -1,62 +0,0 @@ - - \ No newline at end of file diff --git a/taskt/Samples/Program/Execute_Notepad.xml b/taskt/Samples/Program/Execute_Notepad.xml deleted file mode 100644 index d98db8186..000000000 --- a/taskt/Samples/Program/Execute_Notepad.xml +++ /dev/null @@ -1,47 +0,0 @@ - - \ No newline at end of file diff --git a/taskt/Samples/Program/Execute_Notepad_Start_Application.xml b/taskt/Samples/Program/Execute_Notepad_Start_Application.xml new file mode 100644 index 000000000..053358b5d --- /dev/null +++ b/taskt/Samples/Program/Execute_Notepad_Start_Application.xml @@ -0,0 +1,47 @@ + + \ No newline at end of file diff --git a/taskt/Samples/ProgramsProcess_Commands/Run_Custom_Code.xml b/taskt/Samples/ProgramsProcess_Commands/Run_Custom_Code.xml deleted file mode 100644 index 40874a588..000000000 --- a/taskt/Samples/ProgramsProcess_Commands/Run_Custom_Code.xml +++ /dev/null @@ -1,20 +0,0 @@ - - \ No newline at end of file diff --git a/taskt/Samples/ProgramsProcess_Commands/Run_Custom_Code_with_Arguments.xml b/taskt/Samples/ProgramsProcess_Commands/Run_Custom_Code_with_Arguments.xml deleted file mode 100644 index a3dc6a2b2..000000000 --- a/taskt/Samples/ProgramsProcess_Commands/Run_Custom_Code_with_Arguments.xml +++ /dev/null @@ -1,37 +0,0 @@ - - \ No newline at end of file diff --git a/taskt/Samples/ProgramsProcess_Commands/Start_Process.xml b/taskt/Samples/ProgramsProcess_Commands/Start_Process.xml deleted file mode 100644 index 3cc2f6dc5..000000000 --- a/taskt/Samples/ProgramsProcess_Commands/Start_Process.xml +++ /dev/null @@ -1,41 +0,0 @@ - - \ No newline at end of file diff --git a/taskt/Samples/Resources/UIAutomationTester.exe b/taskt/Samples/Resources/UIAutomationTester.exe new file mode 100644 index 000000000..933627cfe Binary files /dev/null and b/taskt/Samples/Resources/UIAutomationTester.exe differ diff --git a/taskt/Samples/Resources/calc.js b/taskt/Samples/Resources/calc.js new file mode 100644 index 000000000..61ba4311f --- /dev/null +++ b/taskt/Samples/Resources/calc.js @@ -0,0 +1,3 @@ +let a = 1; +let b = 1; +return (a + b); \ No newline at end of file diff --git a/taskt/Samples/Resources/dir.bat b/taskt/Samples/Resources/dir.bat new file mode 100644 index 000000000..872451932 --- /dev/null +++ b/taskt/Samples/Resources/dir.bat @@ -0,0 +1 @@ +dir \ No newline at end of file diff --git a/taskt/Samples/Resources/get_argument.js b/taskt/Samples/Resources/get_argument.js new file mode 100644 index 000000000..158e7d0bc --- /dev/null +++ b/taskt/Samples/Resources/get_argument.js @@ -0,0 +1,2 @@ +const arg = arguments[0]; +return "Hello " + arg; \ No newline at end of file diff --git a/taskt/Samples/Resources/sample_10mb.zip b/taskt/Samples/Resources/sample_10mb.zip new file mode 100644 index 000000000..49fbf6652 Binary files /dev/null and b/taskt/Samples/Resources/sample_10mb.zip differ diff --git a/taskt/Samples/Resources/sample_folder/test_file.txt b/taskt/Samples/Resources/sample_folder/test_file.txt new file mode 100644 index 000000000..c91048396 --- /dev/null +++ b/taskt/Samples/Resources/sample_folder/test_file.txt @@ -0,0 +1 @@ +This is sample_folder's file. \ No newline at end of file diff --git a/taskt/Samples/Resources/sample_text.txt b/taskt/Samples/Resources/sample_text.txt new file mode 100644 index 000000000..9d0ee7954 --- /dev/null +++ b/taskt/Samples/Resources/sample_text.txt @@ -0,0 +1 @@ +hello taskt \ No newline at end of file diff --git a/taskt/Samples/System_Commands/Launch_Remote_Desktop_sample.xml b/taskt/Samples/System_Commands/Launch_Remote_Desktop_sample.xml new file mode 100644 index 000000000..56a8bcc61 --- /dev/null +++ b/taskt/Samples/System_Commands/Launch_Remote_Desktop_sample.xml @@ -0,0 +1,69 @@ + + \ No newline at end of file diff --git a/taskt/Samples/System_Commands/Lock_computer.xml b/taskt/Samples/System_Commands/Lock_Computer_System_Action.xml similarity index 65% rename from taskt/Samples/System_Commands/Lock_computer.xml rename to taskt/Samples/System_Commands/Lock_Computer_System_Action.xml index 47e2d14b1..268ed8ed3 100644 --- a/taskt/Samples/System_Commands/Lock_computer.xml +++ b/taskt/Samples/System_Commands/Lock_Computer_System_Action.xml @@ -2,20 +2,20 @@ \ No newline at end of file diff --git a/taskt/Samples/System_Commands/UserName_ComputerName_Get_Environment_Variable.xml b/taskt/Samples/System_Commands/UserName_ComputerName_Get_Environment_Variable.xml new file mode 100644 index 000000000..a9362ffd7 --- /dev/null +++ b/taskt/Samples/System_Commands/UserName_ComputerName_Get_Environment_Variable.xml @@ -0,0 +1,38 @@ + + \ No newline at end of file diff --git a/taskt/Samples/Text_Commands/Replace Text.xml b/taskt/Samples/Text_Commands/Replace Text.xml deleted file mode 100644 index abe75c484..000000000 --- a/taskt/Samples/Text_Commands/Replace Text.xml +++ /dev/null @@ -1,44 +0,0 @@ - - \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_And_Window.xml b/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_And_Window.xml new file mode 100644 index 000000000..f4227f0df --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_And_Window.xml @@ -0,0 +1,286 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_And_Window_By_XPath.xml b/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_And_Window_By_XPath.xml new file mode 100644 index 000000000..bbc000db9 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_And_Window_By_XPath.xml @@ -0,0 +1,50 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_From_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_From_UIElement.xml new file mode 100644 index 000000000..b56bdbe2e --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_From_UIElement.xml @@ -0,0 +1,296 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_From_UIElement_By_XPath.xml b/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_From_UIElement_By_XPath.xml new file mode 100644 index 000000000..96fa62191 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Click_Button_Click_UIElement_Get_UIElement_From_UIElement_By_XPath.xml @@ -0,0 +1,62 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Click_Button_UIElement_Action.xml b/taskt/Samples/UIAutomation_Commands/Click_Button_UIElement_Action.xml new file mode 100644 index 000000000..b473347eb --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Click_Button_UIElement_Action.xml @@ -0,0 +1,326 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Click_Button_UIElement_Action_By_XPath.xml b/taskt/Samples/UIAutomation_Commands/Click_Button_UIElement_Action_By_XPath.xml new file mode 100644 index 000000000..f146b20df --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Click_Button_UIElement_Action_By_XPath.xml @@ -0,0 +1,89 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Click_CheckBox_Click_UIElement_Get_UIElement_From_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Click_CheckBox_Click_UIElement_Get_UIElement_From_UIElement.xml new file mode 100644 index 000000000..3e228def1 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Click_CheckBox_Click_UIElement_Get_UIElement_From_UIElement.xml @@ -0,0 +1,297 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Click_RadioButton_Click_UIElement_Get_UIElement_From_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Click_RadioButton_Click_UIElement_Get_UIElement_From_UIElement.xml new file mode 100644 index 000000000..90842b108 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Click_RadioButton_Click_UIElement_Get_UIElement_From_UIElement.xml @@ -0,0 +1,297 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Click_Tab_Click_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Click_Tab_Click_UIElement.xml new file mode 100644 index 000000000..ca0c99a24 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Click_Tab_Click_UIElement.xml @@ -0,0 +1,296 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Expand_Collapse_ComboBox_Expand_Collapse_Items_In_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Expand_Collapse_ComboBox_Expand_Collapse_Items_In_UIElement.xml new file mode 100644 index 000000000..7ac6de476 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Expand_Collapse_ComboBox_Expand_Collapse_Items_In_UIElement.xml @@ -0,0 +1,306 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_Button_Text_Get_Text_From_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Get_Button_Text_Get_Text_From_UIElement.xml new file mode 100644 index 000000000..cd71d1c75 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Get_Button_Text_Get_Text_From_UIElement.xml @@ -0,0 +1,304 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_CheckBox_State_Get_Selected_State_From_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Get_CheckBox_State_Get_Selected_State_From_UIElement.xml new file mode 100644 index 000000000..259a05951 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Get_CheckBox_State_Get_Selected_State_From_UIElement.xml @@ -0,0 +1,556 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_Element_From_Element_By_XPath_Click_Element.xml b/taskt/Samples/UIAutomation_Commands/Get_Element_From_Element_By_XPath_Click_Element.xml deleted file mode 100644 index ef24a221a..000000000 --- a/taskt/Samples/UIAutomation_Commands/Get_Element_From_Element_By_XPath_Click_Element.xml +++ /dev/null @@ -1,117 +0,0 @@ - - \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_Element_From_Window_Get_Element_Tree_XML_From_Element.xml b/taskt/Samples/UIAutomation_Commands/Get_Element_From_Window_Get_Element_Tree_XML_From_Element.xml deleted file mode 100644 index 834ec82b7..000000000 --- a/taskt/Samples/UIAutomation_Commands/Get_Element_From_Window_Get_Element_Tree_XML_From_Element.xml +++ /dev/null @@ -1,50 +0,0 @@ - - \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_Label_Text_Get_Text_From_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Get_Label_Text_Get_Text_From_UIElement.xml new file mode 100644 index 000000000..244850334 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Get_Label_Text_Get_Text_From_UIElement.xml @@ -0,0 +1,304 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_ListView_Value_Get_Text_From_Table_UIEelement.xml b/taskt/Samples/UIAutomation_Commands/Get_ListView_Value_Get_Text_From_Table_UIEelement.xml new file mode 100644 index 000000000..29a9c6192 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Get_ListView_Value_Get_Text_From_Table_UIEelement.xml @@ -0,0 +1,304 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_RadioButton_State_Get_Selected_State_From_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Get_RadioButton_State_Get_Selected_State_From_UIElement.xml new file mode 100644 index 000000000..b135804a0 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Get_RadioButton_State_Get_Selected_State_From_UIElement.xml @@ -0,0 +1,554 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_Tab_State_Get_Selected_State_From_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Get_Tab_State_Get_Selected_State_From_UIElement.xml new file mode 100644 index 000000000..1ae759260 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Get_Tab_State_Get_Selected_State_From_UIElement.xml @@ -0,0 +1,555 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_Table_Value_Get_Text_From_Table_UIEelement.xml b/taskt/Samples/UIAutomation_Commands/Get_Table_Value_Get_Text_From_Table_UIEelement.xml new file mode 100644 index 000000000..7c6186694 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Get_Table_Value_Get_Text_From_Table_UIEelement.xml @@ -0,0 +1,303 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_UIElement_From_UIElement_By_XPath_Click_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Get_UIElement_From_UIElement_By_XPath_Click_UIElement.xml new file mode 100644 index 000000000..aba46e98a --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Get_UIElement_From_UIElement_By_XPath_Click_UIElement.xml @@ -0,0 +1,68 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Get_UIElement_From_Window_Get_UIElement_Tree_XML_From_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Get_UIElement_From_Window_Get_UIElement_Tree_XML_From_UIElement.xml new file mode 100644 index 000000000..7b3383f58 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Get_UIElement_From_Window_Get_UIElement_Tree_XML_From_UIElement.xml @@ -0,0 +1,50 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/ScrollBar_Scroll_UIElement.xml b/taskt/Samples/UIAutomation_Commands/ScrollBar_Scroll_UIElement.xml new file mode 100644 index 000000000..7ec61d7d8 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/ScrollBar_Scroll_UIElement.xml @@ -0,0 +1,297 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Select_ComboBox_Item_Select_Item_In_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Select_ComboBox_Item_Select_Item_In_UIElement.xml new file mode 100644 index 000000000..56651f526 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Select_ComboBox_Item_Select_Item_In_UIElement.xml @@ -0,0 +1,305 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Set_ComboBox_Value_Set_Text_To_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Set_ComboBox_Value_Set_Text_To_UIElement.xml new file mode 100644 index 000000000..3d625a224 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Set_ComboBox_Value_Set_Text_To_UIElement.xml @@ -0,0 +1,296 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UIAutomation_Commands/Set_TextBox_Value_Set_Text_To_UIElement.xml b/taskt/Samples/UIAutomation_Commands/Set_TextBox_Value_Set_Text_To_UIElement.xml new file mode 100644 index 000000000..e2389b2e9 --- /dev/null +++ b/taskt/Samples/UIAutomation_Commands/Set_TextBox_Value_Set_Text_To_UIElement.xml @@ -0,0 +1,296 @@ + + \ No newline at end of file diff --git a/taskt/Samples/UI_Automation_Commands/UIAutomation_Commands_Sample.xml b/taskt/Samples/UIAutomation_Commands/UIAutomation_Commands_Sample.xml similarity index 82% rename from taskt/Samples/UI_Automation_Commands/UIAutomation_Commands_Sample.xml rename to taskt/Samples/UIAutomation_Commands/UIAutomation_Commands_Sample.xml index 1b93d86c1..8ad34c94a 100644 --- a/taskt/Samples/UI_Automation_Commands/UIAutomation_Commands_Sample.xml +++ b/taskt/Samples/UIAutomation_Commands/UIAutomation_Commands_Sample.xml @@ -2,28 +2,28 @@