Jump to content
Xtreme .Net Talk

joe_pool_is

Avatar/Signature
  • Posts

    512
  • Joined

  • Last visited

Everything posted by joe_pool_is

  1. I've written a Print Screen routine that captures *all* of the information displayed by my project (2 or 3 forms), saves it to a defined image type in a folder that the operator selects, then displays the image in an external viewer. My operators, however, are still trying to use the "Print Screen" key and pasting their images on their own because they forget that my tool is there. So, I want to capture the "Print Screen" key. I've written these two routines and wired them to the MDI Form, but they never fire: void MdiForm_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.PrintScreen) { ScreenCapture(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); e.Handled = true; } } void MdiForm_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e) { if (e.KeyCode == Keys.PrintScreen) { ScreenCapture(Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); } }I'm guessing the problem is that other forms (and their controls) have focus, so the events are being sent to there instead of to my routines. How can I wire up my routine so that I can catch key presses *without* having to wire each and every control to these two events?
  2. That question could take a very large book to answer. Maybe you should say a little more. An Access database can simply be included with your installer. If you want to use an XML file or Excel Spreadsheet for a simple database, they can be created by your application if they do not already exist. If you want to use SQL Server or MySQL, that would likely require a Database Administrator to install and configure.
  3. Sounds like you need to ditch the idea of an MDI application and create a form with multiple panels. Panels can have an order. Why do you need the MDI style if you are forcing forms to be in a specific order? That isn't what an MDI form is for.
  4. I have an application that I have written for my application distributed throughout the company to send data to me through our Windows 2003 server (running IIS 6.0). Small text messages get through, but larger messages containing more data (about 20 KB) are not getting through. I set the byte buffer to the TCP Client�s buffer size. I noticed that my data was being received on the server; however, it only looped through the receive routine once, and my large files were always exactly the size of the buffer size, or 8 KB on our server. In other words, my code only makes it through one loop before the server closes the socket connection. Thinking there might be an issue with filling the whole buffer, I tried limiting my read/writes to just 1 KB but this only resulted in our server closing the socket after receiving 1 KB before closing the connection. I send the server�s error message back to the client so I can view it. The specific error message that I receive from the client is: �Unable to write data to the transport connection: An established connection was aborted by the software in your host machine.� I updated my server application so that the underlying TCP Socket would use �keep alives� with this line: client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true); Now, whenever I attempt sending a message, the client receives the error: �Unable to write data to the transport connection: An existing connection was forcibly closed by the remote host.� Our Network Administrator has told me that he does not have a firewall or any ports blocked on this internal server. Googling the error I received, I found many posts suggesting people try to telnet into the server. I used their directions to telnet into the server, but I am not sure what to make of the response: C:\> telnet Welcome to Microsoft Telnet Client Escape Character is �CTRL+]� Microsoft Telnet> open cpapp 500 Connecting To cpapp� This is all I get. I never get an error, and Microsoft�s Telnet screen will eventually change to �Press any key to continue�� � I guess it times out, but my code is somehow able to connect. I have tried other ports in code and through Telnet including 25, 80, and 8080. Telnet kicks out port 25, but my application seems to read the first loop no matter what port I tell it to run. Here is my code that runs on the clients: int sendUsingTcp(string location) { string result = string.Empty; try { using (FileStream fs = new FileStream(location, FileMode.Open, FileAccess.Read)) { using (TcpClient client = new TcpClient(GetHostIP, CpAppDatabase.ServerPortNumber)) { byte[] riteBuf = new byte[client.SendBufferSize]; byte[] readBuf = new byte[client.ReceiveBufferSize]; using (NetworkStream ns = client.GetStream()) { if ((ns.CanRead == true) && (ns.CanWrite == true)) { int len; string AOK = string.Empty; do { len = fs.Read(riteBuf, 0, riteBuf.Length); ns.Write(riteBuf, 0, len); int nsRsvp = ns.Read(readBuf, 0, readBuf.Length); AOK = Encoding.ASCII.GetString(readBuf, 0, nsRsvp); } while ((len == riteBuf.Length) && (-1 < AOK.IndexOf("AOK"))); result = AOK; return 1; } return 0; } } } } catch (Exception err) { Logger.LogError("Send()", err); MessageBox.Show(err.Message, "Message Failed", MessageBoxButtons.OK, MessageBoxIcon.Hand, 0); return -1; } } Here is my code that runs on the server: SvrForm.Server = new TcpListener(IPAddress.Any, CpAppDatabase.ServerPortNumber); void Worker_Engine(object sender, DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Application.CompanyName); if (Directory.Exists(path) == false) Directory.CreateDirectory(path); Thread.Sleep(0); string eMsg = string.Empty; try { SvrForm.Server.Start(); do { using (TcpClient client = SvrForm.Server.AcceptTcpClient()) { // waits until data is avaiable if (worker.CancellationPending == true) return; client.Client.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, true); string location = Path.Combine(path, string.Format("Acp{0:yyyyMMddHHmmssff}.bin", DateTime.Now)); byte[] buf = new byte[client.ReceiveBufferSize]; try { using (NetworkStream ns = client.GetStream()) { if ((ns.CanRead == true) && (ns.CanWrite == true)) { try { int len; byte[] AOK = Encoding.ASCII.GetBytes("AOK"); using (FileStream fs = new FileStream(location, FileMode.Create, FileAccess.Write)) { do { len = ns.Read(buf, 0, client.ReceiveBufferSize); fs.Write(buf, 0, len); ns.Write(AOK, 0, AOK.Length); } while ((0 < len) && (ns.DataAvailable == true)); } byte[] okBuf = Encoding.ASCII.GetBytes("Message Received on Server"); ns.Write(okBuf, 0, okBuf.Length); } catch (Exception err) { Global.LogError("ServerForm.cs - Worker_Engine(DoWorkEvent)", err); byte[] errBuf = Encoding.ASCII.GetBytes(err.Message); ns.Write(errBuf, 0, errBuf.Length); } } } } finally { client.Close(); } worker.ReportProgress(1, location); } } while (worker.CancellationPending == false); } catch (SocketException) { // See MSDN: Windows Sockets V2 API Error Code Documentation for detailed description of error code e.Cancel = true; } catch (ObjectDisposedException err) { eMsg = "Worker TcpClient Disposed Error:\r\n" + err.Message; e.Cancel = true; e.Result = err; } catch (InvalidOperationException err) { eMsg = "Worker Invalid Operation Error:\r\n" + err.Message; e.Cancel = true; e.Result = err; } catch (ThreadAbortException err) { // If I have to call Abort on this thread eMsg = "Worker Thread Abort Exception:\r\n" + err.Message; SvrForm.Server.Stop(); e.Cancel = true; e.Result = err; } catch (ArgumentNullException err) { eMsg = "Worker Argument Null Error:\r\n" + err.Message; e.Cancel = true; e.Result = err; } catch (ArgumentOutOfRangeException err) { eMsg = "Worker ArgumentOutOfRange:\r\n" + err.Message; e.Cancel = true; e.Result = err; } catch (Exception err) { eMsg = "Worker General Error:\r\n" + err.Message; e.Cancel = true; e.Result = err; } finally { SvrForm.Server.Stop(); } } Why doesn�t my application continue reading from the TCP Client? Have I neglected to set something that tells the Socket to stay open until I have finished? The server code never sees an exception because the TCP Client is never stopped, so I know there is no error. Our Network Administrator has not received his Associates Degree yet, so if it turns out to be an issue with the Server, kindly be detailed in your description of how to resolve this, because we might not understand what you�re saying. Thanks for helping! ~Joe
  5. I've got nice a nice piece of software that can serialize and deserialize settings from my project just fine on one PC, but I need to be able to deserialize the file on another PC running a similar (but different) application. I've searched here and online, and it seems I need to use "Assembly.LoadFile(string pathToAssembly)," but are there any directions on how to do this? I'm not sure how to get the path to the assembly if it is running on another PC. Would this require each PC to have a static IP that I could ping and get this information (our network administrator wouldn't go for that). Should I deploy the assembly for the other PC with this application? Would I call this when my form loads or specify it as part of my deserialize routine? Both projects are in the same VS2005 solution, and both projects use the same Strong Name Key. Any guidance is appreciated. Is example code needed? It's just the same, boring binary deserialize routine found all over the web. I'm just trying to use the TCP connection to send files from the creation software to the production software, open that file in a "ready to use" state, and start acting on it. Regards, Joe
  6. OK, thanks. I like the clean look of the using statement (must have MSG in it, because it is addictive), and I wanted to use it in my class. To use "using" though, I had to implement IDisposable, which was new, virgin territory for me as a developer.
  7. I have recreated System.Net.Mail.Message, because Microsoft did not see a reason to implement the Serializable feature. It looks like everything in Microsoft's Mail.Message class can be duplicated by organizing and naming strings appropriately. I want to implement IDispose in my class so that it cleans itself up nicely, and (with the way I designed my class) all I need to dispose of are strings! My email attachments are loaded from the local PC using a Stream Reader, then loaded into a string buffer (which gives me a 2 GB capacity - I'm hoping this is going to work, but it is still being developed). My custom Message object handles attachments by creating a List of MyAttachments like so: List<MyAttachment> Attachments When I dispose of the resources used by my mail message model, how should I handle the strings? Take the attachments, for example - Should I: Set each String to an Empty String (i.e. attachment = string.Empty)? Set the String to NULL (i.e attachment = null)? Clear the List [i.e. Attachments.Clear()]? A combination of above? Or, are strings managed (i.e. I don't need to do anything)? I would show the code, but I had to create a Mail Address class and an Attachment class to enable my Mail Message class to look like Microsoft's version (makes it easy to learn), so there are several lines of code and I've commented it well. Perhaps one day, I'll post it on CodeProject... For now, here's my snippet of disposing related code: #region IDisposable Members ~JpMessage() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } // If disposing equals false, the method has been called by the // runtime from inside the finalizer and you should not reference // other objects. Only unmanaged resources can be disposed. protected virtual void Dispose(bool disposing) { if (this._disposed == false) { if (disposing == true) { if (!_from.IsDisposed) _from.Dispose(); if (!_replyTo.IsDisposed) _replyTo.Dispose(); if (!_sender.IsDisposed) _sender.Dispose(); foreach (JpMailAddress obj in _bcc) { if (!obj.IsDisposed) obj.Dispose(); } foreach (JpMailAddress obj in _cc) { if (!obj.IsDisposed) obj.Dispose(); } foreach (JpMailAddress obj in _to) { if (!obj.IsDisposed) obj.Dispose(); } foreach (JpAttachment obj in _attachments) { if (!obj.IsDisposed) obj.Dispose(); } } } _disposed = true; } #endregion
  8. I've built an application that reads data from a table, and populates that data into a series of DataGridView (DGV) controls. DataTable table = new DataTable(); SqlDataAdapter da = new SqlDataAdapter(sqlText, sqlConnection); da.Fill(table); DataGridViewX.DataSource = table.DefaultView(); Simple. There is a lot of data, so I've had to limit the amount that I read in, because I can quickly exceed WinXP's 2GB per user limit. In Task Manager, I can see that my App takes up about 17MB (megabytes) while at the IDE, jumps to roughly 24MB in debug mode, then quickly approaches my limit as I pull in data from tables. What I'm working on to keep pulling in data is to take each table and export it to an Excel file in the next (unshown) line of code. For now, the DGV controls are still there. Here's the interesting part: Say I pull in 7 tables (which I did recently), populate 7 different DGV controls and create 7 different Excel files. It all works, but Task Manager now shows that my App is at about 1.7GB whereas the folder where I saved the Excel files shows that all 7 files only add up to about 25MB. Why are the DGV controls so bloated? I know they are powerful and fast, but does this mean they store multiple versions of the data in memory or something?
  9. I just wanted to say that you did an exellent job of describing your problem and providing visual aids. Wonderful job!
  10. In a background worker that will be running on our Server, I am listening for data in the form of a System.Net.Mail.MailMessage object (including attachments) to come from a client on our LAN. (The client PCs and operators on our manufacturing floor do not have an email program). This is a work in progress, so the Client Side hasn't been written yet. The plan is to save the MailMessage object to a MemoryStream, and send the MemoryStream over the network using TCP. My current obstical comes from finding a way to convert the received MemoryStream back into a MailMessage on the Server (the receiving end) so that the Server can send the message. How do I convert a MemoryStream of data into a MailMessage object? I tried the code below, but the compile time error is "Cannot convert type 'byte[]' to 'System.Net.Mail.MailMessage'". Server Side: try { SvrForm.Server.Start(); TcpClient client = SvrForm.Server.AcceptTcpClient(); // waits for data if (worker.CancellationPending == true) return; NetworkStream stream = client.GetStream(); try { byte[] buf = new byte[client.ReceiveBufferSize]; using (MemoryStream ms = new MemoryStream(buf)) { int len; do { len = stream.Read(buf, 0, client.ReceiveBufferSize); ms.Write(buf, 0, len); } while (len == client.ReceiveBufferSize); byte[] byteFile = ms.GetBuffer(); try { MailMessage email = (MailMessage)byteFile; <= ERROR HERE!!! if (email.From.Address != string.Empty) { SmtpClient client = new SmtpClient("172.16.8.200"); client.Send(email); } } catch (Exception er1) { Console.WriteLine(er1.Message); } ms.Close(); } } finally { stream.Close(); client.Close(); SvrForm.Server.Stop(); } } catch (SocketException) { // See MSDN: // Windows Sockets V2 API Error Code Documentation // for detailed description of error code e.Cancel = true; } catch (ThreadAbortException err) { // If I have to call Abort on this thread eMsg = "Worker Thread Abort Exception:\r\n" + err.Message; e.Cancel = true; } catch (Exception err) { eMsg = "General Error:\r\n" + err.Message; e.Cancel = true; } finally { SvrForm.Server.Stop(); }Any helpful tips on writing the Client Side portion are appreciated as well. Regards, ~Joe
  11. Rats! I was really hoping this thread would answer a similar question I have. Looks like I'll have to actually post my question as a new thread, though.
  12. Spambots. I have never used those, but my understanding of them is that they are used to prevent unauthorized use (or spam) in your emails. Right? The applications all run on Windows PCs or Terminals here at work, and the operator has to be logged in on the machine to use the email tool - and I populate the sender field; they can't change it. I just want to make sure someone doesn't inject harmful HTML into the message. Is that what a spambot would be used for? Could someone enter harmful HTML or Javascript into an email message that would cause the WebBrowser control to screw up?
  13. Hmmm... No security measures have been considered by the software development team (me). I suppose I should look into that. Most messages I create and send through my applications, but I'm also adding the emailing tool so that anyone out on the manufacturing plant can send a message to one of the supervisors after they have clocked into that particular machine. They won't know what they're sending, but I should probably look to ensure no html tags are inserted. Anything else to keep an eye out for?
  14. OK, that's simple enough. So, in my case, when the next message is selected from the list and I want to display the message body, would I simply write that data directly? // untested code void ListView1_SelectedItemChanged(object sender, EventArgs e) { // I'm placing the HTML formatted message in the Tag field. // Is this Good or bad? Does the Tag have a size limit? string message = ListView1.SelectedItems[0].Tag; // I'm guessing I don't have to clear anything first, right? webBrowser1.DocumentText = string.Format("<html><head></head><body>{0}</body></html>", message); }
  15. I'm looking for a simple control (like a Text Box or Rich Text Box) to display formatted HTML in. What I am creating is an email viewer for our server. Someone selects the message, and its Message Body will be filled into the control. The closest thing I can find (in Visual Studio 2005) is the WebBrowser control - but I don't want to give the browser a file to display. I simply want a way to show HTML formatted text (tables, unordered lists, hyperlinks, etc.). Has anyone done something like this? What could I look into as far as research goes?
  16. The application is for engineers working out in the field. They collect data, create projects, build reports from existing data, etc. when they are "off the grid." At the end of the day, they want a Synchronize button that allows them to upload their data while downloading the latest data that has been uploaded from others. I was really hoping someone made a magical connection string that enabled me to just act like my database was sitting right there beside me. I suppose a web service is what I'd want. I've never dipped my toes in that water, though.
  17. I need to access our company's website database from a PC using a Windows Form. We are using VS2008, but current policies restrict us to development under Framework 2.0 (i.e. VS2005). How would I connect to a website's database? Is it just a special connection string or do I need to do more? Questions for further down the road: Our installer uses a Verisign security key that we purchased. 1. Will people see a Windows Firewall message asking them to accept or reject the connection? 2. Can an Installer add this firewall exception (to prevent #1 above)?
  18. Hi Marble_Eater, Up until just a day ago, I could have sworn I tried that once before, and it failed because the Application.Run command was wanted a "new Form1()" param. The only thing I can guess is that I used IntelliSense at some point in the past and noticed that the signature for Application.Run was looking for an ApplicationContext object. Ever since then, it had been learned incorrectly in my mind. I guess I just needed to revisit something I'd learned in the past.
  19. Eureka! This tool works, and I am posting it here for anyone who might have need of something like this. Thanks PlausiblyDamp and Marble_Eater! PostingThread.zip
  20. Wow! You're right. I commented that out, and the hang went away. Well... how will I know when my thread has finished now? I was thinking my routine would join the thread and continue after the thread completed. I don't want to continually poll the IsAlive property.
  21. Rats. I thought I did this right, but my application now hangs when I call Invoke. I'm hoping someone can show me my error from my code (a small 12.9 KB attachment). The solution was created with VS2005, and it will appear to have 2 forms in it when viewed through the Solution Explorer. The forms will not display in the Designer, because they are created using a class that is derived from System.Windows.Form. If someone can take the time to look this over, the small application will hang on Line 25 of the file ZParameters.cs "_owner.Invoke(methInvoker);". Yes, I have created this so that it looks a lot like the BackgroundWorker class, but Windows Mobile does not support this class. I'm trying to create a threading class that sends data back to the main thread as it collects information. Help and Pointers are appreciated. ~Joe PostingThread.zip
  22. Thank you, sir! Often I find myself creating a static class to hold a few choice global variables that I want to be accessible throughout the application. It kills 2 birds with 1 stone if I can put it in the Program.cs file, and I can load it before Form1 shows if I design Form1 with some public properties for setting values before it starts. I just wasn't sure if my apps were missing out of some feature of Windows by calling them with ShowDialog() instead of using Application.Run(). Is there a way to create an instance of my app, set public properties with it, and still use Application.Run() on it? I've tried passing an active form in the past, and I know that doesn't work. Perhaps I could modify the form's constructor to accept an object (like calling Thread.Start() with a parameter).
  23. The standard Windows form starts with Main(). What is the benefit to starting my application this way: [sTAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } as opposed to this way? [sTAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 form = new Form1(); form.ShowDialog(); } Also, I've looked up what a STAThread is (Single Threaded Apartment), but I don't really understand what it is or why I should be using this instead of something else. The help for it says it pertains to applications that use COM interop "if the thread actually makes a call to a COM component." Huh? Could someone break it down for me?
  24. THANK YOU! I do not use delegates on a daily basis, but I have found myself using them more as I become more familiar with them. A distinction between Control.Invoke and Delegate.Invoke was not something I would have found on my own, and I could not think of a way to test to see if I was actually on a different thread or not. I briefly thought about trying to create handle variables for each of the threads that I could look at in the debugger, but I just did not see any way that Invoke could *not* be working. (Control.Invoke != Delegate.Invoke) was what I was missing. With that, I can look into how to patch my little class. The BackgroundWorker is fabulous, and that's what I started using; however, the files that the code resides in is linked in to the main project along with a Windows Mobile project - and the Windows Mobile (or Compact Framework) does not include a BackgroundWorker. This is a stab at creating something similar. Again, Thank You! What bar can I leave $20 for your beer tab?
×
×
  • Create New...