Author Topic: StreamReader Problem  (Read 14556 times)

0 Members and 1 Guest are viewing this topic.

wannabe

  • Guest
Re: StreamReader Problem
« Reply #15 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.

MP

  • Seagull
  • Posts: 17748
  • Have thousands of dwgs to process? Contact me.
Re: StreamReader Problem
« Reply #16 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.
Engineering Technologist CAD Automation Practitioner
Automation ▸ Design ▸ Drafting ▸ Document Control ▸ Client
cadanalyst@gmail.com http://cadanalyst.slack.com http://linkedin.com/in/cadanalyst

wannabe

  • Guest
Re: StreamReader Problem
« Reply #17 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.......... ^-^

MikeTuersley

  • Guest
Re: StreamReader Problem
« Reply #18 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.

Bobby C. Jones

  • Swamp Rat
  • Posts: 516
  • Cry havoc and let loose the dogs of war.
Re: StreamReader Problem
« Reply #19 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.
Bobby C. Jones

It's Alive!

  • BricsCAD
  • Needs a day job
  • Posts: 7047
  • AKA Daniel
Re: StreamReader Problem
« Reply #20 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(','));
    }
  }
}


« Last Edit: April 24, 2009, 10:41:55 PM by Daniel »

pkohut

  • Guest
Re: StreamReader Problem
« Reply #21 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

pkohut

  • Guest
Re: StreamReader Problem
« Reply #22 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

wannabe

  • Guest
Re: StreamReader Problem
« Reply #23 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.



Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: StreamReader Problem
« Reply #24 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 ?

 
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

--> Donate to theSwamp<--

pkohut

  • Guest
Re: StreamReader Problem
« Reply #25 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

wannabe

  • Guest
Re: StreamReader Problem
« Reply #26 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.
« Last Edit: April 25, 2009, 05:20:12 AM by wannabe »

wannabe

  • Guest
Re: StreamReader Problem
« Reply #27 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.

« Last Edit: April 25, 2009, 05:20:06 AM by wannabe »

SEANT

  • Bull Frog
  • Posts: 340
Re: StreamReader Problem
« Reply #28 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.
Sean Tessier
AutoCAD 2016 Mechanical

It's Alive!

  • BricsCAD
  • Needs a day job
  • Posts: 7047
  • AKA Daniel
Re: StreamReader Problem
« Reply #29 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?