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 ("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.

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();
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.

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 :

[Serializable]
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

this.filter.Remove(e.Item.Key);
...
this.filter.Save();

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>
[Serializable]
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;
filter.Save();
}

/// <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))
{
Serializer
<T> serializer = new Serializer<T>();
currentFilter
= serializer.Deserialize(filter.Value);
}
else
{
currentFilter
= 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)
{
filter
= new Data.Tables.Filter();
filter.UserID
= userId;
filter.TableID
= tableId;
}

return filter;
}
}

Tuesday, October 21, 2008

Another peace of code that I don't want to rewrite it again (and again)
using System;
using System.Collections.Generic;

/// <summary>
/// This class uses XmlSerializer to do both sides of conversion to xml string
/// </summary>
/// <typeparam name="T">any Serializable class</typeparam>
public class Serializer<T>
{
/// <summary>
/// Convert an instance to XML string
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
public string Serialize(T item)
{

MemoryStream ms
= new MemoryStream();
XmlTextWriter writer
= new XmlTextWriter(ms, Encoding.Unicode);

XmlSerializer serializer
= new XmlSerializer(typeof(T));
serializer.Serialize(writer, item);

writer.Flush();
ms.Position
= 0;

StreamReader reader
= new StreamReader(ms);
return reader.ReadToEnd();

}
/// <summary>
/// another version, could be better
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
private string GetSerialize2(T item)
{
StringWriter wr
= new StringWriter(new StringBuilder());

XmlSerializer serializer
= new XmlSerializer(typeof(T));
serializer.Serialize(wr, item);

wr.Close();
return wr.GetStringBuilder().ToString();
}

/// <summary>
/// Convert the XML string to an instance of an object
/// </summary>
/// <param name="xml"></param>
/// <returns></returns>
public T Deserialize(string xml)
{
XmlTextReader stream
= new XmlTextReader(new StringReader(xml));
XmlSerializer serializer
= new XmlSerializer(typeof(T));
return (T)serializer.Deserialize(stream);
}
}

Sunday, October 19, 2008

LINQ Delayed excecution

Link statements generate the query and make it ready to be used when it comes to the point where the data is needed. In the following example when the datasource is set the data is needed and that is when the communication with the database takes place:


var products =
from p in db.Products
orderby p.ProductName
select new { p.ProductID, p.ProductName, p.UnitPrice };
products = products.Skip(itemsToSkip).Take(pageSize);

DataGridView1.DataSource = products;

LINQ over XML

This example is also from th AppDev:

var doc = CreateDocument(); // returns an XDocument
var items = from item in doc.Descendants("Item")
where (string)item.Parent.Attribute("Name") == "Breads"
select item;


now transforming the xml to a new format:


XElement transformed = new XElement("items",
from item in items
select new XElement("item",
new XAttribute("ItemName", (string)item.Element("Name")),
new XAttribute("Price", (string)item.Element("Price))));

LINQ over untyped DataSets

This example comes from the AppDev (Exploring Visual Studio 2008 Using Visual C#)


DataSetr ds = FillDataset();
DataTable customerTable = ds.Tables["Customers"];

// DataTable does not implement IEnumerable
var cutomers = from c in customerTable.AsEnumerable()
where c.Field("Country") == "USA"
select new
{
CustomerID = c.Field("CustomerID"),
ContractName = c.Field("ContractName")
{;

Lambda Expression and LINQ Extension

As I learn more about LINK I hope these things become more of an automatic choice rather than keeping notes... but for now I am stil new to LINQ:

You can use two different ways to retrieve items from a database. The first one is uses the DataContext to call the stored procedure and in a LINQ syntax:


NorthwindDataContext db = new NorthwindDataContext();
var results = from item in db.CustOrderHist("category")
where item.Total > 10
select item;


and the second way is to use the extension with a lumbda expression:


results = db.CustOrderHist("category")
.where (item => Item.Total > 10);



I still havn't figure out which one has which benefits comparing the other way.

Sunday, August 10, 2008

Modify Visual Studio 2005 templates

Whenever you create a new file in the visual studio, you are asking it to put a file as it is specified in its templates. The templates are located in
C:\Program Files\Microsoft Visual Studio 8\Common7\IDE\ItemTemplatesCache and for web development you need to look into the Web folder in there.
There are some handy parameters like $time$ and $user$ that you can see in the MSDN at Visual Studio Template Reference: http://msdn.microsoft.com/en-us/library/ms247064(VS.80).aspx

Tuesday, January 22, 2008

Cmdlets Extending Windows PowerShell

Coming across a nice article in MSDN about Extending Windows PowerShell With Custom Commands that I paste a short overview of it here :

 

There are some pretty significant differences between a Windows PowerShell cmdlet and commands in other standalone shell environments. For instance,

·         a cmdlet is an instance of a Microsoft® .NET Framework class; it is not a standalone executable.

·         Cmdlets generally output objects rather than text and should not format their output.

·         A cmdlet processes its input objects from an object pipeline rather than from a stream of text.

·         A cmdlet should not parse its own arguments and it should not specify a presentation for errors.

·         Finally, cmdlets are record-oriented and generally process a single object at a time.

 

To declare a .NET class as a cmdlet, you attribute the class with the CmdletAttribute attribute (which is the only required attribute for any cmdlet). When you specify the CmdletAttribute attribute, you must specify a verb and noun name pair, which will be used as the name of the cmdlet. This should describe what the cmdlet does and what sort of resource the cmdlet works with.

 

To declare parameters for a cmdlet, you must first define the properties that represent the parameters. To inform the Windows PowerShell runtime that a property is a cmdlet parameter, you add a ParameterAttribute attribute to the property definition.

 

In order to use these new cmdlets, you need to add them to the Windows PowerShell environment. Windows powerShell has the ability to dynamically add cmdlets to the session via a snap-in. To avoid potential confusion with MMC snap-ins, a Windows PowerShell snap-in is called a PSSnapIn.

To create a PSSnapIn, you need to write a bit of code that will perform two tasks. First, it provides identification for your snap-in so it can be distinguished from other snap-ins installed on your system. Second, it provides information for properly installing the snap-in and for creating the appropriate registry entries to allow Windows PowerShell to find the assembly.