Archive for the ‘C sharp’ Category
File and Image Upload with ASP.NET MVC2 with CKEditor WYSIWYG – Rich Text Editor
This tutorial is for CKeditor not FCKeditor.
1. Download it an extract CKeditor
http://ckeditor.com/download
2. Extract it to /Scripts/wysiwyg
3. Create MVC2 project
4. In
<script type="text/javascript" src="<%= Url.Content("~/Scripts/wysiwyg/ckeditor.js")%>"></script>
5. View will look like this:
<!-- Indicate which textarea to be converted to WYSISWG editor --> ...
<div> <%= Html.LabelFor(model => model.Description) %></div>
<div><%= Html.TextAreaFor(model => model.Description, new { @class = "ckeditor" })%>
<%= Html.ValidationMessageFor(model => model.Description) %>
</div>
<!-- Indicate which action is responsible for image upload -->
<script type="text/javascript">
CKEDITOR.replace('Description', {
filebrowserImageUploadUrl: '/UploadImage'
});
</script>
...
6. Controller will look like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UploadImage(HttpPostedFileBase upload,string CKEditorFuncNum, string CKEditor, string langCode) {
string url; // url to return
string message; // message to display (optional)
// here logic to upload image
// and get file path of the image
// path of the image
string path = "Content/Images/my_uploaded_image.jpg";
// will create http://localhost:1457/Content/Images/my_uploaded_image.jpg
url = Request.Url.GetLeftPart(UriPartial.Authority) +"/"+ path;
// passing message success/failure
message = "Image was saved correctly";
// since it is an ajax request it requires this string
string output = @"<html><body><script>window.parent.CKEDITOR.tools.callFunction("+CKEditorFuncNum+", \""+url+"\", \""+message+"\");</script></body></html>";
return Content(output); }
C# Saving Email Attachments in Exchange 2003 using WebDAV Full Example
This is an example of downloading attachments using WebDAV. I took out this code from a bigger program that I wrote and I compiled mini application that accomplishes search of a particular message and downloads attachments. This code complies but I haven’t tried it since I don’t have an access to Exchange 2003 anymore. Also code is written an quick and dirty way so it will need some cleaning etc.
There are 3 classes involved Mail, Attach, WebDav. WebDav class gets all mails placing them in the list of Mail objects. Each Mail object contains a list of Attach objects and the rest becomes easy…
Mail class
public class Mail
{
private string id;
private string from;
private DateTime datereceived;
private string subject;
private string body;
private string mailURI;
private List<attach> attachments;
public Mail()
{
attachments = new List<attach>();
}
public string Id
{
set { this.id = value; }
get { return this.id; }
}
public string From
{
set { this.from = value; }
get { return this.from; }
}
public DateTime DateReceived
{
set { this.datereceived = value; }
get { return this.datereceived; }
}
public string Subject
{
set { this.subject = value; }
get { return this.subject; }
}
public string BodyText
{
set { this.body = value; }
get { return this.body; }
}
public string MailURI
{
set { this.mailURI = value; }
get { return this.mailURI; }
}
public List<attach> Attachments
{
set { this.attachments = value; }
get { return this.attachments; }
}
}
Attach class
public class Attach
{
private string path;
private string filename;
private string extension;
public string Path
{
set { this.path = value; }
get { return this.path; }
}
public string Filename
{
set { this.filename = value; }
get { return this.filename; }
}
public string Extension
{
set { this.extension = value; }
get { return this.extension; }
}
}
WebDAV class
public class WebDAV
{
private string strUserName;
private string strPassword;
private string strDomain;
private string strMailboxURI;
private NetworkCredential myCred;
private CredentialCache MyCredCache;
System.Net.HttpWebRequest Request;
System.Net.WebResponse Response;
System.IO.Stream ResponseStream = null;
System.Xml.XmlDocument ResponseXmlDoc = null;
System.Xml.XmlNode root = null;
System.Xml.XmlNamespaceManager nsmgr = null;
System.Xml.XmlNodeList PropstatNodes = null;
System.Xml.XmlNodeList HrefNodes = null;
System.Xml.XmlNode StatusNode = null;
System.Xml.XmlNode PropNode = null;
System.Xml.XmlNode AttachNode = null;
List<mail> maillist;
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);
}
// filter by message subject
private List<mail> getMailsBySubject(string subject)
{
List<mail> ret = new List<mail>();
ret = this.getAllMails().FindAll(delegate(Mail m) { return m.Subject.Contains(subject); });
ret.Sort(delegate(Mail m1, Mail m2) { return m1.DateReceived.CompareTo(m2.DateReceived); });
ret.Reverse();
return ret;
}
// get all messages
private List<mail> getAllMails()
{
maillist = new List<mail>();
System.IO.Stream RequestStream = null;
System.IO.Stream ResponseStream = null;
XmlDocument ResponseXmlDoc = null;
byte[] bytes = null;
try
{
string strQuery = "<?xml version=\"1.0\"?><d:searchrequest xmlns:D = \"DAV:\">"
+ "<d:sql>SELECT \"urn:schemas:httpmail:sendername\" , \"urn:schemas:httpmail:subject\","
+ " \"urn:schemas:mailheader:from\", \"urn:schemas:httpmail:datereceived\" ,"
+ " \"urn:schemas:httpmail:date\", \"urn:schemas:httpmail:textdescription\" ,"
+ " \"urn:schema:httpmail:attachmentfilename\","
+ " \"urn:schema:httpmail:displayname\","
+ " \"urn:schemas:httpmail:htmldescription\", \"DAV:id\""
+ ", \"DAV:href\""
+ " FROM \"" + strMailboxURI + "\""
+ " WHERE \"DAV:ishidden\" = false AND \"DAV:isfolder\" = false"
+ " </d:sql></d:searchrequest>";
this.MyCredCache = new CredentialCache();
this.MyCredCache.Add(new System.Uri(strMailboxURI), "NTLM", myCred);
Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strMailboxURI);
Request.Credentials = MyCredCache;
Request.Method = "SEARCH";
bytes = Encoding.UTF8.GetBytes((string)strQuery);
Request.ContentLength = bytes.Length;
RequestStream = Request.GetRequestStream();
RequestStream.Write(bytes, 0, bytes.Length);
RequestStream.Close();
Request.ContentType = "text/xml";
Response = (HttpWebResponse)Request.GetResponse();
ResponseStream = Response.GetResponseStream();
ResponseXmlDoc = new XmlDocument();
ResponseXmlDoc.Load(ResponseStream);
// Create a new XmlNamespaceManager.
nsmgr = new System.Xml.XmlNamespaceManager(ResponseXmlDoc.NameTable);
nsmgr.AddNamespace("a", "DAV:");
nsmgr.AddNamespace("d", "http://schemas.microsoft.com/mapi/proptag/");
nsmgr.AddNamespace("e", "urn:schemas:httpmail:");
XmlNodeList mailId = ResponseXmlDoc.GetElementsByTagName("a:id");
XmlNodeList mailFrom = ResponseXmlDoc.GetElementsByTagName("e:from");
XmlNodeList mailReceivedDate = ResponseXmlDoc.GetElementsByTagName("d:datereceived");
XmlNodeList mailSubject = ResponseXmlDoc.GetElementsByTagName("d:subject");
XmlNodeList mailText = ResponseXmlDoc.GetElementsByTagName("d:textdescription");
XmlNodeList mailAttach = ResponseXmlDoc.GetElementsByTagName("f:attachmentfilename");
XmlNodeList mailProp = ResponseXmlDoc.GetElementsByTagName("a:prop");
List<string> href = new List<string>();
for (int i = 0; i < mailProp.Count; i++)
{
for (int j = 0; j < mailProp[i].ChildNodes.Count; j++)
{
//check to see if we have a match
if (mailProp[i].ChildNodes[j].Name == "a:href")
{
href.Add(mailProp[i].ChildNodes[j].InnerText);
}
}
}
if (mailId.Count > 0)
{
for (int i = 0; i < mailId.Count; i++)
{
Mail mail = new Mail();
mail.Id = mailId[i].InnerText;
mail.From = mailFrom[i].InnerText;
mail.Subject = mailSubject[i].InnerText;
mail.BodyText = mailText[i].InnerText;
mail.MailURI = href[i].ToString();
string datetime = mailReceivedDate[i].InnerText;
datetime = datetime.Replace('T', ' ');
int ind = datetime.IndexOf('.');
datetime = datetime.Substring(0, ind);
DateTime date = DateTime.Parse(datetime);
mail.DateReceived = date;
mail.Attachments = this.getAttachments(href[i].ToString());
maillist.Add(mail);
}
}
else
{
Console.WriteLine("No non-folder items found...");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return maillist;
}
// get all attachments of a particular message
private List<attach> getAttachments(string strMessageURI)
{
List<attach> attachlist = new List<attach>();
try
{
MyCredCache = new CredentialCache();
MyCredCache.Add(new System.Uri(strMessageURI), "NTLM", myCred);
Request = (System.Net.HttpWebRequest)HttpWebRequest.Create(strMessageURI);
Request.Credentials = MyCredCache;
// Specify the method.
Request.Method = "X-MS-ENUMATTS";
if (Request != null)
{
Response = (HttpWebResponse)Request.GetResponse();
ResponseStream = Response.GetResponseStream();
ResponseXmlDoc = new System.Xml.XmlDocument();
// Load the XML response stream.
ResponseXmlDoc.Load(ResponseStream);
// Get the root node.
root = ResponseXmlDoc.DocumentElement;
// Create a new XmlNamespaceManager.
nsmgr = new System.Xml.XmlNamespaceManager(ResponseXmlDoc.NameTable);
nsmgr.AddNamespace("a", "DAV:");
nsmgr.AddNamespace("d", "http://schemas.microsoft.com/mapi/proptag/");
nsmgr.AddNamespace("e", "urn:schemas:httpmail:");
PropstatNodes = root.SelectNodes("//a:propstat", nsmgr);
HrefNodes = root.SelectNodes("//a:href", nsmgr);
// Attachments found?
if (HrefNodes.Count > 0)
{
// Display the number of attachments on the message.
//Console.WriteLine(HrefNodes.Count + " attachments found...");
// Iterate through the attachment properties.
for (int i = 0; i < HrefNodes.Count; i++)
{
StatusNode = PropstatNodes[i].SelectSingleNode("a:status", nsmgr);
if (StatusNode.InnerText != "HTTP/1.1 200 OK")
{
// Console.WriteLine("Attachment: "+ HrefNodes[i].InnerText);
// Console.WriteLine("Status: " +StatusNode.InnerText);
// Console.WriteLine("");
}
else
{
// Console.WriteLine("Attachment: " +HrefNodes[i].InnerText);
// Console.WriteLine("Status: " +StatusNode.InnerText);
// Get the CdoPR_ATTACH_FILENAME_W MAPIproperty tag,
// corresponding to the attachment filename. The
// http://schemas.microsoft.com/mapi/proptag/ namespace is typically
// assigned the d: prefix in the XML response body.
// PropNode = PropstatNodes[i].SelectSingleNode("a:prop/d:x3704001f", nsmgr);
// Console.WriteLine("Attachment name: " +PropNode.InnerText);
// Get the CdoPR_ATTACH_EXTENSION_W MAPIproperty tag,
// corresponding to the attachment fileextension.
PropNode = PropstatNodes[i].SelectSingleNode("a:prop/d:x3703001f", nsmgr);
AttachNode = PropstatNodes[i].SelectSingleNode("a:prop/e:attachmentfilename", nsmgr);
if (PropNode == null)
{
PropNode = PropstatNodes[i].SelectSingleNode("a:prop/d:x3704001f", nsmgr);
}
//if (PropNode != null && PropNode.InnerText.ToLower().IndexOf(".xls") > -1)
if (PropNode != null)
{
try
{
//HrefNodes[i].InnerText, PropNode.InnerText
//DownloadAttachment(HrefNodes[i].InnerText, path + PropNode.InnerText, myCred);
// build attachment list
Attach att = new Attach();
att.Path = HrefNodes[i].InnerText;
att.Extension = PropNode.InnerText;
if (AttachNode != null)
{
att.Filename = AttachNode.InnerText;
//Console.WriteLine(AttachNode.InnerText);
}
//this.DownloadSingleAttachment(att.Path,att.Filename);
attachlist.Add(att);
}
catch (Exception aex)
{
//Error_Logger.ErrorLogger.LogErrorToFile(aex.ToString());
Console.WriteLine(aex.Message.ToString());
}
}
//Console.WriteLine("File extension: " + PropNode.InnerText);
// Get the CdoPR_ATTACH_SIZE MAPI property tag,
// corresponding to the attachment file size.
//PropNode = PropstatNodes[i].SelectSingleNode("a:prop/d:x0e200003", nsmgr);
//Console.WriteLine("Attachment size: " + PropNode.InnerText);
}
}
}
else
{
//Console.WriteLine("No attachments found.");
}
// Clean up.
ResponseStream.Close();
Response.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
return attachlist;
}
// loop through attachment list of each email
private void DownloadAttachments(List<mail> mailList, string pathToSave)
{
try
{
foreach (Mail mail in mailList)
{
foreach (Attach attach in mail.Attachments)
{
DownloadSingleAttachment(attach.Path,attach.Filename,pathToSave);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
// download attchment
private void DownloadSingleAttachment(string emlURI, string fileName, string pathToSave)
{
// 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;
//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(pathToSave+fileName, System.IO.FileMode.Create);
byte[] buffer = new byte[4096];
int length;
length = stm.Read(buffer, 0, 4096);
while (length != 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 ex)
{
Console.WriteLine(ex.Message.ToString());
}
}
public void DownloadBySubject(string subject, string saveToPath)
{
this.DownloadAttachments(this.getMailsBySubject(subject), saveToPath);
}
}
Program
WebDAV webdav = new WebDAV("http://servername/Exchange/Artur.KEDZIOR/Inbox",
"artur", // username
"password", // password
"ARTURITONET"); // domain
webdav.DownloadBySubject("Arturito.NET", @"c:\attachments\");
Accesing shared mailbox in Exchange Web Services 2007 Service Pack 1 and downloading attachments with C#
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);
}
}
}
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!
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);
}
}
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.
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