PDA

View Full Version : [vbnet/C#] Useful Extension Methods



Zachafer
06-13-2013, 04:07 PM
Here is my little collection of Extension methods. I use at least one in every program :P
VB.Net:
Imports System.Runtime.CompilerServices
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Runtime.InteropServices

Public Module Extensions

Public Rand As Random = New Random()

Private Const EM_SETCUEBANNER As Integer = &H1501

<DllImport("user32.dll", CharSet:=CharSet.Auto)> _
Private Function SendMessage(ByVal hWnd As IntPtr, ByVal msg As Integer, ByVal wParam As Integer, <MarshalAs(UnmanagedType.LPWStr)> ByVal lParam As String) As Int32
End Function

''' <summary>
''' Adds cue banner text to control
''' </summary>
''' <param name="control">Control to receive cue text</param>
''' <param name="text">Text to display</param>
<Extension()>
Public Sub SetCueText(ByVal control As Control, ByVal text As String)
SendMessage(control.Handle, EM_SETCUEBANNER, 0, text)
End Sub

''' <summary>
''' Loads listbox contents from a text file
''' </summary>
''' <param name="List">Listbox to fill</param>
''' <param name="Filter">Optional filter used in LoadFileDialog</param>
''' <returns>Boolean value indicating a successful load</returns>
<Extension()>
Public Function LoadList(list As ListBox, Optional filter As String = "Text files (*.txt)|*.txt") As Boolean
Try
Dim ofd As OpenFileDialog = New OpenFileDialog With {.Filter = filter, .RestoreDirectory = True}
If ofd.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
list.Items.AddRange(System.IO.File.ReadAllLines(of d.FileName))
Return True
End If
Catch ex As Exception
Debug.Print("LoadList Error: " & ex.Message)
End Try
Return False
End Function

''' <summary>
''' Saves listbox contents to a text file
''' </summary>
''' <param name="List">Listbox to save</param>
''' <param name="Filter">Optional filter used in SaveFileDialog</param>
''' <returns>Boolean value indicating a successful save</returns>
<Extension()>
Public Function SaveList(list As ListBox, Optional filter As String = "Text files (*.txt)|*.txt") As Boolean
Try
Dim sfd As SaveFileDialog = New SaveFileDialog With {.Filter = filter, .RestoreDirectory = True}
If sfd.ShowDialog() = System.Windows.Forms.DialogResult.OK Then
File.WriteAllLines(sfd.FileName, list.Items.Cast(Of String).ToArray())
Return True
End If
Catch ex As Exception
Debug.Print("SaveList Error: " & ex.Message)
End Try
Return False
End Function
''' <summary>
''' Removes HTML tags.
''' </summary>
''' <param name="html">String with HTML tags</param>
''' <returns>A string without HTML tags.</returns>
<Extension()>
Public Function StripTags(html As String) As String
Return Regex.Replace(html, "<.*?>", String.Empty)
End Function

''' <summary>
''' Parses the text between two strings.
''' </summary>
''' <param name="Main">String to search in</param>
''' <param name="Start">String to start parsing at</param>
''' <param name="Finish">String to stop parsing at</param>
''' <param name="Index">Optional zero-based index to start searching at</param>
''' <returns>String between Start and Finish</returns>
<Extension()>
Public Function GetBetween(main As String, start As String, finish As String, Optional index As Integer = 0) As String
Dim gbMatch As Match = New Regex(Regex.Escape(start) & "(.+?)" & Regex.Escape(finish)).Match(main, index)
If gbMatch.Success Then
Return gbMatch.Groups(1).Value
Else
Return String.Empty
End If
End Function

''' <summary>
''' Parses all occurences of text between two strings.
''' </summary>
''' <param name="Main">String to search in</param>
''' <param name="Start">String to start parsing at</param>
''' <param name="Finish">String to stop parsing at</param>
''' <param name="Index">Optional zero-based index to start searching at</param>
''' <returns>List of Strings between Start and Finish</returns>
<Extension()>
Public Function GetBetweenAll(main As String, start As String, finish As String, Optional index As Integer = 0) As List(Of String)
Dim matches As List(Of String) = New List(Of String)()
Dim gbMatch As Match = New Regex(Regex.Escape(start) & "(.+?)" & Regex.Escape(finish)).Match(main, index)
While gbMatch.Success
matches.Add(gbMatch.Groups(1).Value)
gbMatch = gbMatch.NextMatch()
End While
Return matches
End Function

''' <summary>
''' Randomizes an array
''' </summary>
''' <param name="objs">Array to randomize</param>
''' <returns>Randomized array</returns>
<Extension()>
Public Function Randomize(ByVal objs() As Object) As Object()
For x As Integer = 0 To objs.Count - 1
Dim swapIndex As Integer = Rand.Next(objs.Count)
Dim swapItem As Object = objs(swapIndex)
objs(swapIndex) = objs(x)
objs(x) = swapItem
Next
Return objs
End Function

''' <summary>
''' Randomizes a listbox
''' </summary>
''' <param name="list">Listbox to randomize</param>
<Extension()>
Public Sub RandomizeListbox(list As ListBox)
For x As Integer = 0 To list.Items.Count - 1
Dim swapIndex As Integer = Rand.Next(list.Items.Count)
Dim swapItem As Object = list.Items(swapIndex)
list.Items(swapIndex) = list.Items(x)
list.Items(x) = swapItem
Next
End Sub

End Module

C#:
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.IO;
using System.Text.RegularExpressions;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using System.Text;

public static class Extensions
{

public static Random Rand = new Random();

private const int EM_SETCUEBANNER = 0x1501;
[DllImport("user32.dll", CharSet = CharSet.Auto)]
private static extern void SendMessage(IntPtr hWnd, int msg, int wParam, [MarshalAs(UnmanagedType.LPWStr)]
string lParam);

/// <summary>
/// Adds cue banner text to control
/// </summary>
/// <param name="control">Control to receive cue text</param>
/// <param name="text">Text to display</param>

public static void SetCueText(this Control control, string text)
{
SendMessage(control.Handle, EM_SETCUEBANNER, 0, text);
}

/// <summary>
/// Loads listbox contents from a text file
/// </summary>
/// <param name="List">Listbox to fill</param>
/// <param name="Filter">Optional filter used in LoadFileDialog</param>
/// <returns>Boolean value indicating a successful load</returns>

public static bool LoadList(this ListBox list, string filter = "Text files (*.txt)|*.txt")
{
try
{
OpenFileDialog ofd = new OpenFileDialog
{
Filter = filter,
RestoreDirectory = true
};
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
list.Items.AddRange(System.IO.File.ReadAllLines(of d.FileName));
return true;
}
}
catch (Exception ex)
{
Debug.Print("LoadList Error: " + ex.Message);
}
return false;
}

/// <summary>
/// Saves listbox contents to a text file
/// </summary>
/// <param name="List">Listbox to save</param>
/// <param name="Filter">Optional filter used in SaveFileDialog</param>
/// <returns>Boolean value indicating a successful save</returns>

public static bool SaveList(this ListBox list, string filter = "Text files (*.txt)|*.txt")
{
try
{
SaveFileDialog sfd = new SaveFileDialog
{
Filter = filter,
RestoreDirectory = true
};
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string textout = "";

// assume the li is a string - will fail if not
foreach (string li in list.Items)
{
textout += li + "\n";
}
System.IO.File.WriteAllText(sfd.FileName, textout);
return true;
}
}
catch (Exception ex)
{
Debug.Print("SaveList Error: " + ex.Message);
}
return false;
}
/// <summary>
/// Removes HTML tags.
/// </summary>
/// <param name="html">String with HTML tags</param>
/// <returns>A string without HTML tags.</returns>

public static string StripTags(this string html)
{
return Regex.Replace(html, "<.*?>", string.Empty);
}

/// <summary>
/// Parses the text between two strings.
/// </summary>
/// <param name="Main">String to search in</param>
/// <param name="Start">String to start parsing at</param>
/// <param name="Finish">String to stop parsing at</param>
/// <param name="Index">Optional zero-based index to start searching at</param>
/// <returns>String between Start and Finish</returns>

public static string GetBetween(this string main, string start, string finish, int index = 0)
{
Match gbMatch = new Regex(Regex.Escape(start) + "(.+?)" + Regex.Escape(finish)).Match(main, index);
if (gbMatch.Success)
{
return gbMatch.Groups[1].Value;
}
else
{
return string.Empty;
}
}

/// <summary>
/// Parses all occurences of text between two strings.
/// </summary>
/// <param name="Main">String to search in</param>
/// <param name="Start">String to start parsing at</param>
/// <param name="Finish">String to stop parsing at</param>
/// <param name="Index">Optional zero-based index to start searching at</param>
/// <returns>List of Strings between Start and Finish</returns>

public static List<string> GetBetweenAll(this string main, string start, string finish, int index = 0)
{
List<string> matches = new List<string>();
Match gbMatch = new Regex(Regex.Escape(start) + "(.+?)" + Regex.Escape(finish)).Match(main, index);
while (gbMatch.Success)
{
matches.Add(gbMatch.Groups[1].Value);
gbMatch = gbMatch.NextMatch();
}
return matches;
}

/// <summary>
/// Shuffles an array
/// </summary>
/// <param name="objs">Array to shuffle</param>
public static void Shuffle<T>(this IList<T> list)
{
Random rng = new Random();
int n = list.Count;
while (n > 1)
{
n--;
int k = rng.Next(n + 1);
T value = list[k];
list[k] = list[n];
list[n] = value;
}
}

/// <summary>
/// Normalizes spaces in a string, replacing consecutive spaces with a single space.
/// </summary>
/// <param name="str">The string to normalize.</param>
/// <returns>The normalized string.</returns>
public static string NormalizeSpaces(this string str)
{
StringBuilder sb = new StringBuilder(str.Length);
bool inspaces = false;
foreach (char c in str)
{
if (char.IsWhiteSpace(c))
{
if (inspaces)
continue;
else
{
sb.Append(" ");
inspaces = true;
}
}
else
{
sb.Append(c);
inspaces = false;
}
}
return sb.ToString();
}

}