Sunday, December 21, 2008

Uploading form data with WebRequest

From the chapter 14 of O'Reilly's C# in a NutShell.

WebRequest req = WebRequest.Create ("");

req.Proxy = null;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";

string reqString
= "searchtextbox=webclient&searchmode=simple";
byte[] reqData = Encoding.UTF8.GetBytes (reqString);
req.ContentLength = reqData.Length;

using (Stream reqStream = req.GetRequestStream())
reqStream.Write (reqData, 0, reqData.Length);

using (WebResponse res = req.GetResponse())
using (Stream resSteam = res.GetResponseStream())
using (StreamReader sr = new StreamReader (resSteam))
File.WriteAllText ("SearchResults.html", sr.ReadToEnd());

System.Diagnostics.Process.Start ("SearchResults.html");

Sample Linq Entities

This snippet code shows how easy it is to use LINQ to get to your data in SQL-Server. Before you start you need to add a new ADO.NET Entity Data Model to your project where the wizard leads you to select all you need from your project. You can have multiple modles like OrderModle, PurchaseModle and DistributionModle that may overlap some tables but would make development much easier.
In this sample I use an entity modle from my FamilyTree database.

AhouraEntities model = new AhouraEntities();
ObjectQuery people = model.Person;

var panahy = from person in people
where person.Surname.StartsWith("Panah")
select new

grdPeople.DataSource = people;

lstPanahy.DataSource = panahy;

Obviously you could instanciate the model using the constructor that expects a connectionString.

Sunday, December 14, 2008

Get XML String from XElement

You can use the WriteTo method of the XElement object to an XmlWriter and this can be created in ten different ways like by giving a filename or passing a stream as output or simply giving the StringBuilder to write to:

/// <summary>
/// Generates XML string from an XElement
/// summary>
/// <param name="xml">XElement source</param>
public string GetXmlString(XElement xml)
// could also be any other stream
StringBuilder sb = new StringBuilder();

// Initialize a new writer settings
XmlWriterSettings xws = new XmlWriterSettings();
= true;
= true;

using (XmlWriter xw = XmlWriter.Create(sb, xws))
// the actual writing takes place

return sb.ToString();


It is important to know that the XElement already supports ToString which generates the same results as this code, but when you want to get something else, this could be a good start.

See further information in MSDN.

Thursday, December 4, 2008

ASP.NET assembly build time

One way to put the built date and timeon the footer of your pages is to read the .dll file within the bin folder of your website.

built <%=System.IO.File.GetCreationTime(Server.MapPath("bin") + "\\Assembly.dll").ToString("yyyy-MM-dd hh:mm:ss")%>

Monday, December 1, 2008

Persistor of a Serializer

We had this situation in my last project where we wanted to have some of our objects to get easily serialized into a specific table. Therefor we had to add up to the Serializer an new generic class that uses the Serializer to get the sream to put into a table.
In this example we have several classes like Article, Order, etc. and we wanted to give them a specific addition that would implement the Save and Load for all these classes. So we wanted to have something like this :

public class Article : Persistor

and then later use it as follows:

// Read the last saved Article filter
private Article filter = Article.Load();

// and do something with it and finally save it back to Database


Well, to achive that we implemented the Persistor class as follows:

using System;
using System.Collections.Generic;

/// <summary>
/// Provides the persistance methods for the filter classes.
/// It reads and writes the content in an xml format into the Filter table
/// </summary>
/// <typeparam name="T">The type of the filter. This type should derive from Persistor&lt;T&gt; and have an empty constructor</typeparam>
public class Persistor<T>
where T : Persistor
<T>, new()
/// <summary>
/// Saves this filter as the default filter for the current user.
/// </summary>
public void Save()
// Serialize the current filter instance
Serializer<T> serializer = new Serializer<T>();
string xml = serializer.Serialize(this as T);

// The filter class is a data class that handles the saveing of a record
Data.Tables.Filter filter = Persistor<T>.LoadFilter(true);

// Actual save to database
filter.Value = xml;

/// <summary>
/// Loads the default filter for the current table and user.
/// </summary>
public static T Load()
Tables.Filter filter
= Persistor<T>.LoadFilter(false);

// Deserialize
T currentFilter = null;
if (filter != null && !string.IsNullOrEmpty(filter.Value))
<T> serializer = new Serializer<T>();
= serializer.Deserialize(filter.Value);
= new T();

return currentFilter;

/// <summary>
/// Loads the Filter for the current user and table from the database.
/// </summary>
protected static Tables.Filter LoadFilter(bool createNew)
string tableId = typeof(T).Name;
int userId = UserContext.Current.User.ID;

// Load current filter, if available, otherwise create a new filter instance.
Tables.Filter filter = Tables.Filter.GetForUserTable(userId, tableId);
if (filter == null && createNew)
= new Data.Tables.Filter();
= userId;
= tableId;

return filter;