private void FinalizeRecording() { string sequenceComment = $"Web Sequence Recorded {DateTime.Now}"; dynamic commentCommand = TypeMethods.CreateTypeInstance(_container, "AddCodeCommentCommand"); commentCommand.v_Comment = sequenceComment; dynamic closeBrowserCommand = TypeMethods.CreateTypeInstance(_container, "SeleniumCloseBrowserCommand"); closeBrowserCommand.v_InstanceName = _browserInstanceName; dynamic sequenceCommand = TypeMethods.CreateTypeInstance(_container, "SequenceCommand"); sequenceCommand.ScriptActions = _sequenceCommandList; sequenceCommand.v_Comment = sequenceComment; CallBackForm.AddCommandToListView(commentCommand); if (_browserEngineType != "None") { CallBackForm.AddCommandToListView((ScriptCommand)_createBrowserCommand); } CallBackForm.AddCommandToListView(sequenceCommand); if (_browserEngineType != "None") { CallBackForm.AddCommandToListView(closeBrowserCommand); } }
private void LoadCommands() { //load all commands var commandClasses = TypeMethods.GenerateCommandTypes(AContainer); _uiImages = new ImageList(); _automationCommands = TypeMethods.GenerateAutomationCommands(_uiImages, commandClasses); var groupedCommands = _automationCommands.Where(x => x.Command.CommandName != "BrokenCodeCommentCommand") .GroupBy(f => f.DisplayGroup); tvCommands.Nodes.Clear(); foreach (var cmd in groupedCommands) { TreeNode newGroup = new TreeNode(cmd.Key); foreach (var subcmd in cmd) { TreeNode subNode = new TreeNode(subcmd.ShortName); subNode.ToolTipText = subcmd.Description; newGroup.Nodes.Add(subNode); } tvCommands.Nodes.Add(newGroup); } tvCommands.Sort(); _tvCommandsCopy = new TreeView(); _tvCommandsCopy.ShowNodeToolTips = true; CopyTreeView(tvCommands, _tvCommandsCopy); txtCommandSearch.Text = _txtCommandWatermark; }
public void LoadCommands() { //load all commands _automationCommands = TypeMethods.GenerateAutomationCommands(AContainer).Where(x => x.Command.CommandName != "SequenceCommand").ToList(); //instantiate and populate display icons for commands _uiImages = UIImage.UIImageList(_automationCommands); var groupedCommands = _automationCommands.GroupBy(f => f.DisplayGroup); tvCommands.Nodes.Clear(); foreach (var cmd in groupedCommands) { TreeNode newGroup = new TreeNode(cmd.Key); foreach (var subcmd in cmd) { TreeNode subNode = new TreeNode(subcmd.ShortName); subNode.ToolTipText = subcmd.Description; newGroup.Nodes.Add(subNode); } tvCommands.Nodes.Add(newGroup); } tvCommands.Sort(); _tvCommandsCopy = new TreeView(); _tvCommandsCopy.ShowNodeToolTips = true; CopyTreeView(tvCommands, _tvCommandsCopy); txtCommandSearch.Text = _txtCommandWatermark; }
private void lbxImportedNamespaces_KeyDown(object sender, KeyEventArgs e) { ListBox listBox = (ListBox)sender; if (e.KeyCode == Keys.Delete) { List <string> removaList = new List <string>(); foreach (var item in listBox.SelectedItems) { var pair = (KeyValuePair <string, List <AssemblyReference> >)item; removaList.Add(pair.Key); } removaList.ForEach(x => ScriptContext.ImportedNamespaces.Remove(x)); var importedNameSpacesBinding = new BindingSource(ScriptContext.ImportedNamespaces, null); lbxImportedNamespaces.DataSource = importedNameSpacesBinding; TypeMethods.GenerateAllVariableTypes(NamespaceMethods.GetAssemblies(ScriptContext.ImportedNamespaces), TypeContext.GroupedTypes); ScriptContext.LoadCompilerObjects(); //marks the script as unsaved with changes if (uiScriptTabControl.SelectedTab != null && !uiScriptTabControl.SelectedTab.Text.Contains(" *")) { uiScriptTabControl.SelectedTab.Text += " *"; } } else { dgvVariablesArguments_KeyDown(null, e); } }
private void BuildNavigateToURLCommand(string url) { dynamic navigateToURLCommand = TypeMethods.CreateTypeInstance(_container, "SeleniumNavigateToURLCommand"); navigateToURLCommand.v_InstanceName = _browserInstanceName; navigateToURLCommand.v_URL = url; _sequenceCommandList.Add(navigateToURLCommand); }
public void createpatterns(MusicInfoScript musicinfo) { foreach (TypeProperty typeprop in musicinfo.propertiesList) { TypeMethods luatype = new TypeMethods(typeprop); PlayerScripts temp = null; foreach (PlayerScripts playerscript in staticstuff.SelectedScripts) { LuaFunction checkprop = playerscript.script.GetFunction("checkProp"); object[] returnvalues = checkprop.Call(luatype); if ((bool)returnvalues[0]) { patternindex.Add(typeprop.segmentnumber, new LuaScriptFacade(playerscript.script, bulletrepo, origin, defaultbullet, luatype)); temp = playerscript; break; } } if (temp != null) { staticstuff.SelectedScripts.Remove(temp); } else { patternindex.Add(typeprop.segmentnumber, new LuaScriptFacade(staticstuff.defaultScript.script, bulletrepo, origin, defaultbullet, luatype)); } } //if(musicinfo.patterntypes.Count!=0) //add remaining to default }
private void LoadCommands(frmScriptBuilder scriptBuilder) { //load all commands scriptBuilder._automationCommands = TypeMethods.GenerateAutomationCommands(AContainer); //instantiate and populate display icons for commands scriptBuilder._uiImages = UIImage.UIImageList(scriptBuilder._automationCommands); var groupedCommands = scriptBuilder._automationCommands.Where(x => x.Command.CommandName != "BrokenCodeCommentCommand") .GroupBy(f => f.DisplayGroup); scriptBuilder.tvCommands.Nodes.Clear(); foreach (var cmd in groupedCommands) { TreeNode newGroup = new TreeNode(cmd.Key); foreach (var subcmd in cmd) { TreeNode subNode = new TreeNode(subcmd.ShortName); subNode.ToolTipText = subcmd.Description; newGroup.Nodes.Add(subNode); } scriptBuilder.tvCommands.Nodes.Add(newGroup); } scriptBuilder.tvCommands.Sort(); scriptBuilder._tvCommandsCopy = new TreeView(); scriptBuilder._tvCommandsCopy.ShowNodeToolTips = true; CopyTreeView(scriptBuilder.tvCommands, scriptBuilder._tvCommandsCopy); scriptBuilder.txtCommandSearch.Text = _txtCommandWatermark; }
public IMethodBuilder DefineMethod(string name, MethodAttributes attributes, IType returnType, IType[] parameters, bool entryPoint) { var builder = new AsmMethodBuilder(this, returnType, parameters, attributes, name, entryPoint); TypeMethods.Add(builder); return(builder); }
private void BuildElementClickActionCommand(string clickType) { dynamic clickElementActionCommand = TypeMethods.CreateTypeInstance(_container, "SeleniumElementActionCommand"); clickElementActionCommand.v_InstanceName = _browserInstanceName; clickElementActionCommand.v_SeleniumSearchParameters = SearchParameters; clickElementActionCommand.v_SeleniumElementAction = clickType; _sequenceCommandList.Add(clickElementActionCommand); }
private void BuildActivateWindowCommand() { dynamic activateWindowCommand = TypeMethods.CreateTypeInstance(_container, "ActivateWindowCommand"); activateWindowCommand.v_WindowName = WindowName; _sequenceCommandList.Add(activateWindowCommand); }
public LuaScriptFacade(Lua script, GameObject bulletrepo, GameObject origin, GameObject defaultBullet, TypeMethods luatype) { this.script = script; this.luatype = luatype; container = new BulletsContainer(defaultBullet, origin); luainit = new InitializerMethods(container, bulletrepo); luafire = new FiringMethods(); initroutine = script.GetFunction("Initialize"); fireroutine = script.GetFunction("Fire"); }
private void pbForward_Click(object sender, EventArgs e) { wbElementRecorder.GoForward(); if (IsRecordingSequence && _isRecording) { dynamic navigateForwardBrowserCommand = TypeMethods.CreateTypeInstance(_container, "SeleniumNavigateForwardCommand"); navigateForwardBrowserCommand.v_InstanceName = _browserInstanceName; _sequenceCommandList.Add(navigateForwardBrowserCommand); } }
private void pbRefresh_Click(object sender, EventArgs e) { wbElementRecorder.Reload(); if (IsRecordingSequence && _isRecording) { dynamic refreshBrowserCommand = TypeMethods.CreateTypeInstance(_container, "SeleniumRefreshCommand"); refreshBrowserCommand.v_InstanceName = _browserInstanceName; _sequenceCommandList.Add(refreshBrowserCommand); } }
public static ContainerBuilder LoadBuilder(List <string> assemblyPaths, Dictionary <string, List <Type> > groupedTypes, Dictionary <string, List <AssemblyReference> > allNamespaces, Dictionary <string, List <AssemblyReference> > importedNamespaces) { List <Assembly> existingAssemblies = new List <Assembly>(); foreach (var path in assemblyPaths) { try { var name = AssemblyName.GetAssemblyName(path).Name; var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var existingAssembly = assemblies.Where(x => x.GetName().Name == name && x.GetName().Version.ToString() == AssemblyName.GetAssemblyName(path).Version.ToString()) .FirstOrDefault(); if (existingAssembly == null && name != "RestSharp" && name != "WebDriver" && name != "OpenBots.Core") { //has to be LoadFile because package manager can't update/uninstall assemblies if LoadFrom var assembly = Assembly.LoadFrom(path); existingAssemblies.Add(assembly); } else if (existingAssembly != null) { existingAssemblies.Add(existingAssembly); } } catch (Exception ex) { Console.WriteLine(ex); } } //TODO: limit types to one in loaded assemblies. Previously getting all assemblies instead of just the ones in existingAssemblies because mscorlib was missing TypeMethods.GenerateAllNamespaces(AppDomain.CurrentDomain.GetAssemblies().ToList(), allNamespaces); TypeMethods.GenerateAllVariableTypes(NamespaceMethods.GetAssemblies(importedNamespaces), groupedTypes); //if no commands have been loaded, at least include OpenBots.Core to access the BrokenCodeCommand if (existingAssemblies.Count == 0) { existingAssemblies.Add(Assembly.GetAssembly(typeof(BrokenCodeCommentCommand))); } ContainerBuilder builder = new ContainerBuilder(); builder.RegisterAssemblyTypes(existingAssemblies.ToArray()) .Where(t => t.IsAssignableTo <ScriptCommand>()) .Named <ScriptCommand>(t => t.Name) .AsImplementedInterfaces(); return(builder); }
public void CreateOpenBotsProject(string mainScriptName, string mainScriptPath) { //create OpenBots specific project UIListView mainScriptActions = NewLstScriptActions(mainScriptName); List <ScriptVariable> mainScriptVariables = new List <ScriptVariable>(); List <ScriptArgument> mainScriptArguments = new List <ScriptArgument>(); List <ScriptElement> mainScriptElements = new List <ScriptElement>(); Dictionary <string, List <AssemblyReference> > mainImportedNamespaces = new Dictionary <string, List <AssemblyReference> >(ScriptDefaultNamespaces.DefaultNamespaces); try { dynamic helloWorldCommand = TypeMethods.CreateTypeInstance(AContainer, "ShowMessageCommand"); helloWorldCommand.v_Message = "\"Hello World\""; mainScriptActions.Items.Insert(0, CreateScriptCommandListViewItem(helloWorldCommand)); } catch (Exception) { var brokenHelloWorldCommand = new BrokenCodeCommentCommand(); brokenHelloWorldCommand.v_Comment = "Hello World"; mainScriptActions.Items.Insert(0, CreateScriptCommandListViewItem(brokenHelloWorldCommand)); } //begin saving as main.xml ClearSelectedListViewItems(); try { //serialize main script EngineContext engineContext = new EngineContext { Variables = mainScriptVariables, Arguments = mainScriptArguments, Elements = mainScriptElements, ImportedNamespaces = mainImportedNamespaces, FilePath = mainScriptPath, Container = AContainer }; var mainScript = Script.SerializeScript(mainScriptActions.Items, engineContext); _mainFileName = ScriptProject.Main; OpenOpenBotsFile(mainScriptPath); } catch (Exception ex) { Notify("An Error Occurred: " + ex.Message, Color.Red); } }
private void FinalizeRecording() { string sequenceComment = $"Advanced UI Sequence Recorded {DateTime.Now}"; dynamic commentCommand = TypeMethods.CreateTypeInstance(_container, "AddCodeCommentCommand"); commentCommand.v_Comment = sequenceComment; dynamic sequenceCommand = TypeMethods.CreateTypeInstance(_container, "SequenceCommand"); sequenceCommand.ScriptActions = _sequenceCommandList; sequenceCommand.v_Comment = sequenceComment; CallBackForm.AddCommandToListView(commentCommand); CallBackForm.AddCommandToListView(sequenceCommand); }
//build pause command private static void BuildPauseCommand() { if (_stopWatch.ElapsedMilliseconds < 1) { return; } _stopWatch.Stop(); var pauseTime = _stopWatch.ElapsedMilliseconds; dynamic pauseCommand = TypeMethods.CreateTypeInstance(_container, "PauseScriptCommand"); pauseCommand.v_PauseLength = pauseTime.ToString(); GeneratedCommands.Add(pauseCommand); _stopWatch.Restart(); }
public static bool BuildSendAdvancedKeystrokesCommand(Keys key, List <ScriptCommand> commandList, string windowName, bool isOnlyKeyDown = false) { if ((commandList.Count > 1) && (commandList[commandList.Count - 1] is ISendAdvancedKeystrokesCommand) && (commandList[commandList.Count - 1] as ISendAdvancedKeystrokesCommand).v_KeyActions.Rows.Count > 0 && !isOnlyKeyDown) { DataTable previousKeyActionsDT = (commandList[commandList.Count - 1] as ISendAdvancedKeystrokesCommand).v_KeyActions; int keyCount = previousKeyActionsDT.Rows.Count; var lastPressedKeyName = previousKeyActionsDT.Rows[keyCount - 1].ItemArray[0].ToString().Split('[', ']')[1]; Keys lastPressedKey = (Keys)Enum.Parse(typeof(Keys), lastPressedKeyName); //check that another key is down and that it isn't a shift + letter combination if (IsKeyDown(lastPressedKey) && !(IsKeyDown(Keys.ShiftKey) && key.ToString().Length == 1)) { DataRow newKeyStrokeRow = previousKeyActionsDT.NewRow(); newKeyStrokeRow["Key"] = $"{CommonMethods.GetKeyDescription(key)} [{key}]"; newKeyStrokeRow["Action"] = "Key Down"; previousKeyActionsDT.Rows.Add(newKeyStrokeRow); return(true); } else { bool result = BuildSendAdvancedKeystrokesCommand(key, commandList, windowName, true); return(result); } } else if (key.ToString().Length > 1) { dynamic sendAdvancedKeystrokesCommand = TypeMethods.CreateTypeInstance(_container, "SendAdvancedKeystrokesCommand"); sendAdvancedKeystrokesCommand.v_WindowName = windowName; sendAdvancedKeystrokesCommand.v_KeyUpDefault = "Yes"; sendAdvancedKeystrokesCommand.v_Comment = "Typed in Window: " + windowName; DataTable newkeyActionaDT = sendAdvancedKeystrokesCommand.v_KeyActions; DataRow newKeyStrokeRow = newkeyActionaDT.NewRow(); newKeyStrokeRow["Key"] = $"{CommonMethods.GetKeyDescription(key)} [{key}]"; newKeyStrokeRow["Action"] = "Key Down"; newkeyActionaDT.Rows.Add(newKeyStrokeRow); commandList.Add(sendAdvancedKeystrokesCommand); return(true); } else { return(false); } }
private void BuildElementClickActionCommand(string clickType) { dynamic clickElementActionCommand = TypeMethods.CreateTypeInstance(_container, "UIAutomationCommand"); clickElementActionCommand.v_WindowName = WindowName; clickElementActionCommand.v_UIASearchParameters = SearchParameters; clickElementActionCommand.v_AutomationType = "Click Element"; DataTable webActionDT = clickElementActionCommand.v_UIAActionParameters; DataRow clickTypeRow = webActionDT.NewRow(); clickTypeRow["Parameter Name"] = "Click Type"; clickTypeRow["Parameter Value"] = clickType; webActionDT.Rows.Add(clickTypeRow); _sequenceCommandList.Add(clickElementActionCommand); _stopwatch.Restart(); }
private void cbxAllNamespaces_SelectionChangeCommitted(object sender, EventArgs e) { var pair = (KeyValuePair <string, List <AssemblyReference> >)cbxAllNamespaces.SelectedItem; if (!ScriptContext.ImportedNamespaces.ContainsKey(pair.Key)) { ScriptContext.ImportedNamespaces.Add(pair.Key, pair.Value); var importedNameSpacesBinding = new BindingSource(ScriptContext.ImportedNamespaces, null); lbxImportedNamespaces.DataSource = importedNameSpacesBinding; TypeMethods.GenerateAllVariableTypes(NamespaceMethods.GetAssemblies(ScriptContext.ImportedNamespaces), TypeContext.GroupedTypes); ScriptContext.LoadCompilerObjects(); //marks the script as unsaved with changes if (uiScriptTabControl.SelectedTab != null && !uiScriptTabControl.SelectedTab.Text.Contains(" *")) { uiScriptTabControl.SelectedTab.Text += " *"; } } }
private void ResetVariableArgumentBindings() { dgvVariables.DataSource = new BindingList <ScriptVariable>(ScriptContext.Variables); dgvArguments.DataSource = new BindingList <ScriptArgument>(ScriptContext.Arguments); TypeMethods.GenerateAllVariableTypes(NamespaceMethods.GetAssemblies(ScriptContext.ImportedNamespaces), TypeContext.GroupedTypes); var defaultTypesBinding = new BindingSource(TypeContext.DefaultTypes, null); variableType.DataSource = defaultTypesBinding; argumentType.DataSource = defaultTypesBinding; var importedNameSpacesBinding = new BindingSource(ScriptContext.ImportedNamespaces, null); lbxImportedNamespaces.DataSource = importedNameSpacesBinding; var allNameSpacesBinding = new BindingSource(AllNamespaces, null); cbxAllNamespaces.DataSource = allNameSpacesBinding; }
private void BuildElementSetTextActionCommand(Keys key) { bool toUpperCase = false; //determine if casing is needed if (GlobalHook.IsKeyDown(Keys.ShiftKey) && GlobalHook.IsKeyToggled(Keys.Capital)) { toUpperCase = false; } else if (!GlobalHook.IsKeyDown(Keys.ShiftKey) && GlobalHook.IsKeyToggled(Keys.Capital)) { toUpperCase = true; } else if (GlobalHook.IsKeyDown(Keys.ShiftKey) && !GlobalHook.IsKeyToggled(Keys.Capital)) { toUpperCase = true; } else if (!GlobalHook.IsKeyDown(Keys.ShiftKey) && !GlobalHook.IsKeyToggled(Keys.Capital)) { toUpperCase = false; } var buf = new StringBuilder(256); var keyboardState = new byte[256]; if (toUpperCase) { keyboardState[(int)Keys.ShiftKey] = 0xff; } GlobalHook.ToUnicode((uint)key, 0, keyboardState, buf, 256, 0); var selectedKey = buf.ToString(); //translate key press to sendkeys identifier if (key.ToString() == GlobalHook.StopHookKey) { //STOP HOOK GlobalHook.StopHook(); GlobalHook.HookStopped -= GlobalHook_HookStopped; GlobalHook.MouseEvent -= GlobalHook_MouseEvent; GlobalHook.KeyDownEvent -= GlobalHook_KeyDownEvent; return; } else { bool result = GlobalHook.BuildSendAdvancedKeystrokesCommand(key, _sequenceCommandList, WindowName); if (result) { return; } } //generate sendkeys together if ((_sequenceCommandList.Count > 1) && (_sequenceCommandList[_sequenceCommandList.Count - 1] is IUIAutomationCommand) && (_sequenceCommandList[_sequenceCommandList.Count - 1] as IUIAutomationCommand).v_AutomationType == "Set Text") { var lastCreatedSendKeysCommand = (IUIAutomationCommand)_sequenceCommandList[_sequenceCommandList.Count - 1]; //append chars to previously created command //this makes editing easier for the user because only 1 command is issued rather than multiples var previouslyInputChars = lastCreatedSendKeysCommand.v_UIAActionParameters.Rows[0][1].ToString(); lastCreatedSendKeysCommand.v_UIAActionParameters.Rows[0][1] = previouslyInputChars + selectedKey; } else { //build keyboard command dynamic setTextElementActionCommand = TypeMethods.CreateTypeInstance(_container, "UIAutomationCommand"); setTextElementActionCommand.v_WindowName = WindowName; setTextElementActionCommand.v_UIASearchParameters = SearchParameters; setTextElementActionCommand.v_AutomationType = "Set Text"; DataTable webActionDT = setTextElementActionCommand.v_UIAActionParameters; DataRow textToSetRow = webActionDT.NewRow(); textToSetRow["Parameter Name"] = "Text To Set"; textToSetRow["Parameter Value"] = selectedKey; webActionDT.Rows.Add(textToSetRow); _sequenceCommandList.Add(setTextElementActionCommand); } }
private void lstScriptActions_DragDrop(object sender, DragEventArgs e) { //returns the location of the mouse pointer in the ListView control Point cp = SelectedTabScriptActions.PointToClient(new Point(e.X, e.Y)); //obtain the item that is located at the specified location of the mouse pointer ListViewItem dragToItem = SelectedTabScriptActions.GetItemAt(cp.X, cp.Y); if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode", false)) { TreeNode commandNode = ((TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode")); if (commandNode.Nodes.Count != 0) { return; } var commandName = commandNode.Text; var commandGroupName = commandNode.Parent.Text; var newCommandName = _automationCommands.Where(x => x.ShortName == commandName && x.DisplayGroup == commandGroupName) .Select(x => x.Command).FirstOrDefault().GetType(); dynamic newCommandInstance = TypeMethods.CreateTypeInstance(AContainer, newCommandName.Name); CreateUndoSnapshot(); if (dragToItem != null) { AddCommandToListView(newCommandInstance, dragToItem.Index); } else { AddCommandToListView(newCommandInstance, SelectedTabScriptActions.Items.Count); } } else { //return if the items are not selected in the ListView control if (SelectedTabScriptActions.SelectedItems.Count == 0) { return; } CreateUndoSnapshot(); if (dragToItem == null) { return; } List <ScriptCommand> commandsToMove = new List <ScriptCommand>(); for (int i = 0; i <= SelectedTabScriptActions.SelectedItems.Count - 1; i++) { var command = (ScriptCommand)SelectedTabScriptActions.SelectedItems[i].Tag; commandsToMove.Add(command); } //obtain the index of the item at the mouse pointer int dragIndex = dragToItem.Index; ListViewItem[] sel = new ListViewItem[SelectedTabScriptActions.SelectedItems.Count]; for (int i = 0; i <= SelectedTabScriptActions.SelectedItems.Count - 1; i++) { sel[i] = SelectedTabScriptActions.SelectedItems[i]; } for (int i = 0; i < sel.GetLength(0); i++) { //obtain the ListViewItem to be dragged to the target location ListViewItem dragItem = sel[i]; int itemIndex = dragIndex; if (itemIndex == dragItem.Index) { return; } if (dragItem.Index < itemIndex) { itemIndex++; } else { itemIndex = dragIndex + i; } //insert the item at the mouse pointer ListViewItem insertItem = (ListViewItem)dragItem.Clone(); SelectedTabScriptActions.Items.Insert(itemIndex, insertItem); //removes the item from the initial location while the item is moved to the new location SelectedTabScriptActions.Items.Remove(dragItem); SelectedTabScriptActions.Invalidate(); } } }
public void AddCommandToListView(ScriptCommand selectedCommand, int index = -1) { if (!uiScriptTabControl.SelectedTab.Controls[0].Visible) { uiScriptTabControl.SelectedTab.Controls[0].Show(); } ListViewItem command; //valid command verification for drag/dropped commands if (selectedCommand != null) { command = CreateScriptCommandListViewItem(selectedCommand); } else { return; } int insertionIndex; if (index == -1) { //insert to end by default insertionIndex = SelectedTabScriptActions.Items.Count; //verify setting to insert inline is selected and if an item is currently selected if ((_appSettings.ClientSettings.InsertCommandsInline) && (SelectedTabScriptActions.SelectedItems.Count > 0)) { //insert inline insertionIndex = SelectedTabScriptActions.SelectedItems[0].Index + 1; } } else { insertionIndex = index; } //insert command SelectedTabScriptActions.Items.Insert(insertionIndex, command); ClearSelectedListViewItems(); command.Selected = true; //special types also get a following command and comment if ((selectedCommand.CommandName == "LoopCollectionCommand") || (selectedCommand.CommandName == "LoopContinuouslyCommand") || (selectedCommand.CommandName == "LoopNumberOfTimesCommand") || (selectedCommand.CommandName == "BeginLoopCommand") || (selectedCommand.CommandName == "BeginMultiLoopCommand")) { dynamic addCodeCommentCommand = TypeMethods.CreateTypeInstance(AContainer, "AddCodeCommentCommand"); addCodeCommentCommand.v_Comment = "Items in this section will run within the loop"; SelectedTabScriptActions.Items.Insert(insertionIndex + 1, CreateScriptCommandListViewItem(addCodeCommentCommand)); dynamic endLoopCommand = TypeMethods.CreateTypeInstance(AContainer, "EndLoopCommand"); SelectedTabScriptActions.Items.Insert(insertionIndex + 2, CreateScriptCommandListViewItem(endLoopCommand)); } else if ((selectedCommand.CommandName == "BeginIfCommand") || (selectedCommand.CommandName == "BeginMultiIfCommand")) { dynamic addCodeCommentCommand = TypeMethods.CreateTypeInstance(AContainer, "AddCodeCommentCommand"); addCodeCommentCommand.v_Comment = "Items in this section will run if the statement is true"; SelectedTabScriptActions.Items.Insert(insertionIndex + 1, CreateScriptCommandListViewItem(addCodeCommentCommand)); dynamic endIfCommand = TypeMethods.CreateTypeInstance(AContainer, "EndIfCommand"); SelectedTabScriptActions.Items.Insert(insertionIndex + 2, CreateScriptCommandListViewItem(endIfCommand)); } else if (selectedCommand.CommandName == "BeginTryCommand") { dynamic addCodeCommentCommand = TypeMethods.CreateTypeInstance(AContainer, "AddCodeCommentCommand"); addCodeCommentCommand.v_Comment = "Items in this section will be handled if error occurs"; SelectedTabScriptActions.Items.Insert(insertionIndex + 1, CreateScriptCommandListViewItem(addCodeCommentCommand)); dynamic catchCommand = TypeMethods.CreateTypeInstance(AContainer, "CatchCommand"); SelectedTabScriptActions.Items.Insert(insertionIndex + 2, CreateScriptCommandListViewItem(catchCommand)); dynamic codeCommentCommand = TypeMethods.CreateTypeInstance(AContainer, "AddCodeCommentCommand"); codeCommentCommand.v_Comment = "This section executes if error occurs above"; SelectedTabScriptActions.Items.Insert(insertionIndex + 3, CreateScriptCommandListViewItem(codeCommentCommand)); dynamic endTryCommand = TypeMethods.CreateTypeInstance(AContainer, "EndTryCommand"); SelectedTabScriptActions.Items.Insert(insertionIndex + 4, CreateScriptCommandListViewItem(endTryCommand)); } else if (selectedCommand.CommandName == "BeginRetryCommand") { dynamic addCodeCommentCommand = TypeMethods.CreateTypeInstance(AContainer, "AddCodeCommentCommand"); addCodeCommentCommand.v_Comment = "Items in this section will be retried as long as the condition is not met or an error is thrown"; SelectedTabScriptActions.Items.Insert(insertionIndex + 1, CreateScriptCommandListViewItem(addCodeCommentCommand)); dynamic endRetryCommand = TypeMethods.CreateTypeInstance(AContainer, "EndRetryCommand"); SelectedTabScriptActions.Items.Insert(insertionIndex + 2, CreateScriptCommandListViewItem(endRetryCommand)); } else if (selectedCommand.CommandName == "BeginSwitchCommand") { dynamic caseCommand = TypeMethods.CreateTypeInstance(AContainer, "CaseCommand"); caseCommand.v_CaseValue = "Default"; SelectedTabScriptActions.Items.Insert(insertionIndex + 1, CreateScriptCommandListViewItem(caseCommand)); dynamic addCodeCommentCommand = TypeMethods.CreateTypeInstance(AContainer, "AddCodeCommentCommand"); addCodeCommentCommand.v_Comment = "Items in this section will run if no case statements match"; SelectedTabScriptActions.Items.Insert(insertionIndex + 2, CreateScriptCommandListViewItem(addCodeCommentCommand)); dynamic endSwitchCommand = TypeMethods.CreateTypeInstance(AContainer, "EndSwitchCommand"); SelectedTabScriptActions.Items.Insert(insertionIndex + 3, CreateScriptCommandListViewItem(endSwitchCommand)); } CreateUndoSnapshot(); SelectedTabScriptActions.Invalidate(); AutoSizeLineNumberColumn(); }
private void pbRecord_Click(object sender, EventArgs e) { if (!_isRecording) { _isRecording = true; TopMost = true; if (!chkStopOnClick.Checked) { lblDescription.Text = _recordingMessage; } SearchParameters = NewSearchParameterDataTable(); //clear all SearchParameters.Rows.Clear(); //start global hook and wait for left mouse down event GlobalHook.StartEngineCancellationHook(Keys.F2); GlobalHook.HookStopped += GlobalHook_HookStopped; GlobalHook.StartElementCaptureHook(chkStopOnClick.Checked, _container); wbElementRecorder.DomClick += wbElementRecorder_DomClick; wbElementRecorder.DomDoubleClick += wbElementRecorder_DomDoubleClick; wbElementRecorder.DomKeyDown += WbElementRecorder_DomKeyDown; if (IsRecordingSequence && _isFirstRecordClick) { _isFirstRecordClick = false; _sequenceCommandList = new List <ScriptCommand>(); frmHTMLElementRecorderSettings settingsForm = new frmHTMLElementRecorderSettings(); settingsForm.txtBrowserInstanceName.Text = "DefaultBrowser"; settingsForm.cbxBrowserEngineType.SelectedIndex = 0; settingsForm.ShowDialog(); if (settingsForm.DialogResult == DialogResult.OK) { _browserInstanceName = settingsForm.txtBrowserInstanceName.Text; _browserEngineType = settingsForm.cbxBrowserEngineType.SelectedItem.ToString(); _parameterSettings = settingsForm.ParameterSettingsDT; settingsForm.Dispose(); } else { _isRecording = false; _isFirstRecordClick = true; lblDescription.Text = "Instructions: navigate to the target URL and click the record button. " + "Once recording has started, click the element that you want to capture."; //remove wait for left mouse down event wbElementRecorder.DomClick -= wbElementRecorder_DomClick; wbElementRecorder.DomDoubleClick -= wbElementRecorder_DomDoubleClick; wbElementRecorder.DomKeyDown -= WbElementRecorder_DomKeyDown; GlobalHook.HookStopped -= GlobalHook_HookStopped; settingsForm.Dispose(); return; } if (_browserEngineType != "None") { dynamic seleniumCreateBrowserCommand = TypeMethods.CreateTypeInstance(_container, "SeleniumCreateBrowserCommand"); seleniumCreateBrowserCommand.v_InstanceName = _browserInstanceName; seleniumCreateBrowserCommand.v_EngineType = _browserEngineType; seleniumCreateBrowserCommand.v_URL = $"\"{wbElementRecorder.Url}\""; _createBrowserCommand = seleniumCreateBrowserCommand; } } } else { _isRecording = false; if (!chkStopOnClick.Checked) { lblDescription.Text = "Recording has stopped. Press F2 to save and close."; } } }
//build window command private static void BuildWindowCommand(IntPtr hWinEventHook, _systemEvents @event, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) { switch (@event) { case _systemEvents.EventMin: return; case _systemEvents.EventMax: return; case _systemEvents.EventSystemForeGround: break; case _systemEvents.MinimizeEnd: return; case _systemEvents.MinimizeStart: return; default: return; } int length = GetWindowText(hwnd, _buffer, _buffer.Capacity); var windowName = _buffer.ToString(); //bypass screen recorder and Cortana (Win10) which throws errors if ((windowName == "Screen Recorder") || (windowName == "Cortana")) { return; } if (length > 0) { //wait additional for window to initialize //System.Threading.Thread.Sleep(250); windowName = _buffer.ToString(); dynamic activateWindowCommand = TypeMethods.CreateTypeInstance(_container, "ActivateWindowCommand"); activateWindowCommand.v_WindowName = windowName; GeneratedCommands.Add(activateWindowCommand); //detect if tracking window open location or activate windows to top left if (_trackWindowOpenLocations) { User32Functions.GetWindowRect(hwnd, out Rect windowRect); dynamic moveWindowCommand = TypeMethods.CreateTypeInstance(_container, "MoveWindowCommand"); moveWindowCommand.v_WindowName = windowName; moveWindowCommand.v_XMousePosition = windowRect.left.ToString(); moveWindowCommand.v_YMousePosition = windowRect.top.ToString(); GeneratedCommands.Add(moveWindowCommand); } else if (_activateWindowTopLeft) { dynamic moveWindowCommand = TypeMethods.CreateTypeInstance(_container, "MoveWindowCommand"); moveWindowCommand.v_WindowName = windowName; moveWindowCommand.v_XMousePosition = "0"; moveWindowCommand.v_YMousePosition = "0"; User32Functions.SetWindowPosition(hwnd, 0, 0); GeneratedCommands.Add(moveWindowCommand); } //if tracking window sizes is set if (_trackActivatedWindowSizes) { //create rectangle from hwnd User32Functions.GetWindowRect(hwnd, out Rect windowRect); //do math to get height, etc var width = windowRect.right - windowRect.left; var height = windowRect.bottom - windowRect.top; //generate command to set window position dynamic resizeWindowCommand = TypeMethods.CreateTypeInstance(_container, "ResizeWindowCommand"); resizeWindowCommand.v_WindowName = windowName; resizeWindowCommand.v_XWindowSize = width.ToString(); resizeWindowCommand.v_YWindowSize = height.ToString(); //add to list GeneratedCommands.Add(resizeWindowCommand); } } }
private void pbRecord_Click(object sender, EventArgs e) { // this.WindowState = FormWindowState.Minimized; if (!_isRecording) { _isRecording = true; SearchParameters = NewSearchParameterDataTable(); //clear all SearchParameters.Rows.Clear(); //get window name and find window WindowName = cboWindowTitle.Text; IntPtr hWnd = User32Functions.FindWindow(WindowName); if (IsRecordingSequence && _isFirstRecordClick) { _isFirstRecordClick = false; _sequenceCommandList = new List <ScriptCommand>(); frmThickAppElementRecorderSettings settingsForm = new frmThickAppElementRecorderSettings(); settingsForm.ShowDialog(); if (settingsForm.DialogResult == DialogResult.OK) { _parameterSettings = settingsForm.ParameterSettingsDT; settingsForm.Dispose(); } else { _isRecording = false; _isFirstRecordClick = true; lblDescription.Text = "Instructions: Select the target window name from the drop-down " + "list and click the record button. Once recording has started, click " + "the element in the target application that you want to capture."; //remove wait for left mouse down event GlobalHook.MouseEvent -= GlobalHook_MouseEvent; GlobalHook.KeyDownEvent -= GlobalHook_KeyDownEvent; GlobalHook.HookStopped -= GlobalHook_HookStopped; settingsForm.Dispose(); return; } dynamic activateWindowCommand = TypeMethods.CreateTypeInstance(_container, "ActivateWindowCommand"); activateWindowCommand.v_WindowName = WindowName; _sequenceCommandList.Add(activateWindowCommand); } //check if window is found if (hWnd != IntPtr.Zero) { //set window state and move to 0,0 User32Functions.ActivateWindow(WindowName); User32Functions.SetWindowPosition(hWnd, 0, 0); //start global hook and wait for left mouse down event GlobalHook.StartEngineCancellationHook(Keys.F2); GlobalHook.HookStopped += GlobalHook_HookStopped; GlobalHook.StartElementCaptureHook(chkStopOnClick.Checked, _container); GlobalHook.MouseEvent += GlobalHook_MouseEvent; GlobalHook.KeyDownEvent += GlobalHook_KeyDownEvent; } if (!chkStopOnClick.Checked) { lblDescription.Text = _recordingMessage; MoveFormToBottomRight(this); } else { WindowState = FormWindowState.Minimized; } } else { _isRecording = false; if (!chkStopOnClick.Checked) { lblDescription.Text = "Recording has stopped. Press F2 to save and close."; } } }
public async Task <HttpResponseMessage> CallService(string Service, string Request, TypeMethods Method) { try { string URL = System.Configuration.ConfigurationManager.AppSettings["APIUrl"] + Service; //string Token = DatosFranquicia.Token; //string Key = DatosFranquicia.Key; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(URL); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //client.DefaultRequestHeaders.Add("X-VTEX-API-AppToken", Token); //client.DefaultRequestHeaders.Add("X-VTEX-API-AppKey", Key); HttpContent content = new StringContent(Request, UTF8Encoding.UTF8, "application/json"); HttpResponseMessage response = null; HttpRequestMessage reqMessage = null; //System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls | System.Net.SecurityProtocolType.Tls11 | System.Net.SecurityProtocolType.Tls12 | System.Net.SecurityProtocolType.Ssl3; switch (Method) { case TypeMethods.GET: response = await client.GetAsync(new Uri(URL), HttpCompletionOption.ResponseHeadersRead).ConfigureAwait(false); break; case TypeMethods.POST: response = client.PostAsync(new Uri(URL), content).Result; break; case TypeMethods.PUT: response = client.PutAsync(new Uri(URL), content).Result; break; case TypeMethods.DELETE: response = client.DeleteAsync(new Uri(URL)).Result; break; default: break; } return(response); } catch (System.Exception ex) { return(null); //throw ex; } }
/// <summary> /// Returns a path that contains the generated markdown files /// </summary> /// <returns></returns> public string GenerateMarkdownFiles(AContainer container, string basePath) { //create directory if required var docsFolderName = "docs"; var docsPath = Path.Combine(basePath, docsFolderName); if (!Directory.Exists(docsPath)) { Directory.CreateDirectory(docsPath); } var commandClasses = TypeMethods.GenerateCommandTypes(container); var highLevelCommandInfo = new List <CommandMetaData>(); StringBuilder stringBuilder; string fullFileName; //loop each command foreach (var commandClass in commandClasses) { //instantiate and pull properties from command class ScriptCommand instantiatedCommand = (ScriptCommand)Activator.CreateInstance(commandClass); var groupName = GetClassValue(commandClass, typeof(CategoryAttribute)); var classDescription = GetClassValue(commandClass, typeof(DescriptionAttribute)); var commandName = instantiatedCommand.SelectionName; stringBuilder = new StringBuilder(); //create string builder to build markdown document and append data stringBuilder.AppendLine("<!--TITLE: " + commandName + " Command -->"); stringBuilder.AppendLine("<!-- SUBTITLE: a command in the " + groupName + " group. -->"); stringBuilder.AppendLine("[Go To Automation Commands Overview](/automation-commands)"); stringBuilder.AppendLine(Environment.NewLine); stringBuilder.AppendLine("# " + commandName + " Command"); stringBuilder.AppendLine(Environment.NewLine); //append more stringBuilder.AppendLine("## What does this command do?"); stringBuilder.AppendLine(classDescription); stringBuilder.AppendLine(Environment.NewLine); //build parameter table based on required user inputs stringBuilder.AppendLine("## Command Parameters"); stringBuilder.AppendLine("| Parameter Question | What to input | Sample Data | Remarks |"); stringBuilder.AppendLine("| --- | --- | --- | --- |"); //loop each property foreach (var prop in commandClass.GetProperties().Where(f => f.Name.StartsWith("v_")).ToList()) { //pull attributes from property var commandLabel = CleanMarkdownValue(GetPropertyValue(prop, typeof(DisplayNameAttribute))); var helpfulExplanation = CleanMarkdownValue(GetPropertyValue(prop, typeof(DescriptionAttribute))); var sampleUsage = CleanMarkdownValue(GetPropertyValue(prop, typeof(SampleUsage))); var remarks = CleanMarkdownValue(GetPropertyValue(prop, typeof(Remarks))); //append to parameter table stringBuilder.AppendLine("|" + commandLabel + "|" + helpfulExplanation + "|" + sampleUsage + "|" + remarks + "|"); } stringBuilder.AppendLine(Environment.NewLine); stringBuilder.AppendLine("## Developer/Additional Reference"); stringBuilder.AppendLine("Automation Class Name: " + commandClass.Name); stringBuilder.AppendLine("Parent Namespace: " + commandClass.Namespace); stringBuilder.AppendLine("This page was generated on " + DateTime.Now.ToString("MM/dd/yy hh:mm tt")); stringBuilder.AppendLine(Environment.NewLine); stringBuilder.AppendLine("## Help"); stringBuilder.AppendLine("[Open/Report an issue on GitHub](https://github.com/OpenBotsAI/OpenBots.Studio/issues/new)"); stringBuilder.AppendLine("[Ask a question on the OpenBots Forum](https://openbots.ai/forums/)"); //create kebob destination and command file name var kebobDestination = groupName.Replace(" ", "-").Replace("/", "-").ToLower(); var kebobFileName = commandName.Replace(" ", "-").Replace("/", "-").ToLower() + "-command.md"; //create directory if required var destinationdirectory = Path.Combine(docsPath, kebobDestination); if (!Directory.Exists(destinationdirectory)) { Directory.CreateDirectory(destinationdirectory); } //write file fullFileName = Path.Combine(destinationdirectory, kebobFileName); File.WriteAllText(fullFileName, stringBuilder.ToString()); //add to high level var serverPath = "/automation-commands/" + kebobDestination + "/" + kebobFileName.Replace(".md", ""); highLevelCommandInfo.Add( new CommandMetaData() { Group = groupName, Description = classDescription, Name = commandName, Location = serverPath }); } stringBuilder = new StringBuilder(); stringBuilder.AppendLine("<!--TITLE: Automation Commands -->"); stringBuilder.AppendLine("<!-- SUBTITLE: an overview of available commands in OpenBots. -->"); stringBuilder.AppendLine("## Automation Commands"); stringBuilder.AppendLine("| Command Group | Command Name | Command Description |"); stringBuilder.AppendLine("| --- | --- | --- |"); foreach (var cmd in highLevelCommandInfo) { stringBuilder.AppendLine("|" + cmd.Group + "|[" + cmd.Name + "](" + cmd.Location + ")|" + cmd.Description + "|"); } stringBuilder.AppendLine(Environment.NewLine); stringBuilder.AppendLine("## Help"); stringBuilder.AppendLine("[Open/Report an issue on GitHub](https://github.com/OpenBotsAI/OpenBots.Studio/issues/new)"); stringBuilder.AppendLine("[Ask a question on the OpenBots forum](https://openbots.ai/forums/)"); //write file fullFileName = Path.Combine(docsPath, "automation-commands.md"); File.WriteAllText(fullFileName, stringBuilder.ToString()); return(docsPath); }
private void BuildElementSetTextActionCommand(uint key) { bool toUpperCase = false; //determine if casing is needed if (GlobalHook.IsKeyDown(Keys.ShiftKey) && GlobalHook.IsKeyToggled(Keys.Capital)) { toUpperCase = false; } else if (!GlobalHook.IsKeyDown(Keys.ShiftKey) && GlobalHook.IsKeyToggled(Keys.Capital)) { toUpperCase = true; } else if (GlobalHook.IsKeyDown(Keys.ShiftKey) && !GlobalHook.IsKeyToggled(Keys.Capital)) { toUpperCase = true; } else if (!GlobalHook.IsKeyDown(Keys.ShiftKey) && !GlobalHook.IsKeyToggled(Keys.Capital)) { toUpperCase = false; } var buf = new StringBuilder(256); var keyboardState = new byte[256]; if (toUpperCase) { keyboardState[(int)Keys.ShiftKey] = 0xff; } GlobalHook.ToUnicode(key, 0, keyboardState, buf, 256, 0); string selectedKey = buf.ToString(); //translate key press to sendkeys identifier if ((Keys)Enum.ToObject(typeof(Keys), key) == GlobalHook.StopHookKey) { //STOP HOOK GlobalHook.StopHook(); GlobalHook.HookStopped -= GlobalHook_HookStopped; return; } //check for a selenium compatible advanced key else if (_seleniumAdvancedKeyMap.TryGetValue(key, out string keyName)) { selectedKey = $"[{keyName}]"; } //return if key is neither character nor selenium compatible advanced key else if (selectedKey.Length > 1) { return; } //generate sendkeys together if ((_sequenceCommandList.Count > 1) && (_sequenceCommandList[_sequenceCommandList.Count - 1] is ISeleniumElementActionCommand) && (_sequenceCommandList[_sequenceCommandList.Count - 1] as ISeleniumElementActionCommand).v_SeleniumElementAction == "Set Text") { var lastCreatedSendKeysCommand = (ISeleniumElementActionCommand)_sequenceCommandList[_sequenceCommandList.Count - 1]; //append chars to previously created command //this makes editing easier for the user because only 1 command is issued rather than multiples var previouslyInputChars = lastCreatedSendKeysCommand.v_WebActionParameterTable.Rows[0][1].ToString(); lastCreatedSendKeysCommand.v_WebActionParameterTable.Rows[0][1] = previouslyInputChars.Insert(previouslyInputChars.Length - 1, selectedKey); } else { dynamic setTextElementActionCommand = TypeMethods.CreateTypeInstance(_container, "SeleniumElementActionCommand"); setTextElementActionCommand.v_InstanceName = _browserInstanceName; setTextElementActionCommand.v_SeleniumSearchParameters = SearchParameters; setTextElementActionCommand.v_SeleniumElementAction = "Set Text"; DataTable webActionDT = setTextElementActionCommand.v_WebActionParameterTable; DataRow textToSetRow = webActionDT.NewRow(); textToSetRow["Parameter Name"] = "Text To Set"; textToSetRow["Parameter Value"] = $"\"{selectedKey}\""; webActionDT.Rows.Add(textToSetRow); _sequenceCommandList.Add(setTextElementActionCommand); } }