//Returns the amount of refrences of the block b in the editors private void getReferences(Block b) { switch (source) { case "VARIABLE": foreach (EditorDragDropTarget target in MainPage.editorLists) { references = references + SocketReader.checkCustoms(target.getTreeList(), b); } break; case "METHOD": foreach (EditorDragDropTarget target in MainPage.editorLists) { references = references + SocketReader.checkCustoms(target.getTreeList(), b); } break; case "PARAMETER": break; default: Debug.WriteLine("invalid reference type"); references = -1; break; } }
private void sendCode_Click(object sender, RoutedEventArgs e) { int openSockets = SocketReader.checkOpenSocks(editorDragDrop.getTreeList()); //cannot continue if a socket is open if (openSockets > 0) { MessageBoxButton button = MessageBoxButton.OK; //only allow OK and X buttons MessageBoxResult result = MessageBox.Show("Cannot Execute: There are unfilled sockets", "Error", button); //display message window return; } IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication(); if (iso.FileExists("test.txt")) { iso.DeleteFile("test.txt"); } CodeParser.writeToFile("{"); CodeParser.parseVariable(variableList, editorDragDrop); CodeParser.parseCode(editorDragDrop); CodeParser.writeToFile("\n"); CodeParser.parseMethods(methodList, tabList); CodeParser.writeToFile("}"); messageWindow(); }
//copies the socket contents of a block on moving private Block cloneSockets(Block source, Block destination) { //checks if the sockets are textboxes and routes accordingly if ((destination.flag_isConstant || destination.flag_isRobotConstant) && !destination.flag_hasSocks) { destination = SocketReader.textTransfer(source, destination); } else { List <int> socketList = SocketReader.socketFinder(source); //cycling through all sockets foreach (int location in socketList) { ListBox socket = SocketReader.socketMole(destination, location); ListBox sourceSock = SocketReader.socketMole(source, location); //making sure sockets aren't empty if (sourceSock.Items.Count > 0) { Block hubert = (Block)sourceSock.Items.ElementAt(0); Block cubert = hubert.cloneSelf(hubert.flag_hasSocks); //add the block to the socket ResizeAndAdd(socket, cubert); //recursion to catch nested sockets cubert = cloneSockets(hubert, cubert); } } } return(destination); }
// This will run until the socket is closed. public void StartReceiving(Socket socket, Action <ArraySegment <byte> > process) { SocketReader.ReadFromSocket(socket, 2, _receiveBuffer, (headerData) => { if (headerData.Count == 0) { // nothing/closed return; } // Read the length of the data. int length = BitConverter.ToInt16(headerData.Array, headerData.Offset); // if the receive buffer is too small, reallocate it. if (_receiveBuffer.Length < length) { _receiveBuffer = new byte[length]; } SocketReader.ReadFromSocket(socket, length, _receiveBuffer, (dataBufferSegment) => { if (dataBufferSegment.Count == 0) { // nothing/closed return; } try { process(dataBufferSegment); } catch { } StartReceiving(socket, process); }); }); }
//method to prevent a block from going into one of its own sockets private ListBox preventOuroboros(ItemDragEventArgs itemDragEventArgs, ListBox dropTarget, Block immigrant, Block destination) { //testing dragging into self and catching it if it happens List <int> socks = SocketReader.socketFinder(destination); ListBox test; ListBox sourceBox = itemDragEventArgs.DragSource as ListBox; //handling constants if (immigrant.flag_isConstant || immigrant.flag_isRobotConstant) { //checking constants, accounting for their 1 lvl lower problem try { Block source = SocketReader.getParentBlock(sourceBox); Block dst = SocketReader.getParentBlock(dropTarget); List <int> socketLocs = SocketReader.socketFinder(dst); foreach (int loc in socketLocs) { ListBox targ = SocketReader.socketMole(dst, loc); if (targ.Items.Count > 0) { //checking if the target is the current block's location if (((Block)dropTarget.Items.ElementAt(0)) == source) { isConstant = immigrant.flag_isConstant; //for some reason this gets reset during the process, so setting it back dropTarget = sourceBox; //changing the target to the block's current position, dropping it back in place } } } } catch (Exception) { } //clearing the target so the block can be added if (dropTarget.Items.Count > 0) { if (((Block)dropTarget.Items.ElementAt(0)) == immigrant) { dropTarget.Items.Clear(); } } } //checking the block's socket to ensure that it isn't being added to itself foreach (int loc in socks) { test = SocketReader.socketMole(destination, loc); //resetting the drop zone if true and shrinking the block down if (test == dropTarget) { dropTarget = sourceBox; Debigulate(dropTarget); isCondition = immigrant.flag_isCondition; } //recursively calling, to ensure that the block isn't being added to a socket in a block within its own socket if (test.Items.Count > 0) { dropTarget = preventOuroboros(itemDragEventArgs, dropTarget, immigrant, (Block)test.Items.ElementAt(0)); } } return(dropTarget); }
//method to change combo boxes in directional blocks private static void directionalCombos(ListBox dropTarget, Block copyBlock) { ComboBox cb = (ComboBox)copyBlock.innerPane.Children.ElementAt(2); //if turn, remove front, rear, backwards and forwards if (SocketReader.checkParentBlock(dropTarget).Contains("TURN")) { Debug.WriteLine(copyBlock.innerPane.Children.ElementAt(2)); cb.Items.RemoveAt(3); cb.Items.RemoveAt(2); cb.Items.RemoveAt(1); cb.Items.RemoveAt(0); cb.SelectedItem = cb.Items.ElementAt(0); } //if drive, remove front,rear, left and right else if (SocketReader.checkParentBlock(dropTarget).Contains("DRIVE")) { Debug.WriteLine(copyBlock.innerPane.Children.ElementAt(2)); cb.Items.RemoveAt(5); cb.Items.RemoveAt(4); cb.Items.RemoveAt(3); cb.Items.RemoveAt(2); } //if distance, remove backwards and forwards else if (SocketReader.checkParentBlock(dropTarget).Contains("RANGE")) { Debug.WriteLine(copyBlock.innerPane.Children.ElementAt(2)); cb.Items.RemoveAt(1); cb.Items.RemoveAt(0); cb.SelectedIndex = 0; } }
private void runSim_Click(object sender, RoutedEventArgs e) { int openSockets = SocketReader.checkOpenSocks(editorDragDrop.getTreeList()); //cannot continue if a socket is open if (openSockets > 0) { MessageBoxButton button = MessageBoxButton.OK; //only allow OK and X buttons MessageBoxResult result = MessageBox.Show("Cannot Execute: There are unfilled sockets", "Error", button); //display message window return; } IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication(); if (iso.FileExists("test.txt")) { iso.DeleteFile("test.txt"); } CodeParser.writeToFile("{"); CodeParser.parseVariable(variableList, editorDragDrop); CodeParser.parseCode(editorDragDrop); CodeParser.writeToFile("\n"); CodeParser.parseMethods(methodList, tabList); CodeParser.writeToFile("}"); HtmlPopupWindowOptions options = new HtmlPopupWindowOptions(); options.Width = 1000; options.Height = 1000; HtmlPage.PopupWindow(new Uri("http://webstrar44.fulton.asu.edu/page3/RobotSim/launch.jnlp"), "_blank", options); messageWindow(); }
/// <summary> /// Initialize a new instance of this class /// </summary> public NetClient() { Commands = new CommandCollection(); _SendCommands = new Dictionary <int, NetCommand>(); CommandExecutionManager = new CommandSubscriptionManager(); ServerCommandsManager = new CommandSubscriptionManager(); _SocketReader = new SocketReader(); _SocketReader.CommandIdReaded += new EventHandler(SocketReader_CommandIdReaded); }
/// <summary> /// Initialize a new instance of this class with the provided values /// </summary> /// <param name="socket"></param> /// <param name="server"></param> public ServerClient(Socket socket, NetServer server) { Socket = socket; Server = server; Guid = Guid.NewGuid(); HashCode = Guid.GetHashCode(); Commands = new ServerCommandCollection(); _SendedCommands = new Dictionary <int, NetCommand>(); Operations = new CommandOperationCollection(this); _SocketReader = new SocketReader(); _SocketReader.CommandIdReaded += new EventHandler(OnCommandIdTaken); }
internal override async Task <string> CreateAndShowWindowImpl( string title, byte[] nullableIcon, int width, int height, Func <string, string, bool> handleVmBoundMessage) { System.Net.Sockets.Socket socket = new System.Net.Sockets.Socket( System.Net.Sockets.AddressFamily.Unix, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Unspecified); socket.Bind(new System.Net.Sockets.UnixDomainSocketEndPoint(this.filePath + "_us")); socket.Listen(1); System.ComponentModel.BackgroundWorker bgworker = new System.ComponentModel.BackgroundWorker(); System.Text.StringBuilder sb = new System.Text.StringBuilder(); bgworker.DoWork += async(e, sender) => { System.Net.Sockets.Socket s = socket.Accept(); SocketReader sr = new SocketReader(s); while (true) { int length = sr.ReadLength(); string data = sr.ReadString(length); int colon = data.IndexOf(':'); string type = colon == -1 ? data : data.Substring(0, colon); string payload = colon == -1 ? "" : data.Substring(colon + 1); if (type == "READY") { StartSocketClient(); await this.SendString("SRC", JsResourceUtil.GetU3Source()); } else if (type == "VMJSON") { IDictionary <string, object> jsonPayload = new Wax.Util.JsonParser(payload.Substring(1, payload.Length - 2)).ParseAsDictionary(); handleVmBoundMessage((string)jsonPayload["type"], (string)jsonPayload["message"]); } else { throw new Exception("Unknown message type: " + type); } } }; bgworker.RunWorkerAsync(); await Task.Delay(TimeSpan.FromMilliseconds(10)); return(await RunProcess(title, width, height)); // Process ends when window is closed. }
private static void getSocket(XElement blocks, Block parent) { IEnumerable <XElement> sockets = blocks.Elements("SOCKET"); List <int> socketPosition = SocketReader.socketFinder(parent); int index = 0; foreach (var socket in sockets) { if (socketPosition.Count > 0) { addSocketBlock(socket, parent, socketPosition[index]); index++; } } }
public static (double, double, TimeSpan) RunSmall() { var tempFileName = "abc1.sock"; var serverCancellationSource = new CancellationTokenSource(); var clientCancellationSource = new CancellationTokenSource(); var stopWatch = Stopwatch.StartNew(); TimeSpan elapesedTime; ulong writer_count = 0, reader_count = 0; try { var sw = new SocketWriter(); var sr = new SocketReader(); var socks = UnixSocketRunner.GetUnixSockets(ProtocolType.Unspecified, tempFileName); var wirter = sw.Run(DataType.Small, serverCancellationSource.Token, socks.Server); var reader = sr.Run(DataType.Small, clientCancellationSource.Token, socks.Client); serverCancellationSource.CancelAfter(TimeSpan.FromSeconds(10)); writer_count = wirter.Result; clientCancellationSource.Cancel(); reader_count = reader.Result; } catch (Exception e) { Debug.WriteLine(e.StackTrace); } finally { elapesedTime = stopWatch.Elapsed; stopWatch.Stop(); File.Delete(tempFileName); } double readen_kbPerS = (reader_count / 1024) / elapesedTime.TotalSeconds; double writen_kbPerS = (writer_count / 1024) / elapesedTime.TotalSeconds; return(readen_kbPerS, writen_kbPerS, elapesedTime); }
public static (double, double, TimeSpan) RunBig() { var serverCancellationSource = new CancellationTokenSource(); var clientCancellationSource = new CancellationTokenSource(); var stopWatch = Stopwatch.StartNew(); TimeSpan elapesedTime; ulong writer_count = 0, reader_count = 0; try { var sw = new SocketWriter(); var sr = new SocketReader(); var socks = TcpSocketRunner.GetSockets(); var wirter = sw.Run(DataType.Big, serverCancellationSource.Token, socks.Server); var reader = sr.Run(DataType.Big, clientCancellationSource.Token, socks.Client); serverCancellationSource.CancelAfter(TimeSpan.FromSeconds(10)); writer_count = wirter.Result; clientCancellationSource.Cancel(); reader_count = reader.Result; } catch (Exception e) { Console.WriteLine(e.StackTrace); } finally { elapesedTime = stopWatch.Elapsed; stopWatch.Stop(); } double readen_kbPerS = (reader_count / 1024) / elapesedTime.TotalSeconds; double writen_kbPerS = (writer_count / 1024) / elapesedTime.TotalSeconds; return(readen_kbPerS, writen_kbPerS, elapesedTime); }
/* * Check socket restrictions, will not allow blocks to be added if they are restricted * Check based on return type of blocks * Checks method returns as well */ private bool checkRestrictions(ListBox listBox, Block child) { Block parent = SocketReader.getParentBlock(listBox); //get parent block string returnType = child.returnType; //get return type //If parent is the return block make sure the returnType matches the return block type if (parent.Text.Equals("RETURN")) { if (SocketReader.returnMustMatch(listBox, child)) { return(true); } else { return(false); } } else { //Check to make sure block is allowed in socket based on return type switch (returnType) { case "INT": return(!parent.flag_intDisabled); case "STRING": return(!parent.flag_stringDisabled); case "BOOL": return(!parent.flag_booleanDisabled); default: return(true); } } }
private static void addSocketBlock(XElement socket, Block parent, int position) { IEnumerable <XElement> blocks = socket.Elements(); foreach (var block in blocks) { int blockID = blockLookUp[block.Attribute("type").Value]; string blockName = block.Attribute("type").Value; Debug.WriteLine(blockName + " ID: " + blockID); if (!blockName.Contains("END")) { Block copyBlock = MainPage.createProgramStructureBlock(blockID); //currently adding so that program doesn't break. //need to add correct block in this case methods by name. if (copyBlock == null) { copyBlock = MainPage.createReservedBlock(blockName); switch (blockName) { case "VARIABLE": foreach (Block b in MainPage.variableList) //find method block { if (b.metadataList[1].Equals(block.Element("name").Value)) { copyBlock = b.cloneSelf(true); break; } } break; case "METHOD": foreach (Block b in MainPage.methodList) //find method block { if (b.metadataList[1].Equals(block.Element("name").Value)) { copyBlock = b.cloneSelf(true); break; } } break; case "PARAMETER": TabPage methodCode = (TabPage)MainPage.tabList[methodIndex - 1].Content; //MainPage.methodList.IndexOf(b) //Debug.WriteLine(methodCode.getParamForName(block.Element("name").Value)); copyBlock = methodCode.getParamForName(block.Element("name").Value); //saftey in case name was not written correctly if (copyBlock == null) { copyBlock = MainPage.createReservedBlock(blockName); } break; default: Debug.WriteLine("type not defined"); break; } } else if ((copyBlock.flag_isConstant || copyBlock.flag_isRobotConstant) && !copyBlock.ToString().Contains("RANGE")) { if (copyBlock.flag_hasSocks) { int slot = SocketReader.textFinder(copyBlock); List <System.Windows.UIElement> components = copyBlock.innerPane.Children.ToList(); if (components.ElementAt(slot) is NumericTextBox)//.ToString().Equals("CapGUI.NumericTextBox") || components.ElementAt(location).ToString().Equals("System.Windows.Controls.TextBox")) { NumericTextBox box = (NumericTextBox)components.ElementAt(slot); box.Text = block.Element("VALUE").Value; } else if (components.ElementAt(slot) is TextBox) { TextBox box = (TextBox)components.ElementAt(slot); box.Text = block.Element("VALUE").Value; } } else if (copyBlock.Text.Equals("GETBEARING") || copyBlock.Text.Equals("INFINITY")) //getBearing and infinity both dont have any metadata { } else { ComboBox cb = (ComboBox)copyBlock.innerPane.Children.ElementAt(2); directionalCombos(parent, copyBlock); cb.SelectedIndex = int.Parse(block.Element("INDEX").Value); } } AddToSocket(parent, position, copyBlock); getSocket(block, copyBlock); } } }
//method to write the socket xml data private static void WriteSockets(XmlWriter writer, Block b) { List <int> socketList = SocketReader.socketFinder(b); //writing data from text boxes and combo boxes if ((b.flag_isConstant || b.flag_isRobotConstant) && !b.ToString().Contains("RANGE")) { //handling basic text if (b.flag_hasSocks) { int slot = SocketReader.textFinder(b); writer.WriteStartElement("VALUE"); writer.WriteString(SocketReader.textReader(b, slot)); writer.WriteEndElement(); } else if (b.Text.Equals("GETBEARING") || b.Text.Equals("INFINITY")) //getBearing and infinity both dont have any metadata { } //handling combo boxes else { ComboBox cb = (ComboBox)b.innerPane.Children.ElementAt(1); writer.WriteStartElement("INDEX"); writer.WriteString(cb.SelectedIndex.ToString()); writer.WriteEndElement(); } } //handling standard sockets else { foreach (int location in socketList) { writer.WriteStartElement("SOCKET"); ListBox socket = SocketReader.socketMole(b, location); //ensuring the socket isn't empty if (socket.Items.Count > 0) { Block infosphere = (Block)socket.Items.ElementAt(0); //checking if block is a variable or method if (infosphere.flag_isCustom) { //if (infosphere.Name.Equals("VARIABLE")) // { writer.WriteStartElement("BLOCK"); writer.WriteAttributeString("type", infosphere.Text); //type of block // writer.WriteStartElement("VARIABLE"); //} // else if (infosphere.Name.Equals("METHOD")) // { // writer.WriteStartElement("METHOD"); // } writer.WriteStartElement("name"); writer.WriteString(infosphere.metadataList[1]); //name of variable writer.WriteEndElement(); } else { writer.WriteStartElement("BLOCK"); writer.WriteAttributeString("type", infosphere.Text); //type of block //writer.WriteStartElement(infosphere.ToString()); } WriteSockets(writer, infosphere); writer.WriteEndElement(); } writer.WriteEndElement(); } } }
/* * Event method that is called when an item is dropped into socket. * Checks to see if block can be added to socket and prefroms functions based on those checks. * Set the communication flag for socket to false (handled). */ protected override void OnDropOverride(Microsoft.Windows.DragEventArgs args) { Debug.WriteLine("socket drop"); if ((args.AllowedEffects & Microsoft.Windows.DragDropEffects.Link) == Microsoft.Windows.DragDropEffects.Link || (args.AllowedEffects & Microsoft.Windows.DragDropEffects.Move) == Microsoft.Windows.DragDropEffects.Move) { //changed //gets the data format which is a ItemDragEventArgs object data = args.Data.GetData(args.Data.GetFormats()[0]); //changed //cast from generic object to ItemDragEventArgs and add to SelectionCollection ItemDragEventArgs itemDragEventArgs = data as ItemDragEventArgs; SelectionCollection selectionCollection = itemDragEventArgs.Data as SelectionCollection; //changed //get the target & source listbox from DragEventArgs ListBox dropTarget = GetDropTarget(args); //Copy from parent method if (dropTarget != null && selectionCollection.All(selection => CanAddItem(dropTarget, selection.Item))) { if ((args.Effects & Microsoft.Windows.DragDropEffects.Move) == Microsoft.Windows.DragDropEffects.Move) { args.Effects = Microsoft.Windows.DragDropEffects.Move; } else { args.Effects = Microsoft.Windows.DragDropEffects.Link; } int?index = GetDropTargetInsertionIndex(dropTarget, args); if (index != null) { if (args.Effects == Microsoft.Windows.DragDropEffects.Move && itemDragEventArgs != null && !itemDragEventArgs.DataRemovedFromDragSource) { itemDragEventArgs.RemoveDataFromDragSource(); } //major change place at top of the listbox to act as a stack for undo //needs to have its own method foreach (Selection selection in selectionCollection) { if (selection.Item.GetType().Equals(typeof(Block))) { //creat copy block of the selection item Block copyBlock = MainPage.createProgramStructureBlock(((Block)selection.Item).typeID); if (copyBlock == null || (copyBlock != null && !copyBlock.type.Equals("STATEMENT"))) //check to make sure that you are not adding a STATEMENT to SOCKET { Block selected = (Block)selection.Item; //check to make sure that you are not dragging into self dropTarget = preventOuroboros(itemDragEventArgs, dropTarget, selected, selected); if (copyBlock == null) { if (!((Block)selection.Item).Text.Equals("END")) { copyBlock = (selected).cloneSelf(true); } else { copyBlock = MainPage.createReservedBlock(selected.Text); } } //check to make sure that if there are more than 1 socket that they match if (SocketReader.socketCompatable(dropTarget, copyBlock)) { //alter comboboxes if needed if (checkRestrictions(dropTarget, copyBlock)) { if (copyBlock.ToString().Equals("DIRECTION")) { directionalCombos(dropTarget, copyBlock); } //flag to check if an element did move //used for cloneSockets check bool flag_DidAdd = false; //Add item to socket if allowed if (socketType.Contains(copyBlock.Text) || (copyBlock.returnType != null && socketType.Contains(copyBlock.returnType))) { ResizeAndAdd(dropTarget, copyBlock); flag_DidAdd = true; } else if (isConstant && copyBlock.flag_isConstant) { ResizeAndAdd(dropTarget, copyBlock); flag_DidAdd = true; } else if (isCondition && copyBlock.flag_isCondition) { ResizeAndAdd(dropTarget, copyBlock); flag_DidAdd = true; } //clone sockets if item was added if (copyBlock.flag_hasSocks && flag_DidAdd) { copyBlock = cloneSockets(selected, copyBlock); } if (!flag_DidAdd) { ErrorMessage(1); } } } else { ErrorMessage(2); } } else { ErrorMessage(3); } } } //socket is no longer dragging MainPage.communicate.socket = false; //try to fix half of the communication error } } else { args.Effects = Microsoft.Windows.DragDropEffects.None; } if (args.Effects != args.AllowedEffects) { args.Handled = true; } } }