How to get the current path using VBScript

To get the current path using VBScript you can use the snippet below.

Samples

VBScript Sample

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

Please rate this snippet

How to catch specific MS-SQL SQLExceptions in C# and VB.NET

To catch specific SQLExceptions using Microsoft.NET and Microsoft Sequel Server you can use the snippet below. You also need to look for the specific error numbers/codes you want to catch. To do this you can either execute the following query in the SQL Management Studio or you can use this
List of SQLException Numbers/Codes (Direct-DL around 15mb).

Samples

T-SQL Sample

C# Sample

VB.NET Sample

Compatibility: working .NET 2.0 working .NET 3.0 not tested .NET 3.5 not working .NET 4.0 not working .NET 4.5not working .NET 4.6

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

Please rate this snippet

How to match strings using wildcards in C# and VB.NET

To match strings using wildcards in C# and VB.NET you can use the following snippet.
It will internally convert the wildcard string to a Regex.

The Console-Output of this sample will be:

C:\Test\myFile01.xml
C:\Test\myFile02.xml

Sample C#

#region

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

#endregion

namespace de.fesslersoft.RegexWildCard
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var fileList = new List<String>();
            fileList.Add(@"C:\Test\myFile01.xml");
            fileList.Add(@"C:\Test\myFile02.xml");
            fileList.Add(@"C:\Test\myFolder01.xml");
            fileList.Add(@"C:\Test\myFolder02.xml");

            var wildCard = new Wildcard("*File*.xml", RegexOptions.IgnoreCase);
            foreach (var file in fileList.Where(file => wildCard.IsMatch(file)))
            {
                Console.WriteLine(file);
            }
            Console.Read();
        }
    }


    public class Wildcard : Regex
    {
        public Wildcard(string pattern) : base(ToRegex(pattern))
        {
        }

        public Wildcard(string pattern, RegexOptions options) : base(ToRegex(pattern), options)
        {
        }

        public static string ToRegex(string pattern)
        {
            return "^" + Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$";
        }
    }
}

Sample VB.NET (autoconverted)

#Region ""

Imports System.Collections.Generic
Imports System.Linq
Imports System.Text.RegularExpressions

#End Region

Namespace de.fesslersoft.RegexWildCard
	Friend Class Program
		Private Shared Sub Main(args As String())
			Dim fileList = New List(Of [String])()
			fileList.Add("C:\Test\myFile01.xml")
			fileList.Add("C:\Test\myFile02.xml")
			fileList.Add("C:\Test\myFolder01.xml")
			fileList.Add("C:\Test\myFolder02.xml")

			Dim wildCard = New Wildcard("*File*.xml", RegexOptions.IgnoreCase)
			For Each file As var In fileList.Where(Function(file) wildCard.IsMatch(file))
				Console.WriteLine(file)
			Next
			Console.Read()
		End Sub
	End Class


	Public Class Wildcard
		Inherits Regex
		Public Sub New(pattern As String)
			MyBase.New(ToRegex(pattern))
		End Sub

		Public Sub New(pattern As String, options As RegexOptions)
			MyBase.New(ToRegex(pattern), options)
		End Sub

		Public Shared Function ToRegex(pattern As String) As String
			Return "^" + Escape(pattern).Replace("\*", ".*").Replace("\?", ".") + "$"
		End Function
	End Class
End Namespace

Please rate this snippet

How to get the current Database and Log Filesize using MSSQL

To get the current Database and Log Filesize using MSSQL you can use the snippet below. Tested using SQL Server 2012.

Sample MSSQL

with database_files_CTE as
(
    select
        name, type_desc, physical_name, size_mb = convert(decimal(11, 2), size * 8.0 / 1024),
        space_used_mb = convert(decimal(11, 2), fileproperty(name, 'spaceused') * 8.0 / 1024) from sys.database_files
)
select name,type_desc as [type],physical_name as [path],size_mb as [Filesize],space_used_mb as [Filesize used],
case size_mb when 0 then 0 else convert(decimal(5, 2), space_used_mb / size_mb * 100) end as [Filesize used %]  from database_files_CTE;

Sample Output

Query Results Filesizes

Please rate this snippet

What is the difference between typeof(), GetType() and IS in C# and VB.NET

What is the difference between typeof(), GetType() and is?

  • typeof() takes a type name specified at compile Time.
  • GetType() gets the Type of an Object at runtime
  • is returns true if an instance is in the inheritance tree. Since the is Keyword is casting the object, you should use it with care.
  • here is an example.

    class Employee { } 
    class Developer : Employee { }
    
    void PrintTypes(Employee e) { 
        print(e.GetType() == typeof(Employee)) // false 
        print(e is Employee)                   // true 
        print(e.GetType() == typeof(Developer))    // true
    }
    

    Please rate this snippet

    How to get the executable filename in C# and VB.NET

    To get the executable filename in C# and VB.NET you can use one the following methods.

    Sample C#

    //prefered way to retrieve exe filename
    Console.WriteLine(Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName));
     
    
    Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); //can cause problems when using click once, also this property does not always returns the right result.
    
    Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().Location)); //can fail when used in wcf application.
    Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase)); //better if shadow copy feature is active, but can fail when used in wcf application
    Console.WriteLine(Path.GetFileName(Assembly.GetEntryAssembly().Location));
    

    Sample VB.NET

    'prefered way to retrieve exe filename
    Console.WriteLine(Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName))
    
    
    Console.WriteLine(AppDomain.CurrentDomain.FriendlyName)
    'can cause problems when using click once, also this property does not always returns the right result.
    Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().Location))
    'can fail when used in wcf application.
    Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase))
    'better if shadow copy feature is active, but can fail when used in wcf application
    Console.WriteLine(Path.GetFileName(Assembly.GetEntryAssembly().Location))
    

    Please rate this snippet

    How to round to X decimal places in C# and VB.NET

    To round to X decimal places in C# and VB.NET you can use one of the following methods.
    Take a look at the output image to see the results.

    Sample ConsoleApp in C#

    static void Main(string[] args)
    {
    	decimal input = Decimal.Parse("3,546932");
    	decimal inputZero = Decimal.Zero;
    	decimal inputShort = Decimal.Parse("3,545");
    	decimal inputShorter = 1;
    
    	Console.WriteLine("######################################################################");
    	Console.WriteLine("");
    	Console.WriteLine("Testinput1:\t{0}", input);
    	Console.WriteLine("Testinput2:\t{0}", inputZero);
    	Console.WriteLine("Testinput3:\t{0}", inputShort);
    	Console.WriteLine("Testinput4:\t{0}", inputShorter);
    	Console.WriteLine("");
    
    	Console.WriteLine("########## using decimal.Round AwayFromZero 2 Decimals ##########");
    	Console.WriteLine("");
    	Console.WriteLine("Output 1:\t{0}",decimal.Round(input, 2, MidpointRounding.AwayFromZero));
    	Console.WriteLine("Output 2:\t{0}", decimal.Round(inputShort, 2, MidpointRounding.AwayFromZero));
    	Console.WriteLine("Output 3:\t{0}", decimal.Round(inputShorter, 2, MidpointRounding.AwayFromZero));
    	Console.WriteLine("Output 4:\t{0}", decimal.Round(inputZero, 2, MidpointRounding.AwayFromZero));
    	Console.WriteLine("");
    
    	Console.WriteLine("########## using decimal.Round ToEven 2 Decimals ##########");
    	Console.WriteLine("");
    	Console.WriteLine("Output 1:\t{0}", decimal.Round(input, 2, MidpointRounding.ToEven));
    	Console.WriteLine("Output 2:\t{0}", decimal.Round(inputShort, 2, MidpointRounding.ToEven));
    	Console.WriteLine("Output 3:\t{0}", decimal.Round(inputShorter, 2, MidpointRounding.ToEven));
    	Console.WriteLine("Output 4:\t{0}", decimal.Round(inputZero, 2, MidpointRounding.ToEven));
    	Console.WriteLine("");
    
    	Console.WriteLine("########## using .ToString(\"0.00\") 2 Decimals ##########");
    	Console.WriteLine("");
    	Console.WriteLine("Output 1:\t{0}", input.ToString("0.00"));
    	Console.WriteLine("Output 2:\t{0}", inputShort.ToString("0.00"));
    	Console.WriteLine("Output 3:\t{0}", inputShorter.ToString("0.00"));
    	Console.WriteLine("Output 4:\t{0}", inputZero.ToString("0.00"));
    	Console.WriteLine("");
    
    	Console.WriteLine("########## using .ToString(\"0.00\") 5 Decimals ##########");
    	Console.WriteLine("");
    	Console.WriteLine("Output 1:\t{0}", input.ToString("0.00000"));
    	Console.WriteLine("Output 2:\t{0}", inputShort.ToString("0.00000"));
    	Console.WriteLine("Output 3:\t{0}", inputShorter.ToString("0.00000"));
    	Console.WriteLine("Output 4:\t{0}", inputZero.ToString("0.00000"));
    	Console.WriteLine("");
    
    	Console.Read();
    }
    

    Sample ConsoleApp in VB.NET

    Private Shared Sub Main(args As String())
    	Dim input As Decimal = [Decimal].Parse("3,546932")
    	Dim inputZero As Decimal = [Decimal].Zero
    	Dim inputShort As Decimal = [Decimal].Parse("3,545")
    	Dim inputShorter As Decimal = 1
    
    	Console.WriteLine("######################################################################")
    	Console.WriteLine("")
    	Console.WriteLine("Testinput1:" & vbTab & "{0}", input)
    	Console.WriteLine("Testinput2:" & vbTab & "{0}", inputZero)
    	Console.WriteLine("Testinput3:" & vbTab & "{0}", inputShort)
    	Console.WriteLine("Testinput4:" & vbTab & "{0}", inputShorter)
    	Console.WriteLine("")
    
    	Console.WriteLine("########## using decimal.Round AwayFromZero 2 Decimals ##########")
    	Console.WriteLine("")
    	Console.WriteLine("Output 1:" & vbTab & "{0}", Decimal.Round(input, 2, MidpointRounding.AwayFromZero))
    	Console.WriteLine("Output 2:" & vbTab & "{0}", Decimal.Round(inputShort, 2, MidpointRounding.AwayFromZero))
    	Console.WriteLine("Output 3:" & vbTab & "{0}", Decimal.Round(inputShorter, 2, MidpointRounding.AwayFromZero))
    	Console.WriteLine("Output 4:" & vbTab & "{0}", Decimal.Round(inputZero, 2, MidpointRounding.AwayFromZero))
    	Console.WriteLine("")
    
    	Console.WriteLine("########## using decimal.Round ToEven 2 Decimals ##########")
    	Console.WriteLine("")
    	Console.WriteLine("Output 1:" & vbTab & "{0}", Decimal.Round(input, 2, MidpointRounding.ToEven))
    	Console.WriteLine("Output 2:" & vbTab & "{0}", Decimal.Round(inputShort, 2, MidpointRounding.ToEven))
    	Console.WriteLine("Output 3:" & vbTab & "{0}", Decimal.Round(inputShorter, 2, MidpointRounding.ToEven))
    	Console.WriteLine("Output 4:" & vbTab & "{0}", Decimal.Round(inputZero, 2, MidpointRounding.ToEven))
    	Console.WriteLine("")
    
    	Console.WriteLine("########## using .ToString(""0.00"") 2 Decimals ##########")
    	Console.WriteLine("")
    	Console.WriteLine("Output 1:" & vbTab & "{0}", input.ToString("0.00"))
    	Console.WriteLine("Output 2:" & vbTab & "{0}", inputShort.ToString("0.00"))
    	Console.WriteLine("Output 3:" & vbTab & "{0}", inputShorter.ToString("0.00"))
    	Console.WriteLine("Output 4:" & vbTab & "{0}", inputZero.ToString("0.00"))
    	Console.WriteLine("")
    
    	Console.WriteLine("########## using .ToString(""0.00"") 5 Decimals ##########")
    	Console.WriteLine("")
    	Console.WriteLine("Output 1:" & vbTab & "{0}", input.ToString("0.00000"))
    	Console.WriteLine("Output 2:" & vbTab & "{0}", inputShort.ToString("0.00000"))
    	Console.WriteLine("Output 3:" & vbTab & "{0}", inputShorter.ToString("0.00000"))
    	Console.WriteLine("Output 4:" & vbTab & "{0}", inputZero.ToString("0.00000"))
    	Console.WriteLine("")
    
    	Console.Read()
    End Sub
    

    OUTPUT

    Decimal Place Formatting

    Decimal Place Formatting

    Please rate this snippet

    How to use Doubleclick in Devexpress Gridview in C# and VB.NET

    Using doubleclick events in the Devexpress Gridview Control is a simple task.
    There are 2 different ways of doing this. The variant you choose, depends on the Gridview’s gridView.OptionsBehavior.Editable property. If this property is set to false you have to use the DoubleClick event. If this property is set to true you have to use the ShownEditor and HiddenEditor event. I will also give an example on how to combine both methods, if you are using both (true and false) on the gridView.OptionsBehavior.Editable.

    Samples

    OptionsBehavior.Editable set to False

    C# Sample

    VB.NET Sample

    OptionsBehavior.Editable set to True

    When inplace editing is enabled, a click on a grid cell activates the inplace editor (rowedit).
    All mouse events will be sent to the editor and cannot be handled by the GridView directly. The DoubleClick event handler is no longer being executed.

    C# Sample

    VB.NET Sample

    OptionsBehavior.Editable set to True or False at Runtime

    C# Sample

    VB.NET Sample

    If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

    Related links:

    Please rate this snippet

    NuGet: Failed to initialize the PowerShell Host

    Today i recieved the following Nuget Error while trying to install Automapper.

    Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize the host first.

    To fix that, close all Visual Studio instances and open the Powershell Console as Administrator. Enter Set-ExecutionPolicy RemoteSigned or Set-ExecutionPolicy Unrestricted. Be aware that you need to set the execution policy on both the x86 and the x64 Powershell Console.

    A more simple solution would be to put the code below in a File with an .reg extension and execute that.

    Windows Registry Editor Version 5.00
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell]
    "ExecutionPolicy"="Unrestricted"
    
    
    [HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell]
    "ExecutionPolicy"="Unrestricted"
    

    Now start Visual Studio and Try Again, if the error appears again, try running Visual Studio as Administrator.

    Please rate this snippet

    How to use Node Doubleclick in Devexpress Treelist in C# and VB.NET

    How to use Node Doubleclick in Devexpress Treelist in C# and VB.NET you can use the following snippet.

    Sample C#

    private void treeList1_DoubleClick(object sender, EventArgs e) 
    {
    	var treeList = sender as TreeList;
    	var hitInfo = treeList.CalcHitInfo(treeList.PointToClient(MousePosition));
    	if(hitInfo.Node != null) 
    	{
    		//do something
    	}
    }
    

    Sample VB.NET

    Private Sub treeList1_DoubleClick(sender As Object, e As EventArgs)
    	Dim treeList = TryCast(sender, TreeList)
    	Dim hitInfo = treeList.CalcHitInfo(treeList.PointToClient(MousePosition))
    			'do something
    	If hitInfo.Node IsNot Nothing Then
    	End If
    End Sub
    

    Please rate this snippet