How can I programmatically cancel an outlook meeting with asp.net VB? - asp.net

I can programmatically create a meeting request that is sent to the user through code and appears in Outlook mail where the user can accept the request and if accepted the appointment shows on their Outlook calendar. but am having trouble figuring out how to programmatically cancel the same event.
The below code is what I am using to send the meeting invitation. It works as should and sends the request to the recipient and they can accept or decline. If accepted the appointment goes on their calendar.
Dim smtpServer As String = ConfigurationManager.AppSettings("MailServer").ToString()
Dim credentials As New NetworkCredential(ConfigurationManager.AppSettings("SMTPUser").ToString(), ConfigurationManager.AppSettings("SMTPPassword").ToString())
Dim startTime1 As String = Convert.ToDateTime("10/30/2015 11:00 AM").ToString("yyyyMMddTHHmmss")
Dim endTime1 As String = Convert.ToDateTime("10/30/2015 01:00 PM").ToString("yyyyMMddTHHmmss")
Dim smtp As New SmtpClient(smtpServer)
smtp.Credentials = credentials
Dim msg As New MailMessage()
Dim emailFrom As String = ConfigurationManager.AppSettings("EmailFrom").ToString()
Dim emailTo As String = "jd#dom.com"
msg.From = New MailAddress(emailFrom, "Scheduling System")
msg.[To].Add(New MailAddress(emailTo))
msg.Subject = "JD"
Dim strBody As New StringBuilder()
strBody.AppendLine("Appointment Confirmation")
strBody.AppendLine("Subject: JD")
strBody.AppendLine("1599")
strBody.AppendLine("Location: Exam 1")
strBody.AppendLine("Date: 10/30/2015")
strBody.AppendLine("Time: 11:00AM - 1:00PM")
msg.Body = strBody.ToString()
Dim str As New StringBuilder()
str.AppendLine("BEGIN:VCALENDAR")
'PRODID: identifier for the product that created the Calendar object
str.AppendLine("PRODID:-//CARS//Outlook MIMEDIR//EN")
str.AppendLine("VERSION:2.0")
str.AppendLine("METHOD:REQUEST")
str.AppendLine("BEGIN:VEVENT")
str.AppendLine(String.Format("DTSTART:{0:yyyyMMddTHHmmss}", startTime1))
'TimeZoneInfo.ConvertTimeToUtc("BeginTime").ToString("yyyyMMddTHHmmssZ")));
str.AppendLine(String.Format("DTSTAMP:{0:yyyyMMddTHHmmss}", DateTime.Now))
str.AppendLine(String.Format("DTEND:{0:yyyyMMddTHHmmss}", endTime1))
'TimeZoneInfo.ConvertTimeToUtc("EndTime").ToString("yyyyMMddTHHmmssZ")));
str.AppendLine(String.Format("LOCATION:{0}", "Exam 1"))
' UID should be unique.
str.AppendLine(String.Format("UID:{0}", "jd101"))
str.AppendLine(String.Format("DESCRIPTION:{0}", msg.Body))
str.AppendLine(String.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body))
str.AppendLine(String.Format("SUMMARY:{0}", msg.Subject))
str.AppendLine("STATUS:CONFIRMED")
str.AppendLine("BEGIN:VALARM")
str.AppendLine("TRIGGER:-PT15M")
str.AppendLine("ACTION:Accept")
str.AppendLine("DESCRIPTION:Reminder")
str.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY")
str.AppendLine("END:VALARM")
str.AppendLine("END:VEVENT")
str.AppendLine(String.Format("ORGANIZER:MAILTO:{0}", msg.From.Address))
str.AppendLine(String.Format("ATTENDEE;CN=""{0}"";RSVP=TRUE:mailto:{1}", msg.[To](0).DisplayName, msg.[To](0).Address))
str.AppendLine("END:VCALENDAR")
Dim ct As New System.Net.Mime.ContentType("text/calendar")
ct.Parameters.Add("method", "REQUEST")
ct.Parameters.Add("name", "meeting.ics")
Dim avCal As AlternateView = AlternateView.CreateAlternateViewFromString(str.ToString(), ct)
msg.AlternateViews.Add(avCal)
smtp.Send(msg)
The below code is what I have to CANCEL an existing meeting. It sends the notice out just like the above code does, but it does not cancel/delete/remove the meeting. Can someone point me in the right direction please. I would just like the event to be removed from the Outlook calendar when this part of the code is ran. Thanks for any help.
Dim smtpServer As String = ConfigurationManager.AppSettings("MailServer").ToString()
Dim credentials As New NetworkCredential(ConfigurationManager.AppSettings("SMTPUser").ToString(), ConfigurationManager.AppSettings("SMTPPassword").ToString())
Dim startTime1 As String = Convert.ToDateTime("10/30/2015 11:00 AM").ToString("yyyyMMddTHHmmss")
Dim endTime1 As String = Convert.ToDateTime("10/30/2015 01:00 PM").ToString("yyyyMMddTHHmmss")
Dim smtp As New SmtpClient(smtpServer)
smtp.Credentials = credentials
Dim msg As New MailMessage()
Dim emailFrom As String = ConfigurationManager.AppSettings("EmailFrom").ToString()
Dim emailTo As String = "jd#dom.com"
msg.From = New MailAddress(emailFrom, "Scheduling System")
msg.[To].Add(New MailAddress(emailTo))
msg.Subject = "JD"
Dim strBody As New StringBuilder()
strBody.AppendLine("Appointment Confirmation")
strBody.AppendLine("Subject: JD")
strBody.AppendLine("HRPO#: 1599")
strBody.AppendLine("Location: Exam 1")
strBody.AppendLine("Date: 10/30/2015")
strBody.AppendLine("Time: 11:00AM - 1:00PM")
msg.Body = strBody.ToString()
Dim str As New StringBuilder()
str.AppendLine("BEGIN:VCALENDAR")
'PRODID: identifier for the product that created the Calendar object
str.AppendLine("PRODID:-//CARS//Outlook MIMEDIR//EN")
str.AppendLine("VERSION:2.0")
str.AppendLine("METHOD:REQUEST")
str.AppendLine("BEGIN:VEVENT")
str.AppendLine(String.Format("DTSTART:{0:yyyyMMddTHHmmss}", startTime1))
'TimeZoneInfo.ConvertTimeToUtc("BeginTime").ToString("yyyyMMddTHHmmssZ")));
str.AppendLine(String.Format("DTSTAMP:{0:yyyyMMddTHHmmss}", DateTime.Now))
str.AppendLine(String.Format("DTEND:{0:yyyyMMddTHHmmss}", endTime1))
'TimeZoneInfo.ConvertTimeToUtc("EndTime").ToString("yyyyMMddTHHmmssZ")));
str.AppendLine(String.Format("LOCATION:{0}", "Exam 1"))
' UID should be unique.
str.AppendLine(String.Format("UID:{0}", "jd101"))
str.AppendLine(String.Format("DESCRIPTION:{0}", msg.Body))
str.AppendLine(String.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", msg.Body))
str.AppendLine(String.Format("SUMMARY:{0}", msg.Subject))
str.AppendLine("STATUS:CANCELLED")
str.AppendLine("BEGIN:VALARM")
str.AppendLine("TRIGGER:-PT15M")
str.AppendLine("ACTION:Accept")
str.AppendLine("DESCRIPTION:Reminder")
str.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY")
str.AppendLine("END:VALARM")
str.AppendLine("END:VEVENT")
str.AppendLine(String.Format("ORGANIZER:MAILTO:{0}", msg.From.Address))
str.AppendLine(String.Format("ATTENDEE;CN=""{0}"";RSVP=TRUE:mailto:{1}", msg.[To](0).DisplayName, msg.[To](0).Address))
str.AppendLine("END:VCALENDAR")
Dim ct As New System.Net.Mime.ContentType("text/calendar")
ct.Parameters.Add("method", "CANCEL")
ct.Parameters.Add("name", "meeting.ics")
Dim avCal As AlternateView = AlternateView.CreateAlternateViewFromString(str.ToString(), ct)
msg.AlternateViews.Add(avCal)
smtp.Send(msg)

ANSWERED
To cancel the meeting and have it removed from the outlook calendar you need to change the Method from "REQUEST" to "CANCEL" for the event that sends the cancellation request.
msg.Body = strBody.ToString()
Dim str As New StringBuilder()
str.AppendLine("BEGIN:VCALENDAR")
'PRODID: identifier for the product that created the Calendar object
str.AppendLine("PRODID:-//CARS//Outlook MIMEDIR//EN")
str.AppendLine("VERSION:2.0")
'''ORIGINAL-CHANGE TO CANCEL'''
'str.AppendLine("METHOD:REQUEST")
'''NEW - CHANGE TO CANCEL'''
str.AppendLine("METHOD:CANCEL")
'''Everything else remains the same. Will work and remove meeting from calendar.'''

Currently i am using this code to send meeting to outlook..
StringBuilder OutlookBody = new StringBuilder();
string textvs = #"BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 10.0 MIMEDIR//EN
VERSION:1.0
BEGIN:VEVENT
LOCATION:" + Location + #"
DTSTART:" + string.Format("DTSTART:{0:yyyyMMddTHHmmssZ}", start) + #"
DTEND:" + string.Format("DTEND:{0:yyyyMMddTHHmmssZ}", end) + #"
DESCRIPTION;ENCODING=QUOTED-PRINTABLE:=
" + OutlookBody + #"=0D=0A
SUMMARY:" + AppoitmentName + #"
PRIORITY:3
END:VEVENT
END:VCALENDAR";
And it is working fine..
How can i use the same code to cancel / remove appointment from outlook.

Related

Paypal Express Payment Execution

I'm developing in vb.net and as of right now I am not using any API's to receive transaction details I have only been using IPN and PDT variables to get my details however I began to notice that, when using Paypal Sandbox to test, after I go through the process of check out, I do receive all the variables of the details but in my test account, there are no transactions shown.
Do I need to be using the REST API in order to actually approve and execute the payment for the transaction in order to complete a transaction? I had assumed that the entire transaction had been completed successful since I was getting all of the details back but now that I noticed there aren't any transactions showing in my account I'm not so sure whats going on?
Here is the code I have been using to view transaction details
Dim authToken As String = "c37yqZU7UdVWesSoipRHFOwB3fFLv1CfOKWz10hqp0ULz6dYKrlCNuxp9d0"
Dim txToken As String = Request.QueryString("tx")
txToken = "2F816064M1280054A" '"6AX4295820157674V" '"5PD1935338742763G" ' '"70Y83841KE749971T" '"74C31896AA9005743""2RY90202U2008611C" '"0F824628H9566062P" '"5ET57654YS955312K" '
Dim strRequest As String = "cmd=_notify-synch&tx=" & txToken & "&at=" & authToken
'Dim Payerinfo As New PayerInfo
'Dim trans As New Transaction
'Dim tra As New PayPal.PayPalAPIInterfaceService.Model.GetTransactionDetailsReq
'post back to either sandbox or live
Dim strSandbox As String = "https://www.sandbox.paypal.com/cgi-bin/webscr"
Dim strLive As String = "https://www.paypal.com/cgi-bin/webscr"
Dim req As HttpWebRequest = CType(WebRequest.Create(strSandbox), HttpWebRequest)
'req.Headers = valHeader
'Set values for the request back
req.Method = "POST"
req.ContentType = "application/x-www-form-urlencoded"
req.ContentLength = strRequest.Length
'Send the request to PayPal and get the response
Dim streamOut As StreamWriter = New StreamWriter(req.GetRequestStream(), Encoding.ASCII)
streamOut.Write(strRequest)
streamOut.Close()
Dim streamIn As StreamReader = New StreamReader(req.GetResponse().GetResponseStream())
Dim strResponse As String = streamIn.ReadToEnd()
streamIn.Close()
If Not String.IsNullOrEmpty(strResponse) Then
Dim results As New Dictionary(Of String, String)
Dim reader As New StringReader(strResponse)
Dim line As String = reader.ReadLine()
If line = "SUCCESS" Then
'FormView1.Visible = False
While True
Dim aLine As String
aLine = reader.ReadLine
If aLine IsNot Nothing Then
Dim strArr() As String
strArr = aLine.Split("=")
results.Add(strArr(0), strArr(1))
Else
Exit While
End If
End While
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'when code below is uncommented remove these two end if's below
Response.Write("<li> " + results("payer_id") + "</li>")
Response.Write("<li> " + results("txn_id") + "</li>")
' Displays all the keys for results, helps to see what the keys are named for writing to text file
For Each kvp As KeyValuePair(Of String, String) In results
Dim v1 As String = kvp.Key
Dim v2 As String = kvp.Value
Response.Write(v1.ToString _
+ ": " + v2 + "<br /> ")
Next
End If

Get Paypal Express cart Price right before checkout

I am using paypal express checkout and I'm trying to get the total value that is in the shopping cart when the user decides to checkout. My shipping rate is going to be based on the total price and although I have the shipping calculations filled out in my paypal account settings, the shipping cost is not showing up in the checkout screen. How would I grab the total shopping cart price right upon checkout so that I can add the shipping cost? What I have so far is only the values after the user has checked out and they are returned back to my website but at this point it is too late to add shipping.
Dim authToken As String = "sdf5414FdsfDFS5eEF52s336DFLLJUhhbuzek64"
Dim txToken As String = Request.QueryString("tx")
txToken = "4GGSES84eEWSS"
Dim strRequest As String = "cmd=_notify-synch&tx=" & txToken & "&at=" & authToken
'Dim Payerinfo As New PayerInfo
'Dim trans As New Transaction
'Dim tra As New PayPal.PayPalAPIInterfaceService.Model.GetTransactionDetailsReq
'post back to either sandbox or live
Dim strSandbox As String = "https://www.sandbox.paypal.com/cgi-bin/webscr"
Dim strLive As String = "https://www.paypal.com/cgi-bin/webscr"
Dim req As HttpWebRequest = CType(WebRequest.Create(strSandbox), HttpWebRequest)
'req.Headers = valHeader
'Set values for the request back
req.Method = "POST"
req.ContentType = "application/x-www-form-urlencoded"
req.ContentLength = strRequest.Length
'Send the request to PayPal and get the response
Dim streamOut As StreamWriter = New StreamWriter(req.GetRequestStream(), Encoding.ASCII)
streamOut.Write(strRequest)
streamOut.Close()
Dim streamIn As StreamReader = New StreamReader(req.GetResponse().GetResponseStream())
Dim strResponse As String = streamIn.ReadToEnd()
streamIn.Close()
If Not String.IsNullOrEmpty(strResponse) Then
Dim results As New Dictionary(Of String, String)
Dim reader As New StringReader(strResponse)
Dim line As String = reader.ReadLine()
If line = "SUCCESS" Then
'FormView1.Visible = False
While True
Dim aLine As String
aLine = reader.ReadLine
If aLine IsNot Nothing Then
Dim strArr() As String
strArr = aLine.Split("=")
results.Add(strArr(0), strArr(1))
Else
Exit While
End If
End While
' Displays all the keys for results, helps to see what the keys are named for writing to text file
For Each kvp As KeyValuePair(Of String, String) In results
Dim v1 As String = kvp.Key
Dim v2 As String = kvp.Value
Response.Write(v1.ToString _
+ ": " + v2 + "<br /> ")
Next
End If
I have also been trying to declare a session variable and add to it every time the add to cart button is clicked but I see a problem in this because I don't know how long the items will stay in the paypal cart and if the session variable session runs out of time and is cleared, they will then receive free shipping since the shipping amount clears out. Is their any way to make this work?
Protected Sub AddToCartBtn_Click(sender As Object, e As EventArgs)
Session("CartAmount")
Dim itemNumber As String = str2
Dim itemAmount As String = price
Dim currencyCode As String = "USD"
Dim addItem As Integer = 1
Dim ppHref As StringBuilder = New StringBuilder()
ppHref.Append("https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_cart")
ppHref.Append("&business=" + business)
ppHref.Append("&item_name=" + itemName)
ppHref.Append("&item_number=" + itemNumber)
ppHref.Append("&amount=" + itemAmount)
ppHref.Append("&currency_code=" + currencyCode)
Session("CartAmount") = (cartTotal + Session("CartAmount"))
End Sub
You can pass shopping cart values in the provided variable from the following url reference,
https://developer.paypal.com/docs/classic/paypal-payments-standard/integration-guide/Appx_websitestandard_htmlvariables/#id08A6HF080O3

How to use ASPxFileManager 'SelectedFiles' property to attach files to MailMessage?

I am using DevExpress tools, specifically the FileManager which has a 'SelectedFiles' property which returns all the data needed to (add,insert,delete,retrieve, modify the record). However I can not figure out how to use the selectedfiles as a MailMessage.Attachment. The code below works to send the email, I've changed the credentials and host values for security. I just need some direction or thought on how to use the FileManager collection that is generated via 'SelectedFiles' and add them as an attachment to the email. I would really like to Zip the files if possible, but at this point simply attaching them is fine. Any thoughts?
Dim fileManager As ASPxFileManager = TryCast(sender, ASPxFileManager)
If ASPxFileManager1.SelectedFiles IsNot Nothing AndAlso ASPxFileManager1.SelectedFiles.Length > 0 Then
For i As Integer = 0 To ASPxFileManager1.SelectedFiles.Length - 1
Dim file = ASPxFileManager1.SelectedFiles.ToString
Dim attachments As New Attachment(fileManager.SelectedFiles.ToString)???
Next
End If
Try
Dim mail As New MailMessage("noreply", DropDownEdit.Text)
Dim smtp_Server As New SmtpClient("host") With {.Credentials = New Net.NetworkCredential("username", "password")}
mail.Subject = "SUBJECT"
mail.IsBodyHtml = False
mail.Body = "Testing"
smtp_Server.Send(mail)
successLabel.Text = "Your email was sent successfully."
Catch ex As Exception
End Try
End Sub
Dim attachments As New Attachment(ReadFile(ASPxFileManager1.SelectedFiles(i)), file)
mail.Attachments.Add(attachments)
The function below was needed to Read the bytes and then attach the items to the MailMessage.
Public Function ReadFile(file__1 As FileManagerFile) As System.IO.Stream
'This function allows us to pull the bytes from the DB value to render the file.
Dim filePath As String = (file__1.RelativeName)
Dim fileData As Byte()
Using con As New SqlConnection([Global].conn)
Dim sqlCmd As New SqlCommand()
sqlCmd.Connection = con
sqlCmd.Parameters.Add("#Name", SqlDbType.VarChar).Value = file__1.Name
sqlCmd.Parameters.Add("#APIKey", SqlDbType.Int).Value = Session("_UserAPIKey")
sqlCmd.CommandText = "SELECT STATEMENT"
con.Open()
Dim sqlReader As SqlDataReader = sqlCmd.ExecuteReader()
If sqlReader.HasRows Then
While sqlReader.Read()
fileData = CType(sqlReader(0), Byte())
End While
End If
End Using
Return New MemoryStream(fileData)
End Function

A recipient must be specified error when sending email from ASP.Net

We are trying to send the out the output of a html string to a particular test email address and found this error at runtime:
A recipient must be specified.
Here is the coding from the code-behind file.
Protected Sub EmailTheList()
' Get the rendered HTML.
'-----------------------
Dim SB As New StringBuilder()
Dim SW As New StringWriter(SB)
Dim htmlTW As New HtmlTextWriter(SW)
GridViewSummary.RenderControl(htmlTW)
' Get the HTML into a string.
' This will be used in the body of the email report.
'---------------------------------------------------
Dim dataGridHTML As String = SB.ToString()
Dim SmtpServer As New SmtpClient()
SmtpServer.Credentials = New Net.NetworkCredential("myEmailAddress#gmail.com", "myPassword")
SmtpServer.Port = 587
SmtpServer.Host = "smtp.gmail.com"
SmtpServer.EnableSsl = True
ObjMailMessage = New MailMessage()
Try
ObjMailMessage.From = New MailAddress("myEmailAddress#gmail.com", "Some text is here.", System.Text.Encoding.UTF8)
ObjMailMessage.Subject = "Test message from Emad"
ObjMailMessage.ReplyToList.Add("john.doe#example.com")
ObjMailMessage.Body = dataGridHTML
ObjMailMessage.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure
SmtpServer.Send(ObjMailMessage)
Catch ex As Exception
MsgBox(ex.ToString())
End Try
End Sub
We suspect we are not using the correct syntax for this line:
ObjMailMessage.From = ObjMailMessage.ReplyToList.Add("john.doe#example.com")
You're missing the To: address, which is causing the error regarding a recipient.
ObjMailMessage.To.Add(New MailAddress("mail#somemail.com", "An error happened", System.Text.Encoding.UTF8))
Reference: http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.aspx

sending emails in bcc to multiple users not working

I am developing a project in which I am sending emails to multiple user as follows
Dim users(20) As String
users(0) = "xx#example.com"
users(1) ="xx#xexample.com"
users(2) = "xx#example.com"
users(3) = "xx#example.com"
users(4) = "xx#example.com"
users(5) = "xx#example.com"
users(6) = "xx#example.com"
users(7) = "xx#example.com"
users(8) = "xx#example.com"
users(9) = "xx#example.com"
users(10) = "xx#example.com"
For i = 0 To 10
em.Bcc.Add(users(i))
or
em.Bcc.Add(New MailAddress (users(i)))
Next
mailClient.Send(em)
but it is sending email to only one user I also tried
Dim sendto As String
sendto = Nothing
For i = 0 To 10
sendto = sendto + users(i) + ","
Next
em.Bcc.Add(sendto)
still not working what is wrong in the code
I am using asp.net and vb.
Your code should look more like this:
Sub SendToMany()
'create the mail message
Dim mail As New MailMessage()
mail.From = New MailAddress("me#mycompany.com", "Ashok P")
mail.To.Add("you#yourcompany.com")
mail.Bcc.Add("blindcc1#yourcompany.com")
mail.Bcc.Add("blindcc2#yourcompany.com")
'set the content
mail.Subject = "This is an email"
mail.Body = "this is the body content of the email."
'send the message
Dim smtp As New SmtpClient(youmailserver) 'dont forget to include username/password via networkcredentials
smtp.Send(mail)
End Sub 'MultipleRecipients

Resources