Microsoft CRM is now on the scene and it is increasing its market share, due to Microsoft Business Solutions muscles and marketing strategy. It is tightly integrated with other Microsoft Business Solutions products such as Microsoft Great Plains, Solomon, Navision. Being relatively inexpensive in comparison to competitors, like Siebel, Oracle - Microsoft CRM opens you the door for worldwide operations automation. In this small article we would like to give you, software developer, some hints on Microsoft CRM customizBorisMakushkin.incation.
Today's topic is Activity of email type programming - you usually deal with these customizations when you improve Microsoft Exchange CRM connector. How do you create email attachment - this is the main discussion topic. We'll use VB.Net.
In Exchange handler/event sink you create Activity of email type in MS CRM and one of the tasks is transfer the attachment(s) from the body of the incoming email to the attachment(s) in the Activity. You can realize it through direct access to Microsoft CRM DB. Let's see VB code:
1. First we are getting access to the letter via ExOLEDB:
Private
iMessage As CDO.Message = New CDO.MessageClass()
Private iPrt As CDO.IBodyPart
iMessage.DataSource.Open(bstrURLItem, Nothing, ADODB.ConnectModeEnum.adModeRead, ADODB.RecordCreateOptionsEnum.adFailIfNotExists, ADODB.RecordOpenOptionsEnum.adOpenSource, "", "") 2. Next - we come through the attachment list, get their names and save their bodies into temporary catalogue:
Dim
i As Integer = 1
Do While i <= aNum
Dim fName As String = iMessage.Attachments(i).FileName
Dim eName As String = fName.Substring(fName.Length-3, 3).ToUpper()
log.Debug("Attachment: " & fName)
iPrt = iMessage.Attachments(i)
Dim attName As String = Path.GetTempPath() & fName
iPrt.SaveToFile(attName)
attachments.Add(Guid.NewGuid(), attName)
iPrt = Nothing
i += 1
Loop 3. Then we cycle through the cache, containing attachments info and add them to the Activity created:
If
Not attachments Is Nothing Then
Dim keys As ICollection = attachments.Keys
Dim attCounter As Integer = 0
For Each o As Guid In keys
Dim attName As String = CStr(attachments(o))
crmConnector.AddAttachmentToActivity(emailId, attName, (New FileInfo(attName)).Length, attCounter)
File.Delete(attName)
attCounter += 1
Next o
End If 4. Here is the method of adding attachment to Activity:
Public
Function AddAttachmentToActivity(ByVal emailId As Guid, ByVal filename As String, ByVal filesize As Long, ByVal attachmentNumber As Integer) As Guid
Try
log.Debug("Prepare for Mail Activity Attachment Creating")
' BizUser proxy object
Dim bizUser As Microsoft.Crm.Platform.Proxy.BizUser = New Microsoft.Crm.Platform.Proxy.BizUser()
Dim credentials As ICredentials = New NetworkCredential(sysUserId, sysPassword, sysDomain)
bizUser.Url = crmDir & "BizUser.srf"
bizUser.Credentials = credentials
Dim userAuth As Microsoft.Crm.Platform.Proxy.CUserAuth = bizUser.WhoAmI()
' CRMActivityAttachment proxy object
Dim activityAttachment As Microsoft.Crm.Platform.Proxy.CRMActivityAttachment = New Microsoft.Crm.Platform.Proxy.CRMActivityAttachment()
activityAttachment.Credentials = credentials
activityAttachment.Url = crmDir & "CRMActivityAttachment.srf"
' Set up the XML string for the activity attachment
Dim strXml As String = "<activitymimeattachment>"
strXml &= "<subject>Activity 1</subject>"
strXml &= "<attachmentnumber>" & attachmentNumber & "</attachmentnumber>"
strXml &= "<activityid>" & emailId.ToString("B") & "</activityid>"
strXml &= "</activitymimeattachment>"
' Create the activity attachment
Dim attachmentId As Guid = New Guid(activityAttachment.Create(userAuth, strXml))
log.Debug("Create Attachemnt ID: " & attachmentId.ToString("B"))
UploadFileToDB(attachmentId, filename, filesize)
Return attachmentId
Catch e As System.Web.Services.Protocols.SoapException
log.Debug("ErrorMessage: " & e.Message & " " & e.Detail.OuterXml & " Source: " & e.Source)
Catch e As Exception
log.Debug(e.Message & Constants.vbCrLf & e.StackTrace)
End Try
Return New Guid()
End Function 5. Main problem, however is attachment body adding to MS CRM database. Main requirement is - attachment must be encoded as BASE64 stream and its length must be specified correctly together with Nine Type and file name of the file it will be knows as an attachment in activity. Let's look at the VB code:
Public
Sub UploadFileToDB(ByVal attachmentId As Guid, ByVal filename As String, ByVal filesize As Long)
Dim contentType As String = "application/octet-stream"
Try
Dim mimes As Hashtable = LoadMimeDB(Environment.SystemDirectory & "/Albaspectrum/ContentType.txt")
If Not mimes Is Nothing Then
Dim tmpContentType As String = GetMimeType(mimes, filename)
If Not tmpContentType Is Nothing AndAlso (Not tmpContentType.Equals("")) Then
contentType = tmpContentType
End If
End If
Dim memoryData As Byte() = New Byte(filesize - 1){}
Dim fs As FileStream = New FileStream(filename, FileMode.Open, FileAccess.Read)
Dim reader As BinaryReader = New BinaryReader(fs)
reader.Read(memoryData, 0, CInt(filesize))
reader.Close()
fs.Close()
Dim command As OleDbCommand = conn.CreateCommand()
command.CommandText = "UPDATE ActivityMimeAttachment SET FileSize = (?), MimeType = (?), FileName = (?), Body = (?) WHERE ActivityMimeAttachmentId = (?)"
command.Prepare()
command.Parameters.Add(New OleDbParameter("FileSize", filesize))
command.Parameters.Add(New OleDbParameter("MimeType", contentType))
command.Parameters.Add(New OleDbParameter("FileName", New FileInfo(filename).Name))
command.Parameters.Add(New OleDbParameter("Body", Convert.ToBase64String(memoryData, 0, CInt(filesize))))
command.Parameters.Add(New OleDbParameter("ActivityMimeAttachmentId", attachmentId))
log.Debug("Prepare to upload attachemnt " & attachmentId.ToString("B") & " in ActivityMimeAttachment")
command.ExecuteNonQuery()
memoryData = Nothing
Catch e As Exception
log.Debug(e.Message & Constants.vbCrLf & e.StackTrace)
End Try
End Sub 6. File ContectType.txt is matching list of the files extensions and their mime-type in the following format:
asc application/pgp-encrypted Armored Encrypted file (PGP)
asd application/astound Autosave file (Word for Windows)
asm PC ASM File
asn application/astound
NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (WWW.C-SHARPCORNER.COM).