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.