content creator

Custom Setup Sheet Data from NC FILE C# :

Recommended Posts

Here is some C# codes I use to scan information from a .nc file. In this  console application the information is loaded into a winform. You could also load data from an ncfile easily into a premade excel worksheet by creating a com object of the document C# is very strongly typed when it comes to excel so it is easy to setup.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Drawing;
using System.Windows.Forms;
using System.Globalization;

namespace txtreader
{
    class Program
    {
        
            static string ConvertStringArrayToStringJoin(string[] array)
            {
                // Use string Join to concatenate the string elements.
                string result = string.Join(".", array);
                return result;
            }

            public static string GetBetween(string strSource, string strStart, string strEnd)
            {
                if (strSource == null)
                {
                    throw new ArgumentNullException(nameof(strSource));
                }

                if (strStart == null)
                {
                    throw new ArgumentNullException(nameof(strStart));
                }

                if (strEnd == null)
                {
                    throw new ArgumentNullException(nameof(strEnd));
                }

                int Start, End;
                if (strSource.Contains(value: strStart) && strSource.Contains(value: strEnd))
                {
                    Start = strSource.IndexOf(value: strStart, startIndex: 0) + strStart.Length;
                    End = strSource.IndexOf(value: strEnd, startIndex: Start);
                    return strSource.Substring(startIndex: Start, length: End - Start);

                }
                else
                {
                    return "";
                }
            }

        //in string 1 > initial string to be searched
        //in string 2 > the value to search for
        //returns new string found after first instance of initial string
            public static string GetAfter(string strSource, string toBeSearched)
            {
                int ix = strSource.IndexOf(toBeSearched, StringComparison.InvariantCultureIgnoreCase);

                if (ix != -1)
                {
                    string code = strSource.Substring(ix + toBeSearched.Length);
                    return code;
                }
                return null;

            }
            static void Main(string[] args)
            {
            //intialize some variables
                double lowest_mdpth = 0;
                double lowest_ddpth = 0;
                double z_val_cur = 5;
                double x_val_cur = 0;
                double y_val_cur = 0;
                List<double> zval_rec = new List<double>();
                List<double> xval_rec = new List<double>();
                List<double> yval_rec = new List<double>();
                List<string> list1 = new List<string>();
                List<string> list2 = new List<string>();
                List<string> list3 = new List<string>();
                List<string> list4 = new List<string>();
                List<string> list5 = new List<string>();
                List<string> list6 = new List<string>();
                List<string> list7 = new List<string>();
                List<string> list8 = new List<string>();
                List<string> list9 = new List<string>();
                List<string> list10 = new List<string>();
                List<string> list11 = new List<string>();
                List<string> list12 = new List<string>();
                List<string> list13 = new List<string>();
                List<string> list14 = new List<string>();
                List<string> list15 = new List<string>();
                List<string> list16 = new List<string>();
                int counter = 0;
                string line;
                long count = 0;
                long count2 = 0;
                long count3 = 0;
                long count4 = 0;
                long count5 = 0;
                long count6 = 0;
                long count7 = 0;
                long count8 = 0;
                long count10 = 0;
                long count11 = 0;
                long count12 = 0;
                long count13 = 0;
                long count14 = 0;
                long count15 = 0;
                double stk_thk = 0;
                double minus_stk_thk = 0;
                double thru_cut_depth;
            //create a new winform
                var f2 = new Form() { Text = "System " };
                //create a new label
                Label lbl = new Label();
            //create a point to assign label location
                lbl.Location = new Point(20, 0);
            //create a static text display (uneditable text)
                lbl.Text = "Program Name:";
            //add label to winform
                f2.Controls.Add(lbl);
                Label lbl2 = new Label();
                lbl2.Location = new Point(20, 100);
                lbl2.Text = "Stock Thickness:";
                f2.Controls.Add(lbl2);
                Label lbl3 = new Label();
                lbl3.Location = new Point(20, 200);
                lbl3.Text = "Tool Numbers:";
                f2.Controls.Add(lbl3);
                Label lbl4 = new Label();
                lbl4.Location = new Point(20, 300);
                lbl4.Text = "Lowest Z Mill Tool Depth:";
                f2.Controls.Add(lbl4);
                Label lbl5 = new Label();
                lbl5.Location = new Point(20, 400);
                lbl5.Text = "Lowest Z Drill Tool Depth:";
                Label lbl6 = new Label();
                lbl6.Location = new Point(20, 400);
                lbl6.Text = "Error Message:";
                f2.Controls.Add(lbl6);
                TextBox txt = new TextBox();
                txt.Name = "textBox1";
                f2.Controls.Add(txt);
                txt.Location = new Point(20, 60);
                txt.Size = new Size(300, 100);
                txt.BorderStyle = BorderStyle.FixedSingle;
                TextBox txt2 = new TextBox();
                txt2.Name = "textBox2";
                f2.Controls.Add(txt2);
                txt2.Location = new Point(20, 150);
                txt2.Size = new Size(300, 100);
                txt2.BorderStyle = BorderStyle.FixedSingle;
                TextBox txt3 = new TextBox();
                txt3.Name = "textBox3";
                f2.Controls.Add(txt3);
                txt3.Location = new Point(20, 250);
                txt3.Size = new Size(300, 1000);
                txt3.BorderStyle = BorderStyle.FixedSingle;
                TextBox txt4 = new TextBox();
                txt4.Name = "textBox4";
                f2.Controls.Add(txt4);
                txt4.Location = new Point(20, 350);
                txt4.Size = new Size(300, 1000);
                txt4.BorderStyle = BorderStyle.FixedSingle;
                TextBox txt5 = new TextBox();
                txt5.Name = "textBox5";
                f2.Controls.Add(txt5);
                txt5.Location = new Point(20, 450);
                txt5.Size = new Size(300, 1000);
                txt5.BorderStyle = BorderStyle.FixedSingle;
                TextBox txt6 = new TextBox();
                txt6.Name = "textBox6";
                f2.Controls.Add(txt6);
                txt6.Location = new Point(20, 550);
                txt6.Size = new Size(300, 1000);
                txt6.BorderStyle = BorderStyle.FixedSingle;

                OpenFileDialog openFileDialog1 = new OpenFileDialog
                {
                    //set the directory to load files from
                    InitialDirectory = @"C:\Users\Public\Documents",
                    Title = "Browse Text Files",

                    CheckFileExists = true,
                    CheckPathExists = true,
                    //set default file type filter
                    DefaultExt = "nc",
                    Filter = "nc files (*.nc)|*.nc",
                    FilterIndex = 2,
                    RestoreDirectory = true,

                    ReadOnlyChecked = true,
                    ShowReadOnly = true
                };

                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    var onlyFileName = System.IO.Path.GetFileName(openFileDialog1.FileName);

                    System.IO.StreamReader file =
                    //read file
                    new System.IO.StreamReader(openFileDialog1.FileName);
                //loop through each line of the text file once
                    while ((line = file.ReadLine()) != null)
                    {




                        double info = 0;
                        double info2 = 0;
                        double info3 = 0;
                        double info4 = 0;
                        double info5 = 0;
                        double info6 = 0;
                        double info7 = 0;
                        double info8 = 0;
                        double info10 = 0;
                        double info11 = 0;
                        double info12 = 0;
                        double info13 = 0;
                        double info14 = 0;
                        double info15 = 0;

                    //get some values from the database
                        string input = "stock_thk:";//stock thickness declaration
                        string code = GetStringAfter(ref count, input, line);
                        counter++;
                        if (count == 1)
                        {
                            info = SetStringToList(list1, out count, code, info);
                            count = 0;
                            stk_thk = info;
                            minus_stk_thk = stk_thk * -1;
                            if (code != null) { code = code.Trim(); list1.Add(code); txt2.Text = code; }


                        }


                        string input2 = "z";
                        string code2 = GetStringAfter(ref count2, input2, line);
                        if (count2 == 1)
                        {
                            info2 = SetStringToList(list2, out count2, code2, info2);
                            z_val_cur = info2;
                            if (info2 < lowest_mdpth)
                            {
                                lowest_mdpth = info2;
                            }
                         
                        }

                        string input3 = "i-";
                        string code3 = GetStringAfter(ref count3, input3, line);
                        if (count3 == 1)
                        {
                            info3 = SetStringToList(list3, out count3, code3, info3);
                            count3 = 1;
                            list3.Add(code3);
                        }
                        string input4 = "j";
                        string code4 = GetStringAfter(ref count4, input4, line);
                        if (count4 == 1)
                        {
                            info4 = SetStringToList(list4, out count4, code4, info4);
                            count4 = 1;
                            list4.Add(code4);
                        }
                        string input5 = "g83";
                        string code5 = GetStringAfter(ref count5, input5, line);
                        if (count5 == 1)
                        {
                            info5 = SetStringToList(list5, out count5, code5, info5);
                            count5 = 0;
                            list5.Add(code5);
                        }

                        string input6 = "g99";
                        string code6 = GetStringAfter(ref count6, input6, line);
                        if (count6 == 1)
                        {
                            info6 = SetStringToList(list6, out count6, code6, info6);
                            count6 = 0;
                            list6.Add(code6);
                        }
                        string input7 = "x";
                        string code7 = GetStringAfter(ref count7, input7, line);
                        if (count7 == 1)
                        {
                            info7 = SetStringToList(list7, out count7, code7, info7);
                            count7 = 0;
                            list7.Add(code7);
                            x_val_cur = info7;
                        }
                        string input8 = "y";
                        string code8 = GetStringAfter(ref count8, input8, line);
                        if (count8 == 1)
                        {
                            info8 = SetStringToList(list8, out count8, code8, info8);
                            count8 = 0;
                            list8.Add(code8);
                            y_val_cur = info8;
                        }
                        string input11 = "g81";
                        string code11 = GetStringAfter(ref count11, input11, line);
                        if (count11 == 1)
                        {
                            info11 = SetStringToList(list11, out count11, code11, info11);

                          

                        }
                                                     //prefix of program name
                        string input9 = ";program name     :";
                        string code9 = GetAfter(line, input9);

                        if (code9 != null) { code9 = code9.Trim(); list9.Add(code9); txt.Text = code9; }



                        string input10 = "t";
                        string code10 = GetStringAfter(ref count10, input10, line);
                        if (count10 == 1)
                        {
                            info10 = SetStringToList(list10, out count10, code10, info10);
                            if (count10 == 1)
                            {
                                list10.Add(code10);
                            }

                        }

                        string input12 = "m05";
                        string code12 = GetStringAfter(ref count12, input12, line);
                        if (count12 == 1)
                        {
                            info12 = SetStringToList(list12, out count12, code12, info12);
                            if (count12 == 1)
                            {

                                list10.Add(code12);
                            }

                        }
                        string input13 = "m03";
                        string code13 = GetStringAfter(ref count13, input13, line);
                        if (count13 == 1)
                        {
                            info13 = SetStringToList(list13, out count13, code13, info13);
                            if (count13 == 1)
                            {
                                list13.Add(code13);
                            }

                        }
                        string input14 = "g01";
                        string code14 = GetStringAfter(ref count14, input14, line);
                        if (count14 == 1)
                        {
                            info14 = SetStringToList(list14, out count14, code14, info14);
                            if (count14 == 1)
                            {
                                list14.Add(code14);
                            }

                        }
                        string input15 = "g00";
                        string code15 = GetStringAfter(ref count15, input15, line);
                        if (count15 == 1)
                        {
                            info15 = SetStringToList(list15, out count15, code15, info15);
                            if (count15 == 1)
                            {
                                list14.Add(code14);
                            }

                        }
                    count2 = 0; count3 = 0; count4 = 0; count10 = 0; count11 = 0; count12 = 0; count13 = 0; count14 = 0; count15 = 0;
                    if (x_val_cur != 0 || y_val_cur != 0 || z_val_cur != 0)
                        {
                            xval_rec.Add(x_val_cur);
                            yval_rec.Add(y_val_cur);
                            zval_rec.Add(z_val_cur);
                            string str = "X Value = " + x_val_cur + " Y Value = " + y_val_cur + " Z Value = " + z_val_cur;
                         
                        }
                    }
                    file.Close();
                    //check for duplicate tools in tool list
                    List<string> distinct = list10.Distinct().ToList();
                    string toollist = "";
                    foreach (var tool in distinct)
                    {
                        toollist = toollist + "T" + tool + " ,";

                    }

            
                    if (txt3 != null) { txt3.Text = toollist; }
                    txt4.Text = "z-" + lowest_mdpth.ToString("0.######");
                    txt5.Text = "z-" + lowest_ddpth.ToString("0.######");
                    f2.StartPosition = FormStartPosition.Manual;
                
                    Application.Run(f2);

                }
            }
        //convert string to double value
            private static double SetStringToList(List<string> firstlist, out long count, string code, double info)
            {
                try
                {
                    info = Convert.ToDouble(code, CultureInfo.InvariantCulture);
                }
                catch (FormatException)
                {
                    count = 0;
                    return info;
                }
                count = 1;
                return info;
            }

            public static string GetStringAfter(ref long count, string input, string text)
            {
                string code = GetAfter(text, input);

                if (code != null)
                {
                    count = count + 1;
                    code = code.Trim();
                    code = code.IndexOf(" ") > -1
                                      ? code.Substring(0, code.IndexOf(" "))
                                      : code;
                    return code;
                }

                return null;
            }


     
    }
}

 

  • Like 2

Share this post


Link to post
Share on other sites

I think this is a good idea, but the code leaves a bit to be desired.  In an effort to help you out I created a more organized example.

It's not 100% yet, but you can read in an .NC file and obtain a tool list and the min and max X,Y,Z values.

I hope it helps.

 

 

  • Like 2

Share this post


Link to post
Share on other sites
9 minutes ago, Zaffin said:

I think this is a good idea, but the code leaves a bit to be desired.  In an effort to help you out I created a more organized example.

It's not 100% yet, but you can read in an .NC file and obtain a tool list and the min and max X,Y,Z values.

I hope it helps.

 

 

Yeah the code is pretty rough. Nice work!!!

Share this post


Link to post
Share on other sites

In a more recent version of this I added some excel interaction I need to post. Also the bar code functionality is great to include I will post the dll that contains the symbology and stuff and the implementation code...whem I first looked for that a lot of people were charging an arm and a leg for that.

 

Share this post


Link to post
Share on other sites
 Application.Run(f2);
                Microsoft.Office.Interop.Excel.Application excelapp = new Microsoft.Office.Interop.Excel.Application();
               
                excelapp.Visible = true;
                Microsoft.Office.Interop.Excel._Workbook workbook = (Microsoft.Office.Interop.Excel._Workbook)(excelapp.Workbooks.Open(@"C:\Users\Public\Documents\ExcelWorkBook.Xlsx"));
                Microsoft.Office.Interop.Excel._Worksheet oSheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet;
                Microsoft.Office.Interop.Excel.Range c1 = oSheet.Cells[1, 5];
                Microsoft.Office.Interop.Excel.Range c2 = oSheet.Cells[2, 6];
                Microsoft.Office.Interop.Excel.Range newRng = (Microsoft.Office.Interop.Excel.Range)oSheet.get_Range(c1, c2);
                newRng.EntireColumn.AutoFit();
                oSheet.Paste(newRng, false);
                oSheet.Cells[1, 1] = "Program Name:";
                oSheet.Cells[2, 1] = list9[0];
                oSheet.Cells[1, 2] = "Stock Thickness:";
                oSheet.Cells[2, 2] = stk_thk.ToString("0.######");
                oSheet.Cells[1, 3] = "Tool Numbers:";
                oSheet.Cells[2, 3] = toollist;
                oSheet.Cells[1, 4] = "Material:";
                oSheet.Cells[2, 4] = matval;

When I create macros for setup sheets I usually prepare an excel worksheet with the desired "look", then I simply add in the data from c# using the above blocks of code.

Share this post


Link to post
Share on other sites

Some useful functions for insterting images

 private static void PlacePicture(Image picture, Microsoft.Office.Interop.Excel.Range destination)
        {
            Microsoft.Office.Interop.Excel.Worksheet ws = destination.Worksheet;
            Clipboard.SetImage(picture);
            ws.Paste(destination, false);
            Microsoft.Office.Interop.Excel.Pictures p = ws.Pictures(System.Reflection.Missing.Value) as Microsoft.Office.Interop.Excel.Pictures;
            Microsoft.Office.Interop.Excel.Picture pic = p.Item(p.Count) as Microsoft.Office.Interop.Excel.Picture;
            ScalePicture(pic, (double)destination.Width, (double)destination.Height);
        }

        private static void ScalePicture(Microsoft.Office.Interop.Excel.Picture pic, double width, double height)
        {
            double fX = width / pic.Width;
            double fY = height / pic.Height;
            double oldH = pic.Height;
            if (fX < fY)
            {
                pic.Width *= fX;
                if (pic.Height == oldH) // no change if aspect ratio is locked
                    pic.Height *= fX;
                pic.Top += (height - pic.Height) / 2;
            }
            else
            {
                pic.Width *= fY;
                if (pic.Height == oldH) // no change if aspect ratio is locked
                    pic.Height *= fY;
                pic.Left += (width - pic.Width) / 2;
            }
        }

we need this to resize our image to the range of cells we indicate :

definition:

                Barcode b = new Barcode();
                Image CodeImage = b.Encode(TYPE.CODE128, list9[0], 1500, 40);
                PictureBox picture = new PictureBox
                {
                    Image = CodeImage,
                    Name = "pictureBox",
                    Size = new Size(40, 1500),
                    Location = new Point(10, 15),
                    //SizeMode = PictureBoxSizeMode.AutoSize,
                    Height = 40,
                    Width =1500,
                   // SizeMode = PictureBoxSizeMode.StretchImage,
            };

use

 Microsoft.Office.Interop.Excel._Workbook workbook = (Microsoft.Office.Interop.Excel._Workbook)(excelapp.Workbooks.Open(@"C:\Users\ExcelWorkBook.Xlsx"));
                Microsoft.Office.Interop.Excel._Worksheet oSheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet;
                Microsoft.Office.Interop.Excel.Range c1 = oSheet.Cells[1, 5];
                Microsoft.Office.Interop.Excel.Range c2 = oSheet.Cells[2, 6];
                Microsoft.Office.Interop.Excel.Range newRng = (Microsoft.Office.Interop.Excel.Range)oSheet.get_Range(c1, c2);
                PlacePicture(CodeImage, newRng);//add picture

 

Share this post


Link to post
Share on other sites
5 hours ago, Zaffin said:

I think this is a good idea, but the code leaves a bit to be desired.  In an effort to help you out I created a more organized example.

It's not 100% yet, but you can read in an .NC file and obtain a tool list and the min and max X,Y,Z values.

I hope it helps.

 

 

 

I like the interface and the functionality, may I use this actually? It is very nice. :D

Share this post


Link to post
Share on other sites

When you finish you should repost this for other people if you like. These kind of tools can prevent accidents, since things could always go wrong with posts and software.

Share this post


Link to post
Share on other sites
16 minutes ago, peter ~ said:

 

I like the interface and the functionality, may I use this actually? It is very nice. :D

Yes, you can do whatever you want; that's why it's up there.

  • Thanks 1

Share this post


Link to post
Share on other sites
1 minute ago, Zaffin said:

Yes, you can do whatever you want; that's why it's up there.

Thank you, It seems that you are very advanced in c#, I struggle with c# syntax , maybe If I work with your code I will understand the nuances of the language that escape me for the moment.. I write all my code in c++ and f# now if it goes into mastercam because I had to many issues mixing managed and unmanaged code, but obviously Mastercam write their code in c# no problem so I just am not doing it properly.

Share this post


Link to post
Share on other sites
43 minutes ago, peter ~ said:

Thank you, It seems that you are very advanced in c#, I struggle with c# syntax , maybe If I work with your code I will understand the nuances of the language that escape me for the moment.. I write all my code in c++ and f# now if it goes into mastercam because I had to many issues mixing managed and unmanaged code, but obviously Mastercam write their code in c# no problem so I just am not doing it properly.

I wouldn't say I'm advanced; I have so much to learn it's crippling at times. 

I'm extremely fortunate to work with great people that are willing to share the knowledge they have amassed over the years.

I have done several C++/C# interop hooks and I've never had an issue.  I wouldn't expect F# to make any difference; doesn't it compile to the same intermediate language as C#?

Share this post


Link to post
Share on other sites
9 minutes ago, Zaffin said:

I wouldn't say I'm advanced; I have so much to learn it's crippling at times. 

I'm extremely fortunate to work with great people that are willing to share the knowledge they have amassed over the years.

I have done several C++/C# interop hooks and I've never had an issue.  I wouldn't expect F# to make any difference; doesn't it compile to the same intermediate language as C#?

Sure, f# compiles to IL code it is after all .net. f# has immutable data types,its more type safe,and everything is basically a function, even objects undergo some changes in f#,

I had an issue where a single c++ function I called was mangling the graphics, when I switched it to f# the problem just disappeared, and If I decompile that portion of the code from f# to c# It doesn't make sense:

[email protected](apitools, 0.0, 0.0, 0, 0);
		[email protected](apitools, 0.0, 0.0, 0, 0);
		int x16 = [email protected](apitools, 0.0, 0.0, 0, 0);
		double x15 = apitools.GetMinzOnSldWrapper(x16);
		double x14 = apitools.GetMaxzOnSldWrapper(x16);
		[email protected](apitools, 0.0 - x15 - 0.002, 0.0 - x15 + 0.002, 50, x16);
		[email protected](apitools, 0.0 - x14 - 0.002, 0.0 - x14 + 0.002, 100, x16);

I think there are some fundamental differences between the two, and the same code in c# is probably twice or more the length in fsharp. In conclusion I think that If both languages received the same instructions and carried out the same tasks and one had a bunch of weird glitches there must be a difference.

Share this post


Link to post
Share on other sites

I looked over the thread where you detail the issue and I do see a few odd things in the managed code.

Is the entire Visual Studio solution available some where?  I'd like to see if I can duplicate the behavior.  

Share this post


Link to post
Share on other sites
19 hours ago, Zaffin said:

I went to take a look at this tonight but both links 404'd.  I checked your GitHub user name and it shows that you have no repos.

It was set to private, you may access now!

Share this post


Link to post
Share on other sites
2 hours ago, peter ~ said:

It was set to private, you may access now!

Yes, the links work now. Sorry for the delay, I've been working on my own projects as of late.

Honestly I'm not sure where to begin with the native project, it's in quite a state.  Is there a reason you defined and implemented functions in the header files?  You're also allocating memory on the heap and never freeing it; that's less than ideal.

I'm not much of a developer or a C++ guy, but I'll give refactoring this a shot; it's just going to be a bit.   

  • Like 1

Share this post


Link to post
Share on other sites
59 minutes ago, Zaffin said:

Yes, the links work now. Sorry for the delay, I've been working on my own projects as of late.

Honestly I'm not sure where to begin with the native project, it's in quite a state.  Is there a reason you defined and implemented functions in the header files?  You're also allocating memory on the heap and never freeing it; that's less than ideal.

I'm not much of a developer or a C++ guy, but I'll give refactoring this a shot; it's just going to be a bit.   

I do store functions in the header files, I find it complicated to have many .cpp files in  project. I don't have memory allocation issues since I m not running for long time, and the bulk of the memory gets freed up as the functions go out of scope. Right now, I m actually writing my nethooks in c++/cli since it allows simultaneous access to both languages, even though I am a bit unfamiliar in the syntax, it is speeding up my development projects.

Share this post


Link to post
Share on other sites
1 minute ago, Zaffin said:

I want to help you, but it seems like your cup is full, good luck.

 

I wasn't trying to give that impression 😕 I want to learn..I was just giving my point of view, anyway thanks for your comments.. good luck to you. 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.

Join us!

eMastercam - your online source for all things Mastercam.

Together, we are the strongest Mastercam community on the web with over 56,000 members, and our online store offers a wide selection of training materials for all applications and skill levels.

Follow us