Tuesday, June 24, 2008

Export contacts to vCard

///need a dll for that as well for vCard functinality
named --> Thought.Net.vCards
http://www.thoughtproject.com/Libraries/vCard/

///function to export the contacts
Public Shared Function ExportAllContacts(ByVal destinationFilepath As String) As String
'intiallizing file streams to read and write data
Dim ml_filePath As String = (destinationFilepath + "vCard.vcf")
Dim ml_tempfilePath As String = (destinationFilepath + "tempvCard.vcf")
Dim fs As FileStream = New FileStream(ml_filePath, FileMode.Append)
Dim fsTemp As FileStream = New FileStream(ml_tempfilePath, FileMode.Create)
fsTemp.Close()
'inalizing controller and data object
Dim emplist As New ArrayList
Dim ExportList As New List(Of Modules.Employee.EmployeeInfo)
ExportList = Modules.Employee.EmployeeController.GetAllEmployeeForExport()

For Each exportEmp As EmployeeInfo In ExportList
Dim EmployeevCard As New vCard
EmployeevCard.Organization = ""
EmployeevCard.GivenName = exportEmp.Name.ToString()
EmployeevCard.FamilyName = exportEmp.LastName.ToString()
EmployeevCard.Role = exportEmp.CurrentPosition.ToString()
EmployeevCard.EmailAddresses.Add(New vCardEmailAddress(exportEmp.Email))
EmployeevCard.Phones.Add(New vCardPhone(exportEmp.MobileNumber))
EmployeevCard.BirthDate = exportEmp.DateOfBirth
Dim EmployeeAddressvCard As vCardDeliveryAddress = New vCardDeliveryAddress
EmployeeAddressvCard.AddressType = vCardDeliveryAddressType.Home
EmployeeAddressvCard.City = exportEmp.PermanentAddress
EmployeevCard.DeliveryAddresses.Add(EmployeeAddressvCard)

Dim writer As vCardStandardWriter = New vCardStandardWriter
writer.EmbedInternetImages = False
writer.EmbedLocalImages = True
writer.Options = vCardStandardWriterOptions.IgnoreCommas
writer.Write(EmployeevCard, ml_tempfilePath)
Dim reader As StreamReader = New StreamReader(ml_tempfilePath)
Dim wr As StreamWriter = New StreamWriter(fs)
Dim str As String = reader.ReadToEnd
wr.WriteLine(str)
reader.Close()
wr.Flush()
wr.Close()
fs = New FileStream(ml_filePath, FileMode.Append)
Next
fs.Close()
Return ml_filePath
' returning path of file
End Function



///Click event of a link bttton to export the contacts



Protected Sub multipersonVCard_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles multipersonVCard.Click
Try
Dim ml_directoryPath As String = Server.MapPath("~/DesktopModules/Employee/ExportEmployee/")
If Directory.Exists(ml_directoryPath) Then
Directory.Delete(ml_directoryPath, True)
End If
Directory.CreateDirectory(ml_directoryPath)
'for vcard download
Dim ml_filePath As String = ExportAllContacts(ml_directoryPath)
Response.Clear()
'for card download
Response.ContentType = "text/x-vcard"
Response.AppendHeader("content-disposition", "attachment;filename=Employees.vcf")
Response.TransmitFile(ml_filePath)
Response.End()
Response.Flush()
Catch ex As Exception
Finally
End Try
End Sub

No comments: