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;
}
}

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);
}
}

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.

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 FilesMicrosoft Visual Studio 8Common7IDEItemTemplatesCache 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

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.

Sorting Generic List in C#

You can sort a generic List in C# using different methods. Here I cover only two options which I found them most handy. The third option is to put the method into a class that implements the IComparer interface.

using System;
using System.Collections.Generic;

public class SortingList
{
/// <summary>
/// SortingList: This snippet code demonstrates the delegate method of sorting lists
/// I define an Item type having some fields and sort based on a preferred field
/// To do so I need to implement a method would be called during the sort action for each pair.
///
/// NOTE: You could also create a class implementing IComparer and use the class to pass to the Sort method.
///
/// Asghar Panahy
/// 07-12-2007
/// </summary>
public static void Main()
{
List
<Item> list = new List<Item>();

// Adding some dummy items
list.Add(new Item("6", " Asghar 1"));
list.Add(
new Item("5", " Asghar 2"));
list.Add(
new Item("3", " Asghar 3"));
list.Add(
new Item("4", " Asghar 4"));
list.Add(
new Item("2", " Asghar 5"));
list.Add(
new Item("1", " Asghar 6"));

Console.WriteLine(
"Dumping the list:");
DumpList(list);

// Sorting it by ID
list.Sort(SortByID);

Console.WriteLine(
"Dumping the list:");
DumpList(list);

// Second Option, using anonimous methods
// Sorting it by Birthday
list.Sort(
delegate (Item i1, Item i2)
{
return i1.Birthday.CompareTo(i2.Birthday);
}
);

Console.WriteLine(
"Dumping the list:");
DumpList(list);

// Wait for response before closing it
Console.ReadLine();

}
public static int SortByID(Item s1, Item s2)
{
return s1.ID.CompareTo(s2.ID);
}

public static void DumpList(List<Item> list)
{
foreach(Item l in list)
{
Console.WriteLine(l);
}
}

}

// Sample Class
public class Item
{
public Item(string id, string name)
{
this.ID = id;
this.Name = name;
this.Birthday = DateTime.Now;
}
public string Name;
public string ID;
public DateTime Birthday;
public override string ToString()
{
return String.Format("{0} is born on {1}", this.Name, this.Birthday.ToLocalTime());
}
}
}

Characteristics of a Leader

The following is coted from the book Analyzing Requirements and Defining Solution Architectures.

Finding Effective Leaders

For the person in charge of putting together a project team, the first task is to decide who will work on the project. This seemingly simple (but more often complex) decision can dramatically affect the project’s outcome.

Finding leaders within an organization is not a difficult process. By definition, leaders are recognized by those they work with. It’s important to remember that we are talking about leaders here, not bosses. Every organization has its share of managers, directors, and so on, but the hierarchical structure of an organization does not determine who the true leaders are. Actions and characteristics, rather than job titles, identify leaders.

Why do we need leaders? Because we have so many followers. It’s important to realize that labeling people as leaders and followers does not imply a value judgment. We must have leaders to be successful, but we must also have followers. Leaders provide direction for the team. Followers get the work done. The team needs to strike a balance between its leaders and followers. It must decide what to do and then must do it, so both leaders and followers are equally important and valuable. An absence of either leaders or followers will hinder the project’s success.

Certain characteristics are present in many leaders. Common qualities of leaders include:

  • Understanding and meeting the needs of others.
  • Communicating well with groups and individuals.
  • Earning the respect of internal and external customers.
  • Displaying commitment to well-defined purposes.
  • Making a positive difference.
  • Having confidence in his or her abilities.
  • Practicing good problem-solving skills.
  • Helping others to develop their skills.

Many people will read this list and say, "I do those things." More people will read this list and say, "I intend to do those things." But being a leader also means knowing the difference between intent and impact. When measuring their own success, people measure their intent; when measuring other people’s success, they measure their impact. The impact that leaders have on others may or may not be their intent, and leaders’ intent may not have the impact they were striving for. The proper way to measure people’s leadership skills is by the impact they actually have, not by their intent. We can summarize this concept by saying, "Other people’s perceptions are reality."

Total Participation in Design

Jim McCarthy summarizes the concept of total participation in design in Dynamics of Software Development:

The goal in any product design is to have the best ideas become the basis of the product. Everybody on the team should be working to accomplish that goal.

Each role participates in the generation of the Functional Specification because each role has a unique perspective of the design and tries to ensure that the design meets their role’s objectives, as well as the project team’s objectives.