Visual Basic – Important Stuff to know

The below are little things that have helped me in my development career.

-Cut and Paste code

 

***************************** Force TLS 1.2 *******************************************
System.Net.ServicePointManager.SecurityProtocol = DirectCast( 3072, system.Net.SecurityProtocolType)

***** Debug Visual Studio Service

Shared Sub Main()
#If DEBUG Then
Dim servicio As New Service1
servicio.OnStart(Nothing)
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite)
#Else
Dim ServicesToRun() As System.ServiceProcess.ServiceBase ‘original code
ServicesToRun = New System.ServiceProcess.ServiceBase() {New Service1} ‘original code
System.ServiceProcess.ServiceBase.Run(ServicesToRun) ‘original code
#End If

 

**** DATE FUNCTIONS ****
Public Shared Function FirstDayOfQuarter(ByVal DateIn As DateTime) As DateTime
‘ Calculate first day of DateIn quarter,
‘ with quarters starting at the beginning of Jan/Apr/Jul/Oct
Dim intQuarterNum As Integer = (Month(DateIn) – 1) \ 3 + 1
Return DateSerial(Year(DateIn), 3 * intQuarterNum – 2, 1)
End Function

Public Shared Function LastDayOfQuarter(ByVal DateIn As Date) As Date
‘ Calculate last day of DateIn quarter,
‘ with quarters ending at the end of Mar/Jun/Sep/Dec
Dim intQuarterNum As Integer = (Month(DateIn) – 1) \ 3 + 1
Return DateSerial(Year(DateIn), 3 * intQuarterNum + 1, 0)
End Function

 

*** READ AND WRITE QUICK TEXT FILE.
Using oSR As StreamReader = New StreamReader(sFileName)
_strEmailBody = oSR.ReadToEnd
End Using

Using oSR As StreamWriter = New StreamWriter(sFileName)
_strEmailBody = oSR.WriteLine()
End Using

 

***************************** LOG 4 NET ***************************************************
Private _log As ILog = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)

Public Sub Initialize()

log4net.GlobalContext.Properties(“LogPath”) = _LogPath
If Not Directory.Exists(_LogPath) Then Directory.CreateDirectory(_LogPath)

Dim logfile As New System.IO.FileInfo(Path.Combine(My.Application.Info.DirectoryPath, “log4net.config”))
log4net.Config.XmlConfigurator.ConfigureAndWatch(logfile)

Dim log4netIsConfigured As Boolean = log4net.LogManager.GetRepository().Configured
If log4netIsConfigured = False Then
For Each oMessage As log4net.Util.LogLog In log4net.LogManager.GetRepository.ConfigurationMessages
_log.Info(“Log4Net” & oMessage.Message.ToString)
Next
End If

End Sub

log4net.Config

<!–Name the different types of appenders–>
<appender name=’RollingLogFileAppender’ type=’log4net.Appender.RollingFileAppender’>
<file type=’log4net.Util.PatternString’ value=’%property{LogPath}\’ />
<appendToFile value=”true” />
<rollingStyle value=”Composite” />
<MaximumFileSize value=”5MB” />
<MaxSizeRollBackups value=”1″ />
<staticLogFileName value=”false” />
<datePattern value=”yyyyMMdd’.log'” />