using UriTemplate

Copied from MSDN:

The UriTemplateTable class provides a mechanism for managing a collection of UriTemplate objects. This makes it easy to call Match on the table to find all templates that match the supplied Uri. Alternatively, you can call MatchSingle to ensure it matches only a single UriTemplate in the table.

Uri baseUri = new Uri("http://contoso.com/bookmarkservice");
UriTemplate uriTemplate = new UriTemplate( "users/{username}/bookmarks/{id}");

// generate a new bookmark URI
Uri newBookmarkUri = uriTemplate.BindByPosition(baseUri, "skonnard", "123");

// match an existing bookmark URI
UriTemplateMatch match = uriTemplate.Match(baseUri, newBookmarkUri);
System.Diagnostics.Debug.Assert(match != null);
Console.WriteLine(match.BoundVariables["username"]);
Console.WriteLine(match.BoundVariables["id"]);

Catch the Session Expired case

The project I am working on requires to show a nice custom error page to the user when the session is expired. I searched a bit on the internet and came up with a good solution in forums.asp.net which I worked it out as follows:

As mentioned in the forum you need to implement an IHttpModule and redirect the context’e AcquireRequestState event to your method which goes this:
        void Application_AcquireRequestState(object sender, EventArgs e)
{
if (HttpContext.Current.Session != null && HttpContext.Current.Session.IsNewSession)
{
if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
{
HttpContext.Current.Session.Clear();
HttpContext.Current.Response.Redirect(
"/Errors/SessionTimeout.aspx", true);
}
}
}

}

As you can see I clear the session before redirecting to the SessionTimeout.aspx. The reason for that is that I want the user have a choice of going to login screen by providing a link in the SessionTimeout.aspx. And the login requires a session state unlike the SessionTimeout.aspx that has the attribute EnableSessionState="False" 

URL properties of Request to ASP.NET

The following attributes are some of the usefull properties of the URL object. I use the following url to send my request to localhost:


http://localhost/Test/Asghar.aspx?test=fine

And I get the following results:

AbsolutePath = /Test/Asghar.aspx
AbsoluteUri = http://localhost/Test/Asghar.aspx?test=fine
Authority = localhost
DnsSafeHost = localhost
Fragment =
Host = localhost
HostNameType= Dns
IsAbsoluteUri = True
IsFile = False
LocalPath = /Test/Asghar.aspx
OriginalString = http://localhost:80/Test/Asghar.aspx?test=fine
PathAndQuery = /Test/Asghar.aspx?test=fine
Port = 80
Query = ?test=fine
Scheme = http
UserEscaped = False
UserInfo =

And the code to do it is as followes:

    AbsolutePath = <%= System.Web.HttpContext.Current.Request.Url.AbsolutePath %><br />
AbsoluteUri = <%= System.Web.HttpContext.Current.Request.Url.AbsoluteUri %><br />
Authority = <%= System.Web.HttpContext.Current.Request.Url.Authority %><br />
DnsSafeHost = <%= System.Web.HttpContext.Current.Request.Url.DnsSafeHost %><br />
Fragment = <%= System.Web.HttpContext.Current.Request.Url.Fragment %><br />
Host = <%= System.Web.HttpContext.Current.Request.Url.Host %><br />
HostNameType= <%= System.Web.HttpContext.Current.Request.Url.HostNameType.ToString() %><br />
IsAbsoluteUri = <%= System.Web.HttpContext.Current.Request.Url.IsAbsoluteUri %><br />
IsFile = <%= System.Web.HttpContext.Current.Request.Url.IsFile %><br />
LocalPath = <%= System.Web.HttpContext.Current.Request.Url.LocalPath %><br />
OriginalString = <%= System.Web.HttpContext.Current.Request.Url.OriginalString %><br />
PathAndQuery = <%= System.Web.HttpContext.Current.Request.Url.PathAndQuery %><br />
Port = <%= System.Web.HttpContext.Current.Request.Url.Port %><br />
Query = <%= System.Web.HttpContext.Current.Request.Url.Query %><br />
Scheme = <%= System.Web.HttpContext.Current.Request.Url.Scheme %><br />
UserEscaped = <%= System.Web.HttpContext.Current.Request.Url.UserEscaped %><br />
UserInfo = <%= System.Web.HttpContext.Current.Request.Url.UserInfo %><br />
<hr />

Read CSV file into LINQ

This article is based on the great book of LINQ in Action. I am learning so much from it and I would like to keep a note of some handy subject from the book while not disturbing any copyright of ther authors. For the full story please buy the book from http://www.manning.com/LINQinAction.

 
using (StreamReader reader = new StreamReader("books.csv"))
{
var books =
from line in reader.Lines()
where !line.StartsWith("#")
let parts = line.Split(',')
select new {
Title = parts[1],
Publisher = parts[3],
Isbn = parts[0]
};

// use the books here ...
}

Join And Group Tables

This article is based on the great book of LINQ in Action. I am learning so much from it and I would like to keep a note of some handy subject from the book while not disturbing any copyright of ther authors. For the full story please buy the book from http://www.manning.com/LINQinAction

Group Join


from publisher in SampleData.Publishers
join book in SampleData.Books
on publisher equals book.Publisher into publisherBooks
select new { Publisher=publisher.Name, Books=publisherBooks };

This is a group join. It bundles each publisher’s book as sequences named publisherBooks. This new query is equivalent to this one:


from book in SampleData.Books
group book by book.Publisher into publisherBooks
select new { Publisher=publisherBooks.Key.Name, Books=publisherBooks };

Inner Join
An inner join essentially finds the intersection between two sequences. With an inner join, the elements from two sequences that meet a matching condition are combined to from a single sequence.


from publisher in SampleData.Publishers
join book in SampleData.Books
on publisher equals book.Publisher
select new { Publisher=publisher.Name, Book=book.Title };

Left Outer Join
When we want to keep all the elements from the outer sequence, independently of whether there is a matching element in the inner sequence, we need to perform a left outer join.

A left outer join is like an inner inner join, except that all the left-side elements get included at least once, even if they don’t match any right side elements.


from publisher in SampleData.Publishers
join book in SampleData.Books
on publisher equals book.Publisher into publisherBooks
from book in publisherBooks.DefaultIfEmpty()
select new {
Publisher = publisher.Name,
Book = book == default(Book) ? "(no books)" : book.Title
};

DefaultEmpty operator supplies a default element for an empty sequence.
DefaultEmpty uses the default keyword of generics. It returns null for reference types and zero for numeric value types. For structs, it returns each member of the struct initialized to zero or null depending on whether they are value or reference types.

Cross Join
A cross join computes the Cartesian product of all the elements from two sequences. The result is a sequence that contains a combination of each element from the first sequence with eacht element from the second sequence.


from publisher in SampleData.Publishers
from book in SampleData.Books
select new {
Correct = (publisher == book.Publisher)
Publisher = publisher.Name,
Book = book.Title
};

Uploading form data with WebRequest

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



WebRequest req = WebRequest.Create ("http://safari.oreilly.com/search");

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
{
person.ID,
person.Name
};

grdPeople.DataSource = people;
grdPeople.DataBind();

lstPanahy.DataSource = panahy;
lstPanahy.DataBind();

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

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();
xws.OmitXmlDeclaration
= true;
xws.Indent
= true;

using (XmlWriter xw = XmlWriter.Create(sb, xws))
{
// the actual writing takes place
xml.WriteTo(xw);
}

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.