Hack Forums
[.NET] Some useful code snippets - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [.NET] Some useful code snippets (/showthread.php?tid=4529199)



Some useful code snippets - Dangerous Beef - Nov 9, 2014

Just wanted to share some of the code I'm using on the project I'm working on with you guys because I'm that nice.

A better random system(Love this).
Code
Dim objRandom As New System.Random( _
CType(System.DateTime.Now.Ticks Mod System.Int32.MaxValue, Integer))
    'Link to creators article: http://www.developerfusion.com/code/3940/random-numbers-that-work/
    Public Function GetRandomNumber( _
      Optional ByVal Low As Integer = 1, _
      Optional ByVal High As Integer = 100) As Integer
      ' Returns a random number,
      ' between the optional Low and High parameters
      Return objRandom.Next(Low, High + 1)
    End Function
Usage:
Code
GetRandomNumber(MinVal, MaxVal) 'See Reference #1

Get the average between 2 numbers.

Code
Public Function GetAverage(ByVal val1 As Integer, val2 As Integer)
      Dim input1 As Integer = CInt(val1)
      Dim input2 As Integer = CInt(val2)
      Return (input1 + input2) / 2
    End Function
Usage:
Code
GetAverage(Val1, Val2)

Log system, Requires a Rich text box control. (Useful for debugging.)
Code
Public Sub AddToLog(ByVal TextToInput As String)
      rtb1_Log.Text += TextToInput
      rtb1_Log.Text += vbNewLine 'You can also use environment.Newline for this.
      rtb1_Log.SelectionStart = rtb1_Log.Text.Length 'Set the current caret position at the end
      DebugWindow.rtb1_Log.ScrollToCaret() 'Now scroll it automatically
    End Sub
Usage:
Code
AddToLog("Hello World")

Get percentage between 2 numbers.
Code
'Calculate Percent of the MinVal and the MaxVal
    Public Function GetPercent(ByVal MinVal As Long, ByVal MaxVal As Long) As Integer
      If MinVal >= MaxVal Then
      Return Int(100)
      Else
      Return Int(MinVal / MaxVal * 100 + 0.5)
      End If

    End Function
Usage:
Code
GetPercent(MinVal, MaxVal)

Might add some more if wanted.


* - SIM-1847363 - Nov 9, 2014

I like the random system the most, but the rest is still good.