C# program will only run on the machine it was built with

I am a n00b when it comes to C#, so please forgive me if this seems dumb.

I have written a very simple C# program.  All it does it take a text file (or files) and dumps it to the printer of the user's choice in Landscape orientation.  The program works fine on my machine, but on any other machine, it bombs with the very generic "Program has performed an illegal operation and must be closed" message.

Here's the kicker.  If I take the unmodified source code and actually build it on a different machine, then it magically works.

Any thoughts as to what's going on here?

Also, a couple of other little boogers... not really problems but I am curious how to fix them:
1)  The print dialog pops up at the bottom of the Z-order, so you have to minimize whatever window you launched the executable from in order to see it.
2)  I cannot figure out how to close the form automatically.  Once the program does its thing, I have a blank window labeled Form1 that I have to close to end the program.  I'd like to not have to do that.

I have attached the source code below, with the form designer code omitted.
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
 
namespace PrintMe
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Drawing.Printing.PrintDocument printDocument1;
		private System.Windows.Forms.PrintDialog printDialog1;
		private System.IO.StreamReader fileToPrint;
		private System.Drawing.Font printFont;
 
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
 
		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
 
			// Allow the user to select a file.
			OpenFileDialog ofd = new OpenFileDialog();
			ofd.Multiselect = true;
			if( DialogResult.OK == ofd.ShowDialog(this) )
			{
				PrintDialog pd  = new PrintDialog();
				PageSetupDialog psd = new PageSetupDialog();
				PageSettings ps = new PageSettings();
				Margins margins = new Margins();
				pd.PrinterSettings = new PrinterSettings();
 
				// Set the margins
				margins.Left = 50;
				margins.Right = 50;
				margins.Top = 50;
				margins.Bottom = 50;
 
				// Adjust the page settings
				ps.Landscape = true;
				ps.Margins = margins;
				psd.PageSettings = ps;
				printDocument1.DefaultPageSettings = ps;
 
				// Allow the user to select the printer
				if( DialogResult.OK == pd.ShowDialog(this) )
				{
					printDocument1.PrinterSettings.PrinterName=pd.PrinterSettings.PrinterName;
					foreach(string printPath in ofd.FileNames)
					{
						fileToPrint = new System.IO.StreamReader(printPath);
						printFont = new System.Drawing.Font("Courier New", 8);
						printDocument1.Print();
						fileToPrint.Close();
					}
				}
			}
		}
 
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
 
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}
 
		private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
		{
			float yPos = 0f;
			int count = 0;
			float leftMargin = e.MarginBounds.Left;
			float topMargin = e.MarginBounds.Top;
			string line = null;
			float linesPerPage = e.MarginBounds.Height/printFont.GetHeight(e.Graphics);
			while (count < linesPerPage)
			{
				line = fileToPrint.ReadLine();
				if (line == null)
				{
					break;
				}
				yPos = topMargin + count * printFont.GetHeight(e.Graphics);
				e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
				count++;
			}
			if (line != null)
			{
				e.HasMorePages = true;
			}
		}
	}
}

Open in new window

LVL 14
cuziyqAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

YiogiCommented:
Can you use a try catch so you can catch the error and the line number? Then post that here it will be easier to give u a solution. Like this in your code:

using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
 
namespace PrintMe
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class Form1 : System.Windows.Forms.Form
	{
		private System.Drawing.Printing.PrintDocument printDocument1;
		private System.Windows.Forms.PrintDialog printDialog1;
		private System.IO.StreamReader fileToPrint;
		private System.Drawing.Font printFont;
 
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;
 
		public Form1()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();
                        try {
     				// Allow the user to select a file.
	 			OpenFileDialog ofd = new OpenFileDialog();
				ofd.Multiselect = true;
				if( DialogResult.OK == ofd.ShowDialog(this) )
				{
					PrintDialog pd  = new PrintDialog();
					PageSetupDialog psd = new PageSetupDialog();
					PageSettings ps = new PageSettings();
					Margins margins = new Margins();
					pd.PrinterSettings = new PrinterSettings();
 	
					// Set the margins
					margins.Left = 50;
					margins.Right = 50;
					margins.Top = 50;
					margins.Bottom = 50;
 	
					// Adjust the page settings
					ps.Landscape = true;
					ps.Margins = margins;
					psd.PageSettings = ps;
					printDocument1.DefaultPageSettings = ps;
 
					// Allow the user to select the printer
					if( DialogResult.OK == pd.ShowDialog(this) )
					{
						printDocument1.PrinterSettings.PrinterName=pd.PrinterSettings.PrinterName;
						foreach(string printPath in ofd.FileNames)
						{
							fileToPrint = new System.IO.StreamReader(printPath);
							printFont = new System.Drawing.Font("Courier New", 8);
							printDocument1.Print();
							fileToPrint.Close();
						}
					}
				}
			}
			catch (Exception ex) {
			   MessageBox.Show(ex.Message + Environment.NewLine + ex.StackTrace);
			}
 
}
 
 
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}
 
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			Application.Run(new Form1());
		}
 
		private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
		{
			try {
 
				float yPos = 0f;
				int count = 0;
				float leftMargin = e.MarginBounds.Left;
				float topMargin = e.MarginBounds.Top;
				string line = null;
				float linesPerPage = e.MarginBounds.Height/printFont.GetHeight(e.Graphics);
				while (count < linesPerPage)
				{
					line = fileToPrint.ReadLine();
					if (line == null)
					{
						break;
					}
					yPos = topMargin + count * printFont.GetHeight(e.Graphics);
					e.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
					count++;
				}
				if (line != null)
				{
					e.HasMorePages = true;
					}
			}
			catch (Exception eX) {
			   MessageBox.Show("Print Page Exception" + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace);
			}
 
 
		}
	}
}
 

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
pwrBallCommented:
In regards to your first issue, do the other machines have the same version of .NET installed?
0
YiogiCommented:
You can also try taking a look in the application and system logs on the other machine. Go to start -> run -> eventvwr
0
Learn SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

cuziyqAuthor Commented:
The text of the exception is as follows:

System.Security.SecurityException: Request for the permission of type 'System.Drawing.Printing.PrintingPermission, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' failed.
   at System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean isPermSet)
   at System.Security.CodeAccessPermission.Demand()
   at System.Drawing.Printing.PrinterSettings.get_PrinterName()
   at PrintMe.Form1..ctor()
The action that failed was:
Demand
The type of the first permission that failed was:
System.Drawinf.Printing.PrintingPermission
The Zone of the assembly that failed was:
Intranet

Does this mean a permissions error?  If that's the case, why would it work if you bult the source on the target machine and then did it?
0
cuziyqAuthor Commented:
Also, all the dev boxes have identical configurations as far as the versions of .NET framework they have.
0
YiogiCommented:
Does that user have any printers installed?
0
cuziyqAuthor Commented:
Yes, and the user prints to the one being selected all the time.
0
pwrBallCommented:
Try adding the following System.Security.PermissionSet

using System;
namespace ConsoleApplication
{
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]

class Program
{
static void Main(string[] args)
{
...
}
}
}


0
pwrBallCommented:
You could also try to modify the runtime security policy to trust the assemblies from
local intranet.
For doing that you have to go to control panel - > Administrative Tools ->
Microsoft .NET Framework 2.0 Configuration and manage your Local Intranet
code group to trust the assembly.
0
cuziyqAuthor Commented:
OK, I've done what you suggested, pwrBall, but now I have another problem.  Another exception is being caught; this time it's the following:

System.ComponentModel.Win32Exception: The handle is invalid
   at System.Drawing.Printing.StandardPrintController.OnEndPrint(PrintDocument document, PrintEventArgs e)
   at System.Windows.Forms.PrintControllerWithStatusDialog.OnEndPrint(PrintDocument document, PrintEventArgs e)
   at System.Drawing.Printing.PrintController.Print(PrintDocument document)
   at System.Drawing.Pringint.PrintDocument.Print()
   at PrintMe.Form1..ctor()

What's going on now?  The thing still works on my workstation, and any other workstation it is built on, but not any other computer.
0
pwrBallCommented:
A side note that might help further this, unless you found a solution.

I was unable to replicate your issue using your code.  The difference might have been that I was Publishing the program with Visual C# and then running the published .exe on the system, essentially installing it.  During publishing a public key was generated and I think that was the key (no pun intended).
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.