Windows form - Automatic email issue - VB.NET - vb.net

Here is my code to generate an email and display it to the user:
Imports Outlook = Microsoft.Office.Interop.Outlook
Private Function ReadSignature(sigName As String) As String
Dim oFSO, oTextStream As Object
Dim appDataDir, sig, sigPath, fileName As String
appDataDir = Environ("APPDATA") & "\Microsoft\Signatures"
sigPath = appDataDir & "\" & sigName
oFSO = CreateObject("Scripting.FileSystemObject")
oTextStream = oFSO.OpenTextFile(sigPath)
sig = oTextStream.ReadAll
' fix relative references to images, etc. in sig
' by making them absolute paths, OL will find the image
fileName = Replace(sigName, ".htm", "") & "_files/"
sig = Replace(sig, fileName, appDataDir & "\" & fileName)
ReadSignature = sig
End Function
Private Sub Email()
Dim INC As String
INC = wb1.Document.GetElementById("arid_WIN_2_1000000161").InnerText
Dim sig As String
' MainSig.htm is the name you gave your signature in the OL Options dialog
sig = ReadSignature("MainSig.htm")
Dim Outl As Object
Outl = CreateObject("Outlook.Application")
If Outl IsNot Nothing Then
Dim omsg As Object
omsg = Outl.CreateItem(0)
omsg.To = TextBox35.Text
omsg.cc = TextBox37.Text
omsg.subject = INC & TextBox38.Text
omsg.HTMLBody = "<p>" & TextBox40.Text & "</p><p>" & TextBox41.Text & "</p><p>" & "<p>INC# : " & INC & "<br/>TMS ID: " & TextBox2.Text & TextBox4.Text & "</p><p>Issue : " & "<br/>Resulting in: " & ComboBox6.Text & "<br/>Issue Resolved?: " & TextBox29.Text & "<br/>User error?: " & TextBox30.Text & "</p><p>Person reporting (Or name Of caller): " & TextBox1.Text & "<br/>Reported Source: " & ComboBox2.Text & "<br/>INC# Provided to customer: " & TextBox21.Text & "<br/>Date And Time: " & DateTimePicker2.Value & "<br />(MM/DD/YYYY HH:MM) " & ComboBox1.Text & "</p><p>Site(s) affected:<br />" & TextBox5.Text & "<br/>" & TextBox6.Text & "</p><p>Additional notes: <br />" & TextBox3.Text & "</p><p>" & TextBox24.Text & "<br /></p><p>Impact : " & ComboBox3.Text & "<br />Urgency: " & ComboBox4.Text & "<br /></p><p>" & sig
omsg.Display(True)
End If
End Sub
This is great for when users need to escalate a ticket, as it allows them to add any extra notes before sending it, however I am trying to make it send a copy of every ticket created (whether escalated or not) to our main mailbox as well as any escalation emails (preferably it will be done in the background, without relying on the user clicking send rather than just closing it as i know some of them would).
The issue is when i change omsg.Display(True) to omsg.send it throws an exception and fails
I've even tried leaving omsg.Display(True) and adding omsg.send on the next line, but that just displays the message and then throws the exception
I've read somewhere that it could be a group policy designed to stop self replicating viruses emailing themselves to everyone in your address book, if this is the case can any of you think of a workaround?
Thank you in advance.

Most probably you get a security issue. "Security" in this context refers to the so-called "object model guard" that triggers security prompts and blocks access to certain features in an effort to prevent malicious programs from harvesting email addresses from Outlook data and using Outlook to propagate viruses and spam. These prompts cannot simply be turned off, except in Outlook 2007 and later with an anti-virus application running. This page discusses strategies for avoiding the security prompts:
Develop a COM add-in which doesn't trigger security issues.
You can use the Outlook Security Manager component for disabling security prompts in Outlook.
Use a low-level API on which Outlook is based on and which doesn't trigger security issues/prompts - Extended MAPI or any other third-party wrapper around that API (such as Redemption).
Deploy Outlook security settings via GPO.

Related

Extracting Data Relating To Reminders Snoozed

I have no VBA knowledge but am on a passage of learning. I have obtained the following coding from a public source (Diane Peremsky) of outlook forums. It has a bug I am working on to resolve and strangely returns different data on successive iterations.
Could somebody try provide (or guide me) to add the first 3 lines of the message body to which it refers?
Sub SnoozedReminders()
Dim oReminder As Reminder
Dim oReminders As Outlook.Reminders
Dim RemItems As String
Set oReminders = Outlook.Reminders
For Each oReminder In oReminders
If (oReminder.OriginalReminderDate <> oReminder.NextReminderDate) Then
RemItems = RemItems & oReminder.Caption & vbCrLf & _
"Original Reminder time: " & oReminder.OriginalReminderDate & vbCrLf & _
"Snoozed to: " & oReminder.NextReminderDate & vbCrLf _
& vbCrLf
End If
Next oReminder
Set oMail = Application.CreateItem(olMailItem)
oMail.Subject = "Generated on " & Now
oMail.Body = RemItems
oMail.Display
End Sub
The Reminder.Item property returns a corresponding Outlook item. So, you may get the message body from there.
Sub SnoozedReminders()
Dim oReminder As Reminder
Dim oReminders As Outlook.Reminders
Dim RemItems As String
Set oReminders = Outlook.Reminders
For Each oReminder In oReminders
If (oReminder.OriginalReminderDate <> oReminder.NextReminderDate) Then
RemItems = RemItems & oReminder.Caption & vbCrLf & "Original Reminder time: " &
oReminder.OriginalReminderDate & vbCrLf & "Snoozed to: " & oReminder.NextReminderDate & vbCrLf
& vbCrLf
End If
MsgBox oReminder.Item.Body
Next oReminder
...
End Sub
The Outlook object model provides three main ways for working with item bodies:
Body.
HTMLBody.
The Word editor. The WordEditor property of the Inspector class returns an instance of the Word Document which represents the message body.
See Chapter 17: Working with Item Bodies for more information.

Access abends after DoCmd.OpenReport

A report is called from VBA to receive returned records from an Access pass-through query. After the DoCmd completes the report's parameters are set in the report's appropriate label containers setting their .Caption property as required. Access fails intermittently during this process which leads me to believe that the report is not truly open to receive the parameters. Here's the VBA sub:
Private Sub Report_Open(Cancel As Integer)
Dim strFromDate As String
Dim strToDate As String
Dim strWC As String
Dim intShift As Integer
Dim strSQL As String
strFromDate = InputBox("Enter From Date and Time: ")
strToDate = InputBox("Enter To Date and Time: ")
strWC = InputBox("Enter Work Center: ")
intShift = InputBox("Enter Shift: ")
strSQL = "exec dbo.uspWorkCentreReport_TEST " & "'" & strFromDate & "', " & "'" & strToDate & "', " & "'" & strWC & "', " & intShift & ";"
CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQL
DoCmd.OpenReport "rpt_qry_ptq_uspWorkCentreReport", acViewReport
Me.lblFromDate.Caption = strFromDate
Me.lblToDate.Caption = strToDate
Me.lblWC.Caption = strWC
Me.lblShift.Caption = intShift
End Sub
When the failure occurrs VBA highlights the Me.lblFromDate.Caption = strFromDate. If I press Reset in VBA or End on the Run-time error '2467': dialog, Access abends without any other outward signs. Access then re-opens to save the copied *_Backupx.accdb and opens with a fresh copy of the .accdb. The error seems to be a standars MS error:
As I said the report is intermittent and when it fails VB always highlights the same line in code. How do I capture what is happening or can I make VB wait a half of full second before it tries to write the parameters?
As I remember, captions can not be modified, when report open. Only in design mode. So this is not correct, because you have already opened report
Me.lblFromDate.Caption = strFromDate
You should use text boxes instead of captions. Also you can clear the borders, fillings and so on, that text box will appear like a caption.
Finally the correct set of code was produced. The button click creates strOpenArgs and passes it with .OpenReport. The report opens and splits the OpenArgs and populates the appropriate labels with updated Captions. Text boxes would not work! Here's the button click event:
Private Sub btnPreviewP1_Click()
If (Me.txtToDateP1 < Me.txtFromDateP1) Then
MsgBox ("The From Date must occurr before the To Date!")
End If
Dim strFromDateHMS As String
Dim strToDateHMS As String
Dim strSQLP1 As String
Dim strOpenArgs As String
strFromDateHMS = Format(Me.txtFromDateP1, "yyyy-mm-dd") & " " & Me.cboFromHourP1 & ":" & Me.cboFromMinuteP1 & ":" & Me.cboFromSecondP1
strToDateHMS = Format(Me.txtToDateP1, "yyyy-mm-dd") & " " & Me.cboToHourP1 & ":" & Me.cboToMinuteP1 & ":" & Me.cboToSecondP1
strSQLP1 = "exec dbo.uspWorkCentreReport '" & strFromDateHMS & "','" & strToDateHMS & "','" & strWCP1 & "'," & strShiftP1
strOpenArgs = Me.RecordSource & "|" & strFromDateHMS & "|" & strToDateHMS & "|" & strWCP1 & "|" & strShiftP1
' This line is all that's needed to modify the PT query
CurrentDb.QueryDefs("ptq_uspWorkCentreReport").SQL = strSQLP1
DoCmd.OpenReport "rpt_ptq_uspWorkCentreReport", acViewReport, , , , strOpenArgs
End Sub
And here's the reports _Open:
Private Sub Report_Open(Cancel As Integer)
Dim SplitOpenArgs() As String
SplitOpenArgs = Split(Me.OpenArgs, "|")
Me.lblFromDate.Caption = SplitOpenArgs(1)
Me.lblToDate.Caption = SplitOpenArgs(2)
Me.lblWC.Caption = SplitOpenArgs(3)
Me.lblShift.Caption = SplitOpenArgs(4)
End Sub
This opens the report every time with new appropriate data, so long as the report is closed before the form's button is pressed again for another refresh of the report. If the report is not closed the report stays up with the original data and does not refresh with new data... But that is another question I am about to ask. Thanks All.

Sending meeting requests using ical through outlook

Here is my dilemma. I have a vb.net application for requesting time using an asset. The user submits a request (can contain required and optional users), then an approver has to approve it. When it is approved, I want to send a meeting request. I can't do it using outlook code since it won't let me change the organizer. If I try to send it using outlook.application > outlook.olitemtype.olappointmentitem or whatever it is, it will default the organizer to the person sending the meeting request, which in this case is the approver, which I don't want. So I think I am left with trying to send an ical. This is where I am having issues. I can't use smtpclient to create the email and send it using the proper content-type, etc. I have to send it using outlook. So I create an ics file and add it as an attachment. I am not sure the difference between METHOD:PUBLISH and METHOD:REQUEST. All the searches I've have done say I should use method:request, but when i open the ICS file, it doesn't give me the options to accept, etc. It doesn't add to my calendar. I want the ability to be able to update and cancel the meeting as well, which I think I know how to do with uid, sequence, etc. I've done searches and just can't get to where I need to be. It looks like the best option is to use smtpclient to create the mail message where you add the headers and ical stuff, but I can't do that, is there a way to it using outlook?
If someone can help point me in the right direction, I would greatly appreciate it.
Here is my current code:
Dim msg As MailMessage = New MailMessage
msg.From = New MailAddress(br.requesting_user_email)
msg.To.Add(New MailAddress(br.requesting_user_email))
msg.Subject = variables.UserInfo.last_name & ", " + variables.UserInfo.first_name & " has approved your request through the Bench Scheduler."
Dim bodytxt As String = "User: " & variables.UserInfo.last_name & ", " + variables.UserInfo.first_name & vbLf & "5+2: " + variables.UserInfo.username & vbLf & vbLf
bodytxt += "Has approved your bench request for " & br.program_name & " - " & br.project_name & "." & vbLf & vbLf
bodytxt += "Start: " & br.start_time & vbLf & "End: " & br.end_time & vbLf
bodytxt += "Bench: " & br.bench_name & vbLf & "Priority: " & br.priority & vbLf & "Purpose: " & br.objective & vbLf & vbLf
bodytxt += "Request Notes: " & br.notes & vbLf & vbLf
bodytxt += vbLf & vbLf & vbLf & "This email was automatically generated by Bench Scheduler. You may respond to this email."
msg.Body = bodytxt
Dim str As StringBuilder = New StringBuilder
str.AppendLine("BEGIN:VCALENDAR")
str.AppendLine("PRODID:-//Microsoft Corporation//Outlook 15.0 MIMEDIR//EN")
str.AppendLine("VERSION:2.0")
If cancel Then
str.AppendLine("METHOD:CANCEL")
Else
str.AppendLine("METHOD:REQUEST")
End If
str.AppendLine("BEGIN:VEVENT")
str.AppendLine("X-MS-OLK-FORCEINSPECTOROPEN:TRUE")
str.AppendLine("BEGIN:VTIMEZONE")
str.AppendLine("TZID:Eastern Standard Time")
str.AppendLine("BEGIN:STANDARD")
str.AppendLine("DTSTART:16011104T020000")
str.AppendLine("RRULE:FREQ=YEARLY;BYDAY=1SU;BYMONTH=11")
str.AppendLine("TZOFFSETFROM:-0400")
str.AppendLine("TZOFFSETTO:-0500")
str.AppendLine("END:STANDARD")
str.AppendLine("BEGIN:DAYLIGHT")
str.AppendLine("DTSTART:16010311T020000")
str.AppendLine("RRULE:FREQ=YEARLY;BYDAY=2SU;BYMONTH=3")
str.AppendLine("TZOFFSETFROM:-0500")
str.AppendLine("TZOFFSETTO:-0400")
str.AppendLine("END:DAYLIGHT")
str.AppendLine("END:VTIMEZONE")
Dim dt As New DataTable
Dim ta As New BSDataSetTableAdapters.getUserRequestTableAdapter
dt = ta.GetData(br.request_id, "T")
For Each row As DataRow In dt.Rows
If row("type") = "Required" Then
str.AppendLine(String.Format("ATTENDEE;CN='{0}';RSVP=TRUE:mailto:{1}", row("username"), row("email")))
ElseIf row("type") = "Optional" Then
str.AppendLine(String.Format("ATTENDEE;CN='{0}';ROLE=OPT-PARTICIPANT;RSVP=TRUE:mailto:{1}", row("username"), row("email")))
End If
Next
str.AppendLine("CLASS:PUBLIC")
str.AppendLine("CREATED:" & Format(Date.Now, "yyyyMMddTHHmmssZ"))
str.AppendLine(String.Format("DESCRIPTION:{0}", br.objective))
str.AppendLine("DTEND;TZID=" & """" & "Eastern Standard Time" & """" & ":" & Format(CDate(br.end_time), "yyyyMMddTHHmmss"))
str.AppendLine("DTSTAMP:" & Format(Date.Now, "yyyyMMddTHHmmssZ"))
str.AppendLine("DTSTART;TZID=" & """" & "Eastern Standard Time" & """" & ":" & Format(CDate(br.start_time), "yyyyMMddTHHmmss"))
str.AppendLine(String.Format("LOCATION:{0}", br.bench_name))
str.AppendLine(String.Format("ORGANIZER;CN='" & br.requesting_username & "':mailto:" & br.requesting_user_email))
str.AppendLine("PRIORITY:5")
str.AppendLine("SEQUENCE:0")
str.AppendLine(String.Format("SUMMARY;LANGUAGE=en-us:{0}", "Approved Bench Request (ID-" & br.request_id & "): " & br.program_name & "-" & br.project_name & "-" & br.activity))
str.AppendLine("TRANSP:OPAQUE")
str.AppendLine(String.Format("UID:{0}", br.uid))
str.AppendLine(String.Format("X-ALT-DESC;FMTTYPE=text/html:{0}", br.objective))
str.AppendLine("X-MICROSOFT-CDO-BUSYSTATUS:BUSY")
str.AppendLine("X-MICROSOFT-CDO-IMPORTANCE:1")
str.AppendLine("X-MICROSOFT-CDO-INTENDEDSTATUS:BUSY")
str.AppendLine("X-MICROSOFT-DISALLOW-COUNTER:FALSE")
str.AppendLine("X-MS-OLK-AUTOFILLLOCATION:FALSE")
str.AppendLine("X-MS-OLK-CONFTYPE:0")
str.AppendLine("BEGIN:VALARM")
str.AppendLine("TRIGGER:-PT30M")
str.AppendLine("ACTION:DISPLAY")
str.AppendLine("DESCRIPTION:Reminder")
str.AppendLine("END:VALARM")
str.AppendLine("END:VEVENT")
str.AppendLine("END:VCALENDAR")
Dim smtpclient As SmtpClient = New SmtpClient
smtpclient.Host = "replaced for privacy"
smtpclient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
Dim contype As System.Net.Mime.ContentType = New System.Net.Mime.ContentType("text/calendar")
contype.Parameters.Add("method", "REQUEST")
contype.Parameters.Add("name", "Meeting.ics")
Dim avcal As AlternateView = AlternateView.CreateAlternateViewFromString(str.ToString, contype)
msg.AlternateViews.Add(avcal)
smtpclient.Send(msg)

URL monitor keeps increasing memory usage

I have written a URL monitoring program in vb using .net 4.0. Basically it sets a timer checks the url every 60 minutes using an htpwebreques/httpwebresponse and sends an email if the url is down. However the memory used by the application keeps increasing every time the url is checked. This will obviously eventually cause a problem as the app is designed to run permanently monitoring a website for availability and the monitoring machine will eventually run out of resources.
Code for my CheckURL routine below. Any advice greatly appreciated, thanks in advance.
Private Sub checkURL()
Timer1.Stop()
Dim wReq As HttpWebRequest
Dim wResp As HttpWebResponse ' WebResponse
wReq = HttpWebRequest.Create(url)
wReq.Method = "HEAD"
Try
wResp = wReq.GetResponse()
If wResp.StatusCode = 200 Then
txtResponse.Text = wResp.StatusCode & ": " & wResp.StatusDescription & vbNewLine & "The " & siteName & " is up"
'Only send success results if specified
If sendOnFailure = False Then
sendResults = True
End If
Else txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "Please verify manually that it is operational." & vbNewLine & "The response received was:" & vbNewLine & "Status Code: " & wResp.StatusCode & " - " & wResp.StatusDescription
sendResults = True
End If
wResp.Close()
wResp = Nothing
wReq = Nothing
Catch ex As Exception
txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "The error returned was:" & vbNewLine & ex.ToString
sendResults = True
End Try
txtLastCheck.Text = Now.ToString("d MMM yyyy HH:mm")
setNextCheck()
End Sub
First, you should use Option Strict On, which will show you where you have variable type mismatches and may even suggest corrections for you, for example, see where the DirectCast operator is used in the following code.
Second, HttpWebResponse has a .Dispose() method, so you should call that when you have finished using it, or, as Zaggler pointed out, you can use Using to ensure that unmanaged resources are cleaned up properly, thus removing the memory leak you are concerned with. Note that there may be other similar problems in the code we can't see.
You should not set things to Nothing in an attempt to get rid of them - doing so messes with the garbage collector and does nothing to ensure their clean disposal.
Option Strict On
' ....
Private Sub checkURL()
timer1.Stop()
Dim wReq As HttpWebRequest = DirectCast(HttpWebRequest.Create(url), HttpWebRequest)
wReq.Method = "HEAD"
Try
Using wResp As HttpWebResponse = DirectCast(wReq.GetResponse(), HttpWebResponse)
If wResp.StatusCode = 200 Then
txtResponse.Text = wResp.StatusCode & ": " & wResp.StatusDescription & vbNewLine & "The " & siteName & " is up"
'Only send success results if specified
If sendOnFailure = False Then
sendResults = True
End If
Else txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "Please verify manually that it is operational." & vbNewLine & "The response received was:" & vbNewLine & "Status Code: " & wResp.StatusCode & " - " & wResp.StatusDescription
sendResults = True
End If
wResp.Close()
End Using
Catch ex As Exception
txtResponse.Text = "There may be a problem with the " & siteName & vbNewLine & "The error returned was:" & vbNewLine & ex.ToString
sendResults = True
End Try
txtLastCheck.Text = Now.ToString("d MMM yyyy HH:mm")
setNextCheck()
End Sub

MSXML2.DOMDocument load function fails in VBA

I've been struggling with the below issue for a while now and couldn't find the solution yet.
There is an iShare page with an XML file that I want to download using VBA code, then later process the XML file and save into MS Access database.
I've been using the below code for about 4 years now, it worked perfectly without any issues. But suddenly it stopped working this week.
Any ideas why?
the code:
Private Function GetRequests() As Boolean
On Error GoTo ErrHandler
Dim oDoc As MSXML2.DOMDocument
Dim Url As String
Dim sFileName As String
Set oDoc = New MSXML2.DOMDocument
oDoc.async = False
Url = cUrlDatabase & "/" & cApplicationName & "/In/" & cReqXmlFile
UpdateStatus "Loading " & cReqXmlFile
If Not oDoc.Load(Url) Then
c_sLastError = "Could not load XML " & Url
GoTo EndProc
End If
sFileName = sPath & "\Data\requests.xml"
oDoc.Save sFileName
GetRequests = True
End Function
The code fails at the oDoc.Load(Url) part, it comes back false.
Here's an example of how to gather error details:
Dim xDoc As MSXML.DOMDocument
Set xDoc = New MSXML.DOMDocument
If xDoc.Load("C:\My Documents\cds.xml") Then
' The document loaded successfully.
' Now do something intersting.
Else
' The document failed to load.
Dim strErrText As String
Dim xPE As MSXML.IXMLDOMParseError
' Obtain the ParseError object
Set xPE = xDoc.parseError
With xPE
strErrText = "Your XML Document failed to load" & _
"due the following error." & vbCrLf & _
"Error #: " & .errorCode & ": " & xPE.reason & _
"Line #: " & .Line & vbCrLf & _
"Line Position: " & .linepos & vbCrLf & _
"Position In File: " & .filepos & vbCrLf & _
"Source Text: " & .srcText & vbCrLf & _
"Document URL: " & .url
End With
MsgBox strErrText, vbExclamation End If
Set xPE = Nothing
End If
Example taken from here.
For other people finding this post:
The xml parser by now has implemented different error types (see here).
You would have to use the following code
Set objXML = CreateObject("Msxml2.DOMDocument.6.0")
ObjXML.async=true
objXML.load "/path/to/xml"
If objXML.parseError.errorCode <> 0 Then
MsgBox "Error was " + objXML.parseError.reason
End If
This should help you debug your .xml file.
For anyone else struggling with this, I found this error to be caused by text encoded in a format which could not be parsed in VBA (some weird E symbol). The objXML was nothing after the .load. I'm sure there are many possible causes, but I'll share what I found in case this helps someone. Thanks to the guys above for the error handling routines.