topbanner_forum
  *

avatar image

Welcome, Guest. Please login or register.
Did you miss your activation email?

Login with username, password and session length
  • Thursday March 28, 2024, 7:10 am
  • Proudly celebrating 15+ years online.
  • Donate now to become a lifetime supporting member of the site and get a non-expiring license key for all of our programs.
  • donate

Last post Author Topic: Check Gmail using C#  (Read 48041 times)

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #25 on: December 04, 2010, 09:58 AM »
Used this FTP code, but got the error shown below:

Code: C# [Select]
  1. string FTPAddress = "ftp://glensforkumc.com/non_church";
  2.             FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FTPAddress + "/UploadDownload.pdb");
  3.  
  4.             request.Method = WebRequestMethods.Ftp.UploadFile;
  5.             request.Credentials = new NetworkCredential(username, password);
  6.             request.UsePassive = true;
  7.             request.UseBinary = true;
  8.             request.KeepAlive = false;
  9.  
  10.             FileStream stream = File.OpenRead("UploadDownload.pdb");
  11.             byte[] buffer = new byte[stream.Length];
  12.  
  13.             stream.Read(buffer, 0, buffer.Length);
  14.             stream.Close();
  15.  
  16.             try {
  17.                 Stream reqStream = request.GetRequestStream();
  18.                 reqStream.Write(buffer, 0, buffer.Length);
  19.                 reqStream.Close();
  20.             }
  21.             catch (Exception ex) {
  22.                 MessageBox.Show(ex.Message);
  23.             }

error3.png
« Last Edit: December 04, 2010, 10:39 AM by kyrathaba »

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #26 on: December 04, 2010, 08:10 PM »
I spent some time this afternoon experimenting.  Hacked out this code that seems to work (see class code-listing below).  Note: allows uploading to specific directory on your website, downloading from a specific directory to a specific local directory, and has ability to return a list of files found in the root of any directory.  I also posted a copy of the code on my DC C# Errata.

Code: C# [Select]
  1. public class FTPClient {
  2.  
  3.         // The hostname or IP address of the FTP server
  4.         private string _remoteHost;
  5.  
  6.         // The remote username
  7.         private string _remoteUser;
  8.  
  9.         // Password for the remote user
  10.         private string _remotePass;
  11.  
  12.         public FTPClient(string remoteHost, string remoteUser, string remotePassword) {
  13.             _remoteHost = remoteHost;
  14.             _remoteUser = remoteUser;
  15.             _remotePass = remotePassword;
  16.         }
  17.  
  18.         public string DirectoryListing() {
  19.             FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost);
  20.             request.Method = WebRequestMethods.Ftp.ListDirectory;
  21.             request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
  22.             FtpWebResponse response = (FtpWebResponse)request.GetResponse();
  23.             Stream responseStream = response.GetResponseStream();
  24.             StreamReader reader = new StreamReader(responseStream);
  25.  
  26.             string result = string.Empty;
  27.  
  28.             while (!reader.EndOfStream) {
  29.                 result += reader.ReadLine() + Environment.NewLine;
  30.             }
  31.  
  32.             reader.Close();
  33.             response.Close();
  34.             return result;
  35.         }
  36.  
  37.  
  38.  
  39.  
  40.         public string DirectoryListing(string folder) {
  41.             FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + folder);
  42.             request.Method = WebRequestMethods.Ftp.ListDirectory;
  43.             request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
  44.             FtpWebResponse response = (FtpWebResponse)request.GetResponse();
  45.             Stream responseStream = response.GetResponseStream();
  46.             StreamReader reader = new StreamReader(responseStream);
  47.  
  48.             string result = string.Empty;
  49.  
  50.             while (!reader.EndOfStream) {
  51.                 result += reader.ReadLine() + Environment.NewLine;
  52.             }
  53.  
  54.             reader.Close();
  55.             response.Close();
  56.             return result;
  57.         }
  58.  
  59.  
  60.         public void Download(string file, string destination) {
  61.             FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + file);
  62.             request.Method = WebRequestMethods.Ftp.DownloadFile;
  63.             request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
  64.             FtpWebResponse response = (FtpWebResponse)request.GetResponse();
  65.             Stream responseStream = response.GetResponseStream();
  66.             StreamReader reader = new StreamReader(responseStream);
  67.  
  68.             StreamWriter writer = new StreamWriter(destination);
  69.             writer.Write(reader.ReadToEnd());
  70.  
  71.             writer.Close();
  72.             reader.Close();
  73.             response.Close();
  74.         }
  75.  
  76.  
  77.  
  78.         public void UploadFile(string FullPathFilename) {
  79.             string filename = Path.GetFileName(FullPathFilename);
  80.  
  81.             FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename);
  82.             request.Method = WebRequestMethods.Ftp.UploadFile;
  83.             request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
  84.  
  85.             StreamReader sourceStream = new StreamReader(FullPathFilename);
  86.             byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
  87.  
  88.             request.ContentLength = fileContents.Length;
  89.  
  90.             Stream requestStream = request.GetRequestStream();
  91.             requestStream.Write(fileContents, 0, fileContents.Length);
  92.  
  93.             FtpWebResponse response = (FtpWebResponse)request.GetResponse();
  94.  
  95.             response.Close();
  96.             requestStream.Close();
  97.             sourceStream.Close();
  98.         }
  99.  
  100.  
  101.  
  102.     }

wraith808

  • Supporting Member
  • Joined in 2006
  • **
  • default avatar
  • Posts: 11,186
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #27 on: December 06, 2010, 08:52 AM »
So, that still doesn't explain why you can't use ftp?  Or is it just that you don't want to?

UPDATE: nevermind... didn't see your last posts :)

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #28 on: December 26, 2010, 02:35 PM »
RESOLVED (see my next post).

An interesting issue has arisen in a project I'm working on:

I've created the "C:/[User]/AppData/Roaming/Kyrathaba/ExcuseManager/" subdirectory programmatically, using:

Directory.CreateDirectory()

So far, so good.

But then, using my Imap code, I try to download email attachments to the above directory, and I get an Unauthorized Access Expression.  Funny, because it just let me create the directory, but it now won't let me download anything to it.

The code referenced by the link above works, if you just create a default Windows Forms project in C#.  Must have something to do with the fact that I'm trying to write a binary file into a subdirectory of /[User]/; must be upsetting UAC or something, because I am able to write simple text files to the directory.  

Any ideas what's going on?
« Last Edit: December 26, 2010, 02:54 PM by kyrathaba »

f0dder

  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,153
  • [Well, THAT escalated quickly!]
    • View Profile
    • f0dder's place
    • Read more about this member.
    • Donate to Member
Re: Check Gmail using C#
« Reply #29 on: December 26, 2010, 02:52 PM »
Hmm.

1) how are you creating the above folder?
2) what kind of app is it, and how is it deployed?

I haven't had to deal with this myself yet, but I guess you might have to look at the SecurityPermissionAttribute stuff. Hopefully there's some help around here :)
- carpe noctem

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #30 on: December 26, 2010, 02:53 PM »
Figured it out: I wasn't adding a filename and extension to the end of the filename I tried to build.  DUH and DOUBLE-DUH!

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #31 on: December 26, 2010, 02:59 PM »
@fodder:  Thanks for being willing to take time and try to help.  Turns out there isn't a problem, except me being inattentive.

If you can programmatically create a subdirectory, you can write a file there, as you'd expect.

f0dder

  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,153
  • [Well, THAT escalated quickly!]
    • View Profile
    • f0dder's place
    • Read more about this member.
    • Donate to Member
Re: Check Gmail using C#
« Reply #32 on: December 26, 2010, 03:03 PM »
Turns out there isn't a problem, except me being inattentive.
Bugs happen ^_^

If you can programmatically create a subdirectory, you can write a file there, as you'd expect.
Well, it's definitely what you'd expect - I was guessing that perhaps the IMAP library was running with more paranoid security settings or something. I should really find the time to read properly about .NET security.
- carpe noctem

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #33 on: January 01, 2011, 02:21 PM »
I have the following functioning code to upload programmatically via FTP in C#:

Code: C# [Select]
  1. public void UploadFile(string FullPathFilename) {
  2.             string filename = Path.GetFileName(FullPathFilename);
  3.  
  4.             try {
  5.  
  6.                 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename);
  7.                 request.Method = WebRequestMethods.Ftp.UploadFile;
  8.                 request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
  9.  
  10.                 StreamReader sourceStream = new StreamReader(FullPathFilename);
  11.                 byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
  12.  
  13.                 request.ContentLength = fileContents.Length;
  14.  
  15.                 Stream requestStream = request.GetRequestStream();
  16.                 requestStream.Write(fileContents, 0, fileContents.Length);
  17.  
  18.                 FtpWebResponse response = (FtpWebResponse)request.GetResponse();
  19.  
  20.                 response.Close();
  21.                 requestStream.Close();
  22.                 sourceStream.Close();
  23.  
  24.             }
  25.             catch (Exception ex) {                
  26.                 MessageBox.Show(ex.Message, "Upload error");
  27.             }
  28.             finally {
  29.  
  30.             }

Now for the problem.  When I use this method in the following button click event, it does upload the file to the desired directory of my website, but then my UI hangs.  I have to kill the program from within the IDE.

Code: C# [Select]
  1. private void btnUploadTxtFile_Click(object sender, EventArgs e) {
  2.  
  3.             string username = "my_username";
  4.             string password = "my_password";
  5.             string host = "ftp://glensforkumc.com";
  6.  
  7.             try {
  8.                 clsFTPclient client = new clsFTPclient(host + "/httpdocs/non_church/", username, password);
  9.                 client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt");
  10.             }
  11.             catch (Exception ex) {
  12.                 MessageBox.Show(ex.Message, "Upload problem");
  13.             }
  14.         }

Doesn't hang when using a similar method to download a file.  Any idea why my UI is freezing up after a successful upload?

f0dder

  • Charter Honorary Member
  • Joined in 2005
  • ***
  • Posts: 9,153
  • [Well, THAT escalated quickly!]
    • View Profile
    • f0dder's place
    • Read more about this member.
    • Donate to Member
Re: Check Gmail using C#
« Reply #34 on: January 01, 2011, 02:40 PM »
Have you tried tracing the UploadFile method in the VS debugger to see if there's any particular line of code that causes a hang?

It's not a good idea doing stuff like this from your UI thread, anyway... you should either schedule the task on a background worker thread, or (better) use Async I/O. I'll refrain from saying anything about having non-ui code in a btnWhatever_Click handler :)
- carpe noctem

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #35 on: January 01, 2011, 02:49 PM »
Good points, all.  I was just doing a quick and dirty test of the UploadFile method is all.  In a full-blown application, I'd have the btnWhatever_Click handler hand off the task to a backgroundWorker object.

Maybe I'll create one and see if that fixes this issue.  Although, in the current case, why does DownloadFile work without hanging the UI, but UploadFile hangs it?  Hmm...

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #36 on: January 01, 2011, 03:09 PM »
Okay, my button Click event now hands the file upload off to a backgroundWorker object running on its own thread:

Code: C# [Select]
  1. private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
  2.             MessageBox.Show("Doing some work...");
  3.             string username = "my_username";
  4.             string password = "my_password";
  5.             string host = "ftp://glensforkumc.com";
  6.             string myLocal = Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt";
  7.             string myRemote = host + "/httpdocs/non_church/";
  8.             clsFTPclient client = new clsFTPclient(host + "/httpdocs/non_church/", username, password);
  9.             client.UploadFile(Path.GetDirectoryName(Application.ExecutablePath) + "\\myTextFile.txt");
  10.  
  11.         }
  12.  
  13.         private void backgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) {
  14.  
  15.             MessageBox.Show("I'm done uploading");
  16.         }

The file does get uploaded, but my RunWorkerCompleted() messageBox never pops up... remove everything except the messageBox from the _DoWork() method above, and it's msgBox (as well as RunWorkerCompleted's msgBox) both fire as expected.

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #37 on: January 01, 2011, 04:26 PM »
Interesting.  The second MessageBox never gets invoked.  At least, I never see it pop up when I run the program click my button to upload the file:

Code: C# [Select]
  1. public void UploadFile(string FullPathFilename) {
  2.             string filename = Path.GetFileName(FullPathFilename);
  3.  
  4.             try {
  5.  
  6.                 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename);
  7.                 request.Method = WebRequestMethods.Ftp.UploadFile;
  8.                 request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
  9.  
  10.                 StreamReader sourceStream = new StreamReader(FullPathFilename);
  11.                 byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
  12.  
  13.                 request.ContentLength = fileContents.Length;
  14.  
  15.                 Stream requestStream = request.GetRequestStream();
  16.                 requestStream.Write(fileContents, 0, fileContents.Length);
  17.  
  18.                 MessageBox.Show("About to make upload request..."); //this one "pops-up", as expected
  19.                 FtpWebResponse response = (FtpWebResponse)request.GetResponse(); //does get invoked (my file DOES get uploaded)
  20.                 MessageBox.Show("Made upload request.  About to close streams..."); //I never see this one
  21.  
  22.                 response.Close();
  23.                 requestStream.Close();
  24.                 sourceStream.Close();
  25.  
  26.             }
  27.             catch (Exception ex) {                
  28.                 MessageBox.Show(ex.Message, "Upload error");
  29.             }
  30.             finally {
  31.  
  32.             }
  33.  
  34.         }

kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #38 on: January 01, 2011, 04:48 PM »
I'll be scratching my head over this one for a while, but it all works as expected now; no inexplicable hanging (even when doing the upload on its own asynch thread, it had 'seemed' to be hanging, in that I got a non-responsive UI):


kyrathaba

  • N.A.N.Y. Organizer
  • Honorary Member
  • Joined in 2006
  • **
  • Posts: 3,200
    • View Profile
    • Donate to Member
Re: Check Gmail using C#
« Reply #39 on: January 01, 2011, 07:10 PM »
I've updated my Snipplr posting here.