TheSwamp

Code Red => .NET => Topic started by: wannabe on April 23, 2009, 09:42:33 AM

Title: StreamReader Problem
Post by: wannabe on April 23, 2009, 09:42:33 AM
This loop below is causing me a problem. It never seems that the StreamReader is returning a true for the EndOfStream property.

Code: [Select]
public Dictionary<int, string[]> createCoordsList(string separator) //This method separates the stream into coords/attributes for each block
        {
            StreamReader str;
            Dictionary<int, string[]> coordsList = new Dictionary<int, string[]>();
            int numOfLines = 0; //Assign the number of lines in the stream to this integer
            bool isError = false;
            using (StreamReader tempStream = new StreamReader(File.Open(path, FileMode.Open))) //Create a new stream using our parameter to quantify number of lines
            {
                string tempString = "";//Populate this string with the current line of the stream
                while (true)//This Loop is to determine only the number of lines in this stream
                {
                    try
                    {
                        bool endLines = tempStream.EndOfStream;
                        if (endLines)
                        {
                            isError = true;
                            break;
                        }
                        tempString = tempStream.ReadLine();//Assigned the string for the current line of the stream
                    }

                    catch
                    {
                        throw new System.Exception("There was a problem");
                       
                    }

                    if (tempString == null)
                    {
                        break;//The line was empty so we exit the loop
                    }

                    numOfLines++;//The line wasn't empty so we increment this integer
              }
            }

            if (isError)
            {
                return null;
            }

I'm sure it's a basic problem, but the solution is eluding me after a tenacious effort this morning.

Sorry for "noob" question.
Title: Re: StreamReader Problem
Post by: wannabe on April 23, 2009, 10:11:29 AM
Actually, ignore this for now, please. I'll update accordingly soon.

Cheers.
Title: Re: StreamReader Problem
Post by: wannabe on April 23, 2009, 11:06:31 AM

Ok, here's the full extent of my code. It's designed to read in the coordinates from a txt file, whose values are separated by spaces, and take each individual string from a line read in from a stream to populate a string array. An array for each line will be used to populate a dictionary whose values I just want to spit out to the command line at this point.

However, things aren't going too great. If anyone can spot the errors, please be as brutal as necessary.

Cheers.

Code: [Select]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.Windows;
using System.IO;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.ApplicationServices;

///Notes:
///1. Ensure only actual values are in the file. No suffixes eg. "X = 787878.989" = Invalid
///2. Verify the specified separator is correct for the file to be read from
///3. We could add parameter for filetype later on

namespace Multi_block_insertion
{
    public class MultiB
    {
        Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
        StreamReader coordsFile;
        string path;
        [CommandMethod("MultiB")]
        public void multiB()
        {
            Form1 form1 = new Form1();
            form1.Activate();
            form1.ShowDialog();
            StreamReader coordsFile;
        }

        public StreamReader getCoordsFile(string fileName) //Creates a stream for the selected coordinates file
        {
           
            using (FileStream coordsFileFs = File.Open(fileName, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader coordsFileSr = new StreamReader(coordsFileFs))
                {
                    coordsFile = coordsFileSr;
                    return coordsFileSr;
                }
            }
        }

        public string altGetCoordsFile()
        {
            OpenFileDialog coordsFile = new OpenFileDialog("Select Coords File", null, "txt", "Coords Selection", OpenFileDialog.OpenFileDialogFlags.AllowAnyExtension);
            if (coordsFile.ShowDialog() != System.Windows.Forms.DialogResult.OK)
            {
                throw new System.Exception("Error or User Cancelled");
            }

            path = coordsFile.Filename.ToString();
            return path;


        }

        public Dictionary<int, string[]> createCoordsList(string separator) //This method separates the stream into coords/attributes for each block
        {
            Dictionary<int, string[]> coordsList = new Dictionary<int, string[]>();
            int numOfLines = calculateLinesInStream();  //Assign the number of lines in the stream to this integer

            StreamReader str = new StreamReader(File.Open(path, FileMode.Open));
            for (int i = 1; i < numOfLines; i++)//Loop for splitting each line into individual components - coordinates, attributes etc
            {

                string thisLine = str.ReadLine();
                int charactersThisLine = thisLine.Length;
                Queue<char> thisLineQueue = new Queue<char>(thisLine.ToCharArray());//Convert to a queue for brevity of manipulation
                int numOfCharOnThisLine = thisLineQueue.Count;//Count of the characters so we know when to quit
                int numOfSeparatorsOnThisLine = 0;//Count of separators so we know number of values to add in the array for this line
                foreach (Char thisChar in thisLineQueue)//Loop to count the separators
                {
                    if (thisChar.ToString() == separator)
                    {
                        numOfSeparatorsOnThisLine++;
                    }
                }
                string[] thisLinesValues = new string[numOfSeparatorsOnThisLine + 1];//An array for each of the values on this line (coords, attributes)
                bool endOfLine = false;
                string thisValue = "";
                int count = 0;
                int thisLineValues = 0;
                while (!endOfLine)//Keep looping until we reach the end of the line
                {
               
                    for (int a = 0; a < thisLineQueue.Count(); a++) //Loop to assess and extract each char of the queue
                    {
                        if (count == charactersThisLine )//Check whether we have reached the end of the line
                        {
                            coordsList.Add(charactersThisLine, thisLinesValues); //End of line reached, so add all values for the this line to the Dictionary
                            endOfLine = true;//When we "break", the exit conditions for while(!endOfLine) will be met
                            break;//Effectively ending extrapolation of this line
                        }

                        if (thisLineQueue.Peek().ToString() == separator)//If the next element is a separator we need to add thisValue to our array and reset it
                        {
                            thisLineQueue.Dequeue();
                            thisLinesValues[thisLineValues] = thisValue;
                            thisLineValues++;
                            count++;
                            thisValue = "";
                        }

                        //We now know the next element is valid and needs to be added to our string

                        thisValue += thisLineQueue.Dequeue();//So that's what we do here - concurrently removing the value from the queue
                        count++;

                    }
                }


            }
            return coordsList;
        }

        private int calculateLinesInStream()
        {
            int numOfLines = 0;
            using (StreamReader tempStream = new StreamReader(File.Open(path, FileMode.Open))) //Create a new stream using our parameter to quantify number of lines
            {
                bool isError = false;
                string tempString = "";//Populate this string with the current line of the stream
                while (true)//This Loop is to determine only the number of lines in this stream
                {
                    try
                    {
                        bool endLines = tempStream.EndOfStream;
                        if (endLines)
                        {
                            isError = true;
                            break;
                        }
                        tempString = tempStream.ReadLine();//Assigned the string for the current line of the stream
                    }

                    catch
                    {
                        throw new System.Exception("There was a problem");

                    }

                    if (tempString == null)
                    {
                        break;//The line was empty so we exit the loop
                    }

                    numOfLines++;//The line wasn't empty so we increment this integer
                }
            }
            return numOfLines;
        }

        [CommandMethod("TestFile")]
        public void testFile()
        {
            Dictionary<int, string[]> coordsList;
            using (StreamReader sr = getCoordsFile(altGetCoordsFile()))
            {
                Database db = HostApplicationServices.WorkingDatabase;
                Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

                ed.WriteMessage(sr.ToString());

                 coordsList = new Dictionary<int, string[]>(createCoordsList(" "));
            }
                foreach (KeyValuePair<int, string[]> pair in coordsList)
                {
                    for (int i = 0; i < pair.Value.Count() - 1; i++)
                    {
                        ed.WriteMessage(pair.Value[i].ToString());
                    }
                }
{

}
           
                 
        }
    }
}
Title: Re: StreamReader Problem
Post by: wannabe on April 23, 2009, 03:05:06 PM
I've had no luck with my C# manuals but I did remember DocumentLock in the ACAD .NET API.

All will be revealed tomorrow.

Title: Re: StreamReader Problem
Post by: Glenn R on April 23, 2009, 04:19:16 PM
Do a search on the forum for 'TextReader' - I think this will help.

Also, if you haven't purchased this (http://www.theswamp.org/index.php?topic=23022.0), I and a few others here highly recommend it for learning C#.
Title: Re: StreamReader Problem
Post by: wannabe on April 23, 2009, 05:05:29 PM
I've completed the Headfirst C# manual and read through C# for dummies books. It's just a case of putting it all into working practice and re-reading the sections as I go along. That's why this code is a bit shoddy. It was hard for me to plan when I haven't really got masses of actual coding experience. Although the Headfirst is practical based and kept me coding for a few months to get me up to speed.

For this code I just did a basic flow chart but neglected it and dived right in. And now, I'm thinking of ways I can condense it significantly. For example, I could just read each line of the stream straight into a list. Then do a for loop for each element of the list to split it up into each value.

Cheers for the reply.With the above in mind do you think I should still purchase the book? Does it's scope transcend what I am likely to have learned in the other two books?

And thanks also for the TextReader hint. I was interrupted with work, can you believe, as I was perusing the FileStream literature I had available and was just about to refresh myself on TextReader's functionality.

Cheers.
Title: Re: StreamReader Problem
Post by: Glenn R on April 23, 2009, 05:10:28 PM
Hmmm...to answer succinctly.

Yes the book is better than you have.
Second, do the search as I suggested. You will some examples that will do pretty much what you want (ie reading in each line into a variable, splitting it up based on delimiters and adding to some sort of generic storage variable).

Keep at it - it's definitely worth it! :D
Title: Re: StreamReader Problem
Post by: MP on April 23, 2009, 05:17:04 PM
O/T: Pro C# 2008 and the .NET 3.5 Platform is a great book (tome); I didn't care for the HeadFirst C# book.
Title: Re: StreamReader Problem
Post by: wannabe on April 24, 2009, 03:16:41 AM
Thanks guys. With your recommendations in mind my purchase is imminent. One obstructing factor, though is that with the new C# release and the increased dynamism, as-well-as the other new features, should I wait for an updated version of the book? (My feeling is to just buy this book and then a dedicated manual for the C# updates)

Also having read back my code and studied my manuals last night I can see my posted code is fairly verbose.

Again, thanks for the replies. I'm enthusiastic and I enjoy the challenge of coding a lot, so I'll definitely keep at it. Encouragement appreciated.
Title: Re: StreamReader Problem
Post by: wannabe on April 24, 2009, 08:25:09 AM
Here is the revised portion of my code tha is causing me a bit of a headache. Are there any glaring problems that anyone can notice?

Code: [Select]
public static Dictionary<int, string[]> createCoordsDict(char separator)
        {
                string fileName = getFileWithAcadDialog();
                List<string> coordsAsList;
                Dictionary<int, string[]> returnDict = new Dictionary<int, string[]>();
                int dictKey = 0;

                FileStream fs = new FileStream(fileName, FileMode.Open);
                using (StreamReader str = new StreamReader(fs)) //End of using will close this and wrapped stream (fs)
                {
                    coordsAsList = new List<string>();
                    while (true)
                    {
                        string lineRead = str.ReadLine();
                        if (lineRead == null)
                            break;

                        coordsAsList.Add(lineRead);
                    }
                }

                string[] coordsAsArray = coordsAsList.ToArray();

                for (int i = 0; i < coordsAsArray.Length - 1; i++)
                {
                    char[] thisLineAsChars = coordsAsArray[i].ToCharArray();
                    Queue<char> thisLine = new Queue<char>(thisLineAsChars);
                    string currentValue = "";
                    List<string> lineList = new List<string>(); //Stores each individual value from current line once separated

                    while (true)
                    {
                        if (thisLine.Peek() == null)
                        {
                            returnDict.Add(dictKey, lineList.ToArray());
                            dictKey++;
                            break;
                        }

                        if (thisLine.Peek() != separator)
                        {
                            currentValue += thisLine.Dequeue();
                        }

                        lineList.Add(currentValue);
                        thisLine.Dequeue();
                    }

                }

                return returnDict;
           
        }
Title: Re: StreamReader Problem
Post by: It's Alive! on April 24, 2009, 08:50:21 AM
Why all the conversions from lists to Arrays?
Why not just return Dictionary<int, List<string>>?
Just wondering

Title: Re: StreamReader Problem
Post by: wannabe on April 24, 2009, 10:57:25 AM
I find it simpler to add elements to a list and easier to modify them as an array.
Title: Re: StreamReader Problem
Post by: It's Alive! on April 24, 2009, 11:01:51 AM
and easier to modify them as an array.

Can you elaborate on this point?
Title: Re: StreamReader Problem
Post by: wannabe on April 24, 2009, 11:16:16 AM
Yeah sure. I'm just leaving work now. Give me a few hours.

The problem with the code was the last call to dequeue.

Speak soon.
Title: Re: StreamReader Problem
Post by: It's Alive! on April 24, 2009, 11:21:55 AM
Great! Thank you  :-)
Title: Re: StreamReader Problem
Post by: wannabe on April 24, 2009, 12:37:17 PM
Ok Daniel.

I start off with a list because at compile time the required number of elements is unknown. I previously had a function that counted each line and returned the number (if you look at the original post). As I said, I don't have lots of experience, so initially I made a basic plan and started coding it up. When I was in the bath, and still contemplating this code, I realised I could use a list and just add elements until the file was empty; making my code more succinct and reducing error potential.

Now, you specifically asked why I converted to an array: well, the code that will use this function will make judgments based on the previous and next element to determine how it will use the information in this element. To the best of my logic, I either needed to convert into an array now or later. Doing later would mean I have to create a new dictionary. So it seemed easier to code as is.

I guess I could use a List at the other end to talk about previous elements, but it seemed easier to convert to an array and just say [i+1], [i-1] etc as opposed to elementAt. Probably seems minimally beneficial, but my rationale is that all the small changes add up.

As always, I appreciate brutal honesty, and appreciate comments.

Cheers for taking an interest.
Title: Re: StreamReader Problem
Post by: MP on April 24, 2009, 12:41:02 PM
I appreciate brutal honesty, and appreciate comments.

You appear to be closer to the mirror when you wear those pants.
Title: Re: StreamReader Problem
Post by: wannabe on April 24, 2009, 12:48:20 PM
I appreciate brutal honesty, and appreciate comments.

You appear to be closer to the mirror when you wear those pants.

It's the silky texture.......... ^-^
Title: Re: StreamReader Problem
Post by: MikeTuersley on April 24, 2009, 05:01:50 PM
Each time you post these questions, the best solution is to use XML. Serialize/Deserialize removes the readers; Previous/Next Node handles the comparing; etc., etc.
Title: Re: StreamReader Problem
Post by: Bobby C. Jones on April 24, 2009, 05:06:10 PM
Ok Daniel.

I start off with a list because at compile time the required number of elements is unknown. I previously had a function that counted each line and returned the number (if you look at the original post). As I said, I don't have lots of experience, so initially I made a basic plan and started coding it up. When I was in the bath, and still contemplating this code, I realised I could use a list and just add elements until the file was empty; making my code more succinct and reducing error potential.

Now, you specifically asked why I converted to an array: well, the code that will use this function will make judgments based on the previous and next element to determine how it will use the information in this element. To the best of my logic, I either needed to convert into an array now or later. Doing later would mean I have to create a new dictionary. So it seemed easier to code as is.

I guess I could use a List at the other end to talk about previous elements, but it seemed easier to convert to an array and just say [i+1], [i-1] etc as opposed to elementAt. Probably seems minimally beneficial, but my rationale is that all the small changes add up.

As always, I appreciate brutal honesty, and appreciate comments.

Cheers for taking an interest.

If a standard data type doesn't meet your needs, and they often don't, then it's best to roll your own instead of passing around arrays.  I think you'll find in the long run that using arrays like that will make your code brittle.  Arrays are at their best when they're wrapped and hidden away.
Title: Re: StreamReader Problem
Post by: It's Alive! on April 24, 2009, 10:33:16 PM
Have a look at string.split to get your array size and the data you need.

In this sample the file format is:
1.2 2.3 4.5, 1.2 3.4 2.3, 4.3 3.3 1.7, 8.2 1.2 3.6

Code: [Select]
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Text;
using Autodesk.AutoCAD.Runtime;
using AcAp = Autodesk.AutoCAD.ApplicationServices;
using AcGe = Autodesk.AutoCAD.Geometry;

[assembly: CommandClass(typeof(ExecMethod.Commands))]
//// ++--
namespace ExecMethod
{
  public class MyDataDict : Dictionary<int, List<AcGe.Point3d>>
  {
    public MyDataDict() { }

    public override string ToString()
    {
      StringBuilder sb = new StringBuilder();
      sb.Append("(");
      foreach (KeyValuePair<int, List<AcGe.Point3d>> item in this)
      {
        sb.Append("(");
        sb.Append(String.Format("{0}", item.Key));
        sb.Append(", ");
        foreach (AcGe.Point3d d in item.Value)
        {
          sb.Append(d.ToString());
          sb.Append(", ");
        }
        sb.Remove(sb.Length - 2, 2);
        sb.Append(")");
      }
      sb.Append(")");
      return sb.ToString();
    }
  }


  public static class Commands
  {
    public static MyDataDict createCoordsDict(char separator)
    {
      string fileName = "C:\\Coords.TXT" /*getFileWithAcadDialog()*/;
      MyDataDict dict = new MyDataDict();

      using (TextReader streamReader = new StreamReader(fileName))
      {
        int cntr = 0;
        while (true)
        {
          string lineRead = streamReader.ReadLine();

          if (string.IsNullOrEmpty(lineRead))
          {
            break;
          }
          string[] pointstr = lineRead.Trim().Split(separator);
          List<AcGe.Point3d> ptList = new List<AcGe.Point3d>();

          foreach (string str in pointstr)
          {
            string[] doublestr = str.Trim().Split();

            if (doublestr.Length == 3)
            {
              double[] pt = new double[3];
              for (int i = 0; i < 3; i++)
              {
                double d;
                if (double.TryParse(doublestr[i], out d))
                {
                  pt[i] = d;
                }
              }
              ptList.Add(new AcGe.Point3d(pt));
            }
            else
            {
              throw new System.Exception("\nBad File Format!");
            }
          }
          dict.Add(cntr++, ptList);
        }
      }
      return dict;
    }
     
    [CommandMethod("doit")]
    public static void doit()
    {
      AcAp.Application.DocumentManager.MdiActiveDocument.Editor.WriteMessage("\n{0}", createCoordsDict(','));
    }
  }
}


Title: Re: StreamReader Problem
Post by: pkohut on April 25, 2009, 02:56:25 AM
Hey Wannabe,

"charactersThisLine" used as a key for the dictionary might cause you some
problems.  If a key is already in the collection then adding that key again will
overwrite the value associated with the key.

I read Daniels question and your reply... Do you know you can access a List<T>
using an index just like an array? List<T> implements IList, ICollection, and
IEnumerable.  In this case your interested in IList.

...And as Bobby C says, roll your own datatypes and store these values in a
collection.  The collection can be just about anything, array, list, dictionary, stack,
etc., as long as your aware of the unique strengths and weaknesses of each
collection type.  Once you've implement a couple custom datatypes then it
becomes second nature.  They may look daunting at first but their pretty
simple with just a few rules to follow.

Paul
Title: Re: StreamReader Problem
Post by: pkohut on April 25, 2009, 03:26:19 AM
Each time you post these questions, the best solution is to use XML. Serialize/Deserialize removes the readers; Previous/Next Node handles the comparing; etc., etc.

Sorry, but...are you serious?  How do you suggest he get the data in XML format in the first place?
XML is not the Ron Popeil's Dice-o-matic wonder machine.

Paul
Title: Re: StreamReader Problem
Post by: wannabe on April 25, 2009, 04:01:02 AM
 :-) :-) :-)

Thanks for the replies, folks. I greatly appreciate the input and will be sure to maximise the education potential. Also thanks to Daniel for the code example.


Quote
Sorry, but...are you serious?  How do you suggest he get the data in XML format in the first place?
XML is not the Ron Popeil's Dice-o-matic wonder machine.

I actually took the XML suggestions on board. As yet, I'm not fully up to speed with the procedures so I decided to do a simple code using the C# components I am familiar with - then use that as a base/inspiration for the XML alternative.

Quote
I read Daniels question and your reply... Do you know you can access a List<T>
using an index just like an array? List<T> implements IList, ICollection, and
IEnumerable.  In this case your interested in IList.

It's covered in my books but at the time of composition I admit to not being aware of it. Cheers for that.


Title: Re: StreamReader Problem
Post by: Kerry on April 25, 2009, 04:14:19 AM
You said to be harsh, so ...
You're making the same error that most of us are guilty of ;

trying to describe a problem by attempting to provide a solution instead of explicitly providing ALL the relevant information.

Where is the data file containing your points ; ie why isn't it posted. ?
you have made referenced to AutoCad namespace, so this runs inside AutoCAD, but which version ?


have you taken Glenn's suggestion regarding searching here for TextReader ?

 
Title: Re: StreamReader Problem
Post by: pkohut on April 25, 2009, 04:20:43 AM
It's good that you've decided to tackle the programming problem at it's core.
If you plan to take up programming as more than just a hobby then understanding
common collections, patterns, structures is way more rewarding and efficient.  Every
collection type has strengths and weaknesses, XML is just another collection type, but
when paired with XSD some real magic can happen.

Also, what about the dictionary type your using?  Is non-unique keys going to be a
problem?

Paul
Title: Re: StreamReader Problem
Post by: wannabe on April 25, 2009, 04:54:42 AM
Hi Paul,

I'm not sure where key duplication comes into effect. Every time an array is added to the dictionary the counting integer should be increased by one.

I've been reading up on generic collections, even before I started this code. The fact is, each line read from the stream will contain coordinates, but maybe attributes as well(needed to populate the attributes in a block). Therefore, at this stage, I only saw Dictionary<int, string[]> as being viable.

The code from Daniel seems a big improvement and has taught me a lot. Hopefully I can incorporate attributes into it somehow. Maybe there is a field in Point3d that allows for a string[]. I'll get searching.

EDIT: Or maybe add Xdata to a point3d if possible.
Title: Re: StreamReader Problem
Post by: wannabe on April 25, 2009, 04:56:41 AM
Also, is there a specific XML, XSD resource you recommend, please? I've done my homework on the structure of the language itself, but haven't found a good resource for explaining its strengths and weaknesses for use in this kind of context etc.

Title: Re: StreamReader Problem
Post by: SEANT on April 25, 2009, 07:37:23 AM
EDIT: Or maybe add Xdata to a point3d if possible.

You won't have much luck with the Point3d, but it would be possible with DBPoint.
Title: Re: StreamReader Problem
Post by: It's Alive! on April 25, 2009, 08:13:48 AM
Hey wannabe,

Exactly what are you trying to accomplish? 
Are you wanting to serialize/de-serialize xdata?

Title: Re: StreamReader Problem
Post by: wannabe on April 25, 2009, 08:20:29 AM
The aim is to take a text file which has coordinates and attributes and populate an AutoCAD drawing with blocks that use the data. Each line in the text file has an X & Y coord and potentially strings that are intended to place the block and populate the attributes, respectively.

Title: Re: StreamReader Problem
Post by: pkohut on April 25, 2009, 12:54:28 PM
Hi Paul,

I'm not sure where key duplication comes into effect. Every time an array is added to the dictionary the counting integer should be increased by one.

Code: [Select]
http://www.theswamp.org/index.php?topic=28468.msg340666#msg340666
int charactersThisLine = thisLine.Length;
...
coordsList.Add(charactersThisLine, thisLinesValues);

That is from the 2nd example you posted.  The 3rd example is better in
that it does use a unique key.
Title: Re: StreamReader Problem
Post by: pkohut on April 25, 2009, 12:58:58 PM
Also, is there a specific XML, XSD resource you recommend, please? I've done my homework on the structure of the language itself, but haven't found a good resource for explaining its strengths and weaknesses for use in this kind of context etc.

With hesitation, look up XSD and code generators.  Your not ready for that yet, nor do you need it
for your situation.
Title: Re: StreamReader Problem
Post by: pkohut on April 25, 2009, 01:18:00 PM
The aim is to take a text file which has coordinates and attributes and populate an AutoCAD drawing with blocks that use the data. Each line in the text file has an X & Y coord and potentially strings that are intended to place the block and populate the attributes, respectively.
Ok, there is the custom data structure.  Just create and add a new block reference on the fly...


Quote
the code that will use this function will make judgments based on the previous and next element to determine how it will use the information in this element. To the best of my logic, I either needed to convert into an array now or later. Doing later would mean I have to create a new dictionary. So it seemed easier to code as is.
With just the smallest bit of code you can keep track of the previous element (block reference) and perform any
operations on it and the current element.  No need to store the whole file in concocted dictionaries and arrays, just
process the file line-by-line.

Now that you've got a bit of seat time in you should throw away the code you've done, rethink your approach,
and start over. 
Title: Re: StreamReader Problem
Post by: wannabe on April 25, 2009, 02:42:46 PM
I've been rethinking it for large portions of the day. I was thinking about ways to condense the code and improve efficiency. With your hint in mind, I think will try and develop a routine that does it on the fly whilst reading from the txt file, line by line.

If I set up a method that inserts a block and populates the attributes, I'll just need to call it once for each line of the code.

Catch up with you soon.
Title: Re: StreamReader Problem
Post by: wannabe on April 27, 2009, 08:42:10 AM
Using the comments and constructs in this thread I now have working code. Thanks for all the advice; I appreciate it all.

Now I'm going to tinker with my code until fully congenial. I'll post it up for your criticisms if you want/don't mind.

Cheers again.
Title: Re: StreamReader Problem
Post by: Glenn R on April 27, 2009, 04:02:10 PM
I'm in total agreement with Kerry.

1. Post as good a description as you can of what you're trying to accomplish overall and go into more detail on specific points you're stuck on.
2. Post a sample of the 'text' file you are using as your data input.
3. Indicate what version of AutoCAD you're targeting.
4. Indicate what version of the .NET Framwork you're targeting.
5. Indicate what version of Visual Studio (or other IDE) you're using.

Once members have this critical data, we can better help you, otherwise we are really only guessing based on experience and the alignment of the planets ;)
Also, I have a sneaking suspicion where this is going and if it's what I suspect, you're going to run into a rather large and rather solid wall very shortly. :)

This is becoming interesting...
Title: Re: StreamReader Problem
Post by: wannabe on April 27, 2009, 06:03:44 PM
1. I want to populate drawings with user-specified block(s) using a text file that contains 'to-be' coordinates and attributes on a per-line basis

**I have achieved this task - tested and working - thanks for all the help**

However, to be able to insert in the AutoCAD drafting "Wblock" fashion is proving a little tricky. But I'll only want help when I accept defeat.... if I've not expended my quota already.

2. Attached is a text file and, because I'm nice, a block as well.

3. I'm targeting AutoCAD 2008.

4 & 5 visual Studio C# Express 08 with 3.5 framework.

Quote
public class Commands
    {
        [CommandMethod("MultiBlocks")]
        public void MultiBlocks()
        {
            OpenFileDialog coordsSelectDialog = new OpenFileDialog("Coodinate Selection", "", "txt",
                                                       "Select a Coordinate File", OpenFileDialog.OpenFileDialogFlags.NoUrls);
                bool coordsSelected = false;//So we can loop until valid file selected or user cancels
                while (!coordsSelected)
                {
                    System.Windows.Forms.DialogResult coordsResult = coordsSelectDialog.ShowDialog();

                    if (coordsResult == System.Windows.Forms.DialogResult.Cancel)
                        return;

                    if (coordsResult != System.Windows.Forms.DialogResult.OK)
                    {
                        System.Windows.Forms.MessageBox.Show("Select Another File");
                    }
                    else
                    {
                    coordsSelected = true; //Loop will no longer execute & we have a valid file
                    }
                }
            using (TextReader coordsFile = new StreamReader(coordsSelectDialog.Filename))
            {
                Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
                string blockName = "";
                bool isStringValid = false;//Enabling us to loop until string is valid or user cancels
                while (!isStringValid)
                {
                    PromptStringOptions psoBlockSelect = new PromptStringOptions("Enter The Name of The Block to 'Multi-Insert'");
                    PromptResult prBlockSelected = ed.GetString(psoBlockSelect);

                    if (prBlockSelected.Status == PromptStatus.Cancel)
                        return;

                    if (prBlockSelected.Status != PromptStatus.OK)
                        System.Windows.Forms.MessageBox.Show("Error With User Input - Try Again or Cancel");
                    else
                    {
                        isStringValid = true;
                        blockName = prBlockSelected.StringResult;
                    }
                }

                while (true)
                    try
                    {
                        string lineRead = coordsFile.ReadLine();

                        if (String.IsNullOrEmpty(lineRead))
                            break;

                        string[] lineSeparated = lineRead.Trim().Split(' ');

                        //Convert first two elements to double for our insertion point
                        Point3d insPoint = new Point3d(Double.Parse(lineSeparated[0]), Double.Parse(lineSeparated[1]), 0);

                        Database db = HostApplicationServices.WorkingDatabase;
                        using (Transaction trans = db.TransactionManager.StartTransaction())
                        {
                            BlockTable bt = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                            ObjectId blockId;

                            //Iterate the Block Table, searching for our Block
                            if (!bt.Has(blockName.ToString()))
                            {
                                System.Windows.Forms.MessageBox.Show("Specified Block Name Not Valid in This Document"
                                                                     , "Input Error");
                                                                       
                                return;
                            }

                            blockId = bt[blockName.ToString()];//Essentially our "Block Definition"
                            BlockReference blockRef = new BlockReference(insPoint, blockId);

                            //Add to ModelSpace immediately to ensure successful attribute population
                            BlockTableRecord mSpace = (BlockTableRecord)trans.GetObject(bt[BlockTableRecord.ModelSpace], OpenMode.ForWrite);
                            mSpace.AppendEntity(blockRef);
                            trans.AddNewlyCreatedDBObject(blockRef, true);

                            if (lineSeparated.Count() > 2)//If true, we have attribute data
                            {
                                BlockTableRecord thisBlock = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForRead);
                                int counter = 2; //Element in "lineSeparated" where attribute information will begin - after coordinates
                                foreach (ObjectId obj in thisBlock)
                                {
                                    Entity ent = (Entity)trans.GetObject(obj, OpenMode.ForRead);

                                    if (ent is AttributeDefinition)
                                    {
                                        AttributeDefinition attDef = (AttributeDefinition)(ent);

                                        AttributeReference attRef = new AttributeReference();
                                        attRef.SetPropertiesFrom(ent);
                                        attRef.TextString = lineSeparated[counter];
                                        attRef.Position = new Point3d(blockRef.Position.X + attDef.Position.X,
                                                                      blockRef.Position.Y + attDef.Position.Y,
                                                                      0);
                                        attRef.Tag = attDef.Tag;
                                        attRef.Height = attDef.Height;
                                        attRef.Rotation = attDef.Rotation;

                                        //Add this attribute to the "Block Reference" & the transaction
                                        blockRef.AttributeCollection.AppendAttribute(attRef);
                                        trans.AddNewlyCreatedDBObject(attRef, true);

                                        //Increment the counter so the next attribute will utilise the next array element
                                        counter++;
                                    }

                                }
                            }
                            //Complete by adding Block Referenc to transaction
                            trans.Commit();
                        }
                    }

                    catch
                    {
                        System.Windows.Forms.MessageBox.Show("Error - Application Terminated", "Error");
                        return;
                    }
                }
            }   

There is the code.

I've got plans to make it more robust and to be able to use a "Wblock". But I need to get my head around "Database.Insert(), DeepClone(), Wblock()" etc.

Also I need to add some user information that specifies that attributes will be populated sequentially corresponding to their order in the AutoCAD "Block Attribute Manager".

Fun, fun...
Title: Re: StreamReader Problem
Post by: kdub_nz on April 27, 2009, 07:24:44 PM

Can't make time to have a look, but how do you get out of the while (true) ....  loop.
... and are you sure that's what you want to think of the logic

ie would
while (what condition is true )
be easier to understand next month when you re-visit the code ..


///Kerry
Title: Re: StreamReader Problem
Post by: pkohut on April 27, 2009, 07:34:07 PM
He's breaking out when streamread realine is empty.
Title: Re: StreamReader Problem
Post by: Glenn R on April 28, 2009, 03:44:26 AM
Doing a 'While True' is never a good idea in my opinion, not the least of which is confusion.
Have a look at some of the examples I've posted using TextReader (as I suggested earlier) for a better way of using a loop to read each line from a file and breaking out when at the end.

Other than that, coming along well.
Title: Re: StreamReader Problem
Post by: Glenn R on April 28, 2009, 03:47:13 AM
Also, using ToString() on a String object is well....redundant.
Title: Re: StreamReader Problem
Post by: pkohut on April 28, 2009, 05:07:50 AM
Doing a 'While True' is never a good idea in my opinion, not the least of which is confusion.
Have a look at some of the examples I've posted using TextReader (as I suggested earlier) for a better way of using a loop to read each line from a file and breaking out when at the end.

Other than that, coming along well.

Personally, no problem with while(true) ( c++, while(1) ) and for( ; ; ) in the
right context.  The compiler optimizes the while loops to be as effecent as the for loop here, and the
intent is known.  But in Wannabe's sample, he is better served with while(coordsFile.Peek() >= 0)

Title: Re: StreamReader Problem
Post by: Glenn R on April 28, 2009, 05:19:49 AM
Agreed, however, in inexperienced hands, these sort of constructs can lead to infinite loops - this was where I was coming from.
Forever loops are ok in the right circumstances, but this isn't one of them.
Title: Re: StreamReader Problem
Post by: pkohut on April 28, 2009, 05:47:09 AM
Agreed, however, in inexperienced hands, these sort of constructs can lead to infinite loops - this was where I was coming from.
Forever loops are ok in the right circumstances, but this isn't one of them.

Yeah, I'll admit that with it not being my code I had to look for the exit condition as it wasn't
readily apparent. 

You mentioned he might run into a solid wall soon, care to share?  I'm not seeing it.
Title: Re: StreamReader Problem
Post by: Glenn R on April 28, 2009, 05:54:40 AM
I was thinking that one of the upcoming questions might be along these lines:

How do I link my data for a specific block in my data file to a specific block reference in a specific drawing kind of thing.
The only way I can think of doing this is by tracking drawing name and handles (or a drawing GUID instead of name) and this can be fragile.

However, having re-read some recent posts, I think I was wrong in my assumption. Wannabe is going the other way to what I was thinking - applying his data file to many drawings without any specific linkage.
Title: Re: StreamReader Problem
Post by: wannabe on April 28, 2009, 06:01:51 AM
Cheers all for the quality feedback.

Title: Re: StreamReader Problem
Post by: It's Alive! on April 28, 2009, 06:22:52 AM
Doing a 'While True' is never a good idea in my opinion, not the least of which is confusion.
Have a look at some of the examples I've posted using TextReader (as I suggested earlier) for a better way of using a loop to read each line from a file and breaking out when at the end.

Other than that, coming along well.

Personally, no problem with while(true) ( c++, while(1) ) and for( ; ; ) in the
right context.  The compiler optimizes the while loops to be as effecent as the for loop here, and the
intent is known.  But in Wannabe's sample, he is better served with while(coordsFile.Peek() >= 0)





Neither do I, nor do I with goto statements  :evil:
Title: Re: StreamReader Problem
Post by: Glenn R on April 28, 2009, 06:25:42 AM
Nasty boy! Fight! :D
Title: Re: StreamReader Problem
Post by: Chuck Gabriel on April 28, 2009, 06:31:08 AM
Neither do I, nor do I with goto statements  :evil:

You'll burn for that, heretic! :D
Title: Re: StreamReader Problem
Post by: Glenn R on April 28, 2009, 06:33:10 AM
Next thing you know, he'll be expostulating the virtues of VB of all things! ;)
I'm with the Chuckster - burn, baby, burn.
Title: Re: StreamReader Problem
Post by: Kerry on April 28, 2009, 06:33:28 AM

Neither do I, nor do I with goto statements  :evil:

:D

I'm reminded of this from 'Program Design' by Peter Juliff

(http://www.theswamp.org/screens/index.php?dir=KerryBrown/&file=pseudocode1.png)
Title: Re: StreamReader Problem
Post by: Glenn R on April 28, 2009, 06:34:37 AM
hehe - good one.
Title: Re: StreamReader Problem
Post by: Chuck Gabriel on April 28, 2009, 06:41:09 AM
Next thing you know, he'll be expostulating the virtues of VB of all things! ;)

Touché.  I'll just go back to my hole now. :-)
Title: Re: StreamReader Problem
Post by: MikeTuersley on April 28, 2009, 10:44:44 AM
Each time you post these questions, the best solution is to use XML. Serialize/Deserialize removes the readers; Previous/Next Node handles the comparing; etc., etc.

Sorry, but...are you serious?  How do you suggest he get the data in XML format in the first place?
XML is not the Ron Popeil's Dice-o-matic wonder machine.

Paul

It is is most cases but most of you have no idea how to handle or maintain data. Text, CSV, etc. are vehicles of 20 years ago. Look around, everything is in XML for a reason - from AutoCAD settings to Office's new .???x file formats.
Title: Re: StreamReader Problem
Post by: It's Alive! on April 28, 2009, 11:09:42 AM
You got me there, I didn’t even know who Ron Popeil was till I googled him  :laugh:
Title: Re: StreamReader Problem
Post by: kdub_nz on April 28, 2009, 05:11:18 PM
< ... >  but most of you have no idea how to handle or maintain data.  < ... >

well, that's just plain cruel ..  :lol:
Title: Re: StreamReader Problem
Post by: pkohut on April 28, 2009, 07:38:21 PM
Each time you post these questions, the best solution is to use XML. Serialize/Deserialize removes the readers; Previous/Next Node handles the comparing; etc., etc.

Sorry, but...are you serious?  How do you suggest he get the data in XML format in the first place?
XML is not the Ron Popeil's Dice-o-matic wonder machine.

Paul

It is is most cases but most of you have no idea how to handle or maintain data. Text, CSV, etc. are vehicles of 20 years ago. Look around, everything is in XML for a reason - from AutoCAD settings to Office's new .???x file formats.

I can understand your thinking here, most in this forum don't have a lot of experience with database backends,
xml schema creation, and have little need to share data between applications, it's just the nature of most
AutoCAD programming projects, especially the questions seen in a forum like this.  I use a couple code generators
myself for data persistence and database work.  These save so much time and easy to extend in the future, I
absolutely love them, but not all projects require the processing and storage overhead that also comes with it.

Paul
Title: Re: StreamReader Problem
Post by: Spike Wilbury on April 29, 2009, 10:21:22 AM
Each time you post these questions, the best solution is to use XML. Serialize/Deserialize removes the readers; Previous/Next Node handles the comparing; etc., etc.

Sorry, but...are you serious?  How do you suggest he get the data in XML format in the first place?
XML is not the Ron Popeil's Dice-o-matic wonder machine.

Paul

It is is most cases but most of you have no idea how to handle or maintain data. Text, CSV, etc. are vehicles of 20 years ago. Look around, everything is in XML for a reason - from AutoCAD settings to Office's new .???x file formats.

I can understand your thinking here, most in this forum don't have a lot of experience with database backends,
xml schema creation, and have little need to share data between applications, it's just the nature of most
AutoCAD programming projects, especially the questions seen in a forum like this.  I use a couple code generators
myself for data persistence and database work.  These save so much time and easy to extend in the future, I
absolutely love them, but not all projects require the processing and storage overhead that also comes with it.

Paul

For MikeTuersley - and - Paul

It will be interesting to know how both of you come up with those conclusions.
Title: Re: StreamReader Problem
Post by: Tuoni on April 29, 2009, 10:31:38 AM
Each time you post these questions, the best solution is to use XML. Serialize/Deserialize removes the readers; Previous/Next Node handles the comparing; etc., etc.

Sorry, but...are you serious?  How do you suggest he get the data in XML format in the first place?
XML is not the Ron Popeil's Dice-o-matic wonder machine.

Paul

It is is most cases but most of you have no idea how to handle or maintain data. Text, CSV, etc. are vehicles of 20 years ago. Look around, everything is in XML for a reason - from AutoCAD settings to Office's new .???x file formats.

I can understand your thinking here, most in this forum don't have a lot of experience with database backends,
xml schema creation, and have little need to share data between applications, it's just the nature of most
AutoCAD programming projects, especially the questions seen in a forum like this.  I use a couple code generators
myself for data persistence and database work.  These save so much time and easy to extend in the future, I
absolutely love them, but not all projects require the processing and storage overhead that also comes with it.

Paul

For MikeTuersley - and - Paul

It will be interesting to know how both of you come up with those conclusions.
I agree.
Title: Re: StreamReader Problem
Post by: MP on April 29, 2009, 10:42:20 AM
It will be interesting to know how both of you come up with those conclusions.

(http://i44.tinypic.com/30loqbo.png)
Title: Re: StreamReader Problem
Post by: Tuoni on April 29, 2009, 10:43:13 AM
 :-D
Title: Re: StreamReader Problem
Post by: pkohut on April 29, 2009, 05:16:52 PM

I can understand your thinking here, most in this forum don't have a lot of experience with database backends,


I was trying to figure out where Mike is coming from, so I googled some past posts of his and it looks like he has a bit
of experience with database backends, ADE, and VB, and that that must be the angle.  My statement
probably isn't an accurate reflection of the group, as I had very limited experience with DB's prior to 2005.

XML seems to be everywhere, especially if you look at the consumer market and interoperability, great stuff then.  Beyond
that it's a binary world and interoperability is usually some sort of tab/comma delimited format.  Internal applications,
embedded devices, data publishing sources, legacy apps, the list is long, probably don't support XML.

Paul
Title: Re: StreamReader Problem
Post by: Glenn R on April 29, 2009, 06:00:03 PM
XML, IMO, is the new text/csv/formatgoeshere, but I've always thought of it as an INI file on steroids. It is also becoming extremely prevalent and it does have many uses and I personally will use it in preference to the above mentioned formats, where applicable.

I do take umbrage at Mike's and to some extent Paul's, blanket comments, as I suspect Luis and Tuoni have done, about MOST not having experience with a backend data-store - this is quite simply not the case with myself or many members in this particular group.
Title: Re: StreamReader Problem
Post by: MP on April 29, 2009, 06:04:52 PM
Blanket use of xml for small apps / equally small data sets is akin to being invited to bring a guitar to a BBQ and showing up with a piano.

:D
Title: Re: StreamReader Problem
Post by: kdub_nz on April 29, 2009, 06:08:56 PM


Yep, just because we can doesn't mean we must ..

.. and mike, some of us can :)
Title: Re: StreamReader Problem
Post by: pkohut on April 29, 2009, 06:21:32 PM
umbrage

New word, like it.

I was trying to generalize without stepping on to many toes.  Here's a buck for a shoe
shine  :angel:
Title: Re: StreamReader Problem
Post by: Spike Wilbury on April 29, 2009, 06:59:49 PM
XML, IMO, is the new text/csv/formatgoeshere, but I've always thought of it as an INI file on steroids. It is also becoming extremely prevalent and it does have many uses and I personally will use it in preference to the above mentioned formats, where applicable.

I do take umbrage at Mike's and to some extent Paul's, blanket comments, as I suspect Luis and Tuoni have done, about MOST not having experience with a backend data-store - this is quite simply not the case with myself or many members in this particular group.

No me ofendi, para nada solo me dio curiosidad saber como llegaron a esa conclusion, lo que si el primer comentario echo por Mike es en si demasiado cruel y arrogante.

:)
Title: Re: StreamReader Problem
Post by: Tuoni on April 29, 2009, 07:41:33 PM
I do take umbrage at Mike's and to some extent Paul's, blanket comments, as I suspect Luis and Tuoni have done, about MOST not having experience with a backend data-store - this is quite simply not the case with myself or many members in this particular group.
I've certainly done a little bit of backend database stuff in a couple of different DBMS'.  I think to say "most" is amusing and short-sighted, especially considering some of the posts I have seen recently on here.
Title: Re: StreamReader Problem
Post by: pkohut on April 29, 2009, 08:26:44 PM
I do take umbrage at Mike's and to some extent Paul's, blanket comments, as I suspect Luis and Tuoni have done, about MOST not having experience with a backend data-store - this is quite simply not the case with myself or many members in this particular group.
I've certainly done a little bit of backend database stuff in a couple of different DBMS'.  I think to say "most" is amusing and short-sighted, especially considering some of the posts I have seen recently on here.

Ya, it was a bit short sighted Ed, read the followup post, I as much admitted it.

Paul
Title: Re: StreamReader Problem
Post by: Tuoni on April 29, 2009, 08:30:46 PM
I do take umbrage at Mike's and to some extent Paul's, blanket comments, as I suspect Luis and Tuoni have done, about MOST not having experience with a backend data-store - this is quite simply not the case with myself or many members in this particular group.
I've certainly done a little bit of backend database stuff in a couple of different DBMS'.  I think to say "most" is amusing and short-sighted, especially considering some of the posts I have seen recently on here.
Ya, it was a bit short sighted Ed, read the followup post, I as much admitted it.

Paul
:) so I see - no problems here!  I was just justifying my previous post in terms of Glenn's.
Title: Re: StreamReader Problem
Post by: MikeTuersley on April 30, 2009, 01:02:43 AM
I apologize if my post came across sharply, but it's accurate. "Most" don't have experience outside of their employer so they've never functioned as a professional consultant thrown into diverse environments on every new project and, therefore, forced to find/learn different methodologies. This isn't saying "Most" don't know how to handle their data within the confines they have setup, it's saying "Most" have never had to look for alternative methods so "Most" have no clue what other options are available that might better serve their purposes.

Based upon the follow up posts here, most of you have no idea what XML is or how easy it is to use. Most of you probably agree with a couple of the comments:

Quote
...have little need to share data between applications...
...not all projects require the processing and storage overhead...
...Blanket use of xml for small apps / equally small data sets is akin to being invited to bring a guitar to a BBQ and showing up with a piano....

Unfortunately, none of them are true. There is no overhead, there doesn't need to be sharing between apps, and size of app has nothing to do with whether or not to use Xml. The determining factor is how easily do you want to deal with your data? And, how much code do you want to write?

A lot of questions in this, and other, ngs are people trying to learn the various Autodesk APIs. If you discount those, the majority of the remainder are people trying to tackle problems in a linear fashion - from A to B - and they are getting stuck or hung up on things that if they were using a different approach, their problem would be removed or shifted to something simpler. Lets take this post for example:

- The OP is trying to read in points in a particular order and move forward/backwards within that order.

- Most would approach this by opening the file and reading each line within the file one at a time. If the line holds a single value, they send it to an array or collection; if the line is delimited and holds multiple values, they read the line, split it to an array and then populate a larger array/collection. Saving out the data would be the reverse of reading - reading item by item in the container object, writing to a file as a line (or concatenating into a delimited string then writing). To find an item, they will need to loop each line using a comparer to find the matching value and exit the loop when the value match is found. Moving forward/backward would require storing the current item's position within the container and add/subtract 1 to move.

- Some would follow the above scenario but use a better container object like an arraylist that has a binarysearch option to speed up the find/move functions.

- A few would use XML for the data so they could get all of the data in a useable format with 2 lines of code; saving is 1 line. Once populated, the xmldocument has functions for find, next node, previous node, etc.

- A couple would create a custom object to hold the values then use serialization to open the file and populate their object with all of the data in 4 lines of code; saving the data out is 5 lines of code. Once the data is in their object, now they can wrap the xml methods so other members of their team can use simpler calls such as MyPointList.NextPoint, or MyPointList.FindPoint(4,4,0), etc.

Instead of tackling the problem from A to B, look at it and make it easier. The last 2 options remove the problems around getting/saving the data as well as finding and moving within the data structure. IF the OP doesn't control the creation of the text/csv/ini/? input file, the problem changes focus to getting the input file into xml format. Creating an in-memory converter from original format to xml is easier for most people than dealing with the more complicated data structure that they end up creating with arrays or collections. Using other techniques such as XSLTs or CSSs would make the converter possible with 3 or 4 lines of code.

So working smarter not harder is the way to focus your energies. The best way to do this is by learning as much as possible about what is available in the .NET Framework. If I have time, I'll whip up a quick example for those of you that took umbrage to this so you can have the opportunity to see how simple Xml can be and how much time & energy it can save you.
Title: Re: StreamReader Problem
Post by: Tuoni on April 30, 2009, 03:00:06 AM
I apologize if my post came across sharply, but it's accurate. "Most" don't have experience outside of their employer so they've never functioned as a professional consultant thrown into diverse environments on every new project and, therefore, forced to find/learn different methodologies. This isn't saying "Most" don't know how to handle their data within the confines they have setup, it's saying "Most" have never had to look for alternative methods so "Most" have no clue what other options are available that might better serve their purposes.
In the two and a half years I've been on here, I still wouldn't be able to say what "most" of the guys on here can do, and I think to say "most" is doing a lot of the guys on here a great disservice, as well as being wildly inaccurate and mildly amusing.

Based upon the follow up posts here, most of you have no idea what XML is or how easy it is to use.
I think you misunderstand.  It's not that "most" on here don't know what XML is (I think you'll find other people in the world may have used it too, y'know - by my count, there's at least two of us...) but that "most" on here don't believe in using one blanket solution for EVERYTHING requiring data I/O.  I could apply the same logic by recommending something such as SQlite as the backend because "I know what's best for you!"

Why use a pile driver to hammer in a 3" nail when a simple hammer will do?
Title: Re: StreamReader Problem
Post by: Kerry on April 30, 2009, 05:09:51 AM

[selfControl=ON]

Mike, Instead of giving us a lecture MOST of us don't need, how about posting some sample code to show the OP what you have in mind.
It will probably be better received ... and you'd use less lines of code than your last post.

Regards
Kerry

[selfControl=DEFAULT]
Title: Re: StreamReader Problem
Post by: Glenn R on April 30, 2009, 05:32:01 AM
... If I have time, I'll whip up a quick example for those of you that took umbrage to this so you can have the opportunity to see how simple Xml can be and how much time & energy it can save you.

You seem to be waxing lyrical about the virtues of XML (which I admit, there are many), so please, by all means, post away old boy  :evil:
Title: Re: StreamReader Problem
Post by: Glenn R on April 30, 2009, 05:33:36 AM
umbrage

New word, like it.

I was trying to generalize without stepping on to many toes.  Here's a buck for a shoe
shine  :angel:

Currencies are not worth what they once were....sigh.
Glad you like it. :)
Title: Re: StreamReader Problem
Post by: It's Alive! on April 30, 2009, 06:07:36 AM
[selfControl=DEFAULT]

 :lol:
Title: Re: StreamReader Problem
Post by: Glenn R on April 30, 2009, 06:10:19 AM
Yeah, I liked that also Dan :D
Title: Re: StreamReader Problem
Post by: pkohut on April 30, 2009, 07:45:00 AM
Hey Mike, thanks for your feedback.  I'd be interest in a sample as well, especially
if it created class instances and serialized the data.  I don't know if I'll ever get
back into C# except to support some legacy code, otherwise .Net 2.5, EntitySpaces,
and CodeXS have served me well for a number of years.

Quote
Unfortunately, none of them are true. There is no overhead, there doesn't need to be sharing between apps, and size of app has nothing to do with whether or not to use Xml. The determining factor is how easily do you want to deal with your data? And, how much code do you want to write?

Though your opinion probably won't change, I would point out that parsing XML string data is very CPU intensive and
source files are much bigger than most other format methods, neither of which are free.

Paul
Title: Re: StreamReader Problem
Post by: Spike Wilbury on April 30, 2009, 10:36:00 AM
I apologize if my post came across sharply, but it's accurate. "Most" don't have experience outside of their employer so they've never functioned as a professional consultant thrown into diverse environments on every new project and, therefore, forced to find/learn different methodologies. This isn't saying "Most" don't know how to handle their data within the confines they have setup, it's saying "Most" have never had to look for alternative methods so "Most" have no clue what other options are available that might better serve their purposes.

Based upon the follow up posts here, most of you have no idea what XML is or how easy it is to use. Most of you probably agree with a couple of the comments:

So, you are one of those people that if they are invited into a party, and you don't know anyone there, just the person who took you or invite you and when you just came in, they introduce you to one of the hostess, and you look at that person, and simple say "Oh, you don't have an idea of how to put together a party!" or "Oh, how ugly you are, no one had told you?".

 :ugly:
Title: Re: StreamReader Problem
Post by: MP on April 30, 2009, 10:38:39 AM
(http://www.theswamp.org/screens/mp/snacks.gif)
Title: Re: StreamReader Problem
Post by: Spike Wilbury on April 30, 2009, 10:45:09 AM
(http://www.theswamp.org/screens/mp/snacks.gif)

Send me some of those snacks....  :-P
Title: Re: StreamReader Problem
Post by: MP on April 30, 2009, 12:17:10 PM
Send me some of those snacks....  :-P

address?
Title: Re: StreamReader Problem
Post by: dgorsman on April 30, 2009, 02:14:09 PM
Why use a pile driver to hammer in a 3" nail when a simple hammer will do?

Wish I could remember the original poster on this, but the quote I heard was "Thats like trying to drive a nail with a pickle, or this here instrument:  :pissed:".

From the course of the thread, it looks like the OP is working with point data gathered from a total station or other surveying tool, delivered in PTX or PTZ format.  Yeah, it may be CSV *but* its still widely used in collecting and working with survey information.  There may be some tangible benefits from translating the entire data set to XML, but as I see it the work needed to create the translator plus the possibility of an XML-translated file getting out-of-sync with the original CSV data file makes any gains moot.  In this case I think the easiest, fastest, and best path forward is to just work with the original format.
Title: Re: StreamReader Problem
Post by: Spike Wilbury on April 30, 2009, 02:42:00 PM
Send me some of those snacks....  :-P

address?

Sorry, Michael, and thanks!, I just did some popcorn here.... :)
Title: Re: StreamReader Problem
Post by: Kerry on October 17, 2009, 05:54:27 AM
This sort of passed away quietly, didn't it.
Title: Re: StreamReader Problem
Post by: Glenn R on October 17, 2009, 06:02:07 AM
Yep.
Title: Re: StreamReader Problem
Post by: vegbruiser on October 26, 2009, 10:29:29 AM
A bit of a shame it did really, an example of what Mike was referring to would have been useful.
Title: Re: StreamReader Problem
Post by: Jeff H on April 03, 2011, 02:13:01 PM
I am having some problems with data ......
Nevermind, I just need to throw some XML on it.
Title: Re: StreamReader Problem
Post by: Jeff H on April 10, 2011, 01:33:26 PM
I have seen post like this before where since XML needed for exchanging data = Use Xml for data structures, store data, model data for internal use in application..... etc

I was wondering do any of you really use XML as a data structure or store data?

Or add functionality to structure data in XML for sharing with other applications if needed?

Title: Re: StreamReader Problem
Post by: Glenn R on April 11, 2011, 05:19:37 PM
I was wondering do any of you really use XML as a data structure or store data?

Both.