Example #1
0
        /// <summary>
        /// Process a file
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="U"></typeparam>
        /// <param name="OutDictionary"></param>
        /// <param name="FileName"></param>
        /// <param name="KeyStartFlag"></param>
        /// <param name="KeyStopFlag"></param>
        /// <param name="ValueStartFlag"></param>
        /// <param name="ValueStopFlag"></param>
        /// <param name="CountLabel"></param>
        /// <param name="DataType"></param>
        private void ProcessFile <T, U>(Dictionary <T, U> OutDictionary, String FileName, String KeyStartFlag, String KeyStopFlag, String ValueStartFlag, String ValueStopFlag, Label CountLabel, String DataType)
        {
            OutDictionary.Clear();
            String InLine;

            using (StreamReader sRd = new StreamReader(FileName))
                while ((InLine = sRd.ReadLine()) != null)
                {
                    int StartPoint = InLine.IndexOf(KeyStartFlag);
                    if (StartPoint != -1)
                    {
                        int    EndPoint = InLine.IndexOf(KeyStopFlag, StartPoint + KeyStartFlag.Length);
                        String Key      = InLine.Substring(StartPoint + KeyStartFlag.Length, EndPoint - StartPoint - KeyStartFlag.Length);
                        Object OutKey   = typeof(T) == typeof(int[]) ? new int[] { int.Parse(Key.Split(',')[0]), int.Parse(Key.Split(',')[1]) } : Convert.ChangeType(Key, typeof(T));

                        StartPoint = InLine.IndexOf(ValueStartFlag);
                        EndPoint   = String.IsNullOrEmpty(ValueStopFlag) ? InLine.Length : InLine.IndexOf(ValueStopFlag, StartPoint + ValueStartFlag.Length);
                        String Value    = InLine.Substring(StartPoint + ValueStartFlag.Length, EndPoint - StartPoint - ValueStartFlag.Length);
                        U      OutValue = (U)Convert.ChangeType(Value, typeof(U));

                        OutDictionary.Add((T)OutKey, OutValue);
                    }
                }
            CountLabel.Text = OutDictionary.Count.ToString("#,##0") + " " + DataType;
        }
 private void StartSimulation()
 {
     for (int register = 0; register < NumOfRegisters; register++)
     {
         InLine.Add(new Queue <Customer>());
     }
     ArrivalEvent();
 }
 private void DrawCondition(Rect pos, TriggerCondition condition, GUIContent label)
 {
     EditorGUI.LabelField(InLine.GetRect(pos, 0, 0, 2), "Trigger");
     condition.referenceTrigger = (Trigger)EditorGUI.ObjectField(InLine.GetRect(pos, 0, 100, 1), condition.referenceTrigger, typeof(Trigger), true);
     InLine.SetRect(pos, 1, 0, 6);
     {
         EditorGUI.LabelField(InLine.NextRect(), "IsTrue");
         condition.isTrue = EditorGUI.Toggle(InLine.NextRect(true), condition.isTrue);
     }
 }
    protected void DrawCondition(Rect pos, DestroyedCondition condition, GUIContent label)
    {
        EditorGUI.LabelField(InLine.GetRect(pos, 0, 0, 2), "Object");
        condition.checkObject = EditorGUI.ObjectField(InLine.GetRect(pos, 0, 100, 1), condition.checkObject, typeof(UnityEngine.Object), true);

        InLine.SetRect(pos, 1, 0, 6);
        {
            EditorGUI.LabelField(InLine.NextRect(), "IsAlive");
            condition.isAlive = EditorGUI.Toggle(InLine.NextRect(true), condition.isAlive);
        }
        InLine.Reset();
    }
    protected void DrawCondition(Rect pos, TimedCondition condition, GUIContent label)
    {
        EditorGUI.LabelField(InLine.GetRect(pos, 0, 0, 2), "Timer Amount");
        condition.timerAmount = EditorGUI.FloatField(InLine.GetRect(pos, 0, 100, 1), condition.timerAmount);

        InLine.SetRect(pos, 1, 0, 6);
        {
            EditorGUI.LabelField(InLine.NextRect(), "Loop");
            condition.loop = EditorGUI.Toggle(InLine.NextRect(true), condition.loop);
        }
        InLine.Reset();
    }
 private void DrawCondition(Rect pos, InputCondition condition, GUIContent label)
 {
     InLine.SetRect(pos, 0, 0, 3);
     {
         EditorGUI.LabelField(InLine.NextRect(), "Button");
         condition.button = EditorGUI.TextField(InLine.NextRect(), condition.button);
     }
     InLine.SetRect(pos, 1, 0, 3);
     {
         EditorGUI.LabelField(InLine.NextRect(), "InputType");
         condition.type = (InputType)EditorGUI.EnumPopup(InLine.NextRect(), condition.type);
     }
 }
Example #7
0
        /// <summary>
        /// Process a file for operatorships
        /// </summary>
        /// <param name="OutDictionary"></param>
        /// <param name="FileName"></param>
        /// <param name="CountLabel"></param>
        /// <param name="DataType"></param>
        private void ProcessFile(SortedDictionary <String, String[]> OutDictionary, String FileName, Label CountLabel, String DataType)
        {
            String InLine;

            OutDictionary.Clear();
            using (StreamReader sRd = new StreamReader(FileName))
                while ((InLine = sRd.ReadLine()) != null)
                {
                    if (InLine.Contains(','))
                    {
                        String        Key    = InLine.Substring(0, InLine.IndexOf(','));
                        List <String> Values = new List <String>(InLine.Substring(InLine.IndexOf(',') + 1).Split(','));
                        Values.Sort(StringComparer.CurrentCultureIgnoreCase);
                        OutDictionary.Add(Key, Values.ToArray());
                    }
                }
            CountLabel.Text = OutDictionary.Count.ToString("#,##0") + " " + DataType;
        }
    protected void DrawCondition(Rect pos, AmountCondition condition, GUIContent label)
    {
        InLine.SetRect(pos, 0, 0, 6);
        {
            condition.typeOfFind = (FindType)EditorGUI.EnumPopup(InLine.NextRect(), condition.typeOfFind);
            switch (condition.typeOfFind)
            {
            case FindType.Tag:
                condition.checkTag = EditorGUI.TagField(InLine.NextRect(), condition.checkTag);
                break;

            case FindType.Layer:
                condition.layer = EditorGUI.MaskField(InLine.NextRect(), condition.layer, FindLayerNames());
                break;

            case FindType.ByType:
                condition.typeTemplate = EditorGUI.ObjectField(InLine.NextRect(), condition.typeTemplate, typeof(UnityEngine.Object), true);
                if (condition.typeTemplate == null)
                {
                    EditorGUILayout.HelpBox("A Amount Condition needs a type template", MessageType.Warning);
                }
                break;
            }
            EditorGUI.LabelField(InLine.GetLine(0, pos.width / 3, 5f), "Current", GUIStyle.none);
            EditorGUI.IntField(InLine.NextRect(), condition.numOfObjects, GUIStyle.none);
        }

        InLine.SetRect(pos, 1, 0, 6);
        {
            EditorGUI.LabelField(InLine.NextRect(), "Remaining");
            condition.typeOfCompare = (CompareType)EditorGUI.EnumPopup(InLine.NextRect(), condition.typeOfCompare);
            condition.amount        = EditorGUI.IntField(InLine.NextRect(), condition.amount);
        }

        condition.triggerArea = EditorGUI.BoundsField(InLine.GetLine(0, pos.width / 2, 1), condition.triggerArea);

        InLine.Reset();
    }
    protected void DrawCondition(Rect pos, AreaCondition condition, GUIContent label)
    {
        InLine.SetRect(pos, 0, 0, 6);
        {
            EditorGUI.LabelField(InLine.NextRect(), "Area");
        }
        condition.triggerArea = EditorGUI.BoundsField(InLine.GetLine(0, pos.width / 2, 1), condition.triggerArea);

        InLine.SetRect(pos, 0, 50, 6);
        {
            EditorGUI.LabelField(InLine.NextRect(), "UsePlayer");
            condition.UsePlayer = EditorGUI.Toggle(InLine.NextRect(true), condition.UsePlayer);
        }
        if (!condition.UsePlayer)
        {
            condition.checkObject = (GameObject)EditorGUI.ObjectField(InLine.GetLine(1, 0, 2), condition.checkObject, typeof(GameObject), true);
            if (!condition.checkObject)
            {
                EditorGUILayout.HelpBox("CheckObject is null for AreaCondition", MessageType.Warning);
            }
        }
        InLine.Reset();
    }
Example #10
0
        /// <summary>
        /// Process our command log
        /// </summary>
        /// <param name="state"></param>
        private void ProcessCommandLog(object state)
        {
            List <MM_EMS_Command> NewCommands = new List <MM_EMS_Command>();
            String InLine;

            using (FileStream fS = new FileStream((string)state, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                using (StreamReader sRd = new StreamReader(fS))
                    while ((InLine = sRd.ReadLine()) != null)
                    {
                        if (InLine.Contains("Sent") && InLine.Contains("TEDE"))
                        {
                            InLine = InLine.Substring(InLine.IndexOf('>') + 1);
                            InLine = InLine.Substring(0, InLine.IndexOf('<'));
                            String[] splStr     = InLine.Split(' ');
                            String[] splCommand = splStr[5].Split(',');
                            NewCommands.Add(new MM_EMS_Command()
                            {
                                UserName    = splStr[1],
                                CommandType = splCommand[0],
                                Application = splCommand[1],
                                Family      = splCommand[2],
                                CommandName = splCommand[3],
                                Database    = splCommand[4],
                                Record      = splCommand[5],
                                Field       = splCommand[6],
                                TEID        = Convert.ToInt32(splCommand[7]),
                                Value       = splCommand[8],
                                IssuedOn    = DateTime.Parse(splStr[7] + " " + splStr[8] + " " + splStr[9])
                            });
                        }
                    }
            Invoke((MethodInvoker) delegate
            {
                EMSCommands.Clear();
                AddCommands(NewCommands.ToArray(), Servers[cmbServer.SelectedItem.ToString()]);
            });
        }
Example #11
0
        /// <summary>
        /// Converts the paragraph.
        /// </summary>
        /// <param name="worksheetPart">The worksheet part.</param>
        /// <param name="RTFSection">The RTF section.</param>
        /// <param name="matchShape">The match shape.</param>
        /// <returns></returns>
        public static DrawingSpreadsheet.Shape ConvertParagraph(WorksheetPart worksheetPart, Section RTFSection, DrawingSpreadsheet.Shape matchShape)
        {
            DrawingSpreadsheet.Shape           NewShape = new DrawingSpreadsheet.Shape();
            DocumentFormat.OpenXml.Drawing.Run ShapeRun = null;

            // get the graphic frame from the source anchor
            var sourceAnchor = worksheetPart.DrawingsPart.WorksheetDrawing.GetFirstChild <DrawingSpreadsheet.TwoCellAnchor>();
            var sourceShape  = sourceAnchor.Descendants <DrawingSpreadsheet.Shape>().FirstOrDefault();

            // add it to the target anchor (ie. the one with the shape removed)
            DocumentFormat.OpenXml.Drawing.Spreadsheet.Shape targetShape = (DocumentFormat.OpenXml.Drawing.Spreadsheet.Shape)NewShape.CloneNode(true);

            targetShape.Append(matchShape.NonVisualShapeProperties.CloneNode(true));
            targetShape.Append(matchShape.ShapeProperties.CloneNode(true));
            targetShape.Append(matchShape.ShapeStyle.CloneNode(true));

            targetShape.Append(matchShape.TextBody.CloneNode(true));

            //Remove the text associated with the shape

            foreach (DocumentFormat.OpenXml.Drawing.Paragraph Paragraph in targetShape.TextBody.Descendants <DocumentFormat.OpenXml.Drawing.Paragraph>())
            {
                foreach (DocumentFormat.OpenXml.Drawing.Run RunToRemove in Paragraph.Descendants <DocumentFormat.OpenXml.Drawing.Run>())
                {
                    RunToRemove.Remove();
                }
            }

            try
            {
                foreach (System.Windows.Documents.Paragraph p in RTFSection.Blocks)
                {
                    InlineCollection ParagraphInLines = p.Inlines;


                    DocumentFormat.OpenXml.Drawing.Paragraph ShapeParagraph = new DocumentFormat.OpenXml.Drawing.Paragraph();

                    foreach (var InLine in ParagraphInLines)
                    {
                        if (InLine.GetType() == typeof(System.Windows.Documents.Span))
                        {
                            Span s = (Span)InLine;

                            Brush SourceTextColour = s.Foreground;

                            foreach (System.Windows.Documents.Run r in s.Inlines)
                            {
                                if (r.Text != "\n")
                                {
                                    ShapeRun = new DocumentFormat.OpenXml.Drawing.Run();

                                    DocumentFormat.OpenXml.Drawing.RunProperties ShapeRunProperties = new DocumentFormat.OpenXml.Drawing.RunProperties();
                                    DocumentFormat.OpenXml.Drawing.Text          ShapeText          = new DocumentFormat.OpenXml.Drawing.Text(r.Text);

                                    //the font family will be inherited from the sheet of the target shape
                                    ShapeRunProperties.FontSize = new Int32Value(System.Convert.ToInt32(s.FontSize * 100));

                                    SolidFill textFill = new SolidFill();

                                    SystemColor textColour = new SystemColor();

                                    textColour.Val = new EnumValue <SystemColorValues>(SystemColorValues.WindowText);

                                    Int64Value ColourMask   = 0xFF000000;
                                    Int64Value SourceColour = System.Convert.ToInt64(SourceTextColour.ToString().Replace("#", "0x"), 16);

                                    SourceColour = SourceColour % ColourMask;

                                    textColour.LastColor = new HexBinaryValue(string.Format("{0,10:X}", SourceColour));

                                    textFill.SystemColor = textColour;

                                    ShapeRunProperties.Append(textFill);

                                    if (r.FontWeight == System.Windows.FontWeights.Bold)
                                    {
                                        ShapeRunProperties.Bold = true;
                                    }

                                    if (r.FontStyle == System.Windows.FontStyles.Italic)
                                    {
                                        ShapeRunProperties.Italic = true;
                                    }

                                    if (r.TextDecorations == System.Windows.TextDecorations.Underline)
                                    {
                                        ShapeRunProperties.Underline = new EnumValue <TextUnderlineValues>(TextUnderlineValues.Single);
                                    }

                                    ShapeRun.Text          = ShapeText;
                                    ShapeRun.RunProperties = ShapeRunProperties;

                                    ShapeParagraph.Append(ShapeRun);
                                }
                            }
                        }
                        else
                        {
                            //do something else
                        }
                    }

                    targetShape.TextBody.Append(ShapeParagraph);
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }

            return(targetShape);
        }
Example #12
0
        /// <summary>
        /// Process an incoming client
        /// </summary>
        /// <param name="state"></param>
        private static void ProcessTCPMessage(object state)
        {
            //Now, notify that we have a connection, let's create our stream reader around it, and retrieve our header
            TcpClient Conn      = (TcpClient)state;
            String    FileName  = "";
            DateTime  StartTime = DateTime.Now;

            //If our source IP address changes, notify the console
            IPAddress Address = ((IPEndPoint)Conn.Client.RemoteEndPoint).Address;

            if (Address.ToString() != MM_Server.LastTEDEAddress.ToString())
            {
                MM_Notification.WriteLine(ConsoleColor.Yellow, "TEDE: IP Source Address change detected: {0}, last {1}", Address, MM_Server.LastTEDEAddress);
            }
            MM_Server.LastTEDEAddress = Address;

            using (NetworkStream nRd = Conn.GetStream())
                using (StreamReader sRd = new StreamReader(nRd))
                    try
                    {
                        //Define our key variables
                        List <String>  OutList     = new List <string>();
                        bool           AtBeginning = true;
                        PropertyInfo[] HeaderInfo  = null;
                        DateTime       BatchId     = default(DateTime);
                        Type           TargetType  = null;

                        //Now, read in all of our lines of data, using reflection to store our data
                        String InLine;
                        while ((InLine = sRd.ReadLine()) != null)
                        {
                            if (InLine.StartsWith("#"))
                            {
                                String[] splStr = InLine.TrimStart('#').TrimEnd(',').Split(',');
                                MM_Server.LastTEDEUpdate = DateTime.Now;

                                //If we're at the beginning, process accordingly
                                if (AtBeginning)
                                {
                                    StartTime = DateTime.Now;
                                    //Pull in, and parse our first line.
                                    BatchId  = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(splStr[0]));
                                    FileName = splStr[1];
                                    if (!FileName.EndsWith(".csv", StringComparison.CurrentCultureIgnoreCase))
                                    {
                                        FileName += ".csv";
                                    }

                                    if (InputTypes.TryGetValue(FileName, out TargetType))
                                    {
                                        //Now that we have our first, line, build our outgoing list
                                        OutList.Clear();

                                        //Read our header
                                        String[] HeaderLine = sRd.ReadLine().TrimStart('#').Split(',');

                                        HeaderInfo = MM_Serialization.GetHeaderInfo(TargetType, HeaderLine);
                                        for (int a = 0; a < HeaderLine.Length; a++)
                                        {
                                            if (HeaderInfo[a] == null)
                                            {
                                                MM_Notification.WriteLine(ConsoleColor.Yellow, "Unknown variable {0} in {1}", HeaderLine[a], FileName);
                                            }
                                        }

                                        //Confirm all of our headers are present
                                        foreach (PropertyInfo pI in TargetType.GetProperties())
                                        {
                                            if (Array.FindIndex <String>(HeaderLine, T => T.Equals(pI.Name, StringComparison.CurrentCultureIgnoreCase)) == -1)
                                            {
                                                MM_Notification.WriteLine(ConsoleColor.Yellow, "Missing variable {0} ({1}) in {2} / {3}", pI.Name, pI.PropertyType.Name, TargetType.Name, FileName);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        //Console.WriteLine("Rereading file " + FileName);
                                        sRd.ReadLine();
                                    }

                                    AtBeginning = false;
                                }
                                else
                                {
                                    DateTime EndTime = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(splStr[0]));
                                    if (EndTime != BatchId)
                                    {
                                        MM_Notification.WriteLine(ConsoleColor.Red, "Mismatch date on {0}: Start {1}, End {2}", FileName, BatchId, EndTime);
                                    }
                                    if (OutList != null)
                                    {
                                        ThreadPool.QueueUserWorkItem(new WaitCallback(ProcessData), new object[] { OutList.ToArray(), TargetType, HeaderInfo });
                                    }
                                    else
                                    {
                                        //MM_Notification.WriteLine(ConsoleColor.Yellow, "Ignore processing data from {0}.", FileName);
                                    }
                                    AtBeginning = true;
                                }
                            }
                            else if (OutList != null)
                            {
                                OutList.Add(InLine);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        MM_Notification.WriteLine(ConsoleColor.Red, "Error reading {0} from {1}: {2}", FileName, Conn.Client.RemoteEndPoint, ex);
                    }
        }
Example #13
0
        /// <summary>
        /// Process a stream, reading and parsing its content
        /// </summary>
        /// <param name="InLines"></param>
        /// <param name="FileName"></param>
        public static void ProcessStreamRead(StreamReader sRd, String FileName, Type TargetType, ref DateTime LatestBatchID)
        {
            //Now, parse our stream
            IList OutList = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(TargetType));

            //Read our header
            String FirstLine = sRd.ReadLine().TrimStart('#').TrimEnd(',');

            String[] HeaderLine;
            Double   ProperDate;
            DateTime BatchId = DateTime.Now;

            if (Double.TryParse(FirstLine, out ProperDate))
            {
                BatchId    = new DateTime(1970, 1, 1).AddSeconds(ProperDate);
                HeaderLine = sRd.ReadLine().TrimStart('#').Split(',');
            }
            else
            {
                HeaderLine = FirstLine.Split(',');
            }

            if (BatchId < LatestBatchID)
            {
                MM_Notification.WriteLine(ConsoleColor.Red, "Aborting {0} Batch {1} because it's older than {1}", FileName, BatchId, LatestBatchID);
                return;
            }
            else
            {
                LatestBatchID = BatchId;
            }

            PropertyInfo[] HeaderInfo = MM_Serialization.GetHeaderInfo(TargetType, HeaderLine);
            for (int a = 0; a < HeaderLine.Length; a++)
            {
                if (HeaderInfo[a] == null)
                {
                    MM_Notification.WriteLine(ConsoleColor.Yellow, "Unknown variable {0} in {1}", HeaderLine[a], FileName);
                }
            }

            //Confirm all of our headers are present
            foreach (PropertyInfo pI in TargetType.GetProperties())
            {
                if (Array.FindIndex <String>(HeaderLine, T => T.Equals(pI.Name, StringComparison.CurrentCultureIgnoreCase)) == -1)
                {
                    MM_Notification.WriteLine(ConsoleColor.Yellow, "Missing variable {0} ({1}) in {2} / {3}", pI.Name, pI.PropertyType.Name, TargetType.Name, FileName);
                }
            }

            //Now, read in all of our lines of data, using reflection to store our data
            String InLine;

            while ((InLine = sRd.ReadLine()) != null)
            {
                if (InLine.StartsWith("#"))
                {
                    DateTime EndTime = new DateTime(1970, 1, 1).AddSeconds(Convert.ToDouble(InLine.TrimStart('#').TrimEnd(',')));
                    if (EndTime != BatchId)
                    {
                        MM_Notification.WriteLine(ConsoleColor.Red, "Mismatch date on {0}: Start {1}, End {2}", FileName, BatchId, EndTime);
                    }
                }
                else
                {
                    Object OutObj = MM_Serialization.Deserialize(HeaderInfo, InLine.Split(','), Activator.CreateInstance(TargetType));
                    //if (OutObj is MacomberMapCommunications.Messages.EMS.MM_BreakerSwitch_Data)
                    //{
                    //    MacomberMapCommunications.Messages.EMS.MM_BreakerSwitch_Data bs = (MacomberMapCommunications.Messages.EMS.MM_BreakerSwitch_Data)OutObj;
                    //    if (bs.TEID_CB == 118964)
                    //        MM_Notification.WriteLine(ConsoleColor.Magenta, "   TEID=" + bs.TEID_CB.ToString() + "    status=" + (bs.Open_CB ? "Open" : "Closed"));
                    //}
                    OutList.Add(OutObj);
                }
            }

            //Once our data are done, use the interprocess communication to update our data
            if (TargetType == typeof(MM_EMS_Command))
            {
                MM_Server.EMSCommands.Clear();
                foreach (Object obj in OutList)
                {
                    MM_Server.EMSCommands.Add((MM_EMS_Command)obj);
                }
            }
            else
            {
                MM_EMS_Data_Updater.ProcessUpdate(TargetType, (Array)OutList.GetType().GetMethod("ToArray").Invoke(OutList, null));
            }
            OutList.Clear();
            OutList = null;
        }
Example #14
0
        static void Main(string[] args)
        {
            string InFileName  = null;
            string OutFileName = null;
            string InLine;

            string[]     HpglCommands;
            string       HpglCode;
            StreamReader InFile;
            StreamWriter OutFile;

            Settings settings  = new Settings();
            ArgProc  arguments = new ArgProc(args, settings);

            // test

            /*
             * Console.WriteLine("Arguments:");
             * for (int i = 0; i < arguments.ArgCount; i++)
             * {
             *  Console.WriteLine("[" + i.ToString() + "] " + arguments[i]);
             * }
             * Console.WriteLine("Switches:");
             * foreach (string switchKey in arguments.SwitchKeys)
             * {
             *  Console.WriteLine("[" + switchKey + "] " + arguments[switchKey]);
             * }
             */
            // end test



            double HpglPpmm = arguments["HpglPpmm"].ToDouble(); // Hpgl Points per mm
            //double Speed = arguments["Speed"].ToDouble();
            Cordinate CurrentXY;
            Cordinate CenterXY = new Cordinate(0, 0);;
            double    Angle;
            double    Alpha;
            Cordinate XY = new Cordinate(0, 0);
            double    R;
            Cordinate IJ;

            string[] HpglParams;
            bool     IsDrawing = false;

            Console.WriteLine("HPGL to GCODE Converter v0.1 alpha - Copyright (C) 2017 by SUF");
            Console.WriteLine("This program is free software: you can redistribute it and / or modify");
            Console.WriteLine("it under the terms of the GNU General Public License as published by");
            Console.WriteLine("the Free Software Foundation, either version 3 of the License, or");
            Console.WriteLine("any later version.");

            if (arguments.ArgCount == 2)
            {
                InFileName  = arguments[0];
                OutFileName = arguments[1];
            }
            else
            {
                InFileName  = arguments["Source"];
                OutFileName = arguments["Destination"];
            }
            if (InFileName != null && OutFileName != null)
            {
                InFile  = new StreamReader(InFileName);
                OutFile = new StreamWriter(OutFileName);
                // Write header
                OutFile.WriteLine("G21");
                OutFile.WriteLine(arguments["PenUp"]);
                IsDrawing = false;
                if (!ArgProc.GetBool(arguments["IgnoreSpeed"]))
                {
                    OutFile.WriteLine("G1 F" + arguments["Speed"]);
                }
                OutFile.WriteLine("G28 " + arguments["HomeAxes"]);
                CurrentXY = new Cordinate(0, 0);
                while (!InFile.EndOfStream)
                {
                    InLine       = InFile.ReadLine();
                    HpglCommands = InLine.Split(';');
                    foreach (string HpglCommand in HpglCommands)
                    {
                        if (HpglCommand.Trim().Length > 1)
                        {
                            HpglCode = HpglCommand.Trim().Substring(0, 2);
                            switch (HpglCode)
                            {
                            case "PU":      // Pen Up
                                OutFile.WriteLine(arguments["PenUp"]);
                                IsDrawing = false;
                                CurrentXY = DrawPoly(OutFile, HpglPpmm, HpglCommand.Substring(2).Trim(), false);
                                break;

                            case "PD":     // Pen Down
                                OutFile.WriteLine(arguments["PenDown"]);
                                IsDrawing = true;
                                CurrentXY = DrawPoly(OutFile, HpglPpmm, HpglCommand.Substring(2).Trim(), true);
                                break;

                            case "VS":     // Velocity Set
                                if (!ArgProc.GetBool(arguments["IgnoreVelocity"]))
                                {
                                    OutFile.WriteLine("G1 F" + (HpglCommand.Substring(2).ToDouble() * arguments["VelocityScale"].ToDouble()).ToIString());
                                }
                                break;

                            case "IN":     // Start
                                break;

                            case "SP":
                                break;

                            case "PA":     // Position Absolute
                                XY        = CurrentXY;
                                CurrentXY = DrawPoly(OutFile, HpglPpmm, HpglCommand.Substring(2).Trim(), IsDrawing);
                                CurrentXY = XY;
                                break;

                            case "CI":      // Circle
                                // Parse radius
                                R = HpglCommand.Substring(2).Trim().ToDouble() / HpglPpmm;
                                // Move negative X by Radius to arrive to the arc
                                OutFile.WriteLine("G0 X" + (CurrentXY.X - R).ToIString());
                                // Pen down - there is no PD command before CI, it assume that you draw the circle
                                OutFile.WriteLine(arguments["PenDown"]);
                                IsDrawing = true;
                                // Draw the circle
                                OutFile.WriteLine("G2 I" + R.ToIString());
                                CurrentXY.X -= R;
                                break;

                            case "AA":     // Arc Absolute
                                // gather the parameters
                                HpglParams = HpglCommand.Substring(2).Trim().Split(',');
                                CenterXY.X = HpglParams[0].ToDouble() / HpglPpmm;
                                CenterXY.Y = HpglParams[1].ToDouble() / HpglPpmm;
                                Angle      = HpglParams[2].ToDouble();
                                // calculate the relative center point (I,J)
                                IJ = CenterXY - CurrentXY;
                                // calculate the radius (pythagorean theorem)
                                R = Math.Sqrt(Math.Pow(IJ.X, 2) + Math.Pow(IJ.Y, 2));
                                // calculate the angle between start point and the X axis
                                Alpha = DegMath.Asin((CurrentXY.Y - CenterXY.Y) / R);
                                // extend the -90 to 90 degree angle to -270 to 90
                                if (CurrentXY.X < CenterXY.X)
                                {
                                    Alpha = -180 - Alpha;
                                }
                                // calculate the arc end absolute cordinates
                                XY.X = CenterXY.X + R * DegMath.Cos(Angle + Alpha);
                                XY.Y = CenterXY.Y + R * DegMath.Sin(Angle + Alpha);
                                // generate the gcode
                                // the positive angles moves CCV, the negative angles move CV
                                OutFile.WriteLine((Angle > 0 ? "G3 X" : "G2 X") + XY.XString + " Y" + XY.YString + " I" + IJ.XString + " J" + IJ.YString);
                                // Save the cordinates
                                CurrentXY = XY;
                                break;

                            default:
                                // Unknown or unimplemented command arrived
                                Console.WriteLine("Warrning: Unknown Command: " + HpglCommand);
                                break;
                            }
                        }
                    }
                }
                OutFile.Flush();
                OutFile.Close();
                InFile.Close();
            }
            else
            {
                if (InFileName == null)
                {
                    Console.WriteLine("Command line error: Source file missing");
                }
                if (OutFileName == null)
                {
                    Console.WriteLine("Command line error: Destination file missing");
                }
            }
        }
Example #15
0
        /// <summary>
        /// Handle the drag/drop event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lbl_DragDrop(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent(DataFormats.FileDrop) || ((string[])e.Data.GetData(DataFormats.FileDrop)).Length != 1)
            {
                return;
            }
            string FileName = "";

            try
            {
                FileName = ((string[])e.Data.GetData(DataFormats.FileDrop))[0];
                if (sender == lblDropMode)
                {
                    ProcessFile <int, String>(Modes, FileName, "ID_MODE(", ")", "= ", "", lblCountModes, "modes");
                }
                else if (sender == lblDropUserTypeFile)
                {
                    ProcessFile <int, String>(UserTypeNames, FileName, "USER(", ")", "= ", "", lblCountUserType, "usertypes");
                }
                else if (sender == lblDropUserName)
                {
                    ProcessFile <int, String>(UserNames, FileName, "USER(", ")", "= ", "", lblCountUserNames, "usernames");
                }
                else if (sender == lblDropArea)
                {
                    ProcessFile <int, String>(Areas, FileName, "ID_AREA(", ")", "= ", "", lblCountAreas, "areas");
                }
                else if (sender == lblDropPermission)
                {
                    ProcessFile <int[], bool>(Permissions, FileName, "_AREA_MODE(", ")", "= ", "", lblCountPermissions, "permissions");
                }
                else if (sender == lblDropOldOperatorships)
                {
                    ProcessFile(OldPermissions, FileName, lblCountAreas, "operatorships");
                }
                else if (sender == lblDropUserTypeToModeLinkages)
                {
                    String     InLine;
                    List <int> MappedTypes = null;
                    UserTypeToModeLinkages.Clear();
                    using (StreamReader sRd = new StreamReader(FileName))
                        while ((InLine = sRd.ReadLine()) != null)
                        {
                            if (InLine.StartsWith("USRTYP,"))
                            {
                                int StartStr = InLine.IndexOf("ID='") + 4;
                                UserTypeToModeLinkages.Add(InLine.Substring(StartStr, InLine.IndexOf("'", StartStr + 1) - StartStr), MappedTypes = new List <int>());
                            }
                            else if (InLine.StartsWith("UMODE,"))
                            {
                                MappedTypes.Add(int.Parse(InLine.Substring(InLine.LastIndexOf('=') + 1)));
                            }
                        }

                    foreach (List <int> MappedType in UserTypeToModeLinkages.Values)
                    {
                        MappedType.TrimExcess();
                    }
                    lblCountUserTypeToModeLinkages.Text = UserTypeToModeLinkages.Count.ToString() + " user->mode";
                }

                //Now, if we have enough data, produce our list
                if (Permissions.Count > 0 && Areas.Count > 0 && UserNames.Count > 0 && UserTypeNames.Count > 0 && Modes.Count > 0 && UserTypeToModeLinkages.Count > 0)
                {
                    NewPermissions.Clear();

                    //Now, perform our merging
                    List <String> MissingUsers = new List <String>();
                    List <int>    MissingAreas = new List <int>();
                    Dictionary <String, String> UserNameToUserType = new Dictionary <string, string>();

                    List <int> UserTypeToModeLinkage;
                    foreach (KeyValuePair <int, string> User in UserNames)
                    {
                        if (!UserTypeToModeLinkages.TryGetValue(UserTypeNames[User.Key], out UserTypeToModeLinkage))
                        {
                            MissingUsers.Add(UserTypeNames[User.Key]);
                        }
                        else
                        {
                            UserNameToUserType.Add(User.Value, UserTypeNames[User.Key]);
                            List <String> OutAreas = new List <string>();
                            String        FoundArea;
                            foreach (KeyValuePair <int[], bool> kvp in Permissions)
                            {
                                if (kvp.Value && UserTypeToModeLinkage.Contains(kvp.Key[1]))
                                {
                                    if (!Areas.TryGetValue(kvp.Key[0], out FoundArea))
                                    {
                                        MissingAreas.Add(kvp.Key[0]);
                                    }
                                    else if (!OutAreas.Contains(FoundArea))
                                    {
                                        OutAreas.Add(FoundArea);
                                    }
                                }
                            }
                            OutAreas.Sort(StringComparer.CurrentCultureIgnoreCase);
                            if (OutAreas.Count > 0)
                            {
                                NewPermissions.Add(User.Value, OutAreas.ToArray());
                            }
                        }
                    }


                    //Now, clear our ListView
                    lvOutputs.Items.Clear();
                    if (OldPermissions.Count > 0)
                    {
                        String[] FoundPermissions;
                        foreach (KeyValuePair <String, String[]> kvp in NewPermissions)
                        {
                            if (!OldPermissions.TryGetValue(kvp.Key, out FoundPermissions))
                            {
                                ListViewItem lvI = lvOutputs.Items.Add(kvp.Key);
                                lvI.SubItems.Add(UserNameToUserType[kvp.Key]);
                                lvI.SubItems.Add("Yes");
                                lvI.SubItems.Add(String.Join(",", kvp.Value));
                                lvI.SubItems.Add("");
                            }
                            else
                            {
                                List <String> Additions = new List <string>();
                                List <String> Removals  = new List <string>();
                                foreach (String str in FoundPermissions)
                                {
                                    if (Array.IndexOf(kvp.Value, str) == -1)
                                    {
                                        Removals.Add(str);
                                    }
                                }
                                foreach (String str in kvp.Value)
                                {
                                    if (Array.IndexOf(FoundPermissions, str) == -1)
                                    {
                                        Additions.Add(str);
                                    }
                                }
                                if (Additions.Count + Removals.Count > 0)
                                {
                                    ListViewItem lvI = lvOutputs.Items.Add(kvp.Key);
                                    lvI.SubItems.Add(UserNameToUserType[kvp.Key]);
                                    lvI.SubItems.Add("");
                                    lvI.SubItems.Add(String.Join(",", Additions.ToArray()));
                                    lvI.SubItems.Add(String.Join(",", Removals.ToArray()));
                                }
                            }
                        }

                        //Now, pull in our old ones that are missing
                        foreach (KeyValuePair <String, String[]> kvp in OldPermissions)
                        {
                            if (!NewPermissions.ContainsKey(kvp.Key))
                            {
                                ListViewItem lvI = lvOutputs.Items.Add(kvp.Key);
                                lvI.SubItems.Add("Old");
                                lvI.SubItems.Add(String.Join(",", kvp.Value.ToArray()));
                                lvI.SubItems.Add("");
                            }
                        }
                    }
                    else
                    {
                        foreach (KeyValuePair <String, String[]> kvp in NewPermissions)
                        {
                            ListViewItem lvI = lvOutputs.Items.Add(kvp.Key);
                            lvI.SubItems.Add(UserNameToUserType[kvp.Key]);

                            lvI.SubItems.Add("Yes");
                            lvI.SubItems.Add(String.Join(",", kvp.Value));
                            lvI.SubItems.Add("");
                        }
                    }

                    lvOutputs.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
                    lvOutputs.Sort();
                    if (MissingAreas.Count > 0)
                    {
                        MessageBox.Show("Missing " + MissingAreas.Count.ToString() + " areas: " + String.Join(", ", MissingAreas.ToArray()));
                    }


                    if (MissingUsers.Count > 0)
                    {
                        MessageBox.Show("Missing " + MissingUsers.Count.ToString() + " users: " + String.Join(", ", MissingUsers.ToArray()));
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error loading file " + FileName + ":" + ex.ToString(), Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }