Email a table using VB.Net - vb.net

I need to send an email with a table that has variable values in each cell. I can do this using any method (html via email, an excel/word table, etc.). The only hitch is due to the restrictions of the Emailer program and System.Net.Mail import, it has to be a string.
Here's what I have so far:
Imports DelayEmailer.DelayTrackerWs
Imports System.Configuration
Public Class DelayEmailer
Public Shared Sub Main()
Dim ws As New DelayTrackerWs.DelayUploader
Dim delays As DelayTrackerWs.Delay()
Dim emailer As New Emailer()
Dim delaystring As String
delays = ws.SearchDelaysDate(DelayTrackerWs.AreaEnum.QT, DelayTrackerWs.UnitEnum.QT, Now.AddDays(-1), Now)
delaystring = "Delays" & vbNewLine
delaystring &= "Facilty Start Time Status Category Reason Comment"
For i = 0 To delays.Length - 1
delaystring &= vbNewLine & delays(i).Facility & " "
delaystring &= FormatDateTime(delays(i).DelayStartDateTime, DateFormat.ShortDate) & " "
delaystring &= FormatDateTime(delays(i).DelayStartDateTime, DateFormat.ShortTime) & " "
'delaystring &= delays(i).DelayDuration & " "
delaystring &= delays(i).Status & " "
delaystring &= delays(i).CategoryCode & " "
delaystring &= delays(i).ReasonCode & " "
delaystring &= delays(i).Comment
Next
emailer.Send(ConfigurationManager.AppSettings("EmailList"), "delays", delaystring)
End Sub
As you can see, I currently have just a bunch of concatenated strings that line up if the values of each delays(i) are the same. The other problem is that this needs to be easily viewable via mobile devices and with the strings, it wraps and gets really unreadable. A table here should fix this.

You can send html email from .NET using MailMessage and SmtpClient classes, create an email template as string and set MailMessage's IsBodyHtml property to true:
Dim strHeader As String = "<table><tbody>"
Dim strFooter As String = "</tbody></table>"
Dim sbContent As New StringBuilder()
For i As Integer = 1 To rows
sbContent.Append("<tr>")
For j As Integer = 1 To cols
sbContent.Append(String.Format("<td>{0}</td>", YOUR_TD_VALUE_STRING))
Next j
sbContent.Append("</tr>");
Next i
Dim emailTemplate As String = strHeader & sbContent.ToString() & strFooter
...

Related

VB.net get bitlocker Password ID from Active Directory

I have a VB.net program that I am trying to add a bitlocker lookup tool that will search active directory for the machine name, and display the "Password ID" as well as the "Recovery Password"
So far my script/code works flawlessly for the lookup and displaying the Recovery Password, but I cannot get it to display the Password ID.
I've tried:
Item.Properties("msFVE-RecoveryGuid")(0)
Which returns the error "System.InvalidCastException: Conversion from type 'Byte()' to type 'String' is not valid."
Item.Properties("msFVE-RecoveryGuid")(0).ToString
Which returns "System.Byte[]"
Item.Properties("msFVE-RecoveryGuid").ToString
Which returns "System.DirectoryServices.ResultPropertyValueCollection"
So far in my searching I've only seen C# examples, and I haven't been able to translate.
The same for Recovery Password works however:
(Item.Properties("msFVE-RecoveryPassword")(0))
Here is the larger snippet of what I have for context:
Dim RootDSE As New DirectoryEntry("LDAP://RootDSE")
Dim DomainDN As String = RootDSE.Properties("DefaultNamingContext").Value
Dim ADsearch As New DirectorySearcher("LDAP://" & DomainDN)
ADsearch.Filter = ("(&(objectClass=computer)(name=" & MachineName & "))")
Dim ADresult As SearchResult = ADsearch.FindOne
Dim ADpath As String = ADresult.Path
Dim BTsearch As New DirectorySearcher()
BTsearch.SearchRoot = New DirectoryEntry(ADpath)
BTsearch.Filter = "(&(objectClass=msFVE-RecoveryInformation))"
Dim BitLockers As SearchResultCollection = BTsearch.FindAll()
Dim Item As SearchResult
Dim longTempstring As String = ""
For Each Item In BitLockers
If Item.Properties.Contains("msFVE-RecoveryGuid") Then
Dim tempstring As String = Item.Properties("msFVE-RecoveryGuid")(0).ToString
longTempstring = longTempstring & tempstring & vbNewLine
'ListBox2.Items.Add(Item.Properties("msFVE-RecoveryGuid")(0))
End If
If Item.Properties.Contains("msFVE-RecoveryPassword") Then
ListBox1.Items.Add(Item.Properties("msFVE-RecoveryPassword")(0))
End If
Next
MsgBox(longTempstring)
So I figured out that I needed to convert the bytes to hex in order to get them to match what is viewed in the Microsoft Management Console. Once I began doing that the only problem I ran into is that I discovered the indexing of the byte arrays are not in the same order as they are in Active Directory. -- so instead of looping I had to list out each index of the Byte array and sort them to their proper positions so that they match how they show up in AD.
My end function is:
Function bitread(ByVal GUID As Byte())
Dim tempVar As String
tempVar = GUID(3).ToString("X02") & GUID(2).ToString("X02") _
& GUID(1).ToString("X02") & GUID(0).ToString("X02") & "-" _
& GUID(5).ToString("X02") & GUID(4).ToString("X02") & "-" _
& GUID(7).ToString("X02") & GUID(6).ToString("X02") & "-" _
& GUID(8).ToString("X02") & GUID(9).ToString("X02") & "-" _
& GUID(10).ToString("X02") & GUID(11).ToString("X02") _
& GUID(12).ToString("X02") & GUID(13).ToString("X02") _
& GUID(14).ToString("X02") & GUID(15).ToString("X02")
Return tempVar
End Function
Called with:
bitread(Item.Properties("msFVE-RecoveryGUID")(0))

Getting BC31019 excepetion while compiling vb.net at runtime on Windows 10

we are generating a mass of documents very dynamically. Therefore we concatenate source code and build a dll at runtime. This is running since windows XP.
Now we are in tests of windows 10 and it fails compiling this dll with the error "BC31019: Unable to write to output file 'C:\Users[name]AppData\Local\Temp\xyz.dll': The specified image file did not contain a resource section"
For testing purposes we remove all generated source code and replace it by a rudimental class with only one function (throwing an exception with specified text) and no referenced assemblies.
This is also running on all machines except windows 10. Same error.
Can anybody guess why?
This is the rudimental method
Public Sub Compile()
Dim lSourceCode = "Namespace DynamicOutput" & vbCrLf &
" Public Class Template" & vbCrLf &
" Sub New()" & vbCrLf &
" End Sub" & vbCrLf &
" Public Sub Generate(ByVal spoolJob As Object, ByVal print As Object)" & vbCrLf &
" Throw New System.Exception(""Generate reached"")" & vbCrLf &
" End Sub" & vbCrLf &
"" & vbCrLf &
" End Class" & vbCrLf &
"End Namespace"
Dim lParams As CodeDom.Compiler.CompilerParameters = New CodeDom.Compiler.CompilerParameters
lParams.CompilerOptions = "/target:library /rootnamespace:CompanyName /d:TRACE=TRUE /optimize "
lParams.IncludeDebugInformation = True
lParams.GenerateExecutable = False
lParams.TreatWarningsAsErrors = False
lParams.GenerateInMemory = True
Dim lProviderOptions As New Dictionary(Of String, String) From {{"CompilerVersion", "v4.0"}}
Dim lResult As CodeDom.Compiler.CompilerResults = Nothing
Using provider As New VBCodeProvider(lProviderOptions)
lResult = provider.CompileAssemblyFromSource(lParams, lSourceCode)
End Using
' ... check for errors
Dim lInstance As Object = lResult.CompiledAssembly.CreateInstance("CompanyName.DynamicOutput.Template")
lInstance.GetType.GetMethod("Generate").Invoke(lInstance, New Object() {Me.SpoolJob, Me.Print})
End Sub

Writing To Text File, File In Use By Another Process, Multithreaded Application .NET

Afternoon,
I have a program whereby I really need to be keeping a log of some kind to ascertain what the program is doing. Essentially the software monitors for a window on the desktop to live pause a call recording on our Call Recorder Server.
Lets on argument say a Call Recording itself was pulled up by a monitoring agent and they state that a certain sensitive part of the conversation has been recorded when really it should have been silenced, if they were to say the agent hadn't done their job and clicked the pause recording button OR the onfocus action hadn't occurred I would have a situation whereby I would need to prove what the software was doing at the same.
I decided that I would write the actions of the software to a .txt file stored in the users app data.
This works for the most part, however every now and then even though the .txt is never accessed by any other program I get 'This file is in use by another process'.
This application is multithreaded and does make very frequent calls to write to the log, I am using the below code:
Private Sub WriteToLog(ByVal strSubTitle As String, ByVal strLogInfo As String)
Try
If My.Computer.FileSystem.FileExists(strLogFilePath) = True Then
'Delete yesterdays log file
Dim strFileDate As Date = File.GetCreationTime(strLogFilePath)
strFileDate = FormatDateTime(strFileDate, DateFormat.ShortDate)
'If strFileDate < Date.Today Then
' My.Computer.FileSystem.DeleteFile(strLogFilePath)
'End If
Using outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(strLogFilePath, True)
outFile.WriteLine("" & Date.Today & "," & Date.Now.ToLongTimeString & ", " & strUsername & ", " & strSubTitle & ", " & Replace(strLogInfo, ",", "|") & "")
outFile.Close()
End Using
''CSV File
'outFile.WriteLine("" & Date.Today & "," & Date.Now.ToLongTimeString & ", " & strUsername & ", " & strSubTitle & ", " & Replace(strLogInfo, ",", "|") & "")
'outFile.Close()
Else
Using outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(strLogFilePath, False)
outFile.WriteLine("" & Date.Today & "," & Date.Now.ToLongTimeString & ", " & strUsername & ", " & strSubTitle & ", " & Replace(strLogInfo, ",", "|") & "")
outFile.Close()
End Using
'CSV File
'outFile.WriteLine("Date, Time, Username, Sub(Process), Information")
'outFile.WriteLine("" & Date.Today & "," & Date.Now.ToLongTimeString & ", " & strUsername & ", " & strSubTitle & ", " & Replace(strLogInfo, ",", "|") & "")
'outFile.Close()
End If
Catch ex As Exception
CreateErrorFile(ex.Message, ex.StackTrace, "Log Write Failure!")
End Try
End Sub
Is there any advice/pointers someone could state as to why this would be saying another process is using the file.
I'm guessing the situation would occur when two separate threads try to do the 'WriteToLog' Sub while one or the other is writing to the file.
Am I on the right tracks? If so how could I rectify this?
Cheers,
James
You will either want to make it so that only one thread has the ability to write to the log file by using the Invoke method from the secondary thread(s) to call the write functionality on the main thread, or you can use one of .NET's various synchronization mechanisms.
Here is a simple example of the first approach:
Private Sub BackgroundMethod()
'do stuff
Me.Invoke(New Action(Of String)(AddressOf WriteToLog), "write a line blah blah")
'do more stuff
End Sub
Private Sub WriteToLog(valueToWrite As String)
System.IO.File.AppendAllLines(MyLogFilePath, {valueToWrite})
End Sub
Here's an example using a SyncLock block:
Private lock As New Object()
Private Sub BackgroundMethod()
'do stuff
WriteToLog("write a line blah blah")
'do more stuff
End Sub
Private Sub WriteToLog(valueToWrite As String)
SyncLock (lock)
System.IO.File.AppendAllLines(MyLogFilePath, {valueToWrite})
End SyncLock
End Sub
MSDN has good information on synchronization mechanisms: http://msdn.microsoft.com/en-us/library/ms228964%28v=vs.110%29.aspx
I would use a global Queue where new entries get added to and if the log writer is not busy then start it to write down all available lines.
sth like:
Private LogList As New Queue(Of String)
Private WriterBusy As Boolean = False
Private Sub WriteToLog(ByVal strSubTitle As String, ByVal strLogInfo As String)
LogList.Enqueue("" & Date.Today & "," & Date.Now.ToLongTimeString & ", " & strUsername & ", " & strSubTitle & ", " & Replace(strLogInfo, ",", "|") & "")
If WriterBusy = True Then Exit Sub
WriterBusy = True
Try
If My.Computer.FileSystem.FileExists(strLogFilePath) = True Then
...
Using outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(strLogFilePath, True)
While LogList.Count > 0
outFile.WriteLine(LogList.Dequeue)
End While
outFile.Close()
End Using
...
End Try
WriterBusy = False
End Sub

Get Text between characters in a string

I have a text file with a list of music that looks like this:
BeginSong{
Song Name
Artist
Genre
}EndSong
There are multiple instances of this.
I'm wanting to get the text between the BeginSong{ and }EndSong and put the song info
into a string array. Then I want to add each instance to a ListBox as Artist - Song Name
(that part I'm sure I can figure out though). I hope that was a clear description.
Use the ReadLine() function of the FileStream
since you already know the order of the information, you should be able to loop all File Lines and store them in their corresponding properties.
Pseudo:
WHILE Reader.Read()
Store Line in BeginSongTextVariable
Read Next Line
Store Line in SongNameVariable
Read Next Line
Store Line in ArtistNameVariable
Read Next Line
Store Line in GenreVariable
Read Next Line
Store Line in EndSongTextVariable
Add The Above Variables in List
End While
You can use a regular expression with named groups:
BeginSong{\n(?<song_name>.*)\n(?<artist>.*)\n(?<genre>.*)\n}EndSong
Something like this:
Imports System.Text.RegularExpressions
'...
Dim s As New Regex("BeginSong{\n(?<song_name>.*)\n(?<artist>.*)\n(?<genre>.*)\n}EndSong")
Dim mc As MatchCollection = s.Matches(inputFile)
For Each m As Match In mc
Dim song_name As String = m.Groups("song_name").Value
Dim artist As String = m.Groups("artist").Value
Dim genre As String = m.Groups("genre").Value
'use or store these values as planned
Next
There is a nice answer from Neolisk that uses Regular Expressions. But since you also included the VB6 tag in addition to VB.NET, I'll take a shot at a VB6 solution.
You can use the string Split function, and split on the "ends", i.e. "BeginSong{" and "}EndSong"
Dim songInfos As String
Dim firstArray() As String
Dim secondArray() As String
Dim thirdArray() As String
Dim songInfoArray() As String
Dim i As Integer
Dim songCounter As Integer
' to test:
songInfos = songInfos & "BeginSong{" & vbNewLine
songInfos = songInfos & "Song Name1" & vbNewLine
songInfos = songInfos & "Artist1" & vbNewLine
songInfos = songInfos & "Genre1" & vbNewLine
songInfos = songInfos & "}EndSong" & vbNewLine
songInfos = songInfos & "BeginSong{" & vbNewLine
songInfos = songInfos & "Song Name2" & vbNewLine
songInfos = songInfos & "Artist2" & vbNewLine
songInfos = songInfos & "Genre2" & vbNewLine
songInfos = songInfos & "}EndSong"
firstArray = Split(songInfos, "BeginSong{")
songCounter = 0
ReDim songInfoArray(2, 0)
For i = 1 To UBound(firstArray) Step 1
secondArray = Split(firstArray(i), "}EndSong")
thirdArray = Split(secondArray(0), vbNewLine)
songInfoArray(0, songCounter) = thirdArray(1)
songInfoArray(1, songCounter) = thirdArray(2)
songInfoArray(2, songCounter) = thirdArray(3)
songCounter = songCounter + 1
If i < UBound(firstArray) Then
ReDim Preserve songInfoArray(2, songCounter)
End If
Next i
The watch after the last line. Note the structure of songInfoArray, which was required for it to be ReDimmed

Visual basic and modules

Im writing a application in visual basic to tell the user about their pc.
All this is in a module
Imports Microsoft.VisualBasic.Devices
Imports System.Management
Imports System.Net
Imports System.IO
Imports System.Windows.Forms
Imports System.Deployment.Application
Module ComputerSpecModule
Public Enum infotypes
ProcesserName
VideocardName
VideocardMem
End Enum
Public Function getinfo(ByVal infotype As infotypes) As String
Dim info As New ComputerInfo : Dim value, vganame, vgamem, proc As String
Dim searcher As New Management.ManagementObjectSearcher( _
"root\CIMV2", "Select * FROM Win32_VideoController")
Dim searcher1 As New Management.ManagementObjectSearcher( _
"Select * FROM Win32_Processor")
If infotype = infotypes.ProcesserName Then
For Each queryObject As ManagementObject In searcher1.Get
proc = queryObject.GetPropertyValue("Name").ToString
Next
value = proc
ElseIf infotype = infotypes.VideocardName Then
For Each queryObject As ManagementObject In searcher.Get
vganame = queryObject.GetPropertyValue("Name").ToString
Next
value = vganame
ElseIf infotype = infotypes.VideocardMem Then
For Each queryObject As ManagementObject In searcher.Get
vgamem = queryObject.GetPropertyValue("AdapterRAM").ToString
Next
value = Math.Round((((CDbl(Convert.ToDouble(Val(vgamem))) / 1024)) / 1024), 2) & " MB"
End If
Return value
End Function
Public oAddr As System.Net.IPAddress 'gets the ipv4 add
Public sAddr As String
Public EmailStarterMessage As String = "This message was sent by SpecMee. SpecMee is a light weight application designed to allow the users to find out the specifications of their machines. Please download this application free at http://www.wilson18.com/projects/SpecMee/" + _
Environment.NewLine + _
"" + _
Environment.NewLine + _
"" + _
Environment.NewLine + _
""
'PC SPEC CONTENT
Public ComputerName As String = (My.Computer.Name.ToString)
Public myOS As String = (My.Computer.Info.OSFullName)
Public Processor As String = (getinfo(infotypes.ProcesserName))
Public HDD As String = (Format((My.Computer.FileSystem.Drives.Item(0).TotalSize.ToString / 1024) / 1024 / 1024, "###,###,##0 GB"))
Public RAM As String = (Format((My.Computer.Info.TotalPhysicalMemory / 1024) / 1024 / 1024, "###,###,##0 GB"))
Public VideoCard As String = (getinfo(infotypes.VideocardName))
Public VideoCardMemory As String = (getinfo(infotypes.VideocardMem))
Public Function Resolution() As String
Dim intx As Integer = Screen.PrimaryScreen.Bounds.Width
Dim inty As Integer = Screen.PrimaryScreen.Bounds.Height
Return intx & " x " & inty
End Function
Public Function InternalIPAddress()
With System.Net.Dns.GetHostByName(System.Net.Dns.GetHostName())
oAddr = New System.Net.IPAddress(.AddressList(0).Address)
InternalIPAddress = oAddr.ToString
End With
End Function
Public Function ExternalIPAddress() As String
Dim uri_val As New Uri("http://www.wilson18.com/projects/SpecMee/curip.php")
Dim request As HttpWebRequest = HttpWebRequest.Create(uri_val)
request.Method = WebRequestMethods.Http.Get
Dim response As HttpWebResponse = request.GetResponse()
Dim reader As New StreamReader(response.GetResponseStream())
Dim myip As String = reader.ReadToEnd()
response.Close()
Return myip
End Function
Public EmailContent As String = ("Computer Name: " & ComputerName & Environment.NewLine & "Operating System: " & myOS & Environment.NewLine & "Processor: " & Processor & Environment.NewLine & "Hard Drive Size : " & HDD & Environment.NewLine & "RAM: " & RAM & Environment.NewLine & "Graphics Card: " & VideoCard & Environment.NewLine & "Graphics Onboard Memory: " & VideoCardMemory & Environment.NewLine & "Resolution: " & Resolution() & Environment.NewLine & "Internal IP Address: " & InternalIPAddress() & Environment.NewLine & "External IP Address: " & ExternalIPAddress() & Environment.NewLine)
End Module
The problem I am having is that if one of the things in the module fails such as if the users graphics card does not have any onboard memory then it will fail.This is causing everything else to fail aswell...
I am very new to visual basic so ifyou could please excuse me if I have made any stupidly obvious errors and any suggestions are welcome
Thanks in advance.
Place the parts that can fail in a Try-Catch-statement
Public VideoCardMemory As String = getinfo(infotypes.VideocardMem)
Public Function getinfo(ByVal infotype As infotypes) As String
Try
...
value = ...
...
Catch
value = "Cannot be accessed!"
End Try
Return value
End Function