Friday, October 26, 2007

Uploading a document into a SharePoint Document library from a Exchange 2007 Transport Agent.

SharePoint servers these days are multiplying like rabbits while Sharepoint is a great place to put and index information breaking habits and making sure you have a central repository of things is always a challenge. What this agent does is looks at any email which has any Pdf attachments that have the word “quote” in the filename if these emails have any external recipients this document will get uploaded into a specific SharePoint’s sites shared documents library. So this allows me in this case to have a central repository of all the quotes sent out via email. To make sure the documents that are being uploaded have a unique filename the processing time is added to the filename of the document at the time it’s uploaded to SharePoint.

Because programmatically uploading a document into SharePoint isn’t that straight forward To upload the document into the SharePoint Document library itself I’ve use the S.S. Ahmed cool WSUploadservice which is free,easy to install and use you can get the source from codeplex http://www.codeplex.com/wsuploadservice.

Stepping through the code

The first part of this code is responsible for doing the recipient check as I was only interested in capturing email that was going to be delivered to a external recipient I need some code that would first check the recipient list.

ArrayList dmarray = new ArrayList();
dmarray.Add("domain.com");
Boolean pmProcMessage = false;
EmailMessage emMessage = e.MailItem.Message;
foreach (EnvelopeRecipient recp in e.MailItem.Recipients) {
if (dmarray.Contains(recp.Address.DomainPart)== false) {
pmProcMessage = true;
}

}

This code loops though the recipients of the message and checks the domainpart of the recipient address to see if it matches any of the internal domains. I could have quiered active directory to get the internal domain address information but for performance reasons Its probably better to either hardcode them in the code or put them in a registry key.

The next section of code processes any attachments on a message that is identiified as having a external recipeint. The following line will find any attachments that have a pdf attachment with quote in the filename

if (feFileExtension.ToLower() == ".pdf" | atAttach.FileName.ToLower().IndexOf("quote") != -1)

The next section of code is what performs the Sharepoint upload using the WSUploadservice service. Because Transport agents run under the \NetworkService account privileges to be able to successfully upload a document to a SharePoint site alternate credentials or impersonation must be used. I took the easy way out by using hard coded credentials in the code itself.

string spDocumentLibrary = "http://server/sites/Quotes/Shared%20Documents";
string strUserName = "username";
string strPassword = "password";
string strDomain = "domain";
System.Net.CredentialCache spUploadUserCredentials = new System.Net.CredentialCache();
spUploadUserCredentials.Add(new System.Uri(spDocumentLibrary),
"NTLM", new System.Net.NetworkCredential(strUserName, strPassword, strDomain) ); spUploader.PreAuthenticate = true;
spUploader.Credentials = spUploadUserCredentials;
urUploadResult = spUploader.UploadDocument(fnFileName.ToLower().Replace(".pdf", nfNewFileName), atBytes, spDocumentLibrary);
return urUploadResult;

To use this code you first need to have the WSuploadservice installed on your target SharePoint server. You then need to configure the URL of the SharePoint document library you want to use as well as the user account detail for the account that is going to upload the document to SharePoint and also set your local email domains in the code.

I would consider what this code is doing is pretty heavy lifting so before doing this type of thing in production you might want to ask yourself will it scale?. Its something you can really only determine yourself though your own testing based on the size and volume of information you’re going to process.

I’ve put a download of this code here the full agent looks like

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Diagnostics;
using Microsoft.Exchange.Data.Transport;
using Microsoft.Exchange.Data.Mime;
using Microsoft.Exchange.Data.Transport.Email;
using Microsoft.Exchange.Data.Transport.Smtp;
using Microsoft.Exchange.Data.Transport.Routing;
using Microsoft.Exchange.Data.Common;
using SharepointAttachmentUploadAgent.UploadwebService;

namespace msgdevExchangeRoutingAgents
{
public class SharepointAttachmentUploadFactory : RoutingAgentFactory
{
public override RoutingAgent CreateAgent(SmtpServer server)
{
RoutingAgent emSpUpload = new SharepointAttachUploadAgent();
return emSpUpload;
}
}
}
public class SharepointAttachUploadAgent : RoutingAgent
{
public SharepointAttachUploadAgent()
{
base.OnSubmittedMessage += new SubmittedMessageEventHandler(SharepointAttachUploadAgent_OnSubmittedMessage);
}

void SharepointAttachUploadAgent_OnSubmittedMessage(SubmittedMessageEventSource source, QueuedMessageEventArgs e)
{
ArrayList dmarray = new ArrayList();
dmarray.Add("domain.com");
Boolean pmProcMessage = false;
EmailMessage emMessage = e.MailItem.Message;
foreach (EnvelopeRecipient recp in e.MailItem.Recipients) {
if (dmarray.Contains(recp.Address.DomainPart)== false) {
pmProcMessage = true;
}

}
if (pmProcMessage == true) { ProcessMessage(emMessage); }
}
public static byte[] ReadFully(Stream stream, int initialLength)
{
// ref Function from http://www.yoda.arachsys.com/csharp/readbinary.html
// If we've been passed an unhelpful initial length, just
// use 32K.
if (initialLength < initiallength =" 32768;" buffer =" new" read =" 0;" chunk =" stream.Read(buffer,"> 0)
{
read += chunk;

// If we've reached the end of our buffer, check to see if there's
// any more information
if (read == buffer.Length)
{
int nextByte = stream.ReadByte();

// End of stream? If so, we're done
if (nextByte == -1)
{
return buffer;
}

// Nope. Resize the buffer, put in the byte we've just
// read, and continue
byte[] newBuffer = new byte[buffer.Length * 2];
Array.Copy(buffer, newBuffer, buffer.Length);
newBuffer[read] = (byte)nextByte;
buffer = newBuffer;
read++;
}
}
// Buffer is now too big. Shrink it.
byte[] ret = new byte[read];
Array.Copy(buffer, ret, read);
return ret;
}
static void ProcessMessage(EmailMessage emEmailMessage)
{
for (int index = emEmailMessage.Attachments.Count - 1; index >= 0; index--)
{
Attachment atAttach = emEmailMessage.Attachments[index];
if (atAttach.EmbeddedMessage == null)
{
if (atAttach.AttachmentType == AttachmentType.Regular & atAttach.FileName != null)
{
// Find Any PDF attachments with Quote in the File Name
if (atAttach.FileName.Length >= 3)
{
String feFileExtension = atAttach.FileName.Substring((atAttach.FileName.Length - 4), 4);
if (feFileExtension.ToLower() == ".pdf" | atAttach.FileName.ToLower().IndexOf("quote") != -1)
{
Stream attachstream = atAttach.GetContentReadStream();
String uploadResult = uploadAttachment(attachstream, atAttach.FileName.ToString());
}

}
}
atAttach = null;
}
}
}
static string uploadAttachment(Stream atAttachStream,String fnFileName) {
string nfNewFileName = "-Sent(" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss")+").pdf";

string urUploadResult;
byte[] atBytes = ReadFully(atAttachStream, (int)atAttachStream.Length);
Files spUploader = new Files();
string spDocumentLibrary = "http://servername/sites/Quotes/Shared%20Documents";
string strUserName = "username";
string strPassword = "password";
string strDomain = "domain";
System.Net.CredentialCache spUploadUserCredentials = new System.Net.CredentialCache();
spUploadUserCredentials.Add(new System.Uri(spDocumentLibrary),
"NTLM",
new System.Net.NetworkCredential(strUserName, strPassword, strDomain)
);
spUploader.PreAuthenticate = true;
spUploader.Credentials = spUploadUserCredentials;
urUploadResult = spUploader.UploadDocument(fnFileName.ToLower().Replace(".pdf", nfNewFileName), atBytes, spDocumentLibrary);
return urUploadResult;


}
}

No comments: