Updates from June, 2010 Toggle Comment Threads | Keyboard Shortcuts

  • arturito 11:37 am on June 14, 2010 Permalink | Reply  

    Accesing shared mailbox in Exchange Web Services 2007 Service Pack 1 and downloading attachments with C# 

    In one of the previous articles I presented a sample code which allows to download attachments from email in Microsoft Exchange Server 2003 using WebDAV.
    However, with Microsoft exchange 2007 it can be achieved by using Exchange Web Service (EWS). In order to authenticate, user requires
    webmail access. Here is the sample code that allows to access mail resources of the shared mailbox.
    	    ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
                NetworkCredential cred = new NetworkCredential("username", "password", "domain");
                Uri url = new Uri(@"https://server/EWS/Exchange.asmx");
                service.Url = url;
                service.Credentials = cred;
    
                //Mailbox mb = new Mailbox("artur.kedzior@ext.oami.europa.eu");
                Mailbox mb = new Mailbox("sharedmailbox@yourcompany.com");
    
                FolderId fid1 = new FolderId(WellKnownFolderName.Inbox, mb);
    
                // Add a search filter that searches on the body or subject.
                List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
                searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Financial Reports"));
                SearchFilter searchFilter = new SearchFilter.SearchFilterCollection(LogicalOperator.Or, searchFilterCollection.ToArray());
    
                // Create a view with a page size of 10.
                ItemView view = new ItemView(10);
    
                // Identify the Subject and DateTimeReceived properties to return.
                // Indicate that the base property will be the item identifier
                view.PropertySet = new PropertySet(BasePropertySet.IdOnly, ItemSchema.Subject, ItemSchema.DateTimeReceived);
    
                // Order the search results by the DateTimeReceived in descending order.
                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Ascending);
    
                // Set the traversal to shallow. (Shallow is the default option; other options are Associated and SoftDeleted.)
                view.Traversal = ItemTraversal.Shallow;
    
                FindItemsResults<Item> findResults = service.FindItems(fid1, searchFilter,view);
                foreach (Item item in findResults.Items)
                {
                    EmailMessage message = EmailMessage.Bind(service, item.Id, new PropertySet(BasePropertySet.IdOnly, ItemSchema.Attachments));
    
                    foreach (Attachment attachment in message.Attachments)
                    {
                        if (attachment is FileAttachment)
                        {
                            FileAttachment fileAttachment = attachment as FileAttachment;
    
                            // Load the file attachment into memory and print out its file name.
                            fileAttachment.Load();
                            Console.WriteLine("Attachment name: " + fileAttachment.Name);
    
                            // Stream attachment contents into a file.
                            FileStream theStream = new FileStream("D:\\Downloads\\Attachments\\" + fileAttachment.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                            fileAttachment.Load(theStream);
                            theStream.Close();
                            theStream.Dispose();
                        }
                        else // Attachment is an item attachment.
                        {
                            // Load attachment into memory and write out the subject.
                            ItemAttachment itemAttachment = attachment as ItemAttachment;
                            itemAttachment.Load();
                            Console.WriteLine("Subject: " + itemAttachment.Item.Subject);
                        }
                    }
                }
    
     
    • CJ 5:08 pm on August 10, 2010 Permalink | Reply

      Hi,

      Thanks for this posting. I had a request from a client of mine. They wanted to filter the attached email by the subject line. Which is the itemAttachment.Item.subject in your code. Then load the file attachment based on the subject line of the attached email to a folder that was named after the subject line. Since the email that they received could have multiple emails attached to them, and each attached email could have multiple attached files asscoiated. I am trying to figure out a way to link the item attachment with the file attachment in the attached email and group them by the item attachment subject.

      Would you please give me some pointers on how to implement this?

      Thanks in advance,

      - CJ

    • arturito 4:39 pm on August 11, 2010 Permalink | Reply

      To be honest I’ve never had a need to do it.

      But you could possibly compare the FileAttachment.ContentId with ItemAttachment.ContentId.

      http://msdn.microsoft.com/en-us/library/dd636130(v=EXCHG.80).aspx

      http://msdn.microsoft.com/en-us/library/microsoft.exchange.webservices.data.fileattachment_members(v=EXCHG.80).aspx

      Hope this helps!

  • arturito 12:15 pm on May 20, 2010 Permalink | Reply  

    C# ASP.NET Ajax AutoCompleteExtender with AjaxControlToolkit 

    Here is a tutorial on how to create autocomplete using AjaxControlToolkit

    Create ASP.NET Web Application and paste this code:

        <div>
            <asp:TextBox ID="TextBox1" runat="server" ></asp:TextBox>
            <asp:AutoCompleteExtender ID="AutoCompleteExtender1"
                                      runat="server"
                                      TargetControlID="TextBox1"
                                      ServicePath="AutoCompleter.asmx"
                                      ServiceMethod="GetFilmTitles"
                                      MinimumPrefixLength="1"
                                      Enabled="true"
                                      EnableCaching="true"
            >
            </asp:AutoCompleteExtender>
        </div>
    

    Add WebService to the project and call it AutoCompleter.

    Paste this code:

    
    [WebService(Namespace = "http://tempuri.org/")]
    
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    
    [ToolboxItem(false)]
    
    [ScriptService]
    
    public class AutoCompleter : System.Web.Services.WebService
    
    {
    
    [WebMethod]
    
    [ScriptMethod()]
    
    public string[] GetFilmTitles(string prefixText)
    
    {
    
    ArrayList sampleList = new ArrayList();
    
    sampleList.Add("Akira");
    
    sampleList.Add("Afro Samurai");
    
    sampleList.Add("Gantz");
    
    sampleList.Add("Naruto");
    
    sampleList.Add("Darker Than Black");
    
    sampleList.Add("Monster");
    
    sampleList.Add("Death Note");
    
    sampleList.Add("Berkserk");
    
    sampleList.Add("Evangelion");
    
    sampleList.Add("Full Metal Alchemist");
    
    sampleList.Add("One Piece");
    
    sampleList.Add("Elfen Lied");
    
    sampleList.Add("Ghost In The Shell");<span style="white-space: pre;"> </span>
    
    ArrayList filteredList = new ArrayList();
    
    foreach (string s in sampleList)
    
    {
    
    if (s.ToLower().StartsWith(prefixText.ToLower()))
    
    filteredList.Add(s);
    
    }
    
    return (string[])filteredList.ToArray(typeof(string));
    
    }
    
    }
    

    and vuala! :)

     
    • Anjana 8:11 am on June 29, 2010 Permalink | Reply

      AutoCompleteExtender is getting hide from other dropdown control which is just below the AutoCompleteExtender

      • arturito 8:51 am on July 4, 2010 Permalink | Reply

        You mean the top AutoCompleter goes under the one which is below? In that case it is the matter of changing css property: z-index. (I had exactly the same problem :) )

  • arturito 9:54 am on May 14, 2010 Permalink | Reply  

    Sending emails via Microsoft Exchange 2003 using WebDav 

    Here is the sample of the code that I have been using to send emails vai Exchange 2003 using WebDAV.
    Domain user that authenticates  against mailbox need to have permissions to access webmail.

    	   static void Sendmail(string server,string alias,string password,string domain, string to, string subject,string text)
            {
                System.Net.HttpWebRequest PUTRequest;
                System.Net.HttpWebRequest PUTRequest1;
                System.Net.WebResponse PUTResponse;
                System.Net.WebResponse PUTResponse1;
                System.Net.HttpWebRequest PROPPATCHRequest;
                System.Net.WebResponse PROPPATCHResponse;
                System.Net.HttpWebRequest MOVERequest;
                System.Net.WebResponse MOVEResponse;
                System.Net.CredentialCache MyCredentialCache;
                string strMailboxURI = "http://"+server+"/Exchange/";
                string strSubURI = "http://" + server + "Exchange/";
                string strTempURI = "http://" + server + "/Exchange/";
                string strServer = server;
                string strPassword = password;
                string strDomain = domain;
                string strAlias = alias;
                string strTo = to;
                string strSubject = subject;
                string strText = text;
                string strBody = "";
                byte[] bytes = null;
    
                System.IO.Stream PUTRequestStream = null;
    
                try
                {
                    // Build the mailbox URI.
    
                    strMailboxURI = "http://" + strServer + "/exchange/" + strAlias;
    
                    // Build the submission URI for the message. If Secure
                    // Sockets Layer (SSL) is set up on the server, use
                    // "https://" instead of "http://".
    
                    strSubURI = "http://" + strServer + "/exchange/" + strAlias +
                               "/##DavMailSubmissionURI##/";
                    // Build the temporary URI for the message. If SSL is set
                    // up on the server, use "https://" instead of "http://".
                    strTempURI = "http://" + strServer + "/exchange/" + strAlias + "/drafts/" +
                                   strSubject + ".eml/";
    
                    // Construct the RFC 822 formatted body of the PUT request.
                    // Note: If the From: header is included here,
                    // the MOVE method request will return a
                    // 403 (Forbidden) status. The From address will
                    // be generated by the Exchange server.
                    strBody = "To: " + strTo + "\n" +
                             "Subject: " + strSubject + "\n" +
                             "Date: " + System.DateTime.Now +
                             "X-Mailer: test mailer" + "\n" +
                             "MIME-Version: 1.0" + "\n" +
                             "Content-Type: text/plain;" + "\n" +
                             "Charset = \"iso-8859-1\"" + "\n" +
                             "Content-Transfer-Encoding: 7bit" + "\n" +
                             "\n" + strText;
                    // Create a new CredentialCache object and fill it with the network
                    // credentials required to access the server.
                    MyCredentialCache = new System.Net.CredentialCache();
                    MyCredentialCache.Add(new System.Uri(strMailboxURI),
                    "Basic",
                    new System.Net.NetworkCredential(strAlias, strPassword, strDomain)
                    );
    
                    // Create the HttpWebRequest object.
                    PUTRequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(strTempURI);
                    // Add the network credentials to the request.
                    PUTRequest.Credentials = MyCredentialCache;
                    // Specify the PUT method.
                    PUTRequest.Method = "PUT";
                    // Encode the body using UTF-8.
                    bytes = Encoding.UTF8.GetBytes((string)strBody);
                    // Set the content header length. This must be
                    // done before writing data to the request stream.
                    PUTRequest.ContentLength = bytes.Length;
                    // Get a reference to the request stream.
                    PUTRequestStream = PUTRequest.GetRequestStream();
                    // Write the message body to the request stream.
                    PUTRequestStream.Write(bytes, 0, bytes.Length);
                    // Close the Stream object to release the connection
                    // for further use.
                    PUTRequestStream.Close();
                    // Set the Content-Type header to the RFC 822 message format.
                    PUTRequest.ContentType = "message/rfc822";
                    // PUT the message in the Drafts folder of the
                    // sender's mailbox.
                    PUTResponse = (System.Net.HttpWebResponse)PUTRequest.GetResponse();
                    // Create the HttpWebRequest object.
                    MOVERequest = (System.Net.HttpWebRequest)HttpWebRequest.Create(strTempURI);
                    // Add the network credentials to the request.
                    MOVERequest.Credentials = MyCredentialCache;
                    // Specify the MOVE method.
                    MOVERequest.Method = "MOVE";
                    // Set the Destination header to the
                    // mail submission URI.
                    MOVERequest.Headers.Add("Destination", strSubURI);
                    // Send the message by moving it from the Drafts folder of the
                    // sender's mailbox to the mail submission URI.
                    MOVEResponse = (System.Net.HttpWebResponse)MOVERequest.GetResponse();
                    Console.WriteLine("Message successfully sent.");
                    // Clean up.
                    PUTResponse.Close();
                    MOVEResponse.Close();
                }
                catch (Exception ex)
                {
                    // Catch any exceptions. Any error codes from the PUT
                    // or MOVE method requests on the server will be caught
                    // here, also.
                    Console.WriteLine(ex.Message);
                }
            }
    
     
  • arturito 5:45 pm on March 26, 2010 Permalink | Reply  

    C# Saving Email Attachments in Exchange using WebDAV 

    I’ve been trying to find a good way to download messages from Exchange without using CDO or MAPI as the program was  going to run on the server which doesn’t have Outlook installed and admin didn’t want to have it there. I’ve been looking at WebDAV and I sucessfully managed to search emails and extract attachment names. However I failed to download them. I’ve searched a lot on the Internet but I could not find any working solution. I posted qustion on StackOverflow http://stackoverflow.com/questions/2491595/downloading-attachments-from-exchange-with-webdav but I didn’t get any reply so far.

    In desperation I tried this library http://www.independentsoft.de/webdavex/index.html and it works pretty well. The only problem is the library is not free.

    I ended up using code below.

    Exchange version: 2003
    Tool: Visual Studio 2008
    Language: C#

    Important: I have used this code in the program which is accessing Exchange server within Local Network Area.
    I have no idea whether it works for remote connections or not. But it should be :)

    public WebDAV(string mailboxURI,string user, string password, string domain)
    {
    this.strUserName = user;
    this.strPassword = password;
    this.strDomain = domain;
    this.strMailboxURI = mailboxURI;
    this.myCred = new NetworkCredential(this.strUserName, this.strPassword, this.strDomain);
    }
    
    ....
    
    // emlURL - http//server//Exchange/MailboxName/Inbox/SomeMessage.EML/SomeAttachment.xls
    // fileName - new filename
    // path - local path where file will be saved
    // datareceived - optional I normally stick email date here
    
    private void DownloadSingleAttachment(string emlURI, string fileName, string path, string datereceived)
    {
    // Create our request object
    HttpWebRequest Req;
    Req = (HttpWebRequest)WebRequest.Create(emlURI);
    
    try
    {
    // Use Basic Authentication
    CredentialCache myCredentialCache = new CredentialCache();
    myCredentialCache.Add(new System.Uri(emlURI), "NTLM", myCred);
    Req.Credentials = myCredentialCache;</code>
    
    //Add the headers
    Req.Headers.Add("Translate", "f");
    Req.KeepAlive = true;
    Req.AllowAutoRedirect = false;
    Req.Method = "GET";
    
    // Get the response for our request
    HttpWebResponse Resp = (HttpWebResponse)Req.GetResponse();
    
    switch (Resp.ContentType)
    {
    // add here whatever you need
    case "message/rfc822":
    case "application/vnd.ms-excel":
    case "application/octet-stream":
    case "application/pdf":
    case "application/msword":
    case "application/zip":
    
    Stream stm = Resp.GetResponseStream();
    
    // create file
    
    FileStream file = new FileStream(path+fileName, System.IO.FileMode.Create);
    byte[] buffer = new byte[4096];
    int length;
    length = smt.Read(buffer, 0, 4096);
    while (length &gt; 0)
    {
    file.Write(buffer, 0, length);
    length = stm.Read(buffer, 0, 4096);
    }
    file.Close();
    stm.Close();
    
    break;
    case "text/plain":
    case "text/xml":
    
    StreamReader sr = new StreamReader(Resp.GetResponseStream());
    string strResp = sr.ReadToEnd();
    sr.Close();
    
    StreamWriter sw = new StreamWriter(fileName);
    sw.Write(strResp);
    sw.Close();
    
    break;
    }
    Resp.Close();
    }
    catch (Exception)
    {
    throw;
    }
    }
    

    Code I have tried and didn’t work for me.
    I recieved this error:

    The remote server returned an error:  Forbidden.
    
    static void Main(string[] args)
    {
    
    HttpWebRequest Request;
    WebResponse Response;
    CredentialCache MyCredentialCache;
    string attachment = "http://mailserver/Exchange/Username/Inbox/Test.EML/Test.txt";
    string strUserName = "username";
    string strPassword = "password";
    string strDomain = "domain";
    
    try
    {
    //using  HttpWebRequest
    MyCredentialCache = new System.Net.CredentialCache();
    MyCredentialCache.Add(new System.Uri(attachment), "NTLM", new NetworkCredential(strUserName, strPassword, strDomain));
    
    Request = (HttpWebRequest)HttpWebRequest.Create(attachment);
    Request.Credentials = MyCredentialCache;
    Request.Method = "GET";
    Response = (HttpWebResponse)Request.GetResponse();
    }
    catch(Exception ex)
    {
    Console.WriteLine(ex.Message.ToString());
    }
    
    try
    {
    //using Web Client
    string downloadPath = "D:\\Downloads";
    
    WebClient wcClient = new WebClient();
    wcClient.Credentials = new NetworkCredential(strUserName, strPassword, strDomain);
    string file = Path.GetFileName(attachment);
    string filename = Path.Combine(downloadPath, file);
    wcClient.DownloadFile(attachment, filename);
    }
    
    catch (Exception ex)
    {
    Console.WriteLine(ex.Message.ToString());
    }
    Console.ReadLine();
     }
    

    If anyone would like to see the rest of this class, which searches emails and scans for attachements I can post it here but it is pretty much the same code as in documentation on Microsoft website.

    Hope that someone will find it useful. :)

     
    • Michael 6:04 pm on August 2, 2010 Permalink | Reply

      This was a great article. Finally got me headed in the right direction. I really need to see the code which searches emails and scans for attachements. You can email me directly if you prefer. moconnor@directalliance.com

    • arturito 7:49 am on August 4, 2010 Permalink | Reply

      Micheal – I have sent you an email with code samples. Good Luck!

    • Bablo 8:00 pm on September 1, 2010 Permalink | Reply

      Can you please email me the code too at my email

      • arturito 9:04 am on September 3, 2010 Permalink | Reply

        Since some people have been asking it, I will publish it here.

  • arturito 1:27 pm on March 12, 2010 Permalink | Reply  

    Reading large text files with C# and Visual Studio 2008 

    I managed to read text file with 200 000 lines within 4 seconds.
    on Pentium 4 2.4GHZ with 500MB of RAM (Virtual Machine)


    // this code assumes the following using statements
    // using System.IO;
    // using System.Text.RegularExpressions;

    StreamReader sr = new StreamReader(openFileDialog1.FileName);
    string[] arr = Regex.Split(sr.ReadToEnd(), @"\r\n");
    sr.Close();
    foreach(string s in arr) {
    if (s.Contains("SOMEWORD"))
     {                            
    tbLog.AppendText(s.Trim() + Environment.NewLine);
    }

    }

    Source:

    http://www.dotnet2themax.com/ShowContent.aspx?ID=4ee44d6c-79a9-466d-ab47-56bba526534f

     
c
compose new post
j
next post/next comment
k
previous post/previous comment
r
reply
e
edit
o
show/hide comments
t
go to top
l
go to login
h
show/hide help
esc
cancel