How to get current cpu usage in C# and VB.NET

To get current cpu usage in C# and VB.NET you can use the following snippet.

Sample C#

public static string GetCurrentCpuUsage()
{
	var cpuCounter = new PerformanceCounter
	{
		CategoryName = "Processor",
		CounterName = "% Processor Time",
		InstanceName = "_Total"
	};
	cpuCounter.NextValue();
	System.Threading.Thread.Sleep(1000);
	return (cpuCounter.NextValue() + "%");
}

Sample VB.NET

Public Shared Function GetCurrentCpuUsage() As String
	Dim cpuCounter = New PerformanceCounter() With { _
		Key .CategoryName = "Processor", _
		Key .CounterName = "% Processor Time", _
		Key .InstanceName = "_Total" _
	}
	cpuCounter.NextValue()
	System.Threading.Thread.Sleep(1000)
	Return (cpuCounter.NextValue() + "%")
End Function

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

How to hide a Console Window in C# and VB.NET

To hide a Console Window in C# and VB.NET you can use the following snippet.

Sample C#

public static class Consoles
{
	[DllImport("user32.dll")]
	public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);

	[DllImport("user32.dll")]
	public static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

	public static void SetConsoleWindowVisibility(bool visible, IntPtr hWnd)
	{
		ShowWindow(hWnd, !visible ? 0 : 1);
	}
}

usage:

var hWnd = Consoles.FindWindow(null, Console.Title);
Consoles.SetConsoleWindowVisibility(false, hWnd);

Sample VB.NET

Public NotInheritable Class Consoles
	Private Sub New()
	End Sub
	<DllImport("user32.dll")> _
	Public Shared Function FindWindow(lpClassName As String, lpWindowName As String) As IntPtr
	End Function

	<DllImport("user32.dll")> _
	Public Shared Function ShowWindow(hWnd As IntPtr, nCmdShow As Integer) As Boolean
	End Function

	Public Shared Sub SetConsoleWindowVisibility(visible As Boolean, hWnd As IntPtr)
		ShowWindow(hWnd, If(Not visible, 0, 1))
	End Sub
End Class

usage:

Dim hWnd = Consoles.FindWindow(Nothing, Console.Title)
Consoles.SetConsoleWindowVisibility(False, hWnd)

Please rate this snippet

How to check if Date is Workday in C# and VB.NET

To check if Date is Workday in C# and VB.NET you can use the following snippet.

Sample C#

public static bool IsWorkDay(DateTime date, bool isWorkDaySaturday)
{
	if (date == null) {  throw new ArgumentNullException("date");}
	switch (date.DayOfWeek)
	{
		case DayOfWeek.Saturday:
			return isWorkDaySaturday;
		case DayOfWeek.Sunday:
			return false;
		default:
			return true;
	}
}

Sample VB.NET

Public Shared Function IsWorkDay(date As DateTime, isWorkDaySaturday As Boolean) As Boolean
	If date Is Nothing Then
		Throw New ArgumentNullException("date")
	End If
	Select Case date.DayOfWeek
		Case DayOfWeek.Saturday
			Return isWorkDaySaturday
		Case DayOfWeek.Sunday
			Return False
		Case Else
			Return True
	End Select
End Function

Please rate this snippet

How to scale a Size Object by percentage in C# and VB.NET

To scale a Size Object by percentage in C# and VB.NET you can use the following snippet.

Sample C#

public static Size Scale(this Size size, float scalePercent)
{
	if (Math.Abs(scalePercent - 1) < float.Epsilon)
	{
		return size;
	}

	var height = (int) (size.Height*(scalePercent/100));
	var width = (int)(size.Width * (scalePercent / 100));

	return new Size(width, height);
}

Sample VB.NET

<System.Runtime.CompilerServices.Extension> _
Public Shared Function Scale(size As Size, scalePercent As Single) As Size
	If Math.Abs(scalePercent - 1) < Single.Epsilon Then
		Return size
	End If

	Dim height = CInt(size.Height * (scalePercent / 100))
	Dim width = CInt(size.Width * (scalePercent / 100))

	Return New Size(width, height)
End Function

Please rate this snippet

How to get a random Color in C# and VB.NET

To get a random Color in C# and VB.NET you can use the following snippet.

Sample C#

public static System.Drawing.Color RandomColor()
{
	var rand = new Random();
	var r = rand.Next(0, 256);
	Thread.Sleep(1);
	var g = rand.Next(0, 256);
	Thread.Sleep(1);
	var b = rand.Next(0, 256);
	return System.Drawing.Color.FromArgb(255, r, g, b);
}

Sample VB.NET

Public Shared Function RandomColor() As System.Drawing.Color
	Dim rand As var = New Random
	Dim r As var = rand.Next(0, 256)
	Thread.Sleep(1)
	Dim g As var = rand.Next(0, 256)
	Thread.Sleep(1)
	Dim b As var = rand.Next(0, 256)
	Return System.Drawing.Color.FromArgb(255, r, g, b)
End Function

Please rate this snippet

How to get Devexpress Wizardpage by Name in C# and VB.NET

To get Devexpress Wizardpage by Name in C# and VB.NET you can use the following snippet.

Sample C#

public static WizardPage GetWizardPageByName(WizardControl wizard, string name)
{
	var controls = wizard.Controls.Find(name, false);
	if (controls.Length > 0 && controls[0] is WizardPage)
	{
		return controls[0] as WizardPage;
	}
	return null;
}

Sample VB.NET

Public Shared Function GetWizardPageByName(wizard As WizardControl, name As String) As WizardPage
	Dim controls = wizard.Controls.Find(name, False)
	If controls.Length > 0 AndAlso TypeOf controls(0) Is WizardPage Then
		Return TryCast(controls(0), WizardPage)
	End If
	Return Nothing
End Function

Please rate this snippet

How to get the Youtube VideoId from Url in C# and VB.NET

To get the Youtube VideoId from an Url in C# and VB.NET you can use the following snippet.
It matches these 18 type of Youtube Links (Sample Data):

Sample Input

  • http://youtu.be/AAAAAAAAA01
  • http://www.youtube.com/embed/watch?feature=player_embedded&v=AAAAAAAAA02
  • http://www.youtube.com/embed/watch?v=AAAAAAAAA03
  • http://www.youtube.com/embed/v=AAAAAAAAA04
  • http://www.youtube.com/watch?v=AAAAAAAAA06
  • www.youtube.com/watch?v=AAAAAAAAA07
  • www.youtu.be/AAAAAAAAA08
  • youtu.be/AAAAAAAAA09
  • http://www.youtube.com/watch?feature=player_embedded&v=AAAAAAAAA05
  • http://www.youtube.com/watch?v=i-AAAAAAA14&feature=related
  • http://www.youtube.com/attribution_link?u=/watch?v=AAAAAAAAA15&feature=share&a=9QlmP1yvjcllp0h3l0NwuA
  • http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&u=/watch?v=AAAAAAAAA16&feature=em-uploademail
  • http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&feature=em-uploademail&u=/watch?v=AAAAAAAAA17
  • http://www.youtube.com/v/A-AAAAAAA18?fs=1&rel=0
  • youtube.com/watch?v=AAAAAAAAA10
  • http://www.youtube.com/watch/AAAAAAAAA11
  • http://www.youtube.com/v/AAAAAAAAA12
  • http://www.youtube.com/v/AAAAAAAAA13
  • Sample C#

    using System.Linq;
    using System.Text.RegularExpressions;
    
    namespace de.fesslersoft.YoutubeRegexTest
    {
        internal static class Youtube
        {
            private const string YoutubeLinkRegex = "(?:.+?)?(?:\\/v\\/|watch\\/|\\?v=|\\&v=|youtu\\.be\\/|\\/v=|^youtu\\.be\\/)([a-zA-Z0-9_-]{11})+";
    
            internal static string GetVideoId(string input)
            {
                var regex = new Regex(YoutubeLinkRegex, RegexOptions.Compiled);
                foreach (Match match in regex.Matches(input))
                {
                    //Console.WriteLine(match);
                    foreach (var groupdata in match.Groups.Cast<Group>().Where(groupdata => !groupdata.ToString().StartsWith("http://") && !groupdata.ToString().StartsWith("https://") && !groupdata.ToString().StartsWith("youtu") && !groupdata.ToString().StartsWith("www.")))
                    {
                        return groupdata.ToString();
                    }
                }
                return string.Empty;
            }
        }
    }
    

    Sample VB.NET

    Imports System.Linq
    Imports System.Text.RegularExpressions
     
    Namespace de.fesslersoft.YoutubeRegexTest
        Friend NotInheritable Class Youtube
            Private Sub New()
            End Sub
            Private Const YoutubeLinkRegex As String = "(?:.+?)?(?:\/v\/|watch\/|\?v=|\&v=|youtu\.be\/|\/v=|^youtu\.be\/)([a-zA-Z0-9_-]{11})+"
     
            Friend Shared Function GetVideoId(input As String) As String
                Dim regex = New Regex(YoutubeLinkRegex, RegexOptions.Compiled)
                For Each match As Match In regex.Matches(input)
                    For Each data As Group In match.Groups.Cast(Of Group)().Where(Function(groupdata) Not groupdata.ToString().StartsWith("http://") AndAlso Not groupdata.ToString().StartsWith("https://") AndAlso Not groupdata.ToString().StartsWith("youtu") AndAlso Not groupdata.ToString().StartsWith("www."))
                        Return data.ToString()
                    Next
                Next
                Return String.Empty
            End Function
        End Class
    End Namespace
    

    Output / Sample

    var urlList = new List<String>
    {
    	"http://youtu.be/AAAAAAAAA01",
    	"http://www.youtube.com/embed/watch?feature=player_embedded&v=AAAAAAAAA02",
    	"http://www.youtube.com/embed/watch?v=AAAAAAAAA03",
    	"http://www.youtube.com/embed/v=AAAAAAAAA04",
    	"http://www.youtube.com/watch?feature=player_embedded&v=AAAAAAAAA05",
    	"http://www.youtube.com/watch?v=AAAAAAAAA06",
    	"www.youtube.com/watch?v=AAAAAAAAA07",
    	"www.youtu.be/AAAAAAAAA08",
    	"youtu.be/AAAAAAAAA09",
    	"youtube.com/watch?v=AAAAAAAAA10",
    	"http://www.youtube.com/watch/AAAAAAAAA11",
    	"http://www.youtube.com/v/AAAAAAAAA12",
    	"http://www.youtube.com/v/AAAAAAAAA13",
    	"http://www.youtube.com/watch?v=i-AAAAAAA14&feature=related",
    	"http://www.youtube.com/attribution_link?u=/watch?v=AAAAAAAAA15&feature=share&a=9QlmP1yvjcllp0h3l0NwuA",
    	"http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&u=/watch?v=AAAAAAAAA16&feature=em-uploademail",
    	"http://www.youtube.com/attribution_link?a=fF1CWYwxCQ4&feature=em-uploademail&u=/watch?v=AAAAAAAAA17",
    	"http://www.youtube.com/v/A-AAAAAAA18?fs=1&rel=0"
    };
    
    foreach (var entry in urlList)
    {
    	Console.WriteLine(Youtube.GetVideoId(entry));
    }
    Console.Read();
    

    will result in the follwing output:

    Youtube VideoId Regex Console Window Output

    Youtube VideoId Regex Console Window Output

    A simpler but less matching solution can be found here: How to get the VideoID of a youtube video using Regex

    Please rate this snippet