Sunday, December 13, 2009

jQuery Watermark Plugin

The following code was adapter from Very simple textbox watermark using JQuery and converted into a reusable jQuery plugin.

Given the following text box

<input type="text" id="textBox1" class="watermarkOn"
title="Type here" value="Type here" />

Add the following CSS style:
<style type="text/css">
.watermarkOn {
color: #CCCCCC;
font-style: italic;
}
</style>


jQuery Plugin Code

(function($) {
$.fn.extend({
//plugin name - watermark
watermark: function(options) {

//Settings list and the default values
var defaults = {
css: 'watermarkOn',
tag: 'title'
};

var options = $.extend(defaults, options);

return this.each(function() {
var o = options;

// When the textbox comes under focus:
// 1. Remove the watermark class and
// 2. clear the text box
$(this).focus(function() {

$(this).filter(function() {
//We only want this to apply if
//nothing was actually entered
return $(this).val() == "" ||
$(this).val() == $(this).attr(o.tag)

}).removeClass(o.css).val("");

});

// When the textbox loses focus:
// 1. Add the watermark class and
// 2. Set the default text
$(this).blur(function() {

$(this).filter(function() {
//We only want this to apply if
//nothing was actually entered
return $(this).val() == ""

}).addClass(o.css).val($(this).attr(o.tag));

});

});
}
});
})(jQuery);


Add the following lines to your document.ready function.
$(document).ready(function() {
$("#textBox1").watermark({css:"watermarkOn",tag:"title"});
});

Wednesday, November 25, 2009

JavaScript Object via JQuery Ajax to an Asp.Net WebMethod

Given the following WebMethod

[WebMethod]
public static string UpdatePerson(Person person)
{
Person p = Repository.Instance.Get<Person>(person.Guid);
p.Name = person.Name;
p.Age = person.Age;
Repository.Instance.Update(p);

var result = new WebMethodResult<Person>();
result.Entity = p;
return result.ToJson();
}

[DataContract]
public class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
[DataMember]
public string Modified { get; set; }
}

You can call this UpdatePerson method using the following jQuery code snippet.

function updatePerson() {
var request = {};
var person = {};
person.name = "Daffy Duck";
person.age = 12;
person.title = "Clown"; //Note that title is not a valid property
request.person = person;

var dataString = $.toJSON(request); //using jquery.json
$.blockUI();

$.ajax({
type: "POST",
url: "Default.aspx/UpdatePerson",
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(json) {
var data = eval('(' + json.d + ')');
if (data.hasErrors)
alert(data.message);
else {
alert("updated " + data.entity.Modified);
}

$.unblockUI();
}
});
}

Friday, September 25, 2009

Color Extensions: ToArgb

Cool extension from http://www.jeff.wilcox.name
internal static class ColorExtensions
{
public static int ToArgb(this Color color)
{
int argb = color.A << 24;
argb += color.R << 16;
argb += color.G << 8;
argb += color.B;

return argb;
}
}

Monday, September 14, 2009

Xml Serialization Helper Class


public static class XmlHelper
{
public static string ToXml(this object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, obj);
return sw.ToString();
}
}

public static T FromXml<T>(this string data)
{
XmlSerializer s = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(data))
{
object obj = s.Deserialize(reader);
return (T)obj;
}
}
}



So we can do this:


string personString = person.ToXml();
Person newPerson = personString.FromXml<Person>();

Monday, August 24, 2009

TypeConverter - DbType to >NET Type


public static class TypeConverter

{

private static readonly Dictionary typeToDbType = new Dictionary

{

{ typeof(string), DbType.String },

{ typeof(DateTime), DbType.DateTime },

{ typeof(DateTime?), DbType.DateTime },

{ typeof(int), DbType.Int32 },

{ typeof(int?), DbType.Int32 },

{ typeof(long), DbType.Int64 },

{ typeof(long?), DbType.Int64 },

{ typeof(bool), DbType.Boolean },

{ typeof(bool?), DbType.Boolean },

{ typeof(byte[]), DbType.Binary },

{ typeof(decimal), DbType.Decimal },

{ typeof(decimal?), DbType.Decimal },

{ typeof(double), DbType.Double },

{ typeof(double?), DbType.Double },

{ typeof(float), DbType.Single },

{ typeof(float?), DbType.Single },

{ typeof(Guid), DbType.Guid },

{ typeof(Guid?), DbType.Guid }

};



public static DbType ToDbType(Type type)

{

if (!typeToDbType.ContainsKey(type))

{

throw new InvalidOperationException(string.Format("Type {0} doesn't have a matching DbType configured", type.FullName));

}



return typeToDbType[type];

}

Wednesday, July 22, 2009

Card shuffling and dealing program

Simple card shuffling and dealing program in java (no Jokers)

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DeckOfCards extends JFrame {
private Card deck[];
private int currentCard;
private JButton dealButton, shuffleButton;
private JTextField displayCard;
private JLabel status;

public DeckOfCards() {
super( "Card Dealing Program" );

String faces[] = { "Ace", "Deuce", "Three", "Four",
"Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King" };
String suits[] = { "Hearts", "Diamonds", "Clubs", "Spades" };

deck = new Card[ 52 ];
currentCard = -1;

for ( int i = 0; i < deck.length; i++ )
deck[ i ] = new Card( faces[ i % 13 ], suits[ i / 13 ] );

Container c = getContentPane();
c.setLayout( new FlowLayout() );

dealButton = new JButton( "Deal card" );
dealButton.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e )
{
Card dealt = dealCard();

if ( dealt != null )
{
displayCard.setText( dealt.toString() );
status.setText( "Card #: " + currentCard );
}
else
{
displayCard.setText( "NO MORE CARDS TO DEAL" );
status.setText( "Shuffle cards to continue" );
}
}
} );
c.add( dealButton );

shuffleButton = new JButton( "Shuffle cards" );
shuffleButton.addActionListener( new ActionListener(){
public void actionPerformed( ActionEvent e )
{
displayCard.setText( "SHUFFLING ..." );
shuffle();
displayCard.setText( "DECK IS SHUFFLED" );
}
});
c.add( shuffleButton );

displayCard = new JTextField( 20 );
displayCard.setEditable( false );
c.add( displayCard );

status = new JLabel();
c.add( status );

setSize( 275, 120 ); // set the window size
show(); // show the window
}

public void shuffle()
{
currentCard = -1;

for ( int i = 0; i < deck.length; i++ ) {
int j = ( int ) ( Math.random() * 52 );
Card temp = deck[ i ]; // swap
deck[ i ] = deck[ j ]; // the
deck[ j ] = temp; // cards
}

dealButton.setEnabled( true );
}

public Card dealCard() {
if ( ++currentCard < deck.length )
return deck[ currentCard ];
else
{
dealButton.setEnabled( false );
return null;
}
}

public static void main( String args[] ) {
DeckOfCards app = new DeckOfCards();

app.addWindowListener( new WindowAdapter(){
public void windowClosing( WindowEvent e )
{
System.exit( 0 );
}
} );
}
}

class Card {
private String face;
private String suit;

public Card( String f, String s ) {
face = f;
suit = s;
}

public String toString() {
return face + " of " + suit;
}
}

Thursday, July 2, 2009

IE Min/Max CSS Width

#page-wrap {
min-width: 960px; max-width: 1260px;
margin: 0 auto; padding: 0 10px;
width:expression(document.body.clientWidth < 961? "960px" : document.body.clientWidth > 1261? "1260px" : "auto");
}

Monday, May 18, 2009

jQuery display


$.fn.display = function(show) {
return this.each(function() {
(show) ? $(this).show() : $(this).hide();
});
};

jQuery toggleClass

You can extend jQuery to swap classes with a toggleClass as shown below:

//extend jquery
(function($) {
$.fn.toggleClass = function(check, replace) {
return this.each(function() {
if ($(this).hasClass(check)) {
$(this).removeClass(check);
$(this).addClass(replace);
} else {
if ($(this).hasClass(replace))
$(this).removeClass(replace);
$(this).addClass(check);
}
});
};
})(jQuery);


So you can do stuff like this:

<input type="button" value="Toggle"
onclick="$('#myDiv').toggleClass('expanded','collapsed')"/>

Friday, May 15, 2009

C# Generic Extension Methods

Just found this interesting generic extension method "Is<T>" on hardcodet.net.

/// <summary>
/// Checks a list of candidates for equality to a given
/// reference value.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="value">The evaluated value.</param>
/// <param name="candidates">A list of possible values that are
/// regarded valid.</param>
/// <returns>True if one of the submitted <paramref name="candidates"/>
/// matches the evaluated value. If the <paramref name="candidates"/>
/// parameter itself is null, too, the method returns false as well,
/// which allows to check with null values, too.</returns>
/// <exception cref="ArgumentNullException">If <paramref name="candidates"/>
/// is a null reference.</exception>
public static bool Is<T>(this T value, params T[] candidates)
{
if (candidates == null) return false;

foreach (var t in candidates)
{
if (value.Equals(t)) return true;
}

return false;
}


So you can do stuff like this:

string status = Order.StatusCode;
if(status.Is("UnAssigned","Cancelled","Suspended"))
{
//Do Something
}

Wednesday, May 13, 2009

C# String Extensions


public static class StringExtensions
{
#region - Substring Methods -

/// <summary>
/// Gets the substring after the first occurrence of a separator. The separator is not returned.
/// </summary>
/// <remarks>
/// A null string input will return null. An empty ("") string input will return the empty string.
/// A null separator will return the empty string if the input string is not null.
/// </remarks>
/// <example>
/// StringExtensions.SubstringAfter(null, "*") = null;
/// StringExtensions.SubstringAfter("", "*") = "";
/// StringExtensions.SubstringAfter("*", null) = "";
/// StringExtensions.SubstringAfter("abc", "a") = "bc";
/// StringExtensions.SubstringAfter("abcba", "b") = "cba";
/// StringExtensions.SubstringAfter("abc", "c") = "";
/// StringExtensions.SubstringAfter("abc", "d") = "";
/// StringExtensions.SubstringAfter("abc", "") = "abc";
/// </example>
/// <param name="str">the String to get a substring from, may be null</param>
/// <param name="separator">the String to search for, may be null </param>
/// <returns>the substring after the first occurrence of the separator, null if null String input</returns>
public static string SubstringAfter(this string str, string separator)
{
if (string.IsNullOrEmpty(str))
return str;
if (separator == null)
return string.Empty;

CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo;
int index = compareInfo.IndexOf(str, separator, CompareOptions.Ordinal);
if (index < 0)
{
//No such substring
return string.Empty;
}

return str.Substring(index + separator.Length);
}

/// <summary>
/// Gets the substring after the last occurrence of a separator. The separator is not returned.
/// </summary>
/// <remarks>
/// A null string input will return null. An empty ("") string input will return the empty string.
/// An empty or null separator will return the empty string if the input string is not null.
/// </remarks>
/// <example>
/// StringExtensions.SubstringAfterLast(null, "*") = null;
/// StringExtensions.SubstringAfterLast("", "*") = "";
/// StringExtensions.SubstringAfterLast("*", "") = "";
/// StringExtensions.SubstringAfterLast("*", null) = "";
/// StringExtensions.SubstringAfterLast("abc", "a") = "bc";
/// StringExtensions.SubstringAfterLast("abcba", "b") = "a";
/// StringExtensions.SubstringAfterLast("abc", "c") = "";
/// StringExtensions.SubstringAfterLast("a", "a") = "";
/// StringExtensions.SubstringAfterLast("a", "z") = "";
/// </example>
/// <param name="str">the String to get a substring from, may be null</param>
/// <param name="separator">the String to search for, may be null </param>
/// <returns>the substring after the last occurrence of the separator, null if null String input</returns>
public static string SubstringAfterLast(this string str, string separator)
{
if (string.IsNullOrEmpty(str))
return str;
if (string.IsNullOrEmpty(separator))
return string.Empty;

CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo;
int index = compareInfo.LastIndexOf(str, separator, CompareOptions.Ordinal);
if (index < 0)
{
//No such substring
return string.Empty;
}

return str.Substring(index + separator.Length);
}


/// <summary>
/// Gets the substring before the first occurrence of a separator. The separator is not returned.
/// </summary>
/// <remarks>
/// A null string input will return null. An empty ("") string input will return the empty string.
/// A null separator will return the input string.
/// </remarks>
/// <example>
/// StringExtensions.SubstringBefore(null, "*") = null;
/// StringExtensions.SubstringBefore("", "*") = "";
/// StringExtensions.SubstringBefore("abc", "a") , "";
/// StringExtensions.SubstringBefore("abcba", "b") , "a";
/// StringExtensions.SubstringBefore("abc", "c") , "ab";
/// StringExtensions.SubstringBefore("abc", "d") , "abc";
/// StringExtensions.SubstringBefore("abc", "") , "";
/// StringExtensions.SubstringBefore("abc", null) , "abc";
/// </example>
/// <param name="str">the String to get a substring from, may be null</param>
/// <param name="separator">the String to search for, may be null </param>
/// <returns>the substring before the first occurrence of the separator, null if null String input</returns>
public static string SubstringBefore(this string str, string separator)
{
if (string.IsNullOrEmpty(str) || separator == null)
return str;
if (separator == string.Empty)
return string.Empty;

CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo;
int index = compareInfo.IndexOf(str, separator, CompareOptions.Ordinal);

if (index < 0)
{
//No such substring
return str;
}

return str.Substring(0, index);
}

/// <summary>
/// Gets the substring before the last occurrence of a separator. The separator is not returned.
/// </summary>
/// <remarks>
/// A null string input will return null. An empty ("") string input will return the empty string.
/// An empty or null separator will return the input string.
/// </remarks>
/// <example>
/// StringExtensions.SubstringBeforeLast(null, "*") = null;
/// StringExtensions.SubstringBeforeLast("", "*") = "";
/// StringExtensions.SubstringBeforeLast("abcba", "b") = "abc";
/// StringExtensions.SubstringBeforeLast("abc", "c") = "ab";
/// StringExtensions.SubstringBeforeLast("a", "a") = "";
/// StringExtensions.SubstringBeforeLast("a", "z") = "a";
/// StringExtensions.SubstringBeforeLast("a", null) = "a";
/// StringExtensions.SubstringBeforeLast("a", "") = "a";
/// </example>
/// <param name="str">the String to get a substring from, may be null</param>
/// <param name="separator">the String to search for, may be null</param>
/// <returns>the substring before the last occurrence of the separator, null if null String input</returns>
public static string SubstringBeforeLast(this string str, string separator)
{
if (string.IsNullOrEmpty(str) || string.IsNullOrEmpty(separator))
return str;

CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo;
int index = compareInfo.LastIndexOf(str, separator, CompareOptions.Ordinal);

if (index < 0)
{
//No such substring
return str;
}

return str.Substring(0, index);
}


/// <summary>
/// Gets the String that is nested in between two instances of the same String.
/// </summary>
/// <remarks>A null input String returns null. A null tag returns null.</remarks>
/// <example>
/// StringExtensions.SubstringBetween(null, "*") = null;
/// StringExtensions.SubstringBetween("", "") = "";
/// StringExtensions.SubstringBetween("", "tag") = null;
/// StringExtensions.SubstringBetween("tagabctag", null) = null;
/// StringExtensions.SubstringBetween("tagabctag", "") = "";
/// StringExtensions.SubstringBetween("tagabctag", "tag") = "abc";
/// </example>
/// <param name="str">the String containing the substring, may be null</param>
/// <param name="tag">the String before and after the substring, may be null </param>
/// <returns>the substring, null if no match</returns>
public static string SubstringBetween(this string str, string tag)
{
return SubstringBetween(str, tag, tag);
}

/// <summary>
/// Gets the String that is nested in between two Strings. Only the first match is returned.
/// </summary>
/// <remarks>
/// A null input String returns null. A null open/close returns null (no match).
/// An empty ("") open and close returns an empty string.
/// </remarks>
/// <example>
/// StringExtensions.SubstringBetween("wx[b]yz", "[", "]") = "b";
/// StringExtensions.SubstringBetween(null, "*", "*") = null;
/// StringExtensions.SubstringBetween("*", null, "*") = null;
/// StringExtensions.SubstringBetween("*", "*", null) = null;
/// StringExtensions.SubstringBetween("", "", "") = "";
/// StringExtensions.SubstringBetween("", "", "]") = null;
/// StringExtensions.SubstringBetween("", "[", "]") = null;
/// StringExtensions.SubstringBetween("yabcz", "", "") = "";
/// StringExtensions.SubstringBetween("yabcz", "y", "z") = "abc";
/// StringExtensions.SubstringBetween("yabczyabcz", "y", "z") = "abc";
/// </example>
/// <param name="str">the String containing the substring, may be null</param>
/// <param name="open">the String before the substring, may be null</param>
/// <param name="close">the String after the substring, may be null </param>
/// <returns>the substring, null if no match</returns>
public static string SubstringBetween(this string str, string open, string close)
{
if (str == null || open == null || close == null)
return null;

string result = SubstringBefore(SubstringAfter(str, open), close);
if (result == string.Empty && str == string.Empty && (open != string.Empty || close != string.Empty))
return null;
return result;
}

/// <summary>
/// Searches a String for substrings delimited by a start and end tag,
/// returning all matching substrings in an array.
/// </summary>
/// <remarks>
/// A null input String returns null. A null open/close returns null (no match).
/// An empty ("") open/close returns null (no match).
/// </remarks>
/// <example>
/// StringExtensions.SubstringsBetween("[a][b][c]", "[", "]") = [ "a", "b", "c" ];
/// StringExtensions.SubstringsBetween(null, "*", "*") = null;
/// StringExtensions.SubstringsBetween("*", null, "*") = null;
/// StringExtensions.SubstringsBetween("*", "*", null) = null;
/// StringExtensions.SubstringsBetween("", "[", "]") = []);
/// </example>
/// <param name="str">the String containing the substrings, null returns null, empty returns empty</param>
/// <param name="open">the String identifying the start of the substring, empty returns null</param>
/// <param name="close">the String identifying the end of the substring, empty returns null </param>
/// <returns>a String Array of substrings, or null if no match</returns>
public static string[] SubstringsBetween(this string str, string open, string close)
{
if (str == null || string.IsNullOrEmpty(open) || string.IsNullOrEmpty(close))
{
return null;
}

int strLen = str.Length;
if (strLen == 0)
{
return new string[]{};
}

int closeLen = close.Length;
int openLen = open.Length;
List<string> list = new List<string>();
int pos = 0;
while (pos < (strLen - closeLen))
{
int start = str.IndexOf(open, pos);
if (start < 0)
{
break;
}
start += openLen;
int end = str.IndexOf(close, start);
if (end < 0)
{
break;
}
list.Add(str.Substring(start, end - start));
pos = end + closeLen;
}

if (list.Count == 0)
{
return null;
}

return list.ToArray();

}

/// <summary>
/// Repeats the specified string n times.
/// </summary>
/// <param name="instr">The input string.</param>
/// <param name="n">The number of times input string should be repeated.</param>
/// <returns></returns>
public static string Repeat(this string str, int n)
{
if (string.IsNullOrEmpty(str))
return str;

var result = new StringBuilder(str.Length * n);
return result.Insert(0, str, n).ToString();
}

#endregion

#region - Boolean Check Methods -

/// <summary>
/// Checks if the String can be converted into a numeric value.
/// </summary>
/// <remarks>null or an empty string will return false.</remarks>
/// <param name="str">the String to check, may be null </param>
/// <returns>true if it can be parsed into a numeric (decimal) value</returns>
public static bool IsNumeric(this string str)
{
if (string.IsNullOrEmpty(str))
return false;
decimal tmp;
return decimal.TryParse(str, out tmp);
}

/// <summary>
/// Checks if the String contains only unicode digits.
/// A decimal point is not a unicode digit and returns false.
/// </summary>
/// <remarks>null will return false. An empty String ("") will return true.</remarks>
/// <param name="str">the String to check, may be null </param>
/// <returns>true if only contains digits, and is non-null</returns>
public static bool IsDigit(this string str)
{
if (str == null)
return false;

int sz = str.Length;
for (int i = 0; i < sz; i++)
{
if (Char.IsDigit(str, i) == false)
return false;
}

return true;
}

/// <summary>
/// Checks if the String contains only unicode letters.
/// </summary>
/// <remarks>null will return false. An empty String ("") will return true.</remarks>
/// <param name="str">the String to check, may be null</param>
/// <returns>true if only contains letters, and is non-null</returns>
public static bool IsAlpha(this string str)
{
if (str == null)
return false;

int sz = str.Length;
for (int i = 0; i < sz; i++)
{
if (Char.IsLetter(str, i) == false)
return false;
}

return true;
}

/// <summary>
/// Checks if the String contains only unicode letters or digits.
/// </summary>
/// <remarks>null will return false. An empty String ("") will return true.</remarks>
/// <param name="str">the String to check, may be null</param>
/// <returns>true if only contains letters or digits, and is non-null</returns>
public static bool IsAlphaNumeric(this string str)
{
if (str == null)
return false;

int sz = str.Length;
for (int i = 0; i < sz; i++)
{
if (Char.IsLetterOrDigit(str, i) == false)
return false;
}

return true;
}
#endregion
}

Thursday, May 7, 2009

SQL Server - Get Table Schema


USE [Northwind]
GO
/****** Object: StoredProcedure [dbo].[GetTableSchema] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[GetTableSchema]
(
@table varchar(50)
)
AS
SELECT
c.table_name As TableName,
c.column_name As ColumnName,
c.data_type As DataType,
c.character_maximum_length As MaxLength,
COALESCE (
( SELECT
CASE cu.column_name
WHEN null THEN 0
ELSE 1
END
FROM information_schema.constraint_column_usage cu
INNER join information_schema.table_constraints ct
ON ct.constraint_name = cu.constraint_name
WHERE
ct.constraint_type = 'PRIMARY KEY'
AND ct.table_name = c.table_name
AND cu.column_name = c.column_name
),0) AS IsPrimaryKey
FROM information_schema.columns c
INNER JOIN information_schema.tables t
ON c.table_name = t.table_name
WHERE @table = t.table_name and
(t.table_type = 'BASE TABLE' and not
(t.table_name = 'dtproperties') and not
(t.table_name = 'sysdiagrams'))
ORDER BY c.table_name, c.ordinal_position

Wednesday, April 29, 2009

Convert a delimited string to an interger array


public static int[] ToIntArray(this string value, char separator)
{
return Array.ConvertAll(value.Split(separator), s=>int.Parse(s));
}

So we can do something like this:

int[] result = "1,2,3".ToIntArray(',');

Convert an Enum Array into an Interger Array


DayOfWeek[] enumArray = new DayOfWeek[] {
DayOfWeek.Monday, DayOfWeek.Wednesday };

//Convert enum to int array
int[] result = Array.ConvertAll<DayOfWeek, int>(enumArray,
delegate(DayOfWeek value) { return (int)value; });

//with C# 3.0, a lambda:
int[] result2 = Array.ConvertAll(enumArray, value => (int) value);

//with C# 3.0 using Cast
int[] result3 = enumArray.Cast<int>().ToArray();

Tuesday, April 28, 2009

Measure a function's performance

Use the Stopwatch (in System.Diagnostics)

Stopwatch sw = Stopwatch.StartNew();
PerformWork();
sw.Stop();

Console.WriteLine("Time taken: {0}ms",
sw.Elapsed.TotalMilliseconds);

Tuesday, April 21, 2009

C# - Run a Process (Run an EXE)

CodeProject: Windows Services Can Install Themselves. :

Process myProcess = new Process();
string path = @'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727';
myProcess.StartInfo.FileName = path + '\\InstallUtil.exe';
myProcess.StartInfo.Arguments = @'/u C:\Service1\Service1.exe';
myProcess.StartInfo.CreateNoWindow = true;
myProcess.Start();

myProcess.WaitForExit(60000);
if (!myProcess.HasExited)
myProcess.Kill();
myProcess.Close();

Tuesday, March 24, 2009

Xml Related Extensions

Given the following extension class

public static class XmlHelper
{
public static string ToXml(this object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter sw = new StringWriter())
{
serializer.Serialize(sw, obj);
return sw.ToString();
}
}

public static T FromXml<T>(this string data)
{
XmlSerializer s = new XmlSerializer(typeof(T));
using (StringReader reader = new StringReader(data))
{
object obj = s.Deserialize(reader);
return (T)obj;
}
}
}


You can do something like:

Person person = new Person("Jack Daniels");
string xmlData = person.ToXml();
Person backFromXml = xmlData.FromXml<Person>();



...