ip: 3.145.63.148 DKs blog - VB.NET examples

DK's Blog

VB.NET examples


vb.net  how to use Configuration from web.config (app.config)

 

default.aspx:

ConfigurationManager.AppSettings("connStr"))

web.config:

< appSettings>
	< add key="conn" value="user id=DBUser;password=DBPass;initial catalog=DBName;data source=ServerName;Connect Timeout=10" />
< /appSettings>
 

Vb.net / asp.net database

 example:
Dim Conn As System.Data.SqlClient.SqlConnection
Dim dr As System.Data.SqlClient.SqlDataReader
Dim cmd As System.Data.SqlClient.SqlCommand

Conn = New System.Data.SqlClient.SqlConnection(ConfigurationManager.AppSettings("connStr"))
Conn.Open()

Cmd = New System.Data.SqlClient.SqlCommand("SELECT * FROM table", Conn)
dr = Cmd.ExecuteReader()
dr.Read()

int ttt = Cint(dr(0))

Cmd.Dispose()
Cmd = Nothing
dr.Close()
dr = Nothing
conn.close()
conn = nothing

 


Writing to binary file (create if does not exists or open existing)

Dim arr(10) As Byte
Dim Stream As System.IO.FileStream = New System.IO.FileStream("filek", System.IO.FileMode.OpenOrCreate)
Stream.Write(arr, 0, 1)
Stream.Close()

 


Time measurement, execution time elapsed

Dim t as DateTime = Now() 'start time
'something here

Dim TimeElapsed as TimeSpan = Now().Subtract(t)
Console.Write(TimeElapsed.TotalSeconds.ToString("0.000000"))

 


Sent error mail when there is error on page (asp.net), example of send mail function

 

Import System.Net.Mail

Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.Error
    dim objErr as Exception = Server.GetLastError().GetBaseException()
    dim err as string = "Error Caught in Page_Error event" + vbNewLine + _ 
        "Error in: " + Request.Url.ToString() + vbNewLine + _
        "Error Message: " + objErr.Message.ToString()+ vbNewLine + _
        "Stack Trace:" + objErr.StackTrace.ToString() + vbNewLine
    Server.ClearError()
   
    if Request.ServerVariables ("REMOTE_ADDR")="MyIP" then
        Response.Write(err.ToString())
        response.end()
    else
        SendMailMessage("myMail1@damir.globaldizajn.hr", "myMail2@damir.globaldizajn.hr", "mySubject", "Error subject")
        ''redirect to some page
        response.redirect ("damir.globaldizajn.hr")
        response.end()
    end if
End Sub

function SendMailMessage(From as string, MailTo as string, subject as string, msg as string) as boolean
	Dim smtp As New SmtpClient("localhost")
	try 
		dim objMail as New System.Net.Mail.MailMessage()
		objMail.From = New MailAddress(From)
		objMail.To.Add(MailTo)
		objMail.Subject = subject
		objMail.IsBodyHtml = False
		objMail.Body = msg
		smtp.Send(objMail)
	catch e as Exception
		return false 
	end try

	return true
end function

 


Example of regular expression (regexp) Match

 

Imports System.Text.RegularExpressions

Dim t As String = "./asdasd/asdasd/ad asd /mile.jpg"

Response.Write( "Full path to image: " & t )
    
Dim myMatches As MatchCollection = Regex.Matches(t, "([\.abcdefgh]:?(/[^/]+)*/(.*)\.jp[eg|g]?)")
    
For Each m As Match In myMatches
   Response.Write("*****" + m.Groups(1).Value + " | ")
   Response.Write(m.Groups(2).Value + "******")
Next

Example regular expression read file repace double vbNewLine with single one

 

Imports System.Text.RegularExpressions
Imports System.IO

Dim s As String
Dim s As String
Dim sr As StreamReader
Dim sw As StreamWriter

sr = New StreamReader("c:\1.txt")
s = sr.ReadToEnd()
sr.Close()

s = Regex.Replace(s, "\x0d\x0a\x0d\x0a", vbNewLine)

sw = New StreamWriter("c:\2.txt")
sw.Write(s)
sw.Close()

 


Example how to send email in case of error on web page (asp.net), add this in web.config for 

 

< system.web >
< healthMonitoring enabled="true" >
  < providers >
    < clear />
    < add type="System.Web.Management.SimpleMailWebEventProvider"
      name="EmailWebEventProvider"
      from="error@damir.globaldizajn.hr"
      to="error@globaldizajn.hr"
      bodyHeader="error in damir.globaldizajn.hr"
      bodyFooter="web.config based error sending facility"
      subjectPrefix=" *** damir.globaldizajn.hr *** "
      buffer="false" />
  providers >
  < rules >
    < clear />
    < add name="Email all Errors" eventName="All Errors"
      provider="EmailWebEventProvider" profile="Default" minInstances="1"
      maxLimit="2" minInterval="00:01:00" />
 < /rules >
< /healthMonitoring >
< /system.web >
< system.net >
  < mailsettings >
  
    < network host="localhost" port="25">< /network>
  < smtp >
  < /mailsettings>
< /system.net >

Impersonate example in vb.net (asp.net)

replace [] with <>

 

<%@ Page Language="vb"%>
<%@ Import Namespace="System.IO"%>
<%@ Import Namespace="System.Runtime.InteropServices" %>
< script runat="server">
Dim lnToken As IntPtr
	
[DllImport("advapi32.dll", SetLastError := True)] _
Public Shared Function LogonUser(ByVal lpszUsername As String, ByVal lpszDomain As String, ByVal lpszPassword As String, ByVal dwLogonType As Integer, ByVal dwLogonProvider As Integer, ByRef phToken As IntPtr) As Integer
End Function
[DllImport("advapi32.dll", SetLastError := True)] _
Public Shared Function ImpersonateLoggedOnUser(ByVal hToken As IntPtr) As Integer
End Function
[DllImport("advapi32.dll", SetLastError := True)] _
Private Shared Function RevertToSelf() As Integer
End Function
[DllImport("kernel32.dll", SetLastError := True)] _
Private Shared Function CloseHandle(ByVal hObject As IntPtr) As Integer
End Function
Dim TResult As Integer=0

Sub Page_Load(sender as Object, e as EventArgs)
  TResult  = LogonUser("AKZ_UploadBackupBaze", ".", "AKZ_UploadBackupBaze333", 9, 3, lnToken)
  if TResult > 0 Then
    ImpersonateLoggedOnUser(lnToken)
  end If

  file.delete("\\MyServer\MyShare\test.txt")
    	
  if TResult > 0 Then
    RevertToSelf()
    CloseHandle(lnToken)
  end if

End Sub

< /scriipt>

 


Example of regular expression (regexp) Replace

 

Dim result As String = Regex.Replace(s, "\w+", "123")

 


 

Example of bundling and minification in asp.net 4.0

(if load order of JavaScript is important, use filename to force load order!, also if ValidateRequest="false" then in web.config should be  since this is changed from .net2 to .net4)

2 things are needed

1. you need in /bin directory 3 files:

Microsoft.Web.Infrastructure.dll
System.Web.Optimization.dll
WebGrease.dll

2. you need to modify .aspx file

<%@ Page Title="Home Page" Language="vb" %>
<%@ Import namespace="System.Web.Optimization" %>

    Sub Page_Load(sender As Object, e As EventArgs)
        System.Web.Optimization.BundleTable.EnableOptimizations = True 'only to override debug
        
        Dim siteCssBundle = New StyleBundle("~/Content/css").include("~/default.css")
        siteCssBundle.IncludeDirectory("~/Content", "*.css")
        BundleTable.Bundles.Add(siteCssBundle)
        
        Dim siteJsBundle = New ScriptBundle("~/Scripts/js")
        siteJsBundle.IncludeDirectory("~/Scripts", "*.js")
        BundleTable.Bundles.Add(siteJsBundle)
    End Sub

< script type="text/javascript" src="<%:System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js") %>" > < /script >

< link href="<%:System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Content") %>" rel="stylesheet" type='text/css'/ >

if site uses URL rewrite, add this as first rule

< rule name="Scripts rule" stopProcessing="true">
  < match url="^Scripts/" ignoreCase="false" />
  < action type="None" />
< /rule>  

 


Example how to enable debugging in only one aspx page

if web.config contains:

< compilation defaultLanguage="vb" debug="false" />

add this to page which you want to have debugging on

<%@ Page Debug="true" %>

 


How to change .net temp directory for web application here is example

 

Add tempDirectory="R:\Temp.NETv2" attribute to compilation in system.web in web.config for web application

 

< configuration>
  < system.web>
    < compilation defaultLanguage="vb" debug="false" tempDirectory="R:\Temp.NETv2" />
  < / system.web>
< / configuration>

 


How to change every HTMLencoded character back to original char 

example change ó to chr(243) with regular expression and small vb function

 

Dim myMatches As MatchCollection
Dim m As Match
Dim myRegex As Regex

function ChangeHTML2CHR(byval t as string) as string   
    myRegex = New Regex("&#(\d{1-3});")
    myMatches = myRegex.Matches(t,RegexOptions.IgnoreCase)
    
    For Each m In myMatches
    	t = replace(t, m.groups(0).Value, chr(m.groups(1).Value))
    next
    
    return t           
end function

How to add Error line number in Throw() command

in web.config debug must be set to true (without there is no stack trace)

 

function exceptionLineNumber()

 Dim st As New System.Diagnostics.StackTrace(True)
 Dim sb as New StringBuilder()
 For i as int32 = 0 To st.FrameCount - 1
  Dim sf As System.Diagnostics.StackFrame = st.GetFrame(i)
  if sf.GetFileLineNumber() > 0 then
   sb.appendLine("High up the call stack, Method: " & sf.GetFileLineNumber() & " " & sf.GetMethod().toString() & " < br/ > ")
  end if
 Next
 
 return sb.toString()
 
end function

example:

try
  Throw New System.Exception("An exception has occurred.")
catch ex as exception
  response.write(exceptionLineNumber())
  response.end
end try

 


How to use parameters with sqlhelper

ASP.NET 4+
in /bin directory there MUST be Microsoft.ApplicationBlocks.Data.dll

<%@ Import Namespace="Microsoft.ApplicationBlocks.Data.SqlHelper"%>

Dim sparams As New List(Of SqlParameter)
Dim sql="insert into TableName (username,pass,IP) values (@username,@pass,@IP)"

sparams.Add(New SqlParameter("@username", username))
sparams.Add(New SqlParameter("@pass", password))
sparams.Add(New SqlParameter("@IP", Request.Servervariables("REMOTE_ADDR")))

ExecuteNonquery(s, CommandType.Text, sql, sqlparams.ToArray())

 


How to avoid nasty error page "HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client."

 

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
    Dim ex As Exception = Server.GetLastError()
    If TypeOf ex Is HttpRequestValidationException Then
        Response.Clear()
        Response.StatusCode = 200
        Response.Write(" < html >  < head >  < title > HTML Not Allowed < /title >  < body > HTML entry is not allowed on this page,  < a href='javascript:history.go(-1);' > go back < /a >  < /body >  < /html > ")
        Response.End()
    End If
End Sub

 


How to use SqlDataReader and NOT to forget to close it after usage

in /bin directory there MUST be Microsoft.ApplicationBlocks.Data.dll

<%@ Import Namespace="Microsoft.ApplicationBlocks.Data.SqlHelper"%>

using  r = SqlHelper.ExecuteReader(sConnStr, CommandType.Text, sql)
    while r.read
    end while
end using

 


How to format decimal number with culture info

 

Dim d as decimal

d.ToString(CultureInfo.InvariantCulture)
d.Tostring("#.##", New System.Globalization.CultureInfo("en-US"))

 


How to format integer with leading zeros

 

Dim br as Int32 = 12
Dim s as string = br.ToString("0000")
' s = "0012"

 


How to use AntiXSS from Microsoft

steps:

1. Copy AntiXssLibrary.dll in /bin directory

2. add at top ASPX page:

<%@ Import Namespace="Microsoft.Security.Application"%>

3. use one of this function:

Dim s As String = Request("s")

s = AntiXss.HtmlAttributeEncode(s) 'for response.write inside HTML tags'
s = AntiXss.UrlEncode(s)
s = AntiXss.XmlEncode(s) 'for response.write inside XML'
s = AntiXss.JavaScriptEncode(s)'for response.write inside javascript area'

 


How to enable upload of lage files to IIS through web.config

 

< system.webServer>
...
  < security>
    < requestFiltering>
      < requestLimits maxAllowedContentLength="524288000" />
    < / requestFiltering>
  < /security>
< /system.webServer>

  < httpRuntime
      executionTimeout="1200"
      maxRequestLength="524288000"
      useFullyQualifiedRedirectUrl="false"
      minFreeThreads="8"
      minLocalRequestFreeThreads="4"
      appRequestQueueLimit="100"
      requestValidationMode="2.0" />
< /system.web>

 


How to display AbsolutePath and Query properties separated by a question mark

This is usefull when web uses URLRewrite

Response.Write(Request.Url.PathAndQuery)

How to enable display in IIS files like http://mydomain.com/fsdafasdffasdfa as text files in web.config

 

< system.webserver>
  < staticcontent>
    < mimemap fileextension="." mimetype="text/xml" > < /mimemap>
  < /staticcontent>
< /system.webserver>

 


How to decode JSON to object without declaring object first

json is String vartiable with valid JSON, if there is "brand" inside JSON this is how to fetch it

dim cardData as object
cardData = System.Web.Helpers.Json.Decode(json)
Response.Write(cardData.brand)

 

in bin dir:

System.Web.Helpers.dll
System.Web.Razor.dll
System.Web.WebPages.dll
System.Web.WebPages.Deployment.dll
System.Web.WebPages.Razord.dll

 


How to comapre list object with another list object in LINQ

 

ienum1.Where(Function(a) ienum2.Any(Function(b) b.import_id = a.import_id)).FirstOrDefault()

 

 


How to force HTTPS on IIS with UrlRewrite and also force from non www to www

http to https on IIS with one rule, add this in web.config as first rule

 

< rule name="HTTP to HTTPS redirect" stopProcessing="true">
	< match url=".*" />
	< conditions logicalGrouping="MatchAny">
		< add input="{HTTPS}" pattern="OFF" />
		< add input="{HTTP_HOST}" pattern="^damir.globaldizajn.hr$" />
	< /conditions>
	< action type="Redirect" url="https://www.damir.globaldizajn.hr/{R:0}" redirectType="Permanent" />
< /rule>

 


How to enable TLS1.2 or TLS1.1 or TLS1.0 in VB.NET

 

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls

 

How to enable TLS1.3 or TLS1.2 or TLS1.1 or TLS1.0 in VB.NET

TLS1.3 requres .NET Framework 4.8 or higher !!!

 

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls13 or SecurityProtocolType.Tls12 Or SecurityProtocolType.Tls11 Or SecurityProtocolType.Tls

 

 


How to add rule in web.config for SSL certification check

 

< rule name="SSL provjera" stopProcessing="true">
	< match url="^\.well-known/.*" ignoreCase="false" />
< /rule>    

 


How to redirect http://domain.hr, http://www.domain.hr, https://domain.hr to https://www.domain.hr in one action

 

< rule name="httpsredirect" stopProcessing="true">
	< match url="(.*)" />
	< conditions logicalGrouping="MatchAny">
		< add input="{HTTPS}" pattern="off" />
		< add input="{HTTP_HOST}" pattern="^domain.hr$" />
		< add input="{HTTPS}" pattern="^domain.hr$" />			        
	< /conditions>
	< action type="Redirect" url="https://www.domain.hr/{R:0}" />
< /rule>

 


How to find out client IP if site is behind reverse proxy

Request.headers("X-Forwarded-For")

 


How to block IP with HTTP_X_FORWARDED_FOR in web.config

show empty.txt to IP who is harrasing your site.

 

< rule name="BlockRemote" stopProcessing="true">
	< match url=".*" ignoreCase="false" />
	< conditions logicalGrouping="MatchAny">
		< add input="{HTTP_X_FORWARDED_FOR}" pattern="xxx\.yyy\.www\.zzz" ignoreCase="true" />
		< add input="{HTTP_X_FORWARDED_FOR}" pattern="xxx\.yyy\.www\.zxx" ignoreCase="true" />
	< /conditions>
	< action type="Rewrite" url="/empty.txt" />
< /rule> 

 


How to block some querystring attack with web.config

create empty,txt file in root of web (put this in web.config)

< rule name="block1" stopProcessing="true">
	< match url="(.*)" ignoreCase="true" />
	< conditions>
		< add input="{QUERY_STRING}" pattern="^id=1234$" ignoreCase="true" />
	< /conditions>
	< action type="Rewrite" url="/empty.txt" appendQueryString="false" />
< /rule>	
	

 


How to block all rss.aspx request to web page from web.config

add rule in web.config

< rule name="rss block" stopProcessing="true">
	< match url="rss\.aspx$" />
	< action type="Rewrite" url="/empty.txt" />
< /rule>

 


How to remove headers from static files like pictures on IIS

remove leading space bevor < (put this in web.config)

 

< system.webServer>
	< modules runAllManagedModulesForAllRequests="true">
		< add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
	< /modules>
	< httpProtocol>
		< customHeaders>
			< remove name="X-Powered-By" />
			< remove name="X-AspNet-Version" />
			< remove name="Server" />	
			
			< add name="Content-Security-Policy" value="frame-ancestors 'self' www.epower.amadeus.com" />
			< add name="Strict-Transport-Security" value="max-age=31536000;"/>
			
		< /customHeaders>
	< /httpProtocol>
	< staticContent>
		< clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="1.00:00:00" />
	< /staticContent>
< /system.webServer>

 


How to override IIS error status code 400 / 404 / 500

In web.config add httpErrors like this

< system.webServer>
    < httpErrors errorMode="Custom" existingResponse="Replace">
		  < remove statusCode="400"/> 
		  < error statusCode="400" responseMode="ExecuteURL" path="/404.html"/> 
		  < remove statusCode="404"/>
		  < error statusCode="404" responseMode="ExecuteURL" path="/404.html" /> 
		  < remove statusCode="500"/> 
		  < error statusCode="500" responseMode="ExecuteURL" path="/404.html" /> 
	< /httpErrors>
< /system.webServer>

 

 

 

@2016