Solved

start c# from command line

Posted on 2013-02-05
7
263 Views
Last Modified: 2013-02-11
I'm trying to run this program from command lines and  commented out static main in program.cs (see bottom of code).
What's wrong with this code?
The messages I get  are:

an object reference is required for  the non-static field, method, or property 'ILXSymbolMasterExtract.Form1.arrAttrBond'

An object reference is required for the non-static field, method, or property 'ILXSymbolMasterExtract.Form1.ParseXml(string, string, string, string, string[])'
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using System.Xml.Linq;
using System.Xml.XPath ;
namespace ILXSymbolMasterExtract
{
    public partial class Form1 : Form
    {


        string[] arrAttrBond = {
                                "sedol","curr","localId","issuShortDesc","exch","longIssuerName", "symbol",
                                "action","sectyType","cusip","issuLongDesc","localCode","dfltInd",
                                "mat","isin","sess","issuerName"
                           };
        string[] arrAttrInd = {
                                "sedol","curr","localId","issuShortDesc","exch","longIssuerName", "symbol",
                                "action","sectyType","cusip","issuLongDesc","localCode","dfltInd",
                                "isin","sess","issuerName","sicCode"
                           };

        string[] arrAttrTr = {
                                "sedol","issuerName","mat","symbol","sess","issuShortDesc","cusip",
                                "issuLongDesc","longIssuerName","sectyType","action","isin","exch","curr", 
                           };

        public Form1()
        {
            InitializeComponent();
            this.Load += new System.EventHandler(this.Form1_Load);

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Text = "hello";
        }
        static void Main()
        {
            try
            {
                string[] args = Environment.GetCommandLineArgs();
                string xsdfile = args[2];//ignored
                string inputfile = args[3];
                string Outputfile = args[4];
                string InstrumentType = args[5];
                switch (InstrumentType)
                {
                    case "bond":
                        ParseXml(inputfile, Outputfile, InstrumentType, "bnd", arrAttrBond);
                        break;
                    case "index":
                        ParseXml(inputfile, Outputfile, InstrumentType, "ind", arrAttrInd);
                        break;
                    case "treasury":
                        ParseXml(inputfile, Outputfile, InstrumentType, "tr", arrAttrTr);
                        break;
                }
                //XmlDeclaration xmldecl;
                //xmldecl = doc.CreateXmlDeclaration("1.0", null, null);

                ////Add the new node to the document.
                //XmlElement root = doc.DocumentElement;
                //doc.InsertBefore(xmldecl, root);
                //Console.WriteLine("Display the modified XML...");
                //doc.Save(Console.Out);
            }

            catch (Exception ex)
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(ex.Message);
            }
            Environment.Exit(0);
        }
        private void ParseXml(string fn, string fnout, string InstTypeMain, string InstTypeMinor, string[] AttributeInst)
        {

            using (Stream stream = File.OpenRead(fn))
            {

                XmlTextReader r = new XmlTextReader(stream);
                r.WhitespaceHandling = WhitespaceHandling.None;
                r.MoveToContent();

                using (XmlTextWriter w = new XmlTextWriter(fnout, null))
                //using (XmlTextWriter w = new XmlTextWriter(fnout, Encoding.Unicode))
                {
                    w.Formatting = Formatting.Indented;
                    w.Indentation = 3;
                    //w.IndentChar = '\t';
                    w.IndentChar = ' ';
                    w.WriteStartDocument();
                    w.WriteStartElement("data");

                    int intParsingState = 0;

                    // changed the loop structure to start at root (not really necessary) but also to be able to use "continue" to skip r.Read() after r.Skip()...
                    do
                    {
                        switch (r.NodeType)
                        {
                            case XmlNodeType.Element:

                                if (r.LocalName == InstTypeMain)
                                {
                                    intParsingState = 1;
                                }
                                else if (r.LocalName == InstTypeMinor)
                                {
                                    if (intParsingState > 0)
                                    {
                                        w.WriteStartElement("n");
                                        foreach (string a in AttributeInst)
                                        {
                                            w.WriteElementString(a, r.GetAttribute(a).ToString());
                                        }
                                        w.WriteEndElement();
                                    }

                                }
                                else
                                {
                                    // skip children of other elements on the same depth as the <bond> element
                                    if (r.Depth >= 1)
                                    {
                                        r.Skip();
                                        continue; // don't call r.Read() in this case...
                                    }

                                }

                                break;
                            case XmlNodeType.EndElement:

                                if (r.LocalName == InstTypeMain)
                                {
                                    intParsingState = 2; // break do-while
                                }

                                break;
                            default:
                                break;
                        }
                        if (intParsingState < 2 && !r.Read())
                            break;
                    } while (intParsingState < 2);
                    w.WriteEndElement();
                    w.WriteEndDocument();
                    w.Flush();
                    w.Close();
                }
                r.Close();
            }
        }
        
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace ILXSymbolMasterExtract
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        //[STAThread]
        //static void Main()
        //{
        //    string[] args = Environment.GetCommandLineArgs();
        //    string xsdfile = args[2];//ignored
        //    string inputfile = args[3];
        //    string Outputfile = args[4];
        //    string InstrumentType = args[5];



        //    // Display the number of command line arguments:
        //    // System.Console.WriteLine(args.Length);
        //    //string xsdfile;

        //    Application.EnableVisualStyles();
        //    Application.SetCompatibleTextRenderingDefault(false);
        //    Application.Run(new Form1());
        //}
    }
}

Open in new window

0
Comment
Question by:AlHal2
  • 3
  • 3
7 Comments
 
LVL 42

Expert Comment

by:sedgwick
ID: 38856016
You try to call non static parseXml from ststic main function.
What u wanna do is take the code from main and put it in non static Init function.
In your main function call:
var form = new Form();
form.Init();
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 38856023
If parsexml is a service function which means it doesn't need access class members you can declare it as static to fix the compile error
0
 
LVL 19

Expert Comment

by:Daniel Van Der Werken
ID: 38856028
As sedgwick says, you can't use non-static fields in a static method. For example:

public class myClass
{
   private string myString = "hello";
   public static void doSomething()
   {
      string hello = myString;
   }
}

Open in new window


This simply won't work. In fact, I'm surprised this compiles.

Either make the fields you're using static also or do what Sedgwick says.
0
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 

Author Comment

by:AlHal2
ID: 38856066
I'm getting this message.

'System.Windows.Forms.Form' does not contain a definition for 'Init' and no extension method 'Init' accepting a first argument of type 'System.Windows.Forms.Form' could be found (are you missing a using directive or an assembly reference?)
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 38856080
As i explained, add your own function called Init, and take all the cofe from Main and place it there.
0
 

Accepted Solution

by:
AlHal2 earned 0 total points
ID: 38858789
Is this what you mean?  I'm still getting the same error.

static void Main()
        {
            var form = new Form();
            form.Init();
        }
        private void Init()
        {
        try
            {
                string[] args = Environment.GetCommandLineArgs();
                string xsdfile = args[2];//ignored
                string inputfile = args[3];
                string Outputfile = args[4];
                string InstrumentType = args[5];
                switch (InstrumentType)
                {
                    case "bond":

                        ParseXml(inputfile, Outputfile, InstrumentType, "bnd", arrAttrBond);
                        break;
                    case "index":
                        ParseXml(inputfile, Outputfile, InstrumentType, "ind", arrAttrInd);
                        break;
                    case "treasury":
                        ParseXml(inputfile, Outputfile, InstrumentType, "tr", arrAttrTr);
                        break;
                }
            }

            catch (Exception ex)
            {
                // Let the user know what went wrong.
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(ex.Message);
            }
            Environment.Exit(0);
        }
0
 

Author Closing Comment

by:AlHal2
ID: 38875309
This works.

public static void Main()
        {
           
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
                       
        }

private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                string[] args = Environment.GetCommandLineArgs();
                //MessageBox.Show(args[0] + "|" + args[1] + "|" + args[2] + "|" + args[3] + "|" + args[4] + "|" + args[5]);
                //Environment.Exit(0);
                string xsdfile = args[1];//ignored.  Increment values in args by 1 when running source code
                string inputfile = args[2];
                string Outputfile = args[3];
                string InstrumentType = args[4];
                //MessageBox.Show("Instrument Type = " +InstrumentType);
                switch (InstrumentType)
                {
                    case "bond":
                        ParseXml(inputfile, Outputfile, InstrumentType, "bnd", arrAttrBond);
                        break;
                    case "index":
                        ParseXml(inputfile, Outputfile, InstrumentType, "ind", arrAttrInd);
                        break;
                    case "treasury":
                        ParseXml(inputfile, Outputfile, InstrumentType, "tr", arrAttrTr);
                        break;
                }
}
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

Introduction This article series is supposed to shed some light on the use of IDisposable and objects that inherit from it. In essence, a more apt title for this article would be: using (IDisposable) {}. I’m just not sure how many people would ge…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
This video gives you a great overview about bandwidth monitoring with SNMP and WMI with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're looking for how to monitor bandwidth using netflow or packet s…
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now