CSharp/C# >> Print Documents PrintDocument-- what am I doing wrong? Must be something stupid

by Pavel Minaev » Thu, 28 Aug 2008 19:53:03 GMT

On Aug 28, 5:28燼m, J. Moreno < XXXX@XXXXX.COM > wrote:
> raylopez99 < XXXX@XXXXX.COM > wrote:
> > I am running out of printing paper trying to debug this...it has to be
> > trivial, but I cannot figure it out--can you? 燱hy am I not printing
> > text, but just the initial string "howdy"?
>
> There's 4 things wrong with your code...
> ??. the variable myPrintFilename isn't being set to
> ?爋penFileDialog1.FileName 2. You are using Append when you should be
> ?爑sing AppendLine 3. You have the myGlobalStringBuilder after the
> ???sr.ReadLine instead of after the sb.Append (which should be
> ?爏b.AppendLine) 4. You're using Lucinda 48, instead of something
> ?爏maller...

There's one more here. This:

if ((myStream = openFileDialog1.OpenFile()) !=
null)
{
using (myStream)
{
StreamReader sr =
File.OpenText(openFileDialog1.FileName);
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder();
while (s != null)
{
sb.Append(s);
s = sr.ReadLine();

myGlobalStringBuilder.Append(s); //!!! ??? Why is myGlobal not
appending here?
}
sr.Close();
textBox1.Text = sb.ToString(); //this
works, to show the file text on the screen textBox1

}
}

Note how myStream is never actually used. Also, it is pointlessly
initialized outside the using-expression.

CSharp/C# >> Print Documents PrintDocument-- what am I doing wrong? Must be something stupid

by raylopez99 » Fri, 29 Aug 2008 07:58:39 GMT



Privet Pavel!

I thank you for your time. Now since I've seen so many ways to open/
close read/write a text file, I would appreciate the 'right' way.
Even experts (on the net) have disagreed about this.

So, in my last post (the long one, in this thread, from a few minutes
ago), I include a comment: "// this is code that you need to open a
file. Not really relevant for the 'infinite loop' problem above, but
I include for Pavel"

If you can please tell me what parts of this code is not needed to
safely open/close read/write a text file, I would be thankful. This
way, I can put the 'proper' code into my library, and for future
reference not have to worry about it.

I also have done this for binary files, but for now text file is more
important, for this example. My binary files seem to be working (so
are my text files, but I don't like using code that is superfluous or
not needed, as you say).

Spasibo

RL

CSharp/C# >> Print Documents PrintDocument-- what am I doing wrong? Must be something stupid

by J.B. Moreno » Fri, 29 Aug 2008 10:53:57 GMT


This really has nothing to do with the "right" way to open a file, but
rather an unused variable.


myStream can be left out entirely without changing how the program
works.

But if you want to use the "using" statement, and don't want to use
myStream for anything, then replace


using (myStream)
{
StreamReader sr = File.OpenText(openFileDialog1.FileName);
}

With

using (StreamReader sr = File.OpenText(openFileDialog1.FileName))
{
}

And then delete the if where mystream is assigned.

--
J.B. Moreno

CSharp/C# >> Print Documents PrintDocument-- what am I doing wrong? Must be something stupid

by raylopez99 » Fri, 29 Aug 2008 17:48:46 GMT

J.B. Moreno--I did what you suggested and it appears the code works
fine, but, I take it you are sure that this is as 'safe' as before--
what if somebody is reading from the floppy drive and the drive fails
because the floppy disk is taken out of the slot? But I trust you've
thought through this problem. Anyway I wrapped the 'using' with a try/
catch block just to be safer.

I will update my library with your suggestion in mind.

Thanks,

RL

CSharp/C# >> Print Documents PrintDocument-- what am I doing wrong? Must be something stupid

by J.B. Moreno » Sat, 30 Aug 2008 14:25:02 GMT


-snip-

Try/Catch blocks by themselves don't make your code safer, it just
keeps the program from crashing -- that can in fact make it /less/
safe. The same thing applies to the using statement.

The using statement doesn't prevent exceptions, it just disposes of the
object created whether or not there is an exception.

Take a look at this pseudo-code....

bool eraseFile = true;

try {

using (StreamReader sr) {
throw exception;
eraseFile= false;
}
} catch (Exception ex) {
MessageBox.Show("There was a problem");
}

if (eraseFile) {
//code to delete the file...
}

There's a using statement, there's a try/catch block -- is it safer?

--
J.B. Moreno

CSharp/C# >> Print Documents PrintDocument-- what am I doing wrong? Must be something stupid

by raylopez99 » Sat, 30 Aug 2008 19:14:33 GMT


I assume you're asking a rhetorical question, but to show my level of
competence, or lack thereof, it's not obvious to me that the code you
posted is not safer. So I would vote yes, it is safer.

Anyway, thanks for your input.

RL

Similar Threads

1. Print Documents PrintDocument-- what am I doing wrong? Must be something stupid

I am running out of printing paper trying to debug this...it has to be
trivial, but I cannot figure it out--can you?  Why am I not printing
text, but just the initial string "howdy"?

On the screen, when I open a file, the entire contents of the file is
in fact being shown...so why can't I print it later?  All of this code
I am getting from a book (Chris Sells) and the net.  The solution is
to be found in the fact that stringbuilder is not retaining
information outside the 'using' bracket, despite the fact I made it
'global'.

Keyword search //!!! below to see where I think the problem lies.

RL

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;


namespace MyNameSpace1
{
    public partial class MyForm : Form
    {
        string myPrintFilename;
        StringBuilder myGlobalStringBuilder;  //!!! this is supposed
to be global to the form MyForm, right?

        string strModified; // = String.Copy(strOriginal); //not used

        public MyForm()
        {
            InitializeComponent();
            myGlobalStringBuilder = new StringBuilder("howdy"); //!!!
the only thing that gets printed is 'howdy'!

        }

        private void toolStripButton1_Click(object sender, EventArgs
e)
        {
            Stream myStream;
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Title = "Open text file";
            openFileDialog1.InitialDirectory = @"c:\";
            openFileDialog1.Filter = "txt files (*.txt)|*.txt|All
files (*.*)|*.*";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    if ((myStream = openFileDialog1.OpenFile()) !=
null)
                    {
                        using (myStream)
                        {
                            StreamReader sr =
File.OpenText(openFileDialog1.FileName);
                            string s = sr.ReadLine();
                            StringBuilder sb = new StringBuilder();
                            while (s != null)
                            {
                                sb.Append(s);
                                s = sr.ReadLine();
 
myGlobalStringBuilder.Append(s); //!!! ???  Why is myGlobal not
appending here?
                            }
                            sr.Close();
                            textBox1.Text = sb.ToString(); //this
works, to show the file text on the screen textBox1

                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: could not read file from
disk (myStream); Err: " + ex.Message);
                }
            }
        }

        private void printToolStripButton_Click(object sender,
EventArgs e)
        {
            if (myPrintFilename != "")
            {
                this.printDocument1.DocumentName =
this.myPrintFilename;

            this.printDocument1.Print();
            }
        }

        private void printDocument1_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
        {
            //p. 292 Chris Sells
            //draw to the e.Graphics object that wraps the print
target

            Graphics g = e.Graphics;
            using (Font font = new Font("Lucida Console", 48) )
            {
                string mylocalstring;

                mylocalstring =
myGlobalStringBuilder.ToString(); //!!! only prints "Howdy"--the
initial string--never the appended string from myGlobalStringBuilder--
why?

                if (myGlobalStringBuilder.Length != 0)
                {
                    g.DrawString(mylocalstring, font, Brushes.Blue, 0,
0);
                }
            }

           }


    }
}



2. Print Documents PrintDocument-- what am I doing wrong? Must be so - CSharp/C#

3. Print Documents PrintDocument-- what am I doing wrong? Must be so

Set a breakpoint in printDocument1_PrintPage, at the line where 
"mylocalstring" is set.  I believe you will see that the value is correct for 
"myStringBuilder".  The lack of carriage returns will hide the fact that the 
string is correct when printed.  I believe it is going off the page.  The 
print document functions won't fix newlines, wrapping, etc.  Also, you need 
to worry about the next page when the text is long.  Printing is very 
complicated in .net, until you get the hang of it...

"raylopez99" wrote:

> I am running out of printing paper trying to debug this...it has to be
> trivial, but I cannot figure it out--can you?  Why am I not printing
> text, but just the initial string "howdy"?
> 
> On the screen, when I open a file, the entire contents of the file is
> in fact being shown...so why can't I print it later?  All of this code
> I am getting from a book (Chris Sells) and the net.  The solution is
> to be found in the fact that stringbuilder is not retaining
> information outside the 'using' bracket, despite the fact I made it
> 'global'.
> 
> Keyword search //!!! below to see where I think the problem lies.
> 
> RL
> 
> using System;
> using System.Collections.Generic;
> using System.ComponentModel;
> using System.Data;
> using System.Drawing;
> using System.Linq;
> using System.Text;
> using System.IO;
> using System.Windows.Forms;
> using System.Diagnostics;
> 
> 
> namespace MyNameSpace1
> {
>     public partial class MyForm : Form
>     {
>         string myPrintFilename;
>         StringBuilder myGlobalStringBuilder;  //!!! this is supposed
> to be global to the form MyForm, right?
> 
>         string strModified; // = String.Copy(strOriginal); //not used
> 
>         public MyForm()
>         {
>             InitializeComponent();
>             myGlobalStringBuilder = new StringBuilder("howdy"); //!!!
> the only thing that gets printed is 'howdy'!
> 
>         }
> 
>         private void toolStripButton1_Click(object sender, EventArgs
> e)
>         {
>             Stream myStream;
>             OpenFileDialog openFileDialog1 = new OpenFileDialog();
>             openFileDialog1.Title = "Open text file";
>             openFileDialog1.InitialDirectory = @"c:\";
>             openFileDialog1.Filter = "txt files (*.txt)|*.txt|All
> files (*.*)|*.*";
> 
>             if (openFileDialog1.ShowDialog() == DialogResult.OK)
>             {
>                 try
>                 {
>                     if ((myStream = openFileDialog1.OpenFile()) !=
> null)
>                     {
>                         using (myStream)
>                         {
>                             StreamReader sr =
> File.OpenText(openFileDialog1.FileName);
>                             string s = sr.ReadLine();
>                             StringBuilder sb = new StringBuilder();
>                             while (s != null)
>                             {
>                                 sb.Append(s);
>                                 s = sr.ReadLine();
>  
> myGlobalStringBuilder.Append(s); //!!! ???  Why is myGlobal not
> appending here?
>                             }
>                             sr.Close();
>                             textBox1.Text = sb.ToString(); //this
> works, to show the file text on the screen textBox1
> 
>                         }
>                     }
>                 }
>                 catch (Exception ex)
>                 {
>                     MessageBox.Show("Error: could not read file from
> disk (myStream); Err: " + ex.Message);
>                 }
>             }
>         }
> 
>         private void printToolStripButton_Click(object sender,
> EventArgs e)
>         {
>             if (myPrintFilename != "")
>             {
>                 this.printDocument1.DocumentName =
> this.myPrintFilename;
> 
>             this.printDocument1.Print();
>             }
>         }
> 
>         private void printDocument1_PrintPage(object sender,
> System.Drawing.Printing.PrintPageEventArgs e)
>         {
>             //p. 292 Chris Sells
>             //draw to the e.Graphics object that wraps the print
> target
> 
>             Graphics g = e.Graphics;
>             using (Font font = new Font("Lucida Console", 48) )
>             {
>                 string mylocalstring;
> 
>                 mylocalstring =
> myGlobalStringBuilder.ToString(); //!!! only prints "Howdy"--the
> initial string--never the appended string from myGlobalStringBuilder--
> why?
> 
>                 if (myGlobalStringBuilder.Length != 0)
>                 {
>                     g.DrawString(mylocalstring, font, Brushes.Blue, 0,
> 0);
>                 }
>             }
> 
>            }
> 
> 
>     }
> }
> 
> 
> 
> 

4. slow exe, am I doing something wrong? - CSharp/C#

5. Am I doing something wrong? (Variables)

Hiya all,

I am developing a windows form application. I am coding in C#. What I have
is two forms/Classes, frmMain & frmAdd and they both have the same default
namespace "Q.A._Testing_Centre". In frmMain I have initialize & instantiated
my variable as "public string userName", where the user input name is
stored. I am trying to get the stored data propertied from my frmMain to my
frmAdd. I thought this is the correct syntex for outputting the info in my
textbox (scratching my head), maybe it's not. So please let me know if you
can help, or where I'm going wrong. Code is as follows:

namespace Q.A._Testing_Centre
{
public class frmMain : System.Windows.Forms.Form
{
public string userName; <<<---- I want the data from here
...
...
...


namespace Q.A._Testing_Centre
{
public class frmAdd : System.Windows.Forms.Form
{
private void SubMainMenu()
{
frmMain Main = new frmMain();
txtBoxSample.Text = Convert.ToString(Main.userName);<<<--- to output in my
textbox here
...
...
...


I have tried a sample textbox with in frmMain and this data is in fact
stored until I exit my program. But I cannot seem to reproduce the same
textbox output in frmAdd. I seem to get a blank textbox area. Alternatively
I have try "txtBoxSample.Text = Main.userName" syntex which does not work as
well.
Or maybe if someone has a better alternative, please feel free to let me
know.

All help is truly appreciated & thank you all in advance.

MikeY



6. Print Documents PrintDocument-- (PrintDocument is much harder than it looks) - CSharp/C#

7. What am I doing wrong with LINQ and XML

I have an xml fragment that looks like this assigned to doc variable:
<charge_details>
        <charge>
          <type>Maintenance Charge</type>
          <currency>GBP</currency>
          <percentage>0.35000</percentage>
          <frequency>Monthly</frequency>
          <term>31</term>
          <lower_bound>500000.00</lower_bound>
          <upper_bound>999999.99</upper_bound>
        </charge>
        <charge>
          <type>Maintenance Charge</type>
          <currency>GBP</currency>
          <percentage>0.35000</percentage>
          <frequency>Monthly</frequency>
          <term>31</term>
          <lower_bound>500000.00</lower_bound>
          <upper_bound>999999.99</upper_bound>
        </charge>
        <charge>
          <type>Quarterly Admin Charge</type>
          <currency>GBP</currency>
          <percentage>22.00000</percentage>
          <frequency />
        </charge>
        <charge>
          <type>Dealing Settlement Charge</type>
          <currency>GBP</currency>
          <charge_amount>22.00</charge_amount>
          <frequency />
        </charge>
      </charge_details>

I have a LINQ query that looks like this:
IList<PolicyTerm> policyTerms = (from MMPPolicyTerms in 
doc.Elements("charge_details").Elements("charge")
											 select new PolicyTerm
											 {
												 PolicyTermType = 
(PolicyTermType)(StringEnum.Parse(typeof(PolicyTermType), 
MMPPolicyTerms.Element("type").Value)),
												 Percentage = (double?)MMPPolicyTerms.Element("percentage") ?? 
0.00,
												 Currency = (string)MMPPolicyTerms.Element("currency") ?? 
string.Empty,
												 Amount = (double?)MMPPolicyTerms.Element("charge_amount") ?? 
0.00,
												 Term = (string)MMPPolicyTerms.Element("term") ?? string.Empty
											 }).ToList();

And I keep getting an exception being thrown...I'm assuming because some of 
the nodes aren't always there?
I thought I would be able to get around it by using the ?? operator.

The class PolicyTerm is asimple one that looks like this:
public class PolicyTerm
	{
		public PolicyTermType PolicyTermType { get; set; }
		public double? Percentage { get; set; }
		public double? Amount { get; set; }
		public string Currency { get; set; }
		public string Term { get; set; }
	}


Does anyone have any suggestions as to what I can do to avoid this? I know I 
can choose not to use ToList but then I just get the error thrown when I 
enumerate when I bind on the front end :(

8. What am I doing wrong with GCHandle here... - CSharp/C#