<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">
  <channel>
    <title>dotneat.net</title>
    <link>http://www.dotneat.net/</link>
    <description>neat things about .net</description>
    <language>en-us</language>
    <copyright>Iván Loire</copyright>
    <lastBuildDate>Sun, 22 Mar 2009 13:06:09 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.0.7226.0</generator>
    <managingEditor>iloire@gmail.com</managingEditor>
    <webMaster>iloire@gmail.com</webMaster>
    <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/Dotneatnet" type="application/rss+xml" /><item>
      <trackback:ping>http://www.dotneat.net/Trackback.aspx?guid=3bbf1ff6-34c7-409a-b2a3-34cd66f8c056</trackback:ping>
      <pingback:server>http://www.dotneat.net/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotneat.net/PermaLink,guid,3bbf1ff6-34c7-409a-b2a3-34cd66f8c056.aspx</pingback:target>
      <dc:creator>Iv�n</dc:creator>
      <wfw:comment>http://www.dotneat.net/CommentView,guid,3bbf1ff6-34c7-409a-b2a3-34cd66f8c056.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotneat.net/SyndicationService.asmx/GetEntryCommentsRss?guid=3bbf1ff6-34c7-409a-b2a3-34cd66f8c056</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <title>.NET Serialization (using BinaryFormater, SoapFormatter and XmlSerializer)</title>
      <guid isPermaLink="false">http://www.dotneat.net/PermaLink,guid,3bbf1ff6-34c7-409a-b2a3-34cd66f8c056.aspx</guid>
      <link>http://feedproxy.google.com/~r/Dotneatnet/~3/tzQWIAp3chg/NETSerializationUsingBinaryFormaterSoapFormatterAndXmlSerializer.aspx</link>
      <pubDate>Sun, 22 Mar 2009 13:06:09 GMT</pubDate>
      <description>&lt;p&gt;
Object serialization is the &lt;strong&gt;process of converting an object to a format that
is suitable for persistence&lt;/strong&gt; (database, file, etc) &lt;strong&gt;or transportation&lt;/strong&gt; (remoting,
Web Services, MSMQ, etc). 
&lt;/p&gt;
&lt;p&gt;
The &lt;strong&gt;format of the output byte stream is governed by a formatter object&lt;/strong&gt;.
When you serialize data, you construct a formatter object that implements the required
format. 
&lt;/p&gt;
&lt;p&gt;
With .NET Framework 2.0 and above you can use two formatters: &lt;strong&gt;BinaryFormatter&lt;/strong&gt; and &lt;strong&gt;SoapFormatter&lt;/strong&gt;.
You can also serialize objects (well, just the public members, not the private ones
- which is know as shallow serialization) by using the &lt;strong&gt;XMLSerializer class&lt;/strong&gt;.
&lt;/p&gt;
&lt;p&gt;
The following class &lt;em&gt;Person&lt;/em&gt; implements some attributes that are used in the
process of seralization. This class is also used on the application example &lt;a href="#downloadSerializationExample"&gt;you
can download below&lt;/a&gt;.
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;
 [Serializable] //&lt;-- this atribute is just required by binaryformatter and soapformatter public class person //&lt;-- XMLSerializer needs that the class is defined as public
    {
        //[System.Xml.Serialization.XmlIgnore]   //&lt;-- using this attribute, this field will be ignored in Xml Serialization        

        public string FirstName; //Some few public properties to serialize. They  will be serialize by the three formatters.

        public string LastName;                
               
        [NonSerialized] //&lt;-- Using this attribute, the field Nationality won't be serialized (by any of the three serializers)
        public string Nationality;        
        
        private string _Address; //this private field won't be serialized using XmlSerialization. They will be serialized using Binary or Soap formatters

        private string _ZIPCode; //this private field won't be serialized  using XmlSerialization. They will be serialized using Binary or Soap formatters

		//let's create a method to set the private properties.
        public void SetAddress(string address, string zipCode) 
        {
            _Address = address;
            _ZIPCode = zipCode;
        }

        public override string ToString()
        {
            return string.Format("I'm {0} {1} from {2}!. Address: {3}, {4}", 
				FirstName,LastName,Nationality, _Address,_ZIPCode);
        }
    }
&lt;/pre&gt;
&lt;h2&gt;Serialization formatters in the .NET Framework
&lt;/h2&gt;
&lt;h3&gt;1) BinaryFormatter (System.Runtime.Serialization.Formatters.Binary namespace)
&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
Serializes and object in an &lt;strong&gt;internal binary format that the .NET Framework
understands&lt;/strong&gt;. 
&lt;li&gt;
The type needs to be marked with the &lt;strong&gt;&lt;em&gt;[Serializable]&lt;/em&gt;&lt;/strong&gt; atribute
(see class &lt;em&gt;Person&lt;/em&gt;) 
&lt;li&gt;
&lt;strong&gt;&lt;em&gt;BinaryFormatter&lt;/em&gt;&lt;/strong&gt; saves metadata (assembly and type information)
on the output stream along with object data. This information is necessary to deserialize
the data and rebuild the object in memory. 
&lt;/ul&gt;
&lt;p&gt;
&lt;strong&gt;PROS&lt;/strong&gt;
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
The output byte stream generated is &lt;strong&gt;compact&lt;/strong&gt; 
&lt;li&gt;
The serialization process is &lt;strong&gt;faster&lt;/strong&gt; than using the other formatters. 
&lt;li&gt;
This formatter &lt;strong&gt;can serialize generic and non generic collections&lt;/strong&gt; (being
the items within the collection serializable) 
&lt;li&gt;
Serializes public and private members (deep serialization) 
&lt;/ul&gt;
&lt;p&gt;
&lt;strong&gt;CONS&lt;/strong&gt;
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Format &lt;strong&gt;not readable by other techonolgies&lt;/strong&gt; (just .NET Framework) 
&lt;/ul&gt;
&lt;p&gt;
&lt;strong&gt;BinaryFormatter serialization use example&lt;/strong&gt;
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;
Person p=new Person();
string path=@"c:\myfile.bin";
using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
	System.Runtime.Serialization.Formatters.Binary.BinaryFormatter b = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
	b.Serialize(fs, p);
	fs.Close();
}
&lt;/pre&gt;
&lt;p&gt;
This code will serialize object p (type Person) on file c:\myfile.bin with binary
format
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;BinaryFormatter deserialization use example:&lt;/strong&gt;
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;
string path=@"c:\myfile.bin";
using (System.IO.FileStream ds = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
	System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
	Person p = bf.Deserialize(ds) as Person;	
}
&lt;/pre&gt;
&lt;p&gt;
This code will deserialize object p (type Person) from c:\myfile.bin
&lt;/p&gt;
&lt;h3&gt;2) SoapFormatter (System.Runtime.Serialization.Formatters.Soap namespace)
&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
Serializes an object in &lt;a href="http://en.wikipedia.org/wiki/SOAP" target="_blank"&gt;SOAP&lt;/a&gt; format. 
&lt;li&gt;
The type also needs to be marked with the &lt;strong&gt;&lt;em&gt;[Serializable]&lt;/em&gt;&lt;/strong&gt; atribute. 
&lt;li&gt;
To use this class &lt;strong&gt;you need a reference to the System.Runtime.Serialization.Soap
assembly&lt;/strong&gt;. 
&lt;li&gt;
This formatter also saves metadata (assembly and type information) on the output stream
along with object data. 
&lt;/ul&gt;
&lt;p&gt;
&lt;strong&gt;PROS&lt;/strong&gt;
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Follows a standard (&lt;a href="http://en.wikipedia.org/wiki/SOAP" target="_blank"&gt;SOAP&lt;/a&gt;)
that other platforms can understand. 
&lt;li&gt;
Serializes public and private members (deep serialization) 
&lt;/ul&gt;
&lt;p&gt;
&lt;strong&gt;CONS&lt;/strong&gt;
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
It is more &lt;strong&gt;verbose&lt;/strong&gt; (less efficient) than &lt;strong&gt;BinaryFormatter&lt;/strong&gt;. 
&lt;li&gt;
It &lt;strong&gt;can NOT serialize generic collections&lt;/strong&gt; (System.Collections.Generic
namespace) 
&lt;/ul&gt;
&lt;p&gt;
&lt;strong&gt;SoapFormatter serialization use example:&lt;/strong&gt;
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;
Person p=new Person();
string path=@"c:\myfile.soap";
using (System.IO.FileStream fs = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
	System.Runtime.Serialization.Formatters.Soap.SoapFormatter
	f = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
	f.Serialize(fs, p);
	fs.Close();
}
&lt;/pre&gt;
&lt;p&gt;
This code will serialize object p (type Person) on file c:\myfile.soap with Soap format
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;SoapFormatter deserialization use example:&lt;/strong&gt;
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;
string path=@"c:\myfile.soap";
using (System.IO.FileStream ds = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
	System.Runtime.Serialization.Formatters.Soap.SoapFormatter sf = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();
	Person p = sf.Deserialize(ds) as Person;
	AppendToLog(string.Format("Single person deserialized from {0} in SOAP format: {1}", path, p));
}
&lt;/pre&gt;
&lt;p&gt;
This code will deserialize object p (type Person) from file on c:\myfile.soap using
Soap formatter
&lt;/p&gt;
&lt;p&gt;
A &lt;em&gt;Person&lt;/em&gt; object after Soap serialization looks like this:
&lt;/p&gt;
&lt;pre class="xml" name="code"&gt;
&amp;lt;SOAP-ENV:Envelope xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xmlns:xsd=&amp;quot;http://www.w3.org/2001/XMLSchema&amp;quot; xmlns:SOAP-ENC=&amp;quot;http://schemas.xmlsoap.org/soap/encoding/&amp;quot; xmlns:SOAP-ENV=&amp;quot;http://schemas.xmlsoap.org/soap/envelope/&amp;quot; xmlns:clr=&amp;quot;http://schemas.microsoft.com/soap/encoding/clr/1.0&amp;quot; SOAP-ENV:encodingStyle=&amp;quot;http://schemas.xmlsoap.org/soap/encoding/&amp;quot;&amp;gt;
	&amp;lt;SOAP-ENV:Body&amp;gt;
		&amp;lt;a1:Person id=&amp;quot;ref-1&amp;quot; xmlns:a1=&amp;quot;http://schemas.microsoft.com/clr/nsassem/Serialization/dotneat_net.Serialization%2C%20Version%3D0.0.0.0%2C%20Culture%3Dneutral%2C%20PublicKeyToken%3Dnull&amp;quot;&amp;gt;
			&amp;lt;FirstName id=&amp;quot;ref-3&amp;quot;&amp;gt;Joe&amp;lt;/FirstName&amp;gt;
			&amp;lt;LastName id=&amp;quot;ref-4&amp;quot;&amp;gt;Doe&amp;lt;/LastName&amp;gt;
			&amp;lt;_Address id=&amp;quot;ref-5&amp;quot;&amp;gt;dotneat.net Street, Zaragoza, Spain&amp;lt;/_Address&amp;gt;
			&amp;lt;_ZIPCode id=&amp;quot;ref-6&amp;quot;&amp;gt;50007&amp;lt;/_ZIPCode&amp;gt;
		&amp;lt;/a1:Person&amp;gt;
	&amp;lt;/SOAP-ENV:Body&amp;gt;
&amp;lt;/SOAP-ENV:Envelope&amp;gt;
&lt;/pre&gt;
&lt;h3&gt;3) XMLSerializer
&lt;/h3&gt;
&lt;ul&gt;
&lt;li&gt;
Serializes and object in XML format. 
&lt;li&gt;
Requeriments: 
&lt;ul&gt;
&lt;li&gt;
Type must be public (public class person) 
&lt;li&gt;
Must implement a parameterless constructor (in order to deserialize the object) 
&lt;li&gt;
If you are serializing a non generic collection of items, you must pass the types
that are stored in the collection as a parameter in the constructor of the &lt;strong&gt;XmlSerializer&lt;/strong&gt; (see
example code). 
&lt;/ul&gt;
&lt;/ul&gt;
&lt;p&gt;
&lt;strong&gt;PROS&lt;/strong&gt;
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
It can serialize &lt;strong&gt;generic and non generic collections&lt;/strong&gt; (being the items
within the collection serializable) 
&lt;li&gt;
Class doesn't need to be decorated with &lt;strong&gt;&lt;em&gt;[Serializable]&lt;/em&gt;&lt;/strong&gt; attribute. 
&lt;li&gt;
Developer has a deep control about how each field is going to be serialized by using
the attributes: 
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;[XmlAttribute]&lt;/strong&gt; : over a field, marks that the field will be serialized
as attribute, instead of a node 
&lt;li&gt;
&lt;strong&gt;[XmlIgnore]&lt;/strong&gt; : won't serialize that field. The same as NonSerializable,
but just for the XmlSerializer. 
&lt;li&gt;
&lt;strong&gt;[XmlElement (ElementName="NewName"]&lt;/strong&gt;: Allows you to rename the field
when being serialized. 
&lt;li&gt;
.... 
&lt;/ul&gt;
&lt;/ul&gt;
&lt;p&gt;
&lt;strong&gt;CONS&lt;/strong&gt;
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Only public members will be serialize! (shallow serialization)&lt;/strong&gt; (both &lt;strong&gt;BinaryFormatter&lt;/strong&gt; and &lt;strong&gt;SoapFormatter&lt;/strong&gt; would
serialize also object private members) 
&lt;/ul&gt;
&lt;p&gt;
&lt;strong&gt;XmlSerializer serialization use example:&lt;/strong&gt;
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;
Person p=new Person();
string path=@"c:\myfile.xml";
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Person));
using (System.IO.FileStream xmlStream = new System.IO.FileStream(path, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
	serializer.Serialize(xmlStream, p);
	xmlStream.Close();
}
&lt;/pre&gt;
&lt;p&gt;
This code will serialize object p (type Person) on file on c:\myfile.xml using the
XmlSerializer class
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;XmlSerializer deserialization use example:&lt;/strong&gt;
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;
string path=@"c:\myfile.xml";
System.Xml.Serialization.XmlSerializer dxml = new System.Xml.Serialization.XmlSerializer(typeof(Person));
using (System.IO.FileStream xmlStream = new System.IO.FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
	Person p = dxml.Deserialize(xmlStream) as Person;
	xmlStream.Close();
}                
&lt;/pre&gt;
&lt;p&gt;
This code will deserialize object p (type Person) from file c:\myfile.xml using the
XmlSerializer class
&lt;/p&gt;
&lt;p&gt;
A &lt;em&gt;Person&lt;/em&gt; object after XML serialization looks like this (see how just public
members are serialized):
&lt;/p&gt;
&lt;pre class="xml" name="code"&gt;
&amp;lt;?xml version=&amp;quot;1.0&amp;quot;?&amp;gt;
&amp;lt;Person xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot; xmlns:xsd=&amp;quot;http://www.w3.org/2001/XMLSchema&amp;quot;&amp;gt;
  &amp;lt;FirstName&amp;gt;Joe&amp;lt;/FirstName&amp;gt;
  &amp;lt;LastName&amp;gt;Doe&amp;lt;/LastName&amp;gt;
&amp;lt;/Person&amp;gt;
&lt;/pre&gt;
&lt;p&gt;
As you may see, private members are not serialized.
&lt;/p&gt;
&lt;h2&gt;Selecting Fields to serialize
&lt;/h2&gt;
&lt;p&gt;
You can omit fields from being serialized by marking them with the &lt;strong&gt;&lt;em&gt;[NonSerialized]&lt;/em&gt;&lt;/strong&gt; attribute
(see Nationality field in &lt;em&gt;Person&lt;/em&gt; class).
&lt;/p&gt;
&lt;h2&gt;Customizing the process of serialization and deserialization
&lt;/h2&gt;
&lt;p&gt;
If you are required to, you can modify the way the data in objects is serialized and
deserialized. For example, you may want to serialize the account number and pass code
of the class &lt;em&gt;BackAccount&lt;/em&gt; crypted (just those two fields)
&lt;/p&gt;
&lt;h3&gt;Serialization process
&lt;/h3&gt;
&lt;p&gt;
You need to implement the interface &lt;strong&gt;&lt;em&gt;ISerializable&lt;/em&gt;&lt;/strong&gt; on the
class to serialize. If the type implements &lt;strong&gt;&lt;em&gt;ISerializable&lt;/em&gt;&lt;/strong&gt; interface,
the formatter calls the GetObjectData to convert the object into the stream of bytes. 
&lt;/p&gt;
&lt;p&gt;
Use &lt;strong&gt;OnSerializingAttribute&lt;/strong&gt; and &lt;strong&gt;OnSerializedAttribute&lt;/strong&gt; to
mark methods that will be executed before and after the serialization takes place. 
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;
[Serializable]
public class Person : ISerializable{

    .....

    [OnSerializing]
    public void Deserializing (StreamingContext context){
        //before serialization
    }


    [OnSerialized]
    public void Serialized (StreamingContext context){
        //after serialization
    }
}
&lt;/pre&gt;
&lt;h3&gt;Deserialization process
&lt;/h3&gt;
&lt;p&gt;
It is also possible to control how the deserialization process by implementing a constructor
that takes a &lt;strong&gt;SerializationInfo&lt;/strong&gt; and a &lt;strong&gt;StreamingContext&lt;/strong&gt; as
parameters.
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;
[Serializable]
public class Person : ISerializable{
    //Deserialization constructor
    private Person(SerializationInfo info, StreamingContext context){
        string fname=info.GetString("FirstName");    
        // ...   
    }
}
&lt;/pre&gt;
&lt;p&gt;
Use &lt;strong&gt;OnDeserializingAttribute&lt;/strong&gt; and &lt;strong&gt;OnDeserializedAttribute&lt;/strong&gt; to
specify methods to run before and after the object is deserialized.
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;
[Serializable]
public class Person : ISerializable{

    .....

    [OnDeserializing]
    public void Deserializing (StreamingContext context){
        //before deserialization
    }


    [OnDeserialized]
    public void Deserialized (StreamingContext context){
        //after deserialization
    }

}
&lt;/pre&gt;
&lt;h2&gt;Example application code
&lt;/h2&gt;
&lt;a name="downloadSerializationExample"&gt; &lt;a href="/content/binary/serializationScreen1Big.png"&gt;&lt;img src="/content/binary/serializationScreen1small.png" border="0"&gt;&lt;/a&gt; 
&lt;br /&gt;
(click on the image to view screenshot in full size) 
&lt;p&gt;
&lt;a href="http://dotneatnet.googlecode.com/files/Serialization.zip"&gt;Serialization application
example source code (hosted on google code)&lt;/a&gt; 
&lt;/p&gt;
&lt;h3&gt;About the example application
&lt;/h3&gt;
&lt;p&gt;
You can use the application for serialize/deserialize a simple example class "Person".
You can go and check file size and format of output file. You can also serialize/deserilize
non generic (ArrayList) and generic (List&lt;Person&gt;
) collections of Person, so you can see how the formatters serialize those types.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Performance&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
There is a performance test functionality. You can check which is the faster way of
serializing a simple type. Feel free to extend the example to create performance tests
that suits your needs
&lt;/p&gt;
&lt;h2&gt;Final review
&lt;/h2&gt;
&lt;a href="/content/binary/serializationScreenReviewBig.png"&gt;&lt;img src="/content/binary/serializationScreenReviewsmall.png" border="0"&gt;&lt;/a&gt; &lt;img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=3bbf1ff6-34c7-409a-b2a3-34cd66f8c056" /&gt;</description>
      <comments>http://www.dotneat.net/CommentView,guid,3bbf1ff6-34c7-409a-b2a3-34cd66f8c056.aspx</comments>
      <category>Performance</category>
      <category>Serialization</category>
    <feedburner:origLink>http://www.dotneat.net/2009/03/22/NETSerializationUsingBinaryFormaterSoapFormatterAndXmlSerializer.aspx</feedburner:origLink></item>
    <item>
      <trackback:ping>http://www.dotneat.net/Trackback.aspx?guid=c4a9a4cc-c45c-4147-8342-b93cb5d80cc4</trackback:ping>
      <pingback:server>http://www.dotneat.net/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotneat.net/PermaLink,guid,c4a9a4cc-c45c-4147-8342-b93cb5d80cc4.aspx</pingback:target>
      <dc:creator>Iv�n</dc:creator>
      <wfw:comment>http://www.dotneat.net/CommentView,guid,c4a9a4cc-c45c-4147-8342-b93cb5d80cc4.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotneat.net/SyndicationService.asmx/GetEntryCommentsRss?guid=c4a9a4cc-c45c-4147-8342-b93cb5d80cc4</wfw:commentRss>
      <slash:comments>11</slash:comments>
      <title>Backgroundworker example</title>
      <guid isPermaLink="false">http://www.dotneat.net/PermaLink,guid,c4a9a4cc-c45c-4147-8342-b93cb5d80cc4.aspx</guid>
      <link>http://feedproxy.google.com/~r/Dotneatnet/~3/sKGX_aFQC_Y/BackgroundworkerExample.aspx</link>
      <pubDate>Tue, 10 Feb 2009 17:57:20 GMT</pubDate>
      <description>&lt;p&gt;
The background worker allows you to execute intense or long operations on a &lt;strong&gt;separate
thread&lt;/strong&gt;, without having to deal with threads, invokes or&amp;nbsp;delegates. This
is essential in today's cluttered webspace brought forth by the constant growth of &lt;a href="http://broadband.o2.co.uk/"&gt;broadband&lt;/a&gt; technology. 
&lt;/p&gt;
&lt;p&gt;
This simple example pretty much cover all posibilities of use of this component: &lt;strong&gt;cancellation
support&lt;/strong&gt;, &lt;strong&gt;backgroundworker error handling and&lt;/strong&gt;&amp;nbsp;&lt;strong&gt;report
progress&lt;/strong&gt; (also passing &lt;strong&gt;UserState&lt;/strong&gt; data on report progress
notifications)
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://www.dotneat.net/content/binary/backgroundworker.png"&gt;
&lt;/p&gt;
&lt;pre class="c#" name="code"&gt;&lt; 100; i++)
                {
                    System.Threading.Thread.Sleep(50); //do some intense task here.
                    backgroundWorker1.ReportProgress(i, DateTime.Now); //notify progress to main thread. We also pass time information in UserState to cover this property in the example.
                    //Error handling: uncomment this code if you want to test how an exception is handled by the background worker.
                    //also uncomment the mentioned attribute above to it doesn't stop in the debugger.
                    //if (i == 34)
                    //    throw new Exception("something wrong here!!");

                    //if cancellation is pending, cancel work.
                    if (backgroundWorker1.CancellationPending)
                    {
                        e.Cancel = true; 
                        return;
                    }
                }

                TimeSpan duration = DateTime.Now - start;
                
                //we could return some useful information here, like calculation output, number of items affected, etc.. to the main thread.
                e.Result = "Duration: " + duration.TotalMilliseconds.ToString() + " ms.";
            //}
            //catch(Exception ex){
            //    MessageBox.Show("Don't use try catch here, let the backgroundworker handle it for you!");
            //}
        }


        
        //This event is raised on the main thread.
        //It is safe to access UI controls here.
        private void backgroundWorker1_ProgressChanged(object sender, 
            ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage; //update progress bar
            
            DateTime time = Convert.ToDateTime(e.UserState); //get additional information about progress
            
            //in this example, we log that optional additional info to textbox
            txtOutput.AppendText(time.ToLongTimeString());
            txtOutput.AppendText(Environment.NewLine);            
        }



        //This is executed after the task is complete whatever the task has completed: a) sucessfully, b) with error c)has been cancelled
        private void backgroundWorker1_RunWorkerCompleted(object sender, 
            RunWorkerCompletedEventArgs e)
        {
            if (e.Cancelled) {
                MessageBox.Show("The task has been cancelled");
            }
            else if (e.Error != null)
            {                
                MessageBox.Show("Error. Details: " + (e.Error as Exception).ToString());
            }
            else {
                MessageBox.Show("The task has been completed. Results: " + e.Result.ToString());
            }
            
        }




        private void btoCancel_Click(object sender, EventArgs e)
        {
            //notify background worker we want to cancel the operation.
            //this code doesn't actually cancel or kill the thread that is executing the job.
            backgroundWorker1.CancelAsync();
        }

        private void btoStart_Click(object sender, EventArgs e)
        {
            backgroundWorker1.RunWorkerAsync();
        }

      
    }
}

&lt;/pre&gt;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace BackgroundWorker
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //mandatory. Otherwise will throw an exception when calling ReportProgress method
            backgroundWorker1.WorkerReportsProgress = true; 

            //mandatory. Otherwise we would get an InvalidOperationException when trying to cancel the operation
            backgroundWorker1.WorkerSupportsCancellation = true;
        }



        //This method is executed in a separate thread created by the background worker.
        //so don't try to access any UI controls here!! (unless you use a delegate to do it)
        //this attribute will prevent the debugger to stop here if any exception is raised.
        //[System.Diagnostics.DebuggerNonUserCodeAttribute()]
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            //NOTE: we shouldn't use a try catch block here (unless you rethrow the exception)
            //the backgroundworker will be able to detect any exception on this code.
            //if any exception is produced, it will be available to you on 
            //the RunWorkerCompletedEventArgs object, method backgroundWorker1_RunWorkerCompleted
            //try
            //{
                DateTime start = DateTime.Now;
                e.Result = "";
                for (int i = 0; i 


&lt;p&gt;
&lt;b&gt;Download sample project&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.dotneat.net/content/binary/BackgroundWorker.zip"&gt;Download BackgroundWorker.ZIP
(C# sample project)&lt;/a&gt; 
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=c4a9a4cc-c45c-4147-8342-b93cb5d80cc4" /&gt;</description>
      <comments>http://www.dotneat.net/CommentView,guid,c4a9a4cc-c45c-4147-8342-b93cb5d80cc4.aspx</comments>
      <category>.NET 2.0</category>
      <category>Performance</category>
      <category>Visual Studio 2005</category>
    <feedburner:origLink>http://www.dotneat.net/2009/02/10/BackgroundworkerExample.aspx</feedburner:origLink></item>
    <item>
      <trackback:ping>http://www.dotneat.net/Trackback.aspx?guid=1bcb0593-d633-4253-b802-5e16b3195b73</trackback:ping>
      <pingback:server>http://www.dotneat.net/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotneat.net/PermaLink,guid,1bcb0593-d633-4253-b802-5e16b3195b73.aspx</pingback:target>
      <dc:creator>Iv�n</dc:creator>
      <wfw:comment>http://www.dotneat.net/CommentView,guid,1bcb0593-d633-4253-b802-5e16b3195b73.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotneat.net/SyndicationService.asmx/GetEntryCommentsRss?guid=1bcb0593-d633-4253-b802-5e16b3195b73</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
If you go to <strong>Build</strong>-&gt; <strong>Publish Web Site</strong> menu on
Visual Studio 2005, you will find this publishing screen:
</p>
        <p>
          <img src="http://www.dotneat.net/content/binary/PublishWeb.png" />
        </p>
        <p>
If you <strong>UNCHECK </strong>the "Allow this precompiled site to be updatable",
all the <strong>aspx pages within the projects will be generated empty</strong>. To
be more exact, you will find the following unique line on them:
</p>
        <pre>
          <span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">This <span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">is</span> a
marker file generated by the precompilation tool, and should not be deleted! </span>
        </pre>
        <p>
If you compare this screenshot:
</p>
        <p>
          <img src="http://www.dotneat.net/content/binary/PublishWeb3.png" />
        </p>
        <p>
with this one:
</p>
        <p>
          <img src="http://www.dotneat.net/content/binary/PublishWeb2.png" />
        </p>
        <p>
you will realize how the first was published allowing ASPX pages to be updated and
the second not (notice how in second screenshot, <strong>all the ASPX files have 1kb
file size</strong>)
</p>
        <p>
Don't worry!, All HTML markup and inline code is compiled into assemblies on the bin
folder, and it is correctly executed and rendered when the page is requested. 
</p>
        <p>
This way, nobody would be able to change either code or HTML content after the publishing
is done!
</p>
        <img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=1bcb0593-d633-4253-b802-5e16b3195b73" />
      </body>
      <title>Avoiding ASPX pages to be updated after delivery (by the client or someone else)</title>
      <guid isPermaLink="false">http://www.dotneat.net/PermaLink,guid,1bcb0593-d633-4253-b802-5e16b3195b73.aspx</guid>
      <link>http://feedproxy.google.com/~r/Dotneatnet/~3/45OPSayV_SI/AvoidingASPXPagesToBeUpdatedAfterDeliveryByTheClientOrSomeoneElse.aspx</link>
      <pubDate>Tue, 20 Jan 2009 00:05:22 GMT</pubDate>
      <description>&lt;p&gt;
If you go to &lt;strong&gt;Build&lt;/strong&gt;-&amp;gt; &lt;strong&gt;Publish Web Site&lt;/strong&gt; menu on
Visual Studio 2005, you will find this publishing screen:
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://www.dotneat.net/content/binary/PublishWeb.png"&gt;
&lt;/p&gt;
&lt;p&gt;
If you &lt;strong&gt;UNCHECK &lt;/strong&gt;the "Allow this precompiled site to be updatable",
all the &lt;strong&gt;aspx pages within the projects will be generated empty&lt;/strong&gt;. To
be more exact, you will find the following unique line on them:
&lt;/p&gt;
&lt;pre&gt;&lt;span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;This &lt;span style="FONT-SIZE: 11px; COLOR: blue; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;is&lt;/span&gt; a
marker file generated by the precompilation tool, and should not be deleted! &lt;/span&gt;&lt;/pre&gt;
&lt;p&gt;
If you compare this screenshot:
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://www.dotneat.net/content/binary/PublishWeb3.png"&gt;
&lt;/p&gt;
&lt;p&gt;
with this one:
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://www.dotneat.net/content/binary/PublishWeb2.png"&gt;
&lt;/p&gt;
&lt;p&gt;
you will realize how the first was published allowing ASPX pages to be updated and
the second not (notice how in second screenshot, &lt;strong&gt;all the ASPX files have 1kb
file size&lt;/strong&gt;)
&lt;/p&gt;
&lt;p&gt;
Don't worry!, All HTML markup and inline code is compiled into assemblies on the bin
folder, and it is correctly executed and rendered when the page is requested. 
&lt;/p&gt;
&lt;p&gt;
This way, nobody would be able to change either code or HTML content after the publishing
is done!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=1bcb0593-d633-4253-b802-5e16b3195b73" /&gt;</description>
      <comments>http://www.dotneat.net/CommentView,guid,1bcb0593-d633-4253-b802-5e16b3195b73.aspx</comments>
      <category>.NET 2.0</category>
      <category>Visual Studio 2005</category>
      <category>ASP.NET</category>
    <feedburner:origLink>http://www.dotneat.net/2009/01/20/AvoidingASPXPagesToBeUpdatedAfterDeliveryByTheClientOrSomeoneElse.aspx</feedburner:origLink></item>
    <item>
      <trackback:ping>http://www.dotneat.net/Trackback.aspx?guid=184359d8-5382-4378-b6ec-48d004ff64f6</trackback:ping>
      <pingback:server>http://www.dotneat.net/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotneat.net/PermaLink,guid,184359d8-5382-4378-b6ec-48d004ff64f6.aspx</pingback:target>
      <dc:creator>Iv�n</dc:creator>
      <wfw:comment>http://www.dotneat.net/CommentView,guid,184359d8-5382-4378-b6ec-48d004ff64f6.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotneat.net/SyndicationService.asmx/GetEntryCommentsRss?guid=184359d8-5382-4378-b6ec-48d004ff64f6</wfw:commentRss>
      <slash:comments>4</slash:comments>
      <title>Adding your own Custom Control to a Windows forms Context Menu using ToolStripCustomHost class</title>
      <guid isPermaLink="false">http://www.dotneat.net/PermaLink,guid,184359d8-5382-4378-b6ec-48d004ff64f6.aspx</guid>
      <link>http://feedproxy.google.com/~r/Dotneatnet/~3/VTxfAdn_vnM/AddingYourOwnCustomControlToAWindowsFormsContextMenuUsingToolStripCustomHostClass.aspx</link>
      <pubDate>Mon, 19 Jan 2009 14:46:46 GMT</pubDate>
      <description>&lt;p&gt;
I am sure you know how to add the predefined &lt;strong&gt;TextBox&lt;/strong&gt; or &lt;strong&gt;ComboBox&lt;/strong&gt; controls
to a Windows Forms context Menu:
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://www.dotneat.net/content/binary/ToolStripCustomHost1.png"&gt;
&lt;/p&gt;
&lt;p&gt;
Just wanted to quickly show you how you can &lt;strong&gt;add your own custom controls&lt;/strong&gt; to
that context menu by using the ToolStripControlHost class, like this (the yellow panel
is a user control):
&lt;/p&gt;
&lt;p&gt;
&lt;img src="http://www.dotneat.net/content/binary/ToolStripCustomHost2.png"&gt;
&lt;/p&gt;
&lt;p&gt;
Here is a short video:
&lt;/p&gt;
&lt;p&gt;
&lt;object height=344 width=425&gt;
&lt;param name="movie" value="http://www.youtube.com/v/5XHqGFmDk8k&amp;amp;hl=es&amp;amp;fs=1"&gt;
&lt;param name="allowFullScreen" value="true"&gt;
&lt;param name="allowscriptaccess" value="always"&gt;
&lt;embed src="http://www.youtube.com/v/5XHqGFmDk8k&amp;hl=es&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"&gt;&lt;/embed&gt;
&lt;/object&gt;
&lt;/p&gt;
&lt;p&gt;
And here is the code:
&lt;/p&gt;
&lt;pre class="C#" name="code"&gt;

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //instance my control
            UserControl1 c = new UserControl1();

            //pass as parameter to ToolStripControlHost instance
            ToolStripControlHost host = new ToolStripControlHost(c);

            //add ToolStripControlHost object to context menu. simple!
            contextMenuStrip1.Items.Add(host);
        }
    }
}


&lt;/pre&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=184359d8-5382-4378-b6ec-48d004ff64f6" /&gt;</description>
      <comments>http://www.dotneat.net/CommentView,guid,184359d8-5382-4378-b6ec-48d004ff64f6.aspx</comments>
      <category>.NET 2.0</category>
      <category>.NET UI Controls</category>
      <category>Visual Studio 2005</category>
    <feedburner:origLink>http://www.dotneat.net/2009/01/19/AddingYourOwnCustomControlToAWindowsFormsContextMenuUsingToolStripCustomHostClass.aspx</feedburner:origLink></item>
    <item>
      <trackback:ping>http://www.dotneat.net/Trackback.aspx?guid=e0de3313-b524-4217-8969-d6d55834d4c2</trackback:ping>
      <pingback:server>http://www.dotneat.net/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotneat.net/PermaLink,guid,e0de3313-b524-4217-8969-d6d55834d4c2.aspx</pingback:target>
      <dc:creator>Iv�n</dc:creator>
      <wfw:comment>http://www.dotneat.net/CommentView,guid,e0de3313-b524-4217-8969-d6d55834d4c2.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotneat.net/SyndicationService.asmx/GetEntryCommentsRss?guid=e0de3313-b524-4217-8969-d6d55834d4c2</wfw:commentRss>
      <slash:comments>12</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
If you get a <strong>Validation of viewstate MAC failed</strong> error on <strong>ASP.NET
MVC</strong>, before trying to hard code your &lt;machineKey attribute in web.config, <a href="http://www.codinghorror.com/blog/archives/000132.html">disabling
the keying of viewstate</a></p>
        <p>
          <span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent">&lt;system.web&gt;<br />
  &lt;pages enableViewStateMac=<span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4">"false"</span> /&gt;<br />
&lt;/system.web&gt;</span>
        </p>
        <p>
, or <a href="http://www.google.es/search?rlz=1C1GGLS_esES291ES303&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=Validation+of+viewstate+MAC+failed">any
other literature</a> you may want to check if the page you are posting data from <strong>has
two "&lt;form" attributes</strong> (the one hard coded on the page and the one created
with Html.BeginForm()). If you play with master templates and have to merge some MVC
pages with tradicional ASP.NET you may get to that error.
</p>
        <p>
It took me a while to find the solution... 
</p>
        <p>
Did this post save you some time? post it. I'm curious. :) thanks.
</p>
        <img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=e0de3313-b524-4217-8969-d6d55834d4c2" />
      </body>
      <title>ASP.NET MVC Validation of viewstate MAC failed error</title>
      <guid isPermaLink="false">http://www.dotneat.net/PermaLink,guid,e0de3313-b524-4217-8969-d6d55834d4c2.aspx</guid>
      <link>http://feedproxy.google.com/~r/Dotneatnet/~3/WMNna2RPyIA/ASPNETMVCValidationOfViewstateMACFailedError.aspx</link>
      <pubDate>Sat, 13 Dec 2008 02:30:12 GMT</pubDate>
      <description>&lt;p&gt;
If you get a &lt;strong&gt;Validation of viewstate MAC failed&lt;/strong&gt; error on &lt;strong&gt;ASP.NET
MVC&lt;/strong&gt;, before trying to hard code your &amp;lt;machineKey attribute in web.config, &lt;a href="http://www.codinghorror.com/blog/archives/000132.html"&gt;disabling
the keying of viewstate&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;span style="FONT-SIZE: 11px; COLOR: black; FONT-FAMILY: Courier New; BACKGROUND-COLOR: transparent"&gt;&amp;lt;system.web&amp;gt;&lt;br&gt;
&amp;nbsp; &amp;lt;pages enableViewStateMac=&lt;span style="FONT-SIZE: 11px; COLOR: #666666; FONT-FAMILY: Courier New; BACKGROUND-COLOR: #e4e4e4"&gt;"false"&lt;/span&gt; /&amp;gt;&lt;br&gt;
&amp;lt;/system.web&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;p&gt;
, or &lt;a href="http://www.google.es/search?rlz=1C1GGLS_esES291ES303&amp;amp;sourceid=chrome&amp;amp;ie=UTF-8&amp;amp;q=Validation+of+viewstate+MAC+failed"&gt;any
other literature&lt;/a&gt;&amp;nbsp;you may want to check if the page you are posting data from &lt;strong&gt;has
two "&amp;lt;form" attributes&lt;/strong&gt; (the one hard coded on the page and the one created
with Html.BeginForm()). If you play with master templates and have to merge some MVC
pages with&amp;nbsp;tradicional ASP.NET&amp;nbsp;you may get to that error.
&lt;/p&gt;
&lt;p&gt;
It took me a while to find the solution... 
&lt;/p&gt;
&lt;p&gt;
Did&amp;nbsp;this post save you some time? post it. I'm curious.&amp;nbsp;:) thanks.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=e0de3313-b524-4217-8969-d6d55834d4c2" /&gt;</description>
      <comments>http://www.dotneat.net/CommentView,guid,e0de3313-b524-4217-8969-d6d55834d4c2.aspx</comments>
      <category>MVC</category>
      <category>ASP.NET</category>
      <category>.NET 3.5</category>
    <feedburner:origLink>http://www.dotneat.net/2008/12/13/ASPNETMVCValidationOfViewstateMACFailedError.aspx</feedburner:origLink></item>
    <item>
      <trackback:ping>http://www.dotneat.net/Trackback.aspx?guid=e9ff93d6-9409-4ff9-b295-c0a30b16dae4</trackback:ping>
      <pingback:server>http://www.dotneat.net/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotneat.net/PermaLink,guid,e9ff93d6-9409-4ff9-b295-c0a30b16dae4.aspx</pingback:target>
      <dc:creator>Iv�n</dc:creator>
      <wfw:comment>http://www.dotneat.net/CommentView,guid,e9ff93d6-9409-4ff9-b295-c0a30b16dae4.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotneat.net/SyndicationService.asmx/GetEntryCommentsRss?guid=e9ff93d6-9409-4ff9-b295-c0a30b16dae4</wfw:commentRss>
      <slash:comments>6</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a few lines of code, we can convert a DataGridView control in a powerfull fully
searchable control with <b>dynamically generated filters</b> for <b>each column of
field</b> the DataGridView is binded to.<br /></p>
        <p>
          <b>How does it work?</b>
        </p>
        <ol>
          <li>
The DataGridControl<b />is binded to the datasource.</li>
          <li>
The user hits the button (or shortcut) to start the dynamic filtering feature.</li>
        </ol>
        <ol>
          <li>
A new form is dinamycally generated on top of the DatagridView control (it has some <b>transparency</b> on
it so you can still see the DataGridView data on the background)</li>
          <li>
The form contains several textboxes, one per each column or field the DataGridView
datasource contains (you can change that behaviour)<br /></li>
          <li>
When the user starts entering text in any of the textboxes, the <b>filter condition
is applied to the underlying datasource</b> (for every keystroke) so you <b>can see
how the filtered data looks on the DataGridView as you are typing</b>.</li>
          <li>
You can, of course define filters for one or more textboxes (fields) at the time,
so you can work with multiple filters for many columns/fields.<br /></li>
        </ol>
        <li>
You can choose whatever you create a dynamically generated search form that contains <b>all
the fields on DataGridView datasource</b>, <b>or the ones of your choice</b> (video
and example code shows both cases).<br /></li>
        <p>
        </p>
        <p>
          <strong>Screenshots</strong>
        </p>
        <center>
          <img src="http://www.dotneat.net/content/binary/DynamicDataGridViewFilter_sshot-1.png" border="0" />
          <br />
          <i>This screenshot shows the dynamically search form generated with <b>all </b>the
fields of the underlying DataGridView</i>
          <br />
          <img src="http://www.dotneat.net/content/binary/DynamicDataGridViewFilter_sshot-2.png" border="0" />
          <br />
          <i>This screenshot shows the dynamically search form generated with <b>some</b> of
the fields of the underlying DataGridView</i>
          <br />
        </center>
        <p>
          <strong>Demo Video</strong>
        </p>
        <center>
          <object height="344" width="425">
            <param name="movie" value="http://www.youtube.com/v/eSlz_2Q1HAI&amp;hl=es&amp;fs=1" />
            <param name="allowFullScreen" value="true" />
            <param name="allowscriptaccess" value="always" />
            <embed src="http://www.youtube.com/v/eSlz_2Q1HAI&amp;hl=es&amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" height="344" width="425">
            </embed>
          </object>
          <br />
          <em>(sorry about the video quality. if you are interested, please download the demo.
it may be worthy)</em>
        </center>
        <br />
        <p>
          <b>Some code:</b>
        </p>
        <pre class="C#" name="code">
 /// 
<summary>
/// Build texbox controls for dinamyc search form based on fields collection /// 
</summary>
/// 
<param name="fields" />
private void BuildControls(List<field>
fields) { int top = 10; bool focused = false; #region Loop for each field foreach
(field f in fields) { Label label = new Label(); label.Text = f.FriendlyName + ":";
label.Top = top; label.Left = 5; label.AutoSize = true; this.Controls.Add(label);
TextBox textbox = new TextBox(); textbox.TextChanged += new EventHandler(textBox_TextChanged);
textbox.Tag = f.Field; textbox.Top = top; textbox.Left = 68; textbox.Width = this.Width
- 80; if (!focused) { textbox.Focus(); //the first control focused focused = true;
} top += 35; this.Controls.Add(textbox); } #endregion this.Height = top + 30; } 
</field></pre>
        <pre class="C#" name="code">

  // Raise event to parent form if textbox content changes
        private void textBox_TextChanged(object sender, EventArgs e)
        {
            if (TextChanged != null)
                TextChanged(GetFilterValues());
        }


        #region Shortcuts
        private void frmSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Escape) || (e.KeyCode == Keys.Enter))
                Close();
        }
        #endregion

</pre>
        <pre class="C#" name="code">

namespace dynamicGridFilter
{
    /// 
<summary>
/// This struct contains information about each field to be filtered along with filter
value, if exists. /// 
</summary>
public struct field { public string Field; public string FriendlyName; public string
Value; } } </pre>
        <pre class="C#" name="code">

namespace dynamicGridFilter
{
    public delegate void SearchContextChangedHandler(List<field>
fields); } 
</field></pre>
        <p>
          <b>Complete source code available to download:</b>
        </p>
Includes full source code and compiled binary (use it at your own risk)<br /><a href="http://www.dotneat.net/content/binary/dynamicGridFilter.zip">dynamicGridFilter.zip
(50,23 KB)</a><p><b>What's next?!</b></p><p>
If could have gone all the way up to creating a custom control that inherits from
DataGridView and has all the logic embedded. Well, you have here all you need for
doing it yourself, so don't call me lazy! :P
</p><p>
Comments are welcome!
</p><br /><img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=e9ff93d6-9409-4ff9-b295-c0a30b16dae4" /></body>
      <title>Dynamic DataGridView filtering in C#</title>
      <guid isPermaLink="false">http://www.dotneat.net/PermaLink,guid,e9ff93d6-9409-4ff9-b295-c0a30b16dae4.aspx</guid>
      <link>http://feedproxy.google.com/~r/Dotneatnet/~3/2Rlm8V-XxBE/DynamicDataGridViewFilteringInC.aspx</link>
      <pubDate>Wed, 03 Dec 2008 21:31:20 GMT</pubDate>
      <description>&lt;p&gt;
In a few lines of code, we can convert a DataGridView control in a powerfull fully
searchable control with &lt;b&gt;dynamically generated filters&lt;/b&gt; for &lt;b&gt;each column of
field&lt;/b&gt; the DataGridView is binded to.&lt;br&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;b&gt;How does it work?&lt;/b&gt;
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
The DataGridControl&lt;b&gt; &lt;/b&gt;is binded to the datasource.&lt;/li&gt;
&lt;li&gt;
The user hits the button (or shortcut) to start the dynamic filtering feature.&lt;/li&gt;
&lt;ol&gt;
&lt;li&gt;
A new form is dinamycally generated on top of the DatagridView control (it has some &lt;b&gt;transparency&lt;/b&gt; on
it so you can still see the DataGridView data on the background)&lt;/li&gt;
&lt;li&gt;
The form contains several textboxes, one per each column or field the DataGridView
datasource contains (you can change that behaviour)&lt;br&gt;
&lt;/li&gt;
&lt;li&gt;
When the user starts entering text in any of the textboxes, the &lt;b&gt;filter condition
is applied to the underlying datasource&lt;/b&gt; (for every keystroke) so you &lt;b&gt;can see
how the filtered data looks on the DataGridView as you are typing&lt;/b&gt;.&lt;/li&gt;
&lt;li&gt;
You can, of course define filters for one or more textboxes (fields) at the time,
so you can work with multiple filters for many columns/fields.&lt;br&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;li&gt;
You can choose whatever you create a dynamically generated search form that contains &lt;b&gt;all
the fields on DataGridView datasource&lt;/b&gt;, &lt;b&gt;or the ones of your choice&lt;/b&gt; (video
and example code shows both cases).&lt;br&gt;
&lt;/li&gt;&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Screenshots&lt;/strong&gt;
&lt;/p&gt;
&lt;center&gt;
&lt;img src="http://www.dotneat.net/content/binary/DynamicDataGridViewFilter_sshot-1.png" border="0"&gt;
&lt;br&gt;
&lt;i&gt;This screenshot shows the dynamically search form generated with &lt;b&gt;all &lt;/b&gt;the
fields of the underlying DataGridView&lt;/i&gt;
&lt;br&gt;
&lt;img src="http://www.dotneat.net/content/binary/DynamicDataGridViewFilter_sshot-2.png" border="0"&gt;
&lt;br&gt;
&lt;i&gt;This screenshot shows the dynamically search form generated with &lt;b&gt;some&lt;/b&gt; of
the fields of the underlying DataGridView&lt;/i&gt;
&lt;br&gt;
&lt;/center&gt;
&lt;p&gt;
&lt;strong&gt;Demo Video&lt;/strong&gt;
&lt;/p&gt;
&lt;center&gt;
&lt;object height="344" width="425"&gt;
&lt;param name="movie" value="http://www.youtube.com/v/eSlz_2Q1HAI&amp;amp;hl=es&amp;amp;fs=1"&gt;
&lt;param name="allowFullScreen" value="true"&gt;
&lt;param name="allowscriptaccess" value="always"&gt;&lt;embed src="http://www.youtube.com/v/eSlz_2Q1HAI&amp;amp;hl=es&amp;amp;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" height="344" width="425"&gt;
&lt;/object&gt;
&lt;br&gt;
&lt;em&gt;(sorry about the video quality. if you are interested, please download the demo.
it may be worthy)&lt;/em&gt; 
&lt;/center&gt;
&lt;br&gt;
&lt;p&gt;
&lt;b&gt;Some code:&lt;/b&gt;
&lt;/p&gt;
&lt;pre class="C#" name="code"&gt;
 /// 
&lt;summary&gt;
/// Build texbox controls for dinamyc search form based on fields collection /// 
&lt;/summary&gt;
/// 
&lt;param name="fields"&gt;
&gt;
private void BuildControls(List&lt;field&gt;
fields) { int top = 10; bool focused = false; #region Loop for each field foreach
(field f in fields) { Label label = new Label(); label.Text = f.FriendlyName + ":";
label.Top = top; label.Left = 5; label.AutoSize = true; this.Controls.Add(label);
TextBox textbox = new TextBox(); textbox.TextChanged += new EventHandler(textBox_TextChanged);
textbox.Tag = f.Field; textbox.Top = top; textbox.Left = 68; textbox.Width = this.Width
- 80; if (!focused) { textbox.Focus(); //the first control focused focused = true;
} top += 35; this.Controls.Add(textbox); } #endregion this.Height = top + 30; } 
&lt;/pre&gt;
&lt;pre class="C#" name="code"&gt;

  // Raise event to parent form if textbox content changes
        private void textBox_TextChanged(object sender, EventArgs e)
        {
            if (TextChanged != null)
                TextChanged(GetFilterValues());
        }


        #region Shortcuts
        private void frmSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == Keys.Escape) || (e.KeyCode == Keys.Enter))
                Close();
        }
        #endregion

&lt;/pre&gt;
&lt;pre class="C#" name="code"&gt;

namespace dynamicGridFilter
{
    /// 
&lt;summary&gt;
/// This struct contains information about each field to be filtered along with filter
value, if exists. /// 
&lt;/summary&gt;
public struct field { public string Field; public string FriendlyName; public string
Value; } } &lt;/pre&gt;
&lt;pre class="C#" name="code"&gt;

namespace dynamicGridFilter
{
    public delegate void SearchContextChangedHandler(List&lt;field&gt;
fields); } 
&lt;/pre&gt;
&lt;p&gt;
&lt;b&gt;Complete source code available to download:&lt;/b&gt;
&lt;/p&gt;
Includes full source code and compiled binary (use it at your own risk)&lt;br&gt;
&lt;a href="http://www.dotneat.net/content/binary/dynamicGridFilter.zip"&gt;dynamicGridFilter.zip
(50,23 KB)&lt;/a&gt; 
&lt;p&gt;
&lt;b&gt;What's next?!&lt;/b&gt;
&lt;/p&gt;
&lt;p&gt;
If could have gone all the way up to creating a custom control that inherits from
DataGridView and has all the logic embedded. Well, you have here all you need for
doing it yourself, so don't call me lazy! :P
&lt;/p&gt;
&lt;p&gt;
Comments are welcome!
&lt;/p&gt;
&lt;br&gt;
&lt;img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=e9ff93d6-9409-4ff9-b295-c0a30b16dae4" /&gt;</description>
      <comments>http://www.dotneat.net/CommentView,guid,e9ff93d6-9409-4ff9-b295-c0a30b16dae4.aspx</comments>
      <category>.NET 2.0</category>
      <category>.NET UI Controls</category>
      <category>DataGridView</category>
    <feedburner:origLink>http://www.dotneat.net/2008/12/03/DynamicDataGridViewFilteringInC.aspx</feedburner:origLink></item>
    <item>
      <trackback:ping>http://www.dotneat.net/Trackback.aspx?guid=91520cb7-1649-4d6c-9c60-d271ed183243</trackback:ping>
      <pingback:server>http://www.dotneat.net/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotneat.net/PermaLink,guid,91520cb7-1649-4d6c-9c60-d271ed183243.aspx</pingback:target>
      <dc:creator>Iv�n</dc:creator>
      <wfw:comment>http://www.dotneat.net/CommentView,guid,91520cb7-1649-4d6c-9c60-d271ed183243.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotneat.net/SyndicationService.asmx/GetEntryCommentsRss?guid=91520cb7-1649-4d6c-9c60-d271ed183243</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">Really really simple. Feel free to write
your own custom authentication method to fit your project context.<br /><br />
This is download.aspx:<br /><br /><pre><span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;">&lt;%@
Page Language=<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"C#"</span> AutoEventWireup=<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"true"</span> CodeFile=<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"download.aspx.cs"</span> Inherits=<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"download"</span> %&gt;
&lt;!DOCTYPE html PUBLIC <span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"-//W3C//DTD
XHTML 1.0 Transitional//EN"</span><span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"</span>&gt;
&lt;html xmlns=<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"http://www.w3.org/1999/xhtml"</span> &gt;
&lt;head runat=<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"server"</span>&gt;
&lt;title&gt;Download Page&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;form id=<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"form1"</span> runat=<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"server"</span>&gt;
&lt;div&gt; &lt;/div&gt; &lt;/form&gt; &lt;/body&gt; &lt;/html&gt; </span></pre>
and this is the code behind that file:<br /><pre class="C#" name="code">
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class download : System.Web.UI.Page 
{

    /// 
<summary>
/// Show error to user and close response object. /// 
</summary>
/// 
<param name="error" />
private void WriteError(string error) { Response.Write(error); Response.End(); } /// 
<summary>
/// Check authentication ticket /// 
</summary>
/// 
<returns />
private bool Authenticated() { //whatever is a session ticket, membership provider
base, container in a coded URL querystring parameters, etc.. return true; } private
string GetRepositoryFolder() { System.Configuration.AppSettingsReader r = new AppSettingsReader();
return r.GetValue("RepositoryFolder", typeof(string)).ToString(); } protected void
Page_Load(object sender, EventArgs e) { if (!Authenticated()){ WriteError("You are
not allowed to download this file"); return; } else if (Request.QueryString["id"]
== null) { WriteError("Missing parameter : id"); return; } string filePath = System.IO.Path.Combine(GetRepositoryFolder(),Request.QueryString["id"]);
System.IO.FileInfo file = new System.IO.FileInfo(filePath); if (!file.Exists) { WriteError("File
doesn't exists"); return; } else { Response.Clear(); Response.AddHeader("Content-Disposition",
"attachment; filename=" + file.Name); Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream"; Response.WriteFile(file.FullName);
Response.End(); } } } </pre>
If successfully authenticated, you will be able to directly download the file:<br /><br /><p /><div align="center"><img src="http://www.dotneat.net/content/binary/download.png" border="0" /><br /><div align="left">If not, you will get an error message:<br /><br /><i>You are not allowed to download this file</i><br /><br /></div></div><img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=91520cb7-1649-4d6c-9c60-d271ed183243" /></body>
      <title>Simple download protection for files and document using ASP.NET /  C#</title>
      <guid isPermaLink="false">http://www.dotneat.net/PermaLink,guid,91520cb7-1649-4d6c-9c60-d271ed183243.aspx</guid>
      <link>http://feedproxy.google.com/~r/Dotneatnet/~3/G__M4pz0oFw/SimpleDownloadProtectionForFilesAndDocumentUsingASPNETC.aspx</link>
      <pubDate>Mon, 24 Dec 2007 14:36:11 GMT</pubDate>
      <description>Really really simple. Feel free to write your own custom authentication method to fit your project context.&lt;br&gt;
&lt;br&gt;
This is download.aspx:&lt;br&gt;
&lt;br&gt;
&lt;pre&gt;&lt;span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;&amp;lt;%@
Page Language=&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"C#"&lt;/span&gt; AutoEventWireup=&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"true"&lt;/span&gt; CodeFile=&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"download.aspx.cs"&lt;/span&gt; Inherits=&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"download"&lt;/span&gt; %&amp;gt;
&amp;lt;!DOCTYPE html PUBLIC &lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"-//W3C//DTD
XHTML 1.0 Transitional//EN"&lt;/span&gt; &lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&lt;/span&gt;&amp;gt;
&amp;lt;html xmlns=&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"http://www.w3.org/1999/xhtml"&lt;/span&gt; &amp;gt;
&amp;lt;head runat=&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"server"&lt;/span&gt;&amp;gt;
&amp;lt;title&amp;gt;Download Page&amp;lt;/title&amp;gt; &amp;lt;/head&amp;gt; &amp;lt;body&amp;gt; &amp;lt;form id=&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"form1"&lt;/span&gt; runat=&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"server"&lt;/span&gt;&amp;gt;
&amp;lt;div&amp;gt; &amp;lt;/div&amp;gt; &amp;lt;/form&amp;gt; &amp;lt;/body&amp;gt; &amp;lt;/html&amp;gt; &lt;/span&gt;&lt;/pre&gt;
and this is the code behind that file:&lt;br&gt;
&lt;pre class="C#" name="code"&gt;
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class download : System.Web.UI.Page 
{

    /// 
&lt;summary&gt;
/// Show error to user and close response object. /// 
&lt;/summary&gt;
/// 
&lt;param name="error"&gt;
&gt;
private void WriteError(string error) { Response.Write(error); Response.End(); } /// 
&lt;summary&gt;
/// Check authentication ticket /// 
&lt;/summary&gt;
/// 
&lt;returns&gt;
&lt;/returns&gt;
private bool Authenticated() { //whatever is a session ticket, membership provider
base, container in a coded URL querystring parameters, etc.. return true; } private
string GetRepositoryFolder() { System.Configuration.AppSettingsReader r = new AppSettingsReader();
return r.GetValue("RepositoryFolder", typeof(string)).ToString(); } protected void
Page_Load(object sender, EventArgs e) { if (!Authenticated()){ WriteError("You are
not allowed to download this file"); return; } else if (Request.QueryString["id"]
== null) { WriteError("Missing parameter : id"); return; } string filePath = System.IO.Path.Combine(GetRepositoryFolder(),Request.QueryString["id"]);
System.IO.FileInfo file = new System.IO.FileInfo(filePath); if (!file.Exists) { WriteError("File
doesn't exists"); return; } else { Response.Clear(); Response.AddHeader("Content-Disposition",
"attachment; filename=" + file.Name); Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream"; Response.WriteFile(file.FullName);
Response.End(); } } } &lt;/pre&gt;
If successfully authenticated, you will be able to directly download the file:&lt;br&gt;
&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;div align="center"&gt;&lt;img src="http://www.dotneat.net/content/binary/download.png" border="0"&gt;
&lt;br&gt;
&lt;div align="left"&gt;If not, you will get an error message:&lt;br&gt;
&lt;br&gt;
&lt;i&gt;You are not allowed to download this file&lt;/i&gt;
&lt;br&gt;
&lt;br&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=91520cb7-1649-4d6c-9c60-d271ed183243" /&gt;</description>
      <comments>http://www.dotneat.net/CommentView,guid,91520cb7-1649-4d6c-9c60-d271ed183243.aspx</comments>
      <category>.NET 2.0</category>
      <category>Authentication</category>
      <category>Security</category>
    <feedburner:origLink>http://www.dotneat.net/2007/12/24/SimpleDownloadProtectionForFilesAndDocumentUsingASPNETC.aspx</feedburner:origLink></item>
    <item>
      <trackback:ping>http://www.dotneat.net/Trackback.aspx?guid=d31bbd43-b5f9-4e89-8193-5666ab4ac87c</trackback:ping>
      <pingback:server>http://www.dotneat.net/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotneat.net/PermaLink,guid,d31bbd43-b5f9-4e89-8193-5666ab4ac87c.aspx</pingback:target>
      <dc:creator>Iv�n</dc:creator>
      <wfw:comment>http://www.dotneat.net/CommentView,guid,d31bbd43-b5f9-4e89-8193-5666ab4ac87c.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotneat.net/SyndicationService.asmx/GetEntryCommentsRss?guid=d31bbd43-b5f9-4e89-8193-5666ab4ac87c</wfw:commentRss>
      <slash:comments>19</slash:comments>
      <title>Querying Youtube API using C#</title>
      <guid isPermaLink="false">http://www.dotneat.net/PermaLink,guid,d31bbd43-b5f9-4e89-8193-5666ab4ac87c.aspx</guid>
      <link>http://feedproxy.google.com/~r/Dotneatnet/~3/NMiobYXw1H0/QueryingYoutubeAPIUsingC.aspx</link>
      <pubDate>Thu, 20 Dec 2007 22:40:31 GMT</pubDate>
      <description>&lt;br&gt;
This example shows how to use Google Data API to query and obtain videos from YouTube.
There is also a downloadable zip file with the example in ASP.NET / C#.&lt;br&gt;
&lt;br&gt;
&lt;ol&gt;
&lt;li&gt;
First of all, you need to download the &lt;a href="http://code.google.com/p/google-gdata/downloads/list"&gt;Google
Data APIs Client Libraries.&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
Secondly, use the following namespaces: &lt;pre class="C#" name="code"&gt;
using Google.GData.Client;
using Google.GData.Extensions;
&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
Use the service by querying by &lt;i&gt;tag&lt;/i&gt;, or by &lt;i&gt;search &lt;/i&gt;(you can also query &lt;i&gt;related
items&lt;/i&gt;, etc..):&lt;br&gt;
&lt;br&gt;
&lt;pre class="C#" name="code"&gt;

    //by tag
    //feel free to change number of items, by there is a limit of 50, I believe. 
    //If you want to retreive more, you have to do a loop (retrieve 1-50, then 51 to 100, etc)
    protected void btoGo_Click(object sender, EventArgs e)
    {
        string url = "http://gdata.youtube.com/feeds/videos/-/" + this.txtTag.Text;
        AtomFeed myFeed = GetFeed(url, 1, 20);
        DisplayFeed(myFeed);        
    }

    //by search
    //feel free to change number of items, by there is a limit of 50, I believe. 
    //If you want to retreive more, you have to do a loop (retrieve 1-50, then 51 to 100, etc)
    protected void btoSearch_Click(object sender, EventArgs e)
    {
        string url = "http://gdata.youtube.com/feeds/videos?q=" + this.txtSearch.Text;
        AtomFeed myFeed = GetFeed(url, 1, 15);
        DisplayFeed(myFeed);
    }

&lt;/pre&gt;
&lt;/li&gt;
&lt;li&gt;
Use the following methods, or similars to get and display the Feed:&lt;br&gt;
&lt;br&gt;
&lt;pre class="C#" name="code"&gt;
/// 
&lt;summary&gt;
/// Create and returns and Google.GData.Client.AtomFee from url with the specific
start and number of items /// 
&lt;/summary&gt;
/// 
&lt;param name="url"&gt;
&gt;
/// 
&lt;param name="start"&gt;
&gt;
/// 
&lt;param name="number"&gt;
&gt;
/// 
&lt;returns&gt;
&lt;/returns&gt;
private static AtomFeed GetFeed(string url, int start, int number) { System.Diagnostics.Trace.Write("Conectando
youtube at " + url); FeedQuery query = new FeedQuery(""); Service service = new Service("youtube",
"exampleCo"); query.Uri = new Uri(url); query.StartIndex = start; query.NumberToRetrieve
= number; AtomFeed myFeed = service.Query(query); return myFeed; } /// 
&lt;summary&gt;
/// Renders feed in example aspx page /// 
&lt;/summary&gt;
/// 
&lt;param name="myFeed"&gt;
&gt;
private void DisplayFeed(AtomFeed myFeed) { System.Text.StringBuilder sb = new System.Text.StringBuilder();
foreach (AtomEntry entry in myFeed.Entries) { #region render each sb.Append("&lt;br /&gt;
&lt;b&gt;Title:&lt;/b&gt; "); sb.Append(entry.Title.Text); sb.Append("&lt;br /&gt;
&lt;b&gt;Categories:&lt;/b&gt; "); foreach (AtomCategory cat in entry.Categories) { sb.Append(cat.Term);
sb.Append(","); } sb.Append(RenderVideoEmbedded(getIDSimple(entry.Id.AbsoluteUri)));
sb.Append("&lt;br /&gt;
&lt;b&gt;Published on:&lt;/b&gt; "); sb.Append(entry.Published); #endregion } this.lblResults.Text
= sb.ToString(); } private string RenderVideoEmbedded(string idSimple) { return string.Format("&lt;div id=\"video{0}\"&gt;
&lt;object width=\"425\" height=\"355\"&gt;
&lt;param name=\"movie\" value=\"http://www.youtube.com/v/{0}&amp;rel=1\"&gt;&gt;
&lt;param name=\"wmode\" value=\"transparent\"&gt;&gt;&lt;embed src=\"http://www.youtube.com/v/{0}&amp;rel=1\" type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"425\" height=\"355\"&gt;&lt;/embed&gt;
&lt;/object&gt;
&lt;/div&gt;
", idSimple); } &lt;/pre&gt;
&lt;/li&gt;
&lt;/ol&gt;
&lt;b&gt;Related resources:&lt;/b&gt;
&lt;br&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;a href="http://www.youtube.com/dev"&gt;YouTube developer area&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;a href="http://code.google.com/apis/youtube/overview.html"&gt;What is the YouTube Data
API?&lt;/a&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;br&gt;
&lt;b&gt;Download example web site project in C#:&lt;/b&gt;
&lt;br&gt;
&lt;a href="http://www.dotneat.net/content/binary/youtubeAPIExample.zip"&gt;youtubeAPIExample.zip
(65,91 KB)&lt;/a&gt;
&lt;br&gt;
&lt;br&gt;
&lt;img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=d31bbd43-b5f9-4e89-8193-5666ab4ac87c" /&gt;</description>
      <comments>http://www.dotneat.net/CommentView,guid,d31bbd43-b5f9-4e89-8193-5666ab4ac87c.aspx</comments>
      <category>.NET 2.0</category>
      <category>Google API</category>
      <category>YouTube</category>
    <feedburner:origLink>http://www.dotneat.net/2007/12/20/QueryingYoutubeAPIUsingC.aspx</feedburner:origLink></item>
    <item>
      <trackback:ping>http://www.dotneat.net/Trackback.aspx?guid=4d8b66e0-5454-4355-96d1-5ce63d858de9</trackback:ping>
      <pingback:server>http://www.dotneat.net/pingback.aspx</pingback:server>
      <pingback:target>http://www.dotneat.net/PermaLink,guid,4d8b66e0-5454-4355-96d1-5ce63d858de9.aspx</pingback:target>
      <dc:creator>Iv�n</dc:creator>
      <wfw:comment>http://www.dotneat.net/CommentView,guid,4d8b66e0-5454-4355-96d1-5ce63d858de9.aspx</wfw:comment>
      <wfw:commentRss>http://www.dotneat.net/SyndicationService.asmx/GetEntryCommentsRss?guid=4d8b66e0-5454-4355-96d1-5ce63d858de9</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">Yes, there is a <a href="http://weblogs.asp.net/erobillard/archive/2004/05/10/129134.aspx">bit
of confusion</a> about this (also read <a href="http://www.codinghorror.com/blog/archives/000112.html">this
post</a>). 
<br /><br />
I understand that the right way to create your application specific exceptions classes
is to inherit from Exception class:<br /><pre><span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">public</span><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">class</span> MyCustomEx
: System.Exception{ <span style="color: Green; background-color: transparent; font-family: Courier New; font-size: 11px;">//class
implementation</span> }</span></pre>
And if in any case you have to throw a general application exception that has not
specific type, throw a System.ApplicationException:<br /><pre><span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">throw</span><span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;">new</span> System.ApplicationException(<span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;">"Error
retrieving data. The web service may be down"</span>);</span></pre><br /><p /><img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=4d8b66e0-5454-4355-96d1-5ce63d858de9" /></body>
      <title>Inheriting from System.Exception or System.ApplicationException?</title>
      <guid isPermaLink="false">http://www.dotneat.net/PermaLink,guid,4d8b66e0-5454-4355-96d1-5ce63d858de9.aspx</guid>
      <link>http://feedproxy.google.com/~r/Dotneatnet/~3/iMzqDw3POvQ/InheritingFromSystemExceptionOrSystemApplicationException.aspx</link>
      <pubDate>Mon, 17 Dec 2007 18:02:47 GMT</pubDate>
      <description>Yes, there is a &lt;a href="http://weblogs.asp.net/erobillard/archive/2004/05/10/129134.aspx"&gt;bit
of confusion&lt;/a&gt; about this (also read &lt;a href="http://www.codinghorror.com/blog/archives/000112.html"&gt;this
post&lt;/a&gt;). 
&lt;br&gt;
&lt;br&gt;
I understand that the right way to create your application specific exceptions classes
is to inherit from Exception class:&lt;br&gt;
&lt;pre&gt;&lt;span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;public&lt;/span&gt; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;class&lt;/span&gt; MyCustomEx
: System.Exception{ &lt;span style="color: Green; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;//class
implementation&lt;/span&gt; }&lt;/span&gt;&lt;/pre&gt;
And if in any case you have to throw a general application exception that has not
specific type, throw a System.ApplicationException:&lt;br&gt;
&lt;pre&gt;&lt;span style="color: Black; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;&lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;throw&lt;/span&gt; &lt;span style="color: Blue; background-color: transparent; font-family: Courier New; font-size: 11px;"&gt;new&lt;/span&gt; System.ApplicationException(&lt;span style="color: rgb(102, 102, 102); background-color: rgb(228, 228, 228); font-family: Courier New; font-size: 11px;"&gt;"Error
retrieving data. The web service may be down"&lt;/span&gt;);&lt;/span&gt;&lt;/pre&gt;
&lt;br&gt;
&lt;p&gt;
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.dotneat.net/aggbug.ashx?id=4d8b66e0-5454-4355-96d1-5ce63d858de9" /&gt;</description>
      <comments>http://www.dotneat.net/CommentView,guid,4d8b66e0-5454-4355-96d1-5ce63d858de9.aspx</comments>
      <category>.NET quirks</category>
    <feedburner:origLink>http://www.dotneat.net/2007/12/17/InheritingFromSystemExceptionOrSystemApplicationException.aspx</feedburner:origLink></item>
  </channel>
</rss>
