Thursday, October 28, 2010

SharePoint 2010 BCS

Good site I found is
http://www.chakkaradeep.com/post/BDC-NET-Assembly-Connector-Updating-a-BCS-Entity.aspx

Thanks a lot bro.

It is missing the CREATE/DELETE method, here it is

public static BookEntity Create(BookEntity bookEntity)
{

books.Insert(books.Count, String.Format("{0},{1},{2},{3},{4}", bookEntity.ISBN,
bookEntity.Name, bookEntity.Author, bookEntity.Price, bookEntity.Publisher));

return bookEntity;
}

public static void Delete(string parameter)
{
books.Remove(books.FirstOrDefault(s => s.Contains(parameter)));
}

Thursday, September 30, 2010

Read Emails from exchange server(2003) using C#.Net 3.5 and flag it(read/delete/follow up)

the following code is copied from http://forums.thedailywtf.com/forums/p/4566/104447.aspx

I tried a lot on google to find this solution, thanks to "luke727" , who posted this.

I changed code as per my requirement, ie If a mails has all PDF attachments then copy the files to local disk and delete the mail, if it has other attachments then mark as FOLLOW UP.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Diagnostics;

namespace ConsoleApplication2
{
class WebDAV
{
static void Main(string[] args)
{
TextWriterTraceListener tr2 = new TextWriterTraceListener("EventLogForMailReader.txt");
Debug.Listeners.Add(tr2);
Debug.WriteLine("The Process Start Time:" + System.DateTime.Now.ToString());
Debug.Indent();
string strServer = "webmail.blah-blah.com";
// Exchange server name
string strPassword = "Password";
// Account Domain Password
string strDomain = "Domain";
// Domain
string strAlias = "UserName";
// username

ExchangeDownloader exchangeDownloader = new ExchangeDownloader();
exchangeDownloader.Username = strAlias;
exchangeDownloader.Domain = strDomain;
exchangeDownloader.Password = strPassword;
exchangeDownloader.MailboxUrl = "https://" + strServer + "/exchange/" + strAlias + "/Inbox/";
exchangeDownloader.DownloadPath = "C:\\Raj";
exchangeDownloader.Download();

Debug.Unindent();
Debug.WriteLine("The Process End Time:" + System.DateTime.Now.ToString());
Debug.WriteLine("---------------------------------");
Debug.Flush();
}

public static class Authentications
{
public const string ANONYMOUS = "ANONYMOUS";
public const string BASIC = "BASIC";
public const string DIGEST = "DIGEST";
public const string NTLM = "NTLM";
public const string NEGOTIATE = "NEGOTIATE";
public const string PASSPORT = "PASSPORT";
}
public static class Methods
{
public const string BCOPY = "BCOPY";
public const string BDELETE = "BDELETE";
public const string BMOVE = "BMOVE";
public const string BPROPFIND = "BPROPFIND";
public const string BPROPPATCH = "BPROPPATCH";
public const string COPY = "COPY";
public const string DELETE = "DELETE";
public const string LOCK = "LOCK";
public const string MKCOL = "MKCOL";
public const string MOVE = "MOVE";
public const string NOTIFY = "NOTIFY";
public const string POLL = "POLL";
public const string PROPFIND = "PROPFIND";
public const string PROPPATCH = "PROPPATCH";
public const string SEARCH = "SEARCH";
public const string SUBSCRIBE = "SUBSCRIBE";
public const string UNLOCK = "UNLOCK";
public const string UNSUBSCRIBE = "UNSUBSCRIBE";
public const string X_MS_ENUMATTS = "X-MS-ENUMATTS";
}
public const string CONTENT_TYPE_TEXT_XML = "text/xml";
public const string NS_DAV = "DAV:";
public const string PR_DAV_SEARCHREQUEST = "searchrequest";
public const string PR_DAV_SQL = "sql";
public const string PR_DAV_PROPFIND = "propfind";
public const string PR_DAV_PROP = "prop";
public const string PR_DAV_PROPERTYUPDATE = "propertyupdate";
public const string PR_DAV_SET = "set";
public const string PR_DAV_HREF = "href";
public const string PR_DAV_PROPSTAT = "propstat";
public const string PR_DAV_STATUS = "status";
public const string PR_DAV_RESPONSE = "response";
public const string NS_HTTPMAIL = "urn:schemas:httpmail:";
public const string PR_HTTPMAIL_DATE = "date";
public const string PR_HTTPMAIL_SUBJECT = "subject";
public const string PR_HTTPMAIL_FROM = "from";
public const string PR_HTTPMAIL_TO = "to";
public const string PR_HTTPMAIL_READ = "read";
public const string PR_HTTPMAIL_HASATTACHMENT = "hasattachment";
public const string PR_HTTPMAIL_ATTACHMENTFILENAME = "attachmentfilename";
public const string PR_HTTPMAIL_TEXTDESCRIPTION = "textdescription";
public System.Net.ICredentials Credentials;
public System.Xml.XmlDocument Search(System.Uri uri, string query)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(ms, null);
writer.WriteStartDocument();
writer.WriteStartElement(PR_DAV_SEARCHREQUEST, NS_DAV);
writer.WriteStartElement(PR_DAV_SQL, NS_DAV);
writer.WriteValue(query);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
writer = null;
byte[] data = ms.ToArray();
ms.Close();
ms = null;
return GetXmlResponse(uri, Methods.SEARCH, data);
}
public System.Xml.XmlDocument PropFind(System.Uri uri, string localname, string ns)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(ms, null);
writer.WriteStartDocument();
writer.WriteStartElement(PR_DAV_PROPFIND, NS_DAV);
writer.WriteStartElement(PR_DAV_PROP, NS_DAV);
writer.WriteStartElement(localname, ns);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
writer = null;
byte[] data = ms.ToArray();
ms.Close();
ms = null;
return GetXmlResponse(uri, Methods.SEARCH, data);
}
public void Delete(System.Uri uri)
{
GetEmptyResponse(uri, Methods.DELETE, null);
}
public System.Xml.XmlDocument PropPatch(System.Uri uri, string localname, string ns, object value)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(ms, null);
writer.WriteStartDocument();
writer.WriteStartElement(PR_DAV_PROPERTYUPDATE, NS_DAV);
writer.WriteStartElement(PR_DAV_SET, NS_DAV);
writer.WriteStartElement(PR_DAV_PROP, NS_DAV);
writer.WriteStartElement(localname, ns);
writer.WriteValue(value);
writer.WriteEndElement();
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Close();
writer = null;
byte[] data = ms.ToArray();
ms.Close();
ms = null;
return GetXmlResponse(uri, Methods.PROPPATCH, data);
}
public System.Xml.XmlDocument EnumAtts(System.Uri uri)
{
return GetXmlResponse(uri, Methods.X_MS_ENUMATTS, null);
}
private string GetHtmlResponse(System.Uri uri, string method, byte[] data)
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.Credentials = Credentials;
request.Method = method;
if (data != null)
{
string xml = System.Text.Encoding.UTF8.GetString(data);
request.ContentType = CONTENT_TYPE_TEXT_XML;
request.ContentLength = data.Length;
System.IO.Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream();
int length = 8192;
byte[] buffer = new byte[length];
int count = responseStream.Read(buffer, 0, length);
while (count > 0)
{
memoryStream.Write(buffer, 0, count);
count = responseStream.Read(buffer, 0, length);
}
buffer = memoryStream.ToArray();
memoryStream.Close();
responseStream.Close();
response.Close();
return System.Text.Encoding.UTF8.GetString(buffer);
}
private void GetEmptyResponse(System.Uri uri, string method, byte[] data)
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.Credentials = Credentials;
request.Method = method;
if (data != null)
{
string xml = System.Text.Encoding.UTF8.GetString(data);
request.ContentType = CONTENT_TYPE_TEXT_XML;
request.ContentLength = data.Length;
System.IO.Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
response.Close();
}
private System.Xml.XmlDocument GetXmlResponse(System.Uri uri, string method, byte[] data)
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.Credentials = Credentials;
request.Method = method;
if (data != null)
{
string xml = System.Text.Encoding.UTF8.GetString(data);
request.ContentType = CONTENT_TYPE_TEXT_XML;
request.ContentLength = data.Length;
System.IO.Stream requestStream = request.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
}
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
System.IO.Stream responseStream = response.GetResponseStream();
System.Xml.XmlDocument document = new System.Xml.XmlDocument();
document.Load(responseStream);
responseStream.Close();
response.Close();
return document;
}
}
public class ExchangeDownloader
{
public string Username;
public string Domain;
public string Password;
public string MailboxUrl;
public string DownloadPath;
public void Download()
{
try
{
System.Uri mailboxUri = new System.Uri(MailboxUrl);
System.Net.NetworkCredential credential = new System.Net.NetworkCredential(Username, Password, Domain);
WebDAV webdav = new WebDAV();
System.Net.CredentialCache credentials = new System.Net.CredentialCache();
credentials.Add(mailboxUri, WebDAV.Authentications.BASIC, credential);
webdav.Credentials = credentials;
System.Collections.ArrayList _arrFromName = new System.Collections.ArrayList();
System.Uri[] messageUris = getMessagesWithAttachments(webdav, mailboxUri, out _arrFromName);
System.Uri[] messageUrisForDelete = messageUris;
Boolean boolIsCntSame;
string strStatus=string.Empty;
int intFrommailIterator = 0;
if (messageUris.Length == _arrFromName.Count/2)
{
boolIsCntSame = true;
}
else
boolIsCntSame = false;
Debug.Indent();
Debug.WriteLine("The No. of Mails with attachments :" + messageUris.Count().ToString());
foreach (System.Uri messageUri in messageUris)
{
strStatus=string.Empty;
Debug.Indent();
System.Uri[] attachmentUris = getAttachments(webdav, messageUri);
bool boolAllPDF = true;
foreach (System.Uri attachmentUri in attachmentUris)
{
if (attachmentUri.Segments[5].Split(new char[] { '.' })[attachmentUri.Segments[5].Split(new char[] { '.' }).Length - 1].ToUpper() != "PDF")
{
boolAllPDF = false;
break;
}
}
if (boolAllPDF)
{
foreach (System.Uri attachmentUri in attachmentUris)
{
downloadAttachment(webdav, attachmentUri);
}
//Deleting the mail insted of making as READ
//webdav.PropPatch(messageUri, WebDAV.PR_HTTPMAIL_READ, WebDAV.NS_HTTPMAIL, "1");
webdav.Delete(messageUri);

if (boolIsCntSame)
{
Debug.WriteLine("Email from :" + _arrFromName[intFrommailIterator].ToString() + ", No. of attachments :" + attachmentUris.Length.ToString() + ", Date :" + Convert.ToDateTime(_arrFromName[intFrommailIterator + 1]).ToShortDateString() + ", Status-Processed");
}
}
else
{
Debug.WriteLine("Email from :" + _arrFromName[intFrommailIterator].ToString() + ", No. of attachments :" + attachmentUris.Length.ToString() + ", Date :" + Convert.ToDateTime(_arrFromName[intFrommailIterator + 1]).ToShortDateString() + ", Status-INVALID");
webdav.PropPatch(messageUri, "x-message-flag", "urn:schemas:mailheader:", "1");
}

Debug.Unindent();
intFrommailIterator+=2;
}
Debug.Unindent(); }

catch (Exception ex)
{
Debug.WriteLine("ERROR:- Error occured while processing the request. Error Message :" + ex.Message);
}
}
private void downloadAttachment(WebDAV webdav, System.Uri uri)
{
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.Credentials = webdav.Credentials;
string file =System.DateTime.Now.Ticks.ToString() + System.IO.Path.GetFileName(uri.AbsolutePath);
string filename = System.IO.Path.Combine(DownloadPath, file);
webClient.DownloadFile(uri, filename);
}
private System.Uri[] getAttachments(WebDAV webdav, System.Uri uri)
{
System.Collections.ArrayList attachmentList = new System.Collections.ArrayList();
System.Xml.XmlDocument document = webdav.EnumAtts(uri);
System.Xml.XmlNodeList responseElements = document.GetElementsByTagName(WebDAV.PR_DAV_RESPONSE, WebDAV.NS_DAV);
foreach (System.Xml.XmlElement responseElement in responseElements)
{
System.Xml.XmlElement hrefElement = responseElement[WebDAV.PR_DAV_HREF, WebDAV.NS_DAV];
System.Uri href = new System.Uri(hrefElement.InnerText);
attachmentList.Add(href);
}
return (System.Uri[])attachmentList.ToArray(typeof(System.Uri));
}
private System.Uri[] getMessagesWithAttachments(WebDAV webdav, System.Uri uri,out System.Collections.ArrayList _arrFrom)
{
_arrFrom = new System.Collections.ArrayList();

System.Collections.ArrayList messageList = new System.Collections.ArrayList();
string query = string.Format(
"SELECT \"urn:schemas:httpmail:subject\" , \"urn:schemas:httpmail:sendername\" , \"urn:schemas:mailheader:from\" , \"urn:schemas:httpmail:datereceived\" " +
"FROM \"{0}\" " +
"WHERE \"urn:schemas:httpmail:hasattachment\"=true AND \"urn:schemas:httpmail:read\" = false " +
"ORDER BY \"urn:schemas:httpmail:date DESC\""
, uri);

//WHERE \"DAV:ishidden\" = false AND \"DAV:isfolder\" = false AND \"urn:schemas:httpmail:read\" = false" + " ";

System.Xml.XmlDocument document = webdav.Search(uri, query);
System.Xml.XmlNodeList responseElements = document.GetElementsByTagName(WebDAV.PR_DAV_RESPONSE, WebDAV.NS_DAV);

try
{
XmlNodeList _fromMailIds=document.GetElementsByTagName("e:from");
XmlNodeList _DatesReceived=document.GetElementsByTagName("d:datereceived");
int intIterator=0;
foreach(XmlElement fromElement in _fromMailIds)
{
_arrFrom.Add(fromElement.InnerText);
_arrFrom.Add(_DatesReceived[intIterator].InnerText);
intIterator++;
}
}
catch (Exception)
{
Debug.WriteLine("Error:- While extracting the FROM email Id");
}

foreach (System.Xml.XmlElement responseElement in responseElements)
{
System.Xml.XmlElement hrefElement = responseElement[WebDAV.PR_DAV_HREF, WebDAV.NS_DAV];
System.Uri href = new System.Uri(hrefElement.InnerText);
messageList.Add(href);
}
return (System.Uri[])messageList.ToArray(typeof(System.Uri));
}
}
}