Saturday, December 29, 2007

JavaScript: Decode from Base64

Once again, I will not take credit of this one too...

// ***
// Decode from Base64
// Warning: Do not use for larger content as the loop might take a while
// ***
function base64Decode(data)
{
data = data.replace(/[^a-z0-9\+\/=]/ig, '');
if (typeof(atob) == 'function') return atob(data);
var b64_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var byte1, byte2, byte3;
var ch1, ch2, ch3, ch4;
var result = new Array();
var j=0;
while ((data.length%4) != 0) {
data += '=';
}

for (var i=0; i <data.length; i+=4) {
ch1 = b64_map.indexOf(data.charAt(i));
ch2 = b64_map.indexOf(data.charAt(i+1));
ch3 = b64_map.indexOf(data.charAt(i+2));
ch4 = b64_map.indexOf(data.charAt(i+3));

byte1 = (ch1 <<>> 4);
byte2 = ((ch2 & 15) <<>> 2);
byte3 = ((ch3 & 3) << 6) | ch4;

result[j++] = String.fromCharCode(byte1);
if (ch3 != 64) result[j++] = String.fromCharCode(byte2);
if (ch4 != 64) result[j++] = String.fromCharCode(byte3);
}

return result.join('');
}

JavaScript: Return the NT ID of an user using Shell

// ***
// Returns NT ID of current user
// Note: Would cause an ActiveX warning message if corresponding site is not added in "Trusted Sites" list
// Behavior may also vary with different versions of IE (IE6 vs IE7)
// ***
function getCurrentUserId()
{
var wshell = new ActiveXObject("WScript.Shell");
var userId = wshell.ExpandEnvironmentStrings("%USERNAME%");
return userId;
}

JavaScript: Encode to Base64

Once again, I will not take credit of this one...

// ***
// Encode to Base64
// Warning: Do not use for larger content as the loop might take a while
// ***
function base64Encode(data)
{
if (typeof(btoa) == 'function') return btoa(data);
var b64_map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
var byte1, byte2, byte3;
var ch1, ch2, ch3, ch4;
var result = new Array();
var j=0;
for (var i=0; i byte1 = data.charCodeAt(i);
byte2 = data.charCodeAt(i+1);
byte3 = data.charCodeAt(i+2);
ch1 = byte1 >> 2;
ch2 = ((byte1 & 3) << 4) | (byte2 >> 4);
ch3 = ((byte2 & 15) << 2) | (byte3 >> 6);
ch4 = byte3 & 63;

if (isNaN(byte2)) {
ch3 = ch4 = 64;
} else if (isNaN(byte3)) {
ch4 = 64;
}

result[j++] = b64_map.charAt(ch1)+b64_map.charAt(ch2)+b64_map.charAt(ch3)+b64_map.charAt(ch4);
}

return result.join('');
}

JavaScript: Check if a HTML list contains an element with specified value

// ***
// Check if a HTML list contains an element with specified value
// ***
function optionExists(lst, val)
{
response = false;
for (var i=0; i < lst.length; i++)
{
if (lst.options[i].value==val)
{
response = true;
break;
}
}
return response;
}

JavaScript: Delete a cookie

// ***
// Delete a cookie with specified name
// ***
function eraseCookie(name)
{
createCookie(name,"",-1);
}

JavaScript: Alphabetically sort a HTML list control

// ***
// Sort a HTML list control
// ***
function sortList(lst)
{
if (lst==null)
return;

arrList = new Array();
for(i=0; i < lst.length; i++)
{
arrList[i] = lst.options[i].text;
}
arrList.sort();
for(i=0; i < lst.length; i++)
{
lst.options[i].text = arrList[i];
lst.options[i].value = arrList[i];
}
}

JavaScript: Create a cookie

// ***
// Creates a cookie with specified name, value and expiry days
// ***
function createCookie(name,value,days)
{
if (days)
{
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

JavaScript: Read contents of a cookie

// ***
// Read contents of a cookie
// ***
function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

JavaScript: Request.Querystring equivalent

// ***
// Equivalent of C# Request.QueryString[key]
// ***
function getQueryString(key, query)
{
//query = parent.location.search;e

if (query.length > 1)
{
query = query.substring(1, query.length);
for(var i=0; i < query.split("&").length; i++)
{
subQuery = query.split("&")[i];
subQueryKey = subQuery.split("=")[0];
subQueryValue = subQuery.split("=")[1];
if (subQueryKey.toLowerCase()==key.toLowerCase())
{
return subQueryValue;
}
}
}
else
{
return null;
}
return null;
}

JavaScript: Sleep function

// ***
// Pauses all functionality sleeps the thread for specified time
// ***
function sleep(milliseconds)
{
var now = new Date();
var exitTime = now.getTime() + milliseconds;
while (true)
{
now = new Date();
if (now.getTime() > exitTime)
return;
}
}

JavaScript: Auto-activate all ActiveX controls on the page

// ***
// Activates all ActiveX controls on the page without needing to click on it
// ***
function activate_activex()
{
objects = document.getElementsByTagName("object");
for (var i = 0; i < objects.length; i++)
{
objects[i].outerHTML = objects[i].outerHTML;
}
}

JavaScript: Display a sized modal popup

// ***
// Displays a sized modal popup
// ***
function popUpModalSized(URL,width,height)
{
xwidth = width;
xheight = height;
xleft = (screen.width - width ) / 2;
xtop = (screen.height - height ) / 2;
title = '';
windowOptions = 'dialogWidth:' + xwidth + 'px; dialogHeight:' + xheight + 'px; dialogLeft:' + xleft + 'px; dialogTop:' + xtop + 'px; edge: Raised; center: yes; resizable: no; maximize:no; minimize:yes; status: no; scroll: no; help: no';
var rc = window.showModalDialog(URL,title,windowOptions);
}

JavaScript: Resize and center a modal dialog on screen

// ***
// Resizes and centers a modal dialog on screen. For use in window_onload
// ***
function resizeCenterModalDialog(width,height)
{
top = (screen.height-height)/2;
left = (screen.width-width)/2;
window.dialogHeight=height + 'px';
window.dialogWidth=width + 'px';
window.dialogTop=top + 'px';
window.dialogLeft=left + 'px';
}

JavaScript: Display a non-sized non-modal popup

// ***
// Displays a non-sized non-modal popup
// ***
function popUp(URL)
{
day = new Date();
id = day.getTime();
eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1');");
}

JavaScript: Display a sized non-modal popup

// ***
// Displays a sized non-modal popup
// ***
function popUpSized(URL, width, height)
{
day = new Date();
id = day.getTime();
xwidth = width;
xheight = height;
xleft = (screen.width - xwidth ) / 2;
xtop = (screen.height - xheight ) / 2;
eval("page" + id + " = window.open(URL, '" + id + "', 'height=" + xheight + ",width=" + xwidth + ",left=" + xleft + ",top=" + xtop + ",toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=1');");
}

JavaScript: Display a non-sized modal popup

// ***
// Displays a non-sized modal popup
// ***
function popUpModal(URL,title)
{
windowOptions = 'edge: Raised; center: yes; resizable: no; maximize:no; minimize:yes; status: no; scroll: no; help: no';
var rc = window.showModalDialog(URL,title,windowOptions);
}

C#: Popup a window from ASPX

public static void PopUpWindow(System.Web.UI.Page page, string url)
{
string js = "";
page.RegisterClientScriptBlock("PopUpWindow", js);
}

C#: Display a JavaScript alert from ASPX

public static void ShowMessage(System.Web.UI.Page page, string message)
{
string sJavaScript = "";
page.RegisterStartupScript("MessageBox", sJavaScript);
}

C#: Class for TIFF manipulation

This is probably the best compilation I have ever made. Whoever is reading this, might as well have contributed in creation of this. Special mention for Bob Powell's tips found at www.bobpowell.net...

using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.Collections;
using System.Threading;
using System.Drawing.Imaging;
using System.IO;

namespace TiffUtil
{

public class TiffUtil
{
#region Variable & Class Definitions

private static System.Drawing.Imaging.ImageCodecInfo tifImageCodecInfo;

private static EncoderParameter tifEncoderParameterMultiFrame;
private static EncoderParameter tifEncoderParameterFrameDimensionPage;
private static EncoderParameter tifEncoderParameterFlush;
private static EncoderParameter tifEncoderParameterCompression;
private static EncoderParameter tifEncoderParameterLastFrame;
private static EncoderParameter tifEncoderParameter24BPP;
private static EncoderParameter tifEncoderParameter1BPP;

private static EncoderParameters tifEncoderParametersPage1;
private static EncoderParameters tifEncoderParametersPageX;
private static EncoderParameters tifEncoderParametersPageLast;

private static System.Drawing.Imaging.Encoder tifEncoderSaveFlag;
private static System.Drawing.Imaging.Encoder tifEncoderCompression;
private static System.Drawing.Imaging.Encoder tifEncoderColorDepth;

private static bool encoderAssigned;

public static string tempDir;
public static bool initComplete;

public TiffUtil(string tempPath)
{
try
{
if (!initComplete)
{
if (!tempPath.EndsWith("\\"))
tempDir = tempPath + "\\";
else
tempDir = tempPath;

Directory.CreateDirectory(tempDir);
initComplete = true;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
}

#endregion

#region Retrieve Page Count of a multi-page TIFF file

public int getPageCount(string fileName)
{
int pageCount = -1;

try
{
Image img = Bitmap.FromFile(fileName);
pageCount = img.GetFrameCount(FrameDimension.Page);
img.Dispose();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}

return pageCount;
}

public int getPageCount(Image img)
{
int pageCount = -1;
try
{
pageCount = img.GetFrameCount(FrameDimension.Page);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
return pageCount;
}

#endregion

#region Retrieve multiple single page images from a single multi-page TIFF file

public Image[] getTiffImages(Image sourceImage, int[] pageNumbers)
{
MemoryStream ms = null;
Image[] returnImage = new Image[pageNumbers.Length];

try
{
Guid objGuid = sourceImage.FrameDimensionsList[0];
FrameDimension objDimension = new FrameDimension(objGuid);

for (int i = 0; i < pageNumbers.Length; i++)
{
ms = new MemoryStream();
sourceImage.SelectActiveFrame(objDimension, pageNumbers[i]);
sourceImage.Save(ms, ImageFormat.Tiff);
returnImage[i] = Image.FromStream(ms);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
ms.Close();
}

return returnImage;
}

public Image[] getTiffImages(Image sourceImage)
{
MemoryStream ms = null;
int pageCount = getPageCount(sourceImage);

Image[] returnImage = new Image[pageCount];

try
{
Guid objGuid = sourceImage.FrameDimensionsList[0];
FrameDimension objDimension = new FrameDimension(objGuid);

for (int i = 0; i < pageCount; i++)
{
ms = new MemoryStream();
sourceImage.SelectActiveFrame(objDimension, i);
sourceImage.Save(ms, ImageFormat.Tiff);
returnImage[i] = Image.FromStream(ms);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
ms.Close();
}

return returnImage;
}

public Image[] getTiffImages(string sourceFile, int[] pageNumbers)
{
Image[] returnImage = new Image[pageNumbers.Length];

try
{
Image sourceImage = Bitmap.FromFile(sourceFile);
returnImage = getTiffImages(sourceImage, pageNumbers);
sourceImage.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
returnImage = null;
}

return returnImage;
}

#endregion

#region Retrieve a specific page from a multi-page TIFF image

public Image getTiffImage(string sourceFile, int pageNumber)
{
Image returnImage = null;

try
{
Image sourceImage = Image.FromFile(sourceFile);
returnImage = getTiffImage(sourceImage, pageNumber);
sourceImage.Dispose();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
returnImage = null;
}

return returnImage;
}

public Image getTiffImage(Image sourceImage, int pageNumber)
{
MemoryStream ms = null;
Image returnImage = null;

try
{
ms = new MemoryStream();
Guid objGuid = sourceImage.FrameDimensionsList[0];
FrameDimension objDimension = new FrameDimension(objGuid);
sourceImage.SelectActiveFrame(objDimension, pageNumber);
sourceImage.Save(ms, ImageFormat.Tiff);
returnImage = Image.FromStream(ms);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ms.Close();
}

return returnImage;
}

public bool getTiffImage(string sourceFile, string targetFile, int pageNumber)
{
bool response = false;

try
{
Image returnImage = getTiffImage(sourceFile, pageNumber);
returnImage.Save(targetFile);
returnImage.Dispose();
response = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

return response;
}

#endregion

#region Split a multi-page TIFF file into multiple single page TIFF files

public string[] splitTiffPages(string sourceFile, string targetDirectory)
{
string[] returnImages;

try
{
Image sourceImage = Bitmap.FromFile(sourceFile);
Image[] sourceImages = splitTiffPages(sourceImage);

int pageCount = sourceImages.Length;

returnImages = new string[pageCount];
for (int i = 0; i < pageCount; i++)
{
FileInfo fi = new FileInfo(sourceFile);
string babyImg = targetDirectory + "\\" + fi.Name.Substring(0, (fi.Name.Length - fi.Extension.Length)) + "_PAGE" + (i + 1).ToString().PadLeft(3, '0') + fi.Extension;
sourceImages[i].Save(babyImg);
returnImages[i] = babyImg;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
returnImages = null;
}

return returnImages;
}

public Image[] splitTiffPages(Image sourceImage)
{
Image[] returnImages;

try
{
int pageCount = getPageCount(sourceImage);
returnImages = new Image[pageCount];

for (int i = 0; i < pageCount; i++)
{
Image img = getTiffImage(sourceImage, i);
returnImages[i] = (Image)img.Clone();
img.Dispose();
}

}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
returnImages = null;
}

return returnImages;
}

#endregion

#region Merge multiple single page TIFF to a single multi page TIFF

public bool mergeTiffPages(string[] sourceFiles, string targetFile)
{
bool response = false;

try
{
assignEncoder();

// If only 1 page was passed, copy directly to output
if (sourceFiles.Length == 1)
{
File.Copy(sourceFiles[0], targetFile, true);
return true;
}

int pageCount = sourceFiles.Length;

// First page
Image finalImage = Image.FromFile(sourceFiles[0]);
finalImage.Save(targetFile, tifImageCodecInfo, tifEncoderParametersPage1);

// All other pages
for (int i = 1; i < pageCount; i++)
{
Image img = Image.FromFile(sourceFiles[i]);
finalImage.SaveAdd(img, tifEncoderParametersPageX);
img.Dispose();
}

// Last page
finalImage.SaveAdd(tifEncoderParametersPageLast);
finalImage.Dispose();
response = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
response = false;
}

return response;
}

public bool mergeTiffPages(string sourceFile, string targetFile, int[] pageNumbers)
{
bool response = false;

try
{
assignEncoder();

// Get individual Images from the original image
Image sourceImage = Bitmap.FromFile(sourceFile);
MemoryStream ms = new MemoryStream();
Image[] sourceImages = new Image[pageNumbers.Length];
Guid guid = sourceImage.FrameDimensionsList[0];
FrameDimension objDimension = new FrameDimension(guid);
for (int i = 0; i < pageNumbers.Length; i++)
{
sourceImage.SelectActiveFrame(objDimension, pageNumbers[i]);
sourceImage.Save(ms, ImageFormat.Tiff);
sourceImages[i] = Image.FromStream(ms);
}

// Merge individual Images into one Image
// First page
Image finalImage = sourceImages[0];
finalImage.Save(targetFile, tifImageCodecInfo, tifEncoderParametersPage1);
// All other pages
for (int i = 1; i < pageNumbers.Length; i++)
{
finalImage.SaveAdd(sourceImages[i], tifEncoderParametersPageX);
}
// Last page
finalImage.SaveAdd(tifEncoderParametersPageLast);
finalImage.Dispose();

response = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

return response;
}

public bool mergeTiffPagesAlternate(string sourceFile, string targetFile, int[] pageNumbers)
{
bool response = false;

try
{
// Initialize the encoders, occurs once for the lifetime of the class
assignEncoder();

// Get individual Images from the original image
Image sourceImage = Bitmap.FromFile(sourceFile);
MemoryStream[] msArray = new MemoryStream[pageNumbers.Length];
Guid guid = sourceImage.FrameDimensionsList[0];
FrameDimension objDimension = new FrameDimension(guid);
for (int i = 0; i < pageNumbers.Length; i++)
{
msArray[i] = new MemoryStream();
sourceImage.SelectActiveFrame(objDimension, pageNumbers[i]);
sourceImage.Save(msArray[i], ImageFormat.Tiff);
}

// Merge individual page streams into single stream
MemoryStream ms = mergeTiffStreams(msArray);
Image targetImage = Bitmap.FromStream(ms);
targetImage.Save(targetFile);

response = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

return response;
}

public System.IO.MemoryStream mergeTiffStreams(System.IO.MemoryStream[] tifsStream)
{
EncoderParameters ep = null;
System.IO.MemoryStream singleStream = new System.IO.MemoryStream();

try
{
assignEncoder();

Image imgTif = Image.FromStream(tifsStream[0]);

if (tifsStream.Length > 1)
{
// Multi-Frame
ep = new EncoderParameters(2);
ep.Param[0] = new EncoderParameter(tifEncoderSaveFlag, (long)EncoderValue.MultiFrame);
ep.Param[1] = new EncoderParameter(tifEncoderCompression, (long)EncoderValue.CompressionRle);
}
else
{
// Single-Frame
ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(tifEncoderCompression, (long)EncoderValue.CompressionRle);
}

//Save the first page
imgTif.Save(singleStream, tifImageCodecInfo, ep);

if (tifsStream.Length > 1)
{
ep = new EncoderParameters(2);
ep.Param[0] = new EncoderParameter(tifEncoderSaveFlag, (long)EncoderValue.FrameDimensionPage);

//Add the rest of pages
for (int i = 1; i < tifsStream.Length; i++)
{
Image pgTif = Image.FromStream(tifsStream[i]);

ep.Param[1] = new EncoderParameter(tifEncoderCompression, (long)EncoderValue.CompressionRle);

imgTif.SaveAdd(pgTif, ep);
}

ep = new EncoderParameters(1);
ep.Param[0] = new EncoderParameter(tifEncoderSaveFlag, (long)EncoderValue.Flush);
imgTif.SaveAdd(ep);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (ep != null)
{
ep.Dispose();
}
}

return singleStream;
}

#endregion

#region Internal support functions

private void assignEncoder()
{
try
{
if (encoderAssigned == true)
return;

foreach(ImageCodecInfo ici in ImageCodecInfo.GetImageEncoders())
{
if (ici.MimeType == "image/tiff")
{
tifImageCodecInfo = ici;
}
}

tifEncoderSaveFlag = System.Drawing.Imaging.Encoder.SaveFlag;
tifEncoderCompression = System.Drawing.Imaging.Encoder.Compression;
tifEncoderColorDepth = System.Drawing.Imaging.Encoder.ColorDepth;

tifEncoderParameterMultiFrame = new EncoderParameter(tifEncoderSaveFlag, (long)EncoderValue.MultiFrame);
tifEncoderParameterFrameDimensionPage = new EncoderParameter(tifEncoderSaveFlag, (long)EncoderValue.FrameDimensionPage);
tifEncoderParameterFlush = new EncoderParameter(tifEncoderSaveFlag, (long)EncoderValue.Flush);
tifEncoderParameterCompression = new EncoderParameter(tifEncoderCompression, (long)EncoderValue.CompressionRle);
tifEncoderParameterLastFrame = new EncoderParameter(tifEncoderSaveFlag, (long)EncoderValue.LastFrame);
tifEncoderParameter24BPP = new EncoderParameter(tifEncoderColorDepth, (long)24);
tifEncoderParameter1BPP = new EncoderParameter(tifEncoderColorDepth, (long)8);

// ******************************************************************* //
// *** Have only 1 of the following 3 groups assigned for encoders *** //
// ******************************************************************* //

// Regular
tifEncoderParametersPage1 = new EncoderParameters(1);
tifEncoderParametersPage1.Param[0] = tifEncoderParameterMultiFrame;
tifEncoderParametersPageX = new EncoderParameters(1);
tifEncoderParametersPageX.Param[0] = tifEncoderParameterFrameDimensionPage;
tifEncoderParametersPageLast = new EncoderParameters(1);
tifEncoderParametersPageLast.Param[0] = tifEncoderParameterFlush;

//// Regular
//tifEncoderParametersPage1 = new EncoderParameters(2);
//tifEncoderParametersPage1.Param[0] = tifEncoderParameterMultiFrame;
//tifEncoderParametersPage1.Param[1] = tifEncoderParameterCompression;
//tifEncoderParametersPageX = new EncoderParameters(2);
//tifEncoderParametersPageX.Param[0] = tifEncoderParameterFrameDimensionPage;
//tifEncoderParametersPageX.Param[1] = tifEncoderParameterCompression;
//tifEncoderParametersPageLast = new EncoderParameters(2);
//tifEncoderParametersPageLast.Param[0] = tifEncoderParameterFlush;
//tifEncoderParametersPageLast.Param[1] = tifEncoderParameterLastFrame;

//// 24 BPP Color
//tifEncoderParametersPage1 = new EncoderParameters(2);
//tifEncoderParametersPage1.Param[0] = tifEncoderParameterMultiFrame;
//tifEncoderParametersPage1.Param[1] = tifEncoderParameter24BPP;
//tifEncoderParametersPageX = new EncoderParameters(2);
//tifEncoderParametersPageX.Param[0] = tifEncoderParameterFrameDimensionPage;
//tifEncoderParametersPageX.Param[1] = tifEncoderParameter24BPP;
//tifEncoderParametersPageLast = new EncoderParameters(2);
//tifEncoderParametersPageLast.Param[0] = tifEncoderParameterFlush;
//tifEncoderParametersPageLast.Param[1] = tifEncoderParameterLastFrame;

//// 1 BPP BW
//tifEncoderParametersPage1 = new EncoderParameters(2);
//tifEncoderParametersPage1.Param[0] = tifEncoderParameterMultiFrame;
//tifEncoderParametersPage1.Param[1] = tifEncoderParameterCompression;
//tifEncoderParametersPageX = new EncoderParameters(2);
//tifEncoderParametersPageX.Param[0] = tifEncoderParameterFrameDimensionPage;
//tifEncoderParametersPageX.Param[1] = tifEncoderParameterCompression;
//tifEncoderParametersPageLast = new EncoderParameters(2);
//tifEncoderParametersPageLast.Param[0] = tifEncoderParameterFlush;
//tifEncoderParametersPageLast.Param[1] = tifEncoderParameterLastFrame;

encoderAssigned = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
}

private Bitmap ConvertToGrayscale(Bitmap source)
{
try
{
Bitmap bm = new Bitmap(source.Width, source.Height);
Graphics g = Graphics.FromImage(bm);

ColorMatrix cm = new ColorMatrix(new float[][]{new float[]{0.5f,0.5f,0.5f,0,0}, new float[]{0.5f,0.5f,0.5f,0,0}, new float[]{0.5f,0.5f,0.5f,0,0}, new float[]{0,0,0,1,0,0}, new float[]{0,0,0,0,1,0}, new float[]{0,0,0,0,0,1}});
ImageAttributes ia = new ImageAttributes();
ia.SetColorMatrix(cm);
g.DrawImage(source, new Rectangle(0, 0, source.Width, source.Height), 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, ia);
g.Dispose();

return bm;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw ex;
}
}

#endregion
}
}

C#: Class for generating image thumbnails using Windows Shell

Update July 19, 2011: Replaced all instances of deprecated SHGetMalloc (from shell32.dll) with CoTaskMemFree (from ole32.dll) for better compatibility with Windows 7.

Question is, why not use GDI+? Answer is, it is tooo slow when you are working with quite a few files. GDI+ is full proof though, as windows shell would return the cached thumbnails...

By the way, I must mention that I will not take complete credit of this piece of gem! Kudos to whoever wrote this from scratch, but I do not mind taking credit for publishing it in my blog ;-)
So here it is...

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
 
namespace KodeSharp.SharedClasses
{
 public class ShellThumbnail : IDisposable
 {
  #region ShellFolder Enumerations
  [Flags]
  private enum ESTRRET : int
  {
   STRRET_WSTR = 0x0000,
   STRRET_OFFSET = 0x0001,
   STRRET_CSTR = 0x0002
  }
  [Flags]
  private enum ESHCONTF : int
  {
   SHCONTF_FOLDERS = 32,
   SHCONTF_NONFOLDERS = 64,
   SHCONTF_INCLUDEHIDDEN = 128
  }
 
  [Flags]
  private enum ESHGDN : int
  {
   SHGDN_NORMAL = 0,
   SHGDN_INFOLDER = 1,
   SHGDN_FORADDRESSBAR = 16384,
   SHGDN_FORPARSING = 32768
  }
  [Flags]
  private enum ESFGAO : int
  {
   SFGAO_CANCOPY = 1,
   SFGAO_CANMOVE = 2,
   SFGAO_CANLINK = 4,
   SFGAO_CANRENAME = 16,
   SFGAO_CANDELETE = 32,
   SFGAO_HASPROPSHEET = 64,
   SFGAO_DROPTARGET = 256,
   SFGAO_CAPABILITYMASK = 375,
   SFGAO_LINK = 65536,
   SFGAO_SHARE = 131072,
   SFGAO_READONLY = 262144,
   SFGAO_GHOSTED = 524288,
   SFGAO_DISPLAYATTRMASK = 983040,
   SFGAO_FILESYSANCESTOR = 268435456,
   SFGAO_FOLDER = 536870912,
   SFGAO_FILESYSTEM = 1073741824,
   SFGAO_HASSUBFOLDER = -2147483648,
   SFGAO_CONTENTSMASK = -2147483648,
   SFGAO_VALIDATE = 16777216,
   SFGAO_REMOVABLE = 33554432,
   SFGAO_COMPRESSED = 67108864
  }
  #endregion
 
  #region IExtractImage Enumerations
  private enum EIEIFLAG
  {
   IEIFLAG_ASYNC = 0x0001,
   IEIFLAG_CACHE = 0x0002,
   IEIFLAG_ASPECT = 0x0004,
   IEIFLAG_OFFLINE = 0x0008,
   IEIFLAG_GLEAM = 0x0010,
   IEIFLAG_SCREEN = 0x0020,
   IEIFLAG_ORIGSIZE = 0x0040,
   IEIFLAG_NOSTAMP = 0x0080,
   IEIFLAG_NOBORDER = 0x0100,
   IEIFLAG_QUALITY = 0x0200
  }
  #endregion
 
  #region ShellFolder Structures
  [StructLayoutAttribute(LayoutKind.Sequential, Pack = 4, Size = 0, CharSet = CharSet.Auto)]
  private struct STRRET_CSTR
  {
   public ESTRRET uType;
   [MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray, SizeConst = 520)]
   public byte[] cStr;
  }
 
  [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Auto)]
  private struct STRRET_ANY
  {
   [FieldOffset(0)]
   public ESTRRET uType;
   [FieldOffset(4)]
   public IntPtr pOLEString;
  }
 
  [StructLayoutAttribute(LayoutKind.Sequential)]
  private struct SIZE
  {
   public int cx;
   public int cy;
  }
  #endregion
 
  #region Com Interop for IUnknown
  [ComImportGuid("00000000-0000-0000-C000-000000000046")]
  [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  private interface IUnknown
  {
   [PreserveSig]
   IntPtr QueryInterface(ref Guid riid, out IntPtr pVoid);
 
   [PreserveSig]
   IntPtr AddRef();
 
   [PreserveSig]
   IntPtr Release();
  }
  #endregion
 
  #region COM Interop for IEnumIDList
  [ComImportAttribute()]
  [GuidAttribute("000214F2-0000-0000-C000-000000000046")]
  [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
  private interface IEnumIDList
  {
   [PreserveSig]
   int Next(
    int celt,
    ref IntPtr rgelt,
    out int pceltFetched);
 
   void Skip(
    int celt);
 
   void Reset();
 
   void Clone(
    ref IEnumIDList ppenum);
  };
  #endregion
 
  #region COM Interop for IShellFolder
  [ComImportAttribute()]
  [GuidAttribute("000214E6-0000-0000-C000-000000000046")]
  [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
  private interface IShellFolder
  {
   void ParseDisplayName(
    IntPtr hwndOwner,
    IntPtr pbcReserved,
    [MarshalAs(UnmanagedType.LPWStr)] string lpszDisplayName,
    out int pchEaten,
    out IntPtr ppidl,
    out int pdwAttributes
    );
 
   void EnumObjects(
    IntPtr hwndOwner,
    [MarshalAs(UnmanagedType.U4)] ESHCONTF grfFlags,
    ref IEnumIDList ppenumIDList
    );
 
   void BindToObject(
    IntPtr pidl,
    IntPtr pbcReserved,
    ref Guid riid,
    ref IShellFolder ppvOut
    );
 
   void BindToStorage(
    IntPtr pidl,
    IntPtr pbcReserved,
    ref Guid riid,
    IntPtr ppvObj
    );
 
   [PreserveSig]
   int CompareIDs(
    IntPtr lParam,
    IntPtr pidl1,
    IntPtr pidl2
    );
 
   void CreateViewObject(
    IntPtr hwndOwner,
    ref Guid riid,
    IntPtr ppvOut
    );
 
   void GetAttributesOf(
    int cidl,
    IntPtr apidl,
    [MarshalAs(UnmanagedType.U4)] ref ESFGAO rgfInOut
    );
 
   void GetUIObjectOf(
    IntPtr hwndOwner,
    int cidl,
    ref IntPtr apidl,
    ref Guid riid,
    out int prgfInOut,
    ref IUnknown ppvOut
    );
 
   void GetDisplayNameOf(
    IntPtr pidl,
    [MarshalAs(UnmanagedType.U4)] ESHGDN uFlags,
    ref STRRET_CSTR lpName
    );
 
   void SetNameOf(
    IntPtr hwndOwner,
    IntPtr pidl,
    [MarshalAs(UnmanagedType.LPWStr)] string lpszName,
    [MarshalAs(UnmanagedType.U4)] ESHCONTF uFlags,
    ref IntPtr ppidlOut
    );
 
  };
 
  #endregion
 
  #region COM Interop for IExtractImage
  [ComImportAttribute()]
  [GuidAttribute("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1")]
  [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)]
  private interface IExtractImage
  {
   void GetLocation(
    [Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszPathBuffer,
    int cch,
    ref int pdwPriority,
    ref SIZE prgSize,
    int dwRecClrDepth,
    ref int pdwFlags
    );
 
   void Extract(
    out IntPtr phBmpThumbnail
    );
  }
  #endregion
 
  #region UnmanagedMethods for IShellFolder
  private class UnmanagedMethods
  {
   [DllImport("ole32", CharSet = CharSet.Auto)]
   internal extern static void CoTaskMemFree(IntPtr ptr);
 
   [DllImport("shell32", CharSet = CharSet.Auto)]
   internal extern static int SHGetDesktopFolder(out IShellFolder ppshf);
 
   [DllImport("shell32", CharSet = CharSet.Auto)]
   internal extern static int SHGetPathFromIDList(IntPtr pidl, StringBuilder pszPath);
 
   [DllImport("gdi32", CharSet = CharSet.Auto)]
   internal extern static int DeleteObject(IntPtr hObject);
  }
  #endregion
 
  #region Member Variables
  private bool disposed = false;
  private System.Drawing.Bitmap thumbNail = null;
  #endregion
 
  #region Implementation
  public System.Drawing.Bitmap ThumbNail
  {
   get
   {
    return thumbNail;
   }
  }
 
  public System.Drawing.Bitmap GetThumbnail(string file, int width, int height)
  {
   if ((!File.Exists(file)) && (!Directory.Exists(file)))
   {
    throw new FileNotFoundException(
     String.Format("The file '{0}' does not exist", file),
     file);
   }
 
   if (thumbNail != null)
   {
    thumbNail.Dispose();
    thumbNail = null;
   }
 
   IShellFolder folder = null;
   try
   {
    folder = GetDesktopFolder;
   }
   catch (Exception ex)
   {
    throw ex;
   }
 
   if (folder != null)
   {
    IntPtr pidlMain = IntPtr.Zero;
    try
    {
     int cParsed = 0;
     int pdwAttrib = 0;
     string filePath = Path.GetDirectoryName(file);
     pidlMain = IntPtr.Zero;
     folder.ParseDisplayName(
      IntPtr.Zero,
      IntPtr.Zero,
      filePath,
      out cParsed,
      out pidlMain,
      out pdwAttrib);
    }
    catch (Exception ex)
    {
     Marshal.ReleaseComObject(folder);
     throw ex;
    }
 
    if (pidlMain != IntPtr.Zero)
    {
     // IShellFolder:
     Guid iidShellFolder = new Guid("000214E6-0000-0000-C000-000000000046");
     IShellFolder item = null;
 
     try
     {
      folder.BindToObject(pidlMain, IntPtr.Zero, ref
       iidShellFolder, ref item);
     }
     catch (Exception ex)
     {
      Marshal.ReleaseComObject(folder);
      UnmanagedMethods.CoTaskMemFree(pidlMain);
      throw ex;
     }
 
     if (item != null)
     {
      IEnumIDList idEnum = null;
      try
      {
       item.EnumObjects(
        IntPtr.Zero,
        (ESHCONTF.SHCONTF_FOLDERS |
        ESHCONTF.SHCONTF_NONFOLDERS),
        ref idEnum);
      }
      catch (Exception ex)
      {
       Marshal.ReleaseComObject(folder);
       UnmanagedMethods.CoTaskMemFree(pidlMain);
       throw ex;
      }
 
      if (idEnum != null)
      {
       int hRes = 0;
       IntPtr pidl = IntPtr.Zero;
       int fetched = 0;
       bool complete = false;
       while (!complete)
       {
        hRes = idEnum.Next(1, ref pidl, out fetched);
        if (hRes != 0)
        {
         pidl = IntPtr.Zero;
         complete = true;
        }
        else
        {
         if (GetThumbnail(file, pidl, item, width, height))
         {
          complete = true;
         }
        }
        if (pidl != IntPtr.Zero)
        {
         UnmanagedMethods.CoTaskMemFree(pidl);
        }
       }
 
       Marshal.ReleaseComObject(idEnum);
      }
 
 
      Marshal.ReleaseComObject(item);
     }
 
     UnmanagedMethods.CoTaskMemFree(pidlMain);
    }
 
    Marshal.ReleaseComObject(folder);
   }
   return thumbNail;
  }
 
  private bool GetThumbnail(string file, IntPtr pidl, IShellFolder item, int width, int height)
  {
   IntPtr hBmp = IntPtr.Zero;
   IExtractImage extractImage = null;
 
   try
   {
    string pidlPath = PathFromPidl(pidl);
    if (Path.GetFileName(pidlPath).ToUpper().Equals(Path.GetFileName(file).ToUpper()))
    {
     IUnknown iunk = null;
     int prgf = 0;
     Guid iidExtractImage = new Guid("BB2E617C-0920-11d1-9A0B-00C04FC2D6C1");
     item.GetUIObjectOf(IntPtr.Zero, 1, ref pidl, ref iidExtractImage, out prgf, ref iunk);
     extractImage = (IExtractImage)iunk;
 
     if (extractImage != null)
     {
      SIZE sz = new SIZE();
      sz.cx = width;
      sz.cy = height;
      StringBuilder location = new StringBuilder(260, 260);
      int priority = 0;
      int requestedColourDepth = 32;
      EIEIFLAG flags = EIEIFLAG.IEIFLAG_ASPECT | EIEIFLAG.IEIFLAG_SCREEN;
      int uFlags = (int)flags;
 
      extractImage.GetLocation(location, location.Capacity, ref priority, ref sz, requestedColourDepth, ref uFlags);
 
      extractImage.Extract(out hBmp);
      if (hBmp != IntPtr.Zero)
      {
       thumbNail = System.Drawing.Bitmap.FromHbitmap(hBmp);
      }
 
      Marshal.ReleaseComObject(extractImage);
      extractImage = null;
     }
     return true;
    }
    else
    {
     return false;
    }
   }
   catch (Exception ex)
   {
    if (hBmp != IntPtr.Zero)
    {
     UnmanagedMethods.DeleteObject(hBmp);
    }
    if (extractImage != null)
    {
     Marshal.ReleaseComObject(extractImage);
    }
    throw ex;
   }
  }
 
  private string PathFromPidl(IntPtr pidl)
  {
   StringBuilder path = new StringBuilder(260, 260);
   int result = UnmanagedMethods.SHGetPathFromIDList(pidl, path);
   if (result == 0)
   {
    return string.Empty;
   }
   else
   {
    return path.ToString();
   }
  }
 
  private IShellFolder GetDesktopFolder
  {
   get
   {
    IShellFolder ppshf;
    int r = UnmanagedMethods.SHGetDesktopFolder(out ppshf);
    return ppshf;
   }
  }
  #endregion
 
  #region Constructor, Destructor, Dispose
  public ShellThumbnail()
  {
  }
 
  public void Dispose()
  {
   if (!disposed)
   {
    if (thumbNail != null)
    {
     thumbNail.Dispose();
    }
    disposed = true;
   }
  }
 
  ~ShellThumbnail()
  {
   Dispose();
  }
  #endregion
 }
}
 

C#: CheckUrl class for checking contents of an URL

using System;
using System.Text;
using System.IO;
using System.Net;

namespace CheckUrl
{
public class CheckUrl
{
public string GetUrlResponse(string url, string proxyAddress)
{
StringBuilder sb = new StringBuilder();
byte[] buf = new byte[8192];
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
if (proxyAddress != null && proxyAddress.Length > 0)
{
System.Net.WebProxy proxy = new WebProxy(proxyAddress);
proxy.BypassProxyOnLocal = true;
proxy.Credentials = CredentialCache.DefaultCredentials;
request.Proxy = proxy;
}
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
string tempString = null;
int count = 0;

do
{
count = resStream.Read(buf, 0, buf.Length);
if (count != 0)
{
tempString = Encoding.ASCII.GetString(buf, 0, count);
sb.Append(tempString);
}
}
while (count > 0);

return sb.ToString();
}

public bool CheckUrlForContentMatch(string url, string proxy, string content)
{
string response = getUrlResponse(url, proxy);

// Remove all carriage returns, starting & trailing spaces, tab characters and make lower cacse
response = response.Trim().Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t",string.Empty).ToLower();
content = content.Trim().Replace("\r", string.Empty).Replace("\n", string.Empty).Replace("\t", string.Empty).ToLower();

int startPos = response.IndexOf(content);
if (startPos == -1)
return false;
else
return true;
}

}
}

C#: Find max in an array

public int getMax(int[] thearray)
{
int max = 0;
for (int i = 1; i != thearray[max]; )
{
max = i;
}
return thearray[max];
}

C#: Logical equivalent of Request.QueryString

public string SearchQueryString(string queryString, string key)
{
string response = null;
if (queryString.Length > 0 && queryString.Contains(key))
{
queryString = queryString.Substring(1, queryString.Length - 1);
for (int i = 0; i < queryString.Split('&').Length; i++)
{
string subQuery = queryString.Split('&')[i];
string subQueryKey = subQuery.Split('=')[0];
string subQueryValue = subQuery.Split('=')[1];
if (subQueryKey.ToLower() == key.ToLower())
return subQueryValue;
}
}
return response;
}

C#: Delete all sub keys under a registry key

public bool DeleteRegistrySubkey(Microsoft.Win32.RegistryKey regHive, string regKey)
{
bool response = false;

regHive.DeleteSubKeyTree(regKey);
response = true;

return response;
}

C#: Find position of the max integer in an array

public int GetMaxIndexInIntegerArray(int[] thearray)
{
int max = 0;
for (int i = 1; i <> thearray[max])
{
max = i;
}
}
return max;
}

C#: Delete a specific key from a registry

public bool DeleteRegistryKey(Microsoft.Win32.RegistryKey regHive, string regKey, string regName)
{
bool response = false;

Microsoft.Win32.RegistryKey key = regHive.OpenSubKey(regKey, true);
if (key == null)
{
response = true;
}
else
{
key.DeleteValue(regName);
}
response = true;

return response;
}

C#: Read value of a specific registry key

public string ReadRegistryKey(Microsoft.Win32.RegistryKey regHive, string regKey, string regName)
{
string value = null;

Microsoft.Win32.RegistryKey key = regHive.OpenSubKey(regKey);
value = (string)key.GetValue(regName);

return value;
}

C#: Set value of a specific registry key

public bool SetRegistryKey(Microsoft.Win32.RegistryKey regHive, string regKey, string regName, string regValue)
{
bool response = false;

Microsoft.Win32.RegistryKey key = regHive.OpenSubKey(regKey);
if (key == null)
{
regHive.CreateSubKey(regKey, Microsoft.Win32.RegistryKeyPermissionCheck.ReadWriteSubTree);
}
key = regHive.OpenSubKey(regKey,true);
key.SetValue(regName, (string)regValue);
//regHive.Flush(); //Try not to use Flush(): http://msdn2.microsoft.com/en-us/library/microsoft.win32.registrykey.flush.aspx
response = true;

return response;
}

C#: Convert EBCDIC to ASCII

public string ConvertEBCDICtoASCII(string strEBCDICString)
{
int[] e2a = new int[256]{
0, 1, 2, 3,156, 9,134,127,151,141,142, 11, 12, 13, 14, 15,
16, 17, 18, 19,157,133, 8,135, 24, 25,146,143, 28, 29, 30, 31,
128,129,130,131,132, 10, 23, 27,136,137,138,139,140, 5, 6, 7,
144,145, 22,147,148,149,150, 4,152,153,154,155, 20, 21,158, 26,
32,160,161,162,163,164,165,166,167,168, 91, 46, 60, 40, 43, 33,
38,169,170,171,172,173,174,175,176,177, 93, 36, 42, 41, 59, 94,
45, 47,178,179,180,181,182,183,184,185,124, 44, 37, 95, 62, 63,
186,187,188,189,190,191,192,193,194, 96, 58, 35, 64, 39, 61, 34,
195, 97, 98, 99,100,101,102,103,104,105,196,197,198,199,200,201,
202,106,107,108,109,110,111,112,113,114,203,204,205,206,207,208,
209,126,115,116,117,118,119,120,121,122,210,211,212,213,214,215,
216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,
123, 65, 66, 67, 68, 69, 70, 71, 72, 73,232,233,234,235,236,237,
125, 74, 75, 76, 77, 78, 79, 80, 81, 82,238,239,240,241,242,243,
92,159, 83, 84, 85, 86, 87, 88, 89, 90,244,245,246,247,248,249,
48, 49, 50, 51, 52, 53, 54, 55, 56, 57,250,251,252,253,254,255
};

char chrItem = Convert.ToChar("0");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strEBCDICString.Length; i++)
{
try
{
chrItem = Convert.ToChar(strEBCDICString.Substring(i, 1));
sb.Append(Convert.ToChar(e2a[(int)chrItem]));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return string.Empty;
}

}
string result = sb.ToString();
sb = null;
return result;
}

C#: Convert ASCII to EBCDIC

public string ConvertASCIItoEBCDIC(string strASCIIString)
{
int[] a2e = new int[256]{
0, 1, 2, 3, 55, 45, 46, 47, 22, 5, 37, 11, 12, 13, 14, 15,
16, 17, 18, 19, 60, 61, 50, 38, 24, 25, 63, 39, 28, 29, 30, 31,
64, 79,127,123, 91,108, 80,125, 77, 93, 92, 78,107, 96, 75, 97,
240,241,242,243,244,245,246,247,248,249,122, 94, 76,126,110,111,
124,193,194,195,196,197,198,199,200,201,209,210,211,212,213,214,
215,216,217,226,227,228,229,230,231,232,233, 74,224, 90, 95,109,
121,129,130,131,132,133,134,135,136,137,145,146,147,148,149,150,
151,152,153,162,163,164,165,166,167,168,169,192,106,208,161, 7,
32, 33, 34, 35, 36, 21, 6, 23, 40, 41, 42, 43, 44, 9, 10, 27,
48, 49, 26, 51, 52, 53, 54, 8, 56, 57, 58, 59, 4, 20, 62,225,
65, 66, 67, 68, 69, 70, 71, 72, 73, 81, 82, 83, 84, 85, 86, 87,
88, 89, 98, 99,100,101,102,103,104,105,112,113,114,115,116,117,
118,119,120,128,138,139,140,141,142,143,144,154,155,156,157,158,
159,160,170,171,172,173,174,175,176,177,178,179,180,181,182,183,
184,185,186,187,188,189,190,191,202,203,204,205,206,207,218,219,
220,221,222,223,234,235,236,237,238,239,250,251,252,253,254,255
};

char chrItem = Convert.ToChar("0");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < strASCIIString.Length; i++)
{
try
{
chrItem = Convert.ToChar(strASCIIString.Substring(i, 1));
sb.Append(Convert.ToChar(a2e[(int)chrItem]));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return string.Empty;
}
}
string result = sb.ToString();
sb = null;
return result;
}

C#: Read all registry values under a key

public string[,] ReadRegistryValues(Microsoft.Win32.RegistryKey regHive, string regKey)
{
string[,] values = null;

Microsoft.Win32.RegistryKey key = regHive.OpenSubKey(regKey);
string[] valNames = key.GetValueNames();
values = new string[valNames.Length,2];
for (int i = 0; i < valNames.Length; i++)
{
values[i,0] = valNames[i];
values[i,1] = (string)key.GetValue(valNames[i]);
}

return values;
}

C#: Write a byte array to a file

public bool writeByteArrayToFile(byte[] buff, string fileName)
{
bool response = false;

try
{
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(buff);
bw.Close(); //Thanks Karlo for pointing out!
response = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

return response;
}

C#: Encode a string to Base64

public string EncodeStringToBase64(string toEncode)
{
byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue = System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}

C#: Decode a string from Base64

public string DecodeBase64String(string encodedData)
{
byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);
string returnValue = System.Text.ASCIIEncoding.ASCII.GetString(encodedDataAsBytes);
return returnValue;
}

C#: Read a file into a byte array

public byte[] ReadByteArrayFromFile(string fileName)
{
byte[] buff = null;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
long numBytes = new FileInfo(fileName).Length;
buff = br.ReadBytes((int)numBytes);
return buff;
}

C#: Convert byte array to string

public string ConvertByteArrayToString(byte[] input)
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
return enc.GetString(input);
}

C#: Convert byte array to Stream

public Stream ConvertByteArrayToStream(byte[] input)
{
return new MemoryStream(input);
}

C#: Convert string to byte array

public byte[] ConvertStringToByteArray(string input)
{
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
return enc.GetBytes(input);
}

C#: Get an array of integeres from a delimited string

public int[] GetIntArrayFromDelimitedString(string str, char delimiter)
{
int[] response = new int[str.Split(delimiter).Length];
for (int i = 0; i < response.Length; i++)
response[i] = Convert.ToInt32(str.Split(delimiter)[i]);
return response;
}

C#: Generate a temporary file name on disk

public string GetTemporaryFile(string extn)
{
string response = string.Empty;

if (!extn.StartsWith("."))
extn = "." + extn;

response = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + extn;

return response;
}

C#: Compare 2 DataTables and return a 3rd with differences

public DataTable CompareDataTables(DataTable first, DataTable second)
{
first.TableName = "FirstTable";
second.TableName = "SecondTable";

//Create Empty Table
DataTable table = new DataTable("Difference");

try
{
//Must use a Dataset to make use of a DataRelation object
using (DataSet ds = new DataSet())
{
//Add tables
ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });

//Get Columns for DataRelation
DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];

for (int i = 0; i < firstcolumns.Length; i++)
{
firstcolumns[i] = ds.Tables[0].Columns[i];
}

DataColumn[] secondcolumns = new DataColumn[ds.Tables[1].Columns.Count];

for (int i = 0; i < secondcolumns.Length; i++)
{
secondcolumns[i] = ds.Tables[1].Columns[i];
}

//Create DataRelation
DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);

ds.Relations.Add(r);

//Create columns for return table
for (int i = 0; i < first.Columns.Count; i++)
{
table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
}

//If First Row not in Second, Add to return table.
table.BeginLoadData();

foreach (DataRow parentrow in ds.Tables[0].Rows)
{
DataRow[] childrows = parentrow.GetChildRows(r);
if (childrows == null || childrows.Length == 0)
table.LoadDataRow(parentrow.ItemArray, true);
}

table.EndLoadData();

}
}
catch (Exception ex)
{
throw ex;
}

return table;
}

C#: Check if a string is a valid GUID

***NOTE*** After a lot of constructive criticism from my fellow blog-posters (and I really do appreciate it all), I am questioning my own post about its effectiveness over something simple like this (which was not unknown though). Please read all the comments for your education if you care to:

public bool CheckGuid(string guidString)
{
try
{
Guid g = new Guid(guidString);
return true;
}
catch
{
return false;
}
}

Here is my original posting:

public bool CheckGuid(string guidString)
{
bool response = false;
try
{
System.Text.RegularExpressions.Regex isGuid =
new System.Text.RegularExpressions.Regex(@"^(\{){0,1}[0-9a-fA-F]{8}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{4}\-[0-9a-fA-F]{12}(\}){0,1}$",
System.Text.RegularExpressions.RegexOptions.Compiled);
response = isGuid.IsMatch(guidString);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}

return response;
}

What's next

With a cylindrical power of -3.5 on each eye :-) I see Sharper than many do, and that's what I do for living. Yeah Yeah you got that right, I am a C# .Net developer. Like every other developer under the sun, I do admit that I google every day and every hour to get answers to my questions. But what I do not want to do like every other developer is loose those valuable code snippets that I get from some other people who may have been seeing sharper than I. So I will start blogging my findings over here so I and many others can find their answers on their fingertips!

Sunday, December 9, 2007

Welcome

Thanks for visiting my blog. I am working on the contents right now, so please be sure to visit back for updates. Thanks, KC!