A software engineer's glory so often goes unnoticed. Attention seems to come either when there are bugs or when the final project ships. But rarely is a developer appreciated for all the nuances and subtleties of a piece of code--and all the heroics it took to write it. With Visual Studio Achievements Beta, your talents are recognized as you perform various coding feats, unlock achievements and earn badges.
see more...
CebuCoders
Friday, January 27, 2012
Wednesday, November 2, 2011
Mapping of XML Node to Entity Objects
Problem: How to map the xml node to your entity class object dynamically?
- Requirements:
- .Net 3.5 and above
- C# Language
- OOP Knowledge
- Reflection and Generics
- Linq
- Recursive
XML File: This will be the source of your data and you need to map its value to the entity class object.

Solution Structure: Basically you need 4 entity objects for Country, Currency, Moon, and Planet. Then a GenericEntityMapping class that contains the mapping method.

CountryEntity.cs
using System.ComponentModel;
namespace EntityMapReflection.Entity
{
public class CountryEntity
{
[Description("Name")]
public string PlanetName { get; set; }
[Description("Population")]
public string PlanetTotalPopulation { get; set; }
[Description("Currency")]
public CurrencyEntity PlanetCurrency { get; set; }
}
}
CurrencyEntity.csusing System.ComponentModel;
namespace EntityMapReflection.Entity
{
public class CurrencyEntity
{
[Description("Name")]
public string CurrencyName { get; set; }
[Description("Code")]
public string CurrencyCode { get; set; }
}
}
MoonEntity.cs
using System.ComponentModel;
namespace EntityMapReflection.Entity
{
public class MoonEntity
{
[Description("Total")]
public string Total { get; set; }
[Description("Names")]
public string MoonNames { get; set; }
}
}
PlanetEntity.cs
using System.ComponentModel;
namespace EntityMapReflection.Entity
{
public class PlanetEntity
{
[Description("Name")]
public string PlanetName { get; set; }
[Description("Size")]
public string PlanetSize { get; set; }
[Description("Country")]
public CountryEntity Country { get; set; }
[Description("Moon")]
public MoonEntity PlanetMoon { get; set; }
}
}
Note:
1.) I am using the Automatic Properties wherein we don't need to declare its body and the property itself will serve as the variable already.
2.) We are using the Description attribute to define our Property. The value enclosed with double quote in the Description attribute must be the exact text specified in the xml file.
3.) We need to include System.ComponentModel; namespace because the Description attribute was defined inside System.ComponentModel namespace. Namespace is the logical grouping of your objects.
4.) These entity objects will serve as our container for the value from xml nodes.
GenericEntityMapping.cs This class is reponsible for the mapping of data from our XML Nodes to our Entity Objects dynamically.
GenericEntityMapping needs to include the following namespaces:
1. using System; //namespace for Type, Attribute, Activator, & Premitive Type
2. using System.Collections.Generic; //namespace for the Type-safe implementation <T>
3. using System.Xml; //namespace for XmlNode
4. using System.Reflection; //namespace for Assembly, PropertyInfo, & MethodInfo
5. using System.ComponentModel; //namespace for DescriptionAttribute.
6. using System.Linq; //namespace for the Language Integrated Query where you can perform query statement in C#
The following are the Methods defined in this class: Details will be discussed later.
- private string GetDescription(PropertyInfo pInfo)
- private bool IsDefinedClassType(string name)
- public T XmlToEntityMapping<T>(XmlNode xNode, T entityObject)
private string GetDescription(PropertyInfo pInfo) Will get the description defined in the property. The reason why our property has a description is because when ever there are changes in the xml schema
we don't need to change the entity property it self but rather the entity property description.
private string GetDescription(PropertyInfo pInfo)
{
if (pInfo != null)
{
DescriptionAttribute attr = Attribute.GetCustomAttribute
(pInfo,typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null) return attr.Description;
}
return string.Empty;
}
* PropertyInfo class holds all information of the single property defined in our class.
* Attribute.GetCustomAttribute This will retrieve the attributes defined in the object. So if we say Attribute.GetCustomAttribute(pInfo, typeof(DescriptionAttribute)) it means get the Description attribute of this property.
private bool IsDefinedClassType(string name) Function to validate if the property data type is a userdefined class or not. Using Linq we will be able to validate if the name parameter has a corresponding entity class defined in the EntityMapReflection.Entity namespace "please revisit Solution Structure for the screenshot".
private bool IsDefinedClassType(string name)
{
string myNamespace = "EntityMapReflection.Entity";
Type[] types = Assembly.GetExecutingAssembly().GetTypes();
var q = from t in types
where t.IsClass &&
t.Namespace == myNamespace &&
t.Name.ToLower() == name.ToLower()
select t;
return q.ToList().Count > 0;
}
* Assembly.GetExecutingAssembly().GetTypes() Will retrieve all classes defined the running assembly. So from here we will be able to get all classespublic T XmlToEntityMapping<T>(XmlNode xNode, T entityObject)
* Then we will use Linq to query if the specified parameter "name" is in the collection.
/// <summary>
/// Map the data from the XML nodes to Entity objects. It performs a recursive calls within.
/// </summary>
/// <typeparam name="T">This will be the xml entity</typeparam>
/// <param name="xNode">This should be the parent node where you want to start to traverse its child node for mapping</param>
/// <param name="entityObject"></param>
/// <returns>Returns the mapped entity</returns>
public T XmlToEntityMapping<T>(XmlNode xNode, T entityObject)
{
bool isFound = false;
T entity = entityObject;
PropertyInfo[] entityProperties = typeof(T).GetProperties();
foreach (XmlNode node in xNode.ChildNodes)
{
//Check if the xml node matches with the entity object properties
isFound = false;
foreach (PropertyInfo pInfo in entityProperties)
{
if (GetDescription(pInfo).ToLower().Equals(node.Name.ToLower()))
{
isFound = true;
if (IsDefinedClassType(pInfo.PropertyType.Name))
{
//Recursive call passing the current node and the instance of the new entity based on
//the datatype of the current property.
//e.g: public XMLOrderSystemEntity OrderSystem{get;set;}
// -> take the XMLOrderSystemEntity
//Create dynamically a generic method. Recursive call
MethodInfo method = typeof(GenericEntityMapping).
GetMethod("XmlToEntityMapping");
//Attached the generic type to the method.
//This will be the Class DataType of the property
MethodInfo generic = method.MakeGenericMethod(Type.GetType(pInfo.PropertyType.FullName));
//Prepare method parameters: (XmlNode xNode, object entityObject)
object[] methodParam =
{
node,
System.Activator.CreateInstance(Type.GetType(pInfo.PropertyType.FullName))
};
//Invoke the generic method and get the result and assign to property
pInfo.SetValue(entity, generic.Invoke(this, methodParam), null);
}
else
{
//Set the value to the property
pInfo.SetValue(entity, node.InnerText, null);
break;
}
}
}
if (!isFound)
{
if (node.HasChildNodes && (node.ChildNodes.Count > 1 ||
node.ChildNodes.Count == 1 &&
!node.ChildNodes[0].Name.ToLower().Equals("#text")))
{
//For those xmlnodes that have childnodes but that node doesn't
//have corresponding entity yet we still need to drilldown to its child node because
//it is the child node that we need to map to our entity. Therefore the purpose of this
//is to go down to the last xml node if ever the node have children. Recursive call.
entity = new GenericEntityMapping().XmlToEntityMapping<T>(node, entity);
}
}
}
return entity;
}
FYI. I included the explanation into the line of code 'coz it's simple that way hehehehehe peace... :p
Integration
//we still need to include the following namespaces
using System.Xml;
using EntityMapReflection.Entity;
//... integration ...
XmlDocument xDoc = new XmlDocument();
xDoc.Load(@"C:\EntityMappingReflection\XML1.xml");
PlanetEntity entity = new GenericEntityMapping().
XmlToEntityMapping<PlanetEntity>(xDoc.FirstChild, new PlanetEntity());
Comments and feedback are very much appreciated...
The source code can be downloaded from the following Site.
Labels:
.Net 3.5+,
C#,
Generic Collection,
Linq,
Recursive,
Reflection
Friday, October 28, 2011
DataTable to Entity Mapping (Generics and Reflection)
This article will discuss how to use Reflection and Generic Collections when mapping the value from the DataTable to the Entity List.
Requirements
1. Visual Studio 3.0 version and above
2. Knowledge in C#
3. Idea of what is Reflection and Generics
4. Knowledge in 3-tier Architecture
Step to achieve the objectives
1. Need to create Entity classes (e.g: AssetEntity.cs)
2. Need to create generic methods for Entity Mapping
3. Need to create DataAccess class that will return a DataTable
AssetEntity.cs
It is possible that when we perform query to the database, sometimes the columns will return null values. Therefore we have to make sure that our property will also accept null values. To do that we'll just add question mark after the datatype e.g: int?.
We will only do that only if the datatype by default won't accept null values like int, DateTime, etc. The AssetEntity object is using an Automatic property where the property itself will serve as the variable as well.
public class AssetEntity
{
public int? IdentityID { get; set; }
public string AssetName { get; set; }
public string SerialNumber { get; set; }
public System.DateTime? DatePurchase { get; set; }
}
DataAccess.cs
The DataTable, DataColumn, and DataRow belongs to System.Data namespace. While DateTime and DBNull is under System namespace. With these classes we'll be able mimic the data returned from Database Query, Grid Datasource, DataView Source, etc.
At the same time will give you idea on how to manually add columns and rows in our DataTable. One notable point to remember here for beginner is that when we execute query to the database sometimes the columns returns null value and the corresponding datatype in .Net is DBNull.
using System;
using System.Data;
public class DataAccess
{
public DataTable GetAsset()
{
// Define the datatype of the
// columns in datatable
DataTable dt = new DataTable();
dt.Columns.Add
(
new DataColumn
(
"IdentityID",
typeof(int)
)
);
dt.Columns.Add
(
new DataColumn
(
"AssetName",
typeof(string)
)
);
dt.Columns.Add
(
new DataColumn
(
"SerialNumber",
typeof(string)
)
);
dt.Columns.Add
(
new DataColumn
(
"DatePurchase",
typeof(DateTime)
)
);
//Assign value to the data table
DataRow dr = dt.NewRow();
dr["IdentityID"] = DBNull.Value;
dr["AssetName"] = "Pillow";
dr["SerialNumber"] = "ASDF12390";
dr["DatePurchase"] = "09/23/2005";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr["IdentityID"] = 2;
dr["AssetName"] = "Table";
dr["SerialNumber"] = "JKLJ09321";
dr["DatePurchase"] = DBNull.Value;
dt.Rows.Add(dr);
return dt;
}
}
Entity Mapping Method
This method can be written whereever you want to write so long as the class is accessible. This method can be reused every time you want to map the datatable to the entity object regardless of the number of properties, name of entities, and datatype of the properties.
DataTableToEntityList is a Generic Typesafe Method that will accept DataTable as it's parameter and will bind the data from DataTable to the Entity. If the column in DataRow does not exist in the entity it will simply skip during mapping of values.
* Type-safe. T represents a generic type and can hold any type. To assign AssetEntity to the generic type just do the following e.g: DataTableToEntityList<AssetEntity>(new DataTable());
* Instantiation. Based on the T type we need to create a new instance of T but we cannot do it the usual way like T entity = new T(); because T doesn't have constructor that is why we need to use the Activator class and call CreateInstance static function to dynamically create instance of the generic type. e.g: System.Activator.CreateInstance<t>();
* All Properties. To get all properties defined inside type T we need to use Reflection which is capable of extracting class members at runtime e.g: typeof(T).GetProperties();
* Set the property. Lastly we need to dynamically assign value to that propertye.g: item.SetValue(entity, dr[item.Name], null);
using System;
using System.Data;
using System.Collections.Generic;
/// <summary>
/// Map the data from datatable to entity objects
/// </summary>
/// <param name="dtSource">
/// Data source from datatable to map to entity object
/// </param>
/// <returns>
/// Returns the generic list collection
/// </returns>
public static
List<T> DataTableToEntityList<T>(DataTable dtSource)
{
string propName = string.Empty;
List<T> entityList = new List<T>();
foreach (DataRow dr in dtSource.Rows)
{
// Create Instance of the Type T
T entity = System.Activator.CreateInstance();
// Get all properties of the Type T
System.Reflection.PropertyInfo[]
entityProperties = typeof(T).GetProperties();
// Loop through the properties defined in the
// entityList entity object and mapped the value
foreach(System.Reflection.PropertyInfo item in
entityProperties)
{
propName = string.Empty;
if (propName.Equals(string.Empty))
propName = item.Name;
if (dtSource.Columns.Contains(propName))
{
// Assign value to the property
item.SetValue
(
entity,
dr[propName].GetType().
Name.Equals(typeof(DBNull).Name)
? null : dr[propName],
null
);
}
}
entityList.Add(entity);
}
return entityList;
}
Integration
Somewhere in your code just do the following:
DataAccess da = new DataAccess();
DataTable dtAsset = da.GetAsset();
// In my case Common is the class where i placed my
// Generic Method DataTableToEntityList
List<EntityObject> list =
Common.DataTableToEntityList<AssetEntity>(dt);
Rev 1: Updates as of January 28, 2012
* Requirements section* Step to achieve the objectives
* Updated the AssetEntity.cs section
* Removed EmployeeEntity (too much for the example)
* Replaced EntityMapping.cs section with Entity Mapping Method
* Updated all of the sample code snippets
Hope you like this mini article and if you have any questions please feel free to add comment and I will reply to it.
Thursday, October 13, 2011
Thursday, September 8, 2011
XMLDocument Bug: Can't apply encoding for double and single quote
XmlDocument is one of the many available object that will help developer manipulate xml files without a fuss.
XmlDocument xmlDoc = new XmlDocument();
XmlNode myNode = xmlDoc.CreateElement("MyNode");
myNode.InnerText = '"' + "naruto & jeph" + '"';
xmlDoc.AppendChild(myNode);
xmlDoc.Save("c:/SampleXmlFile.xml");
Basically the above example would supposed to be output "naruto & jeph" yet the actual output does not have encoded value for double quote "naruto & jeph"
With that approach alone the double quote will not be included in the parsing probably because it with xmldocument object double quote and single quote serves a difference purpose.
But the problem is that:
Using web application in .net I need to create an xml using XMLDocument object and should perform encoding on the node text of the xml tags. Example Input: "naruto & jeph" encoded output: "naruto & jeph" using XMLDocument it will not encode double quote and single quote.
Therefore the following is the workaround that I have thought of:
XmlDocument xmlDoc = new XmlDocument();
XmlNode myNode = xmlDoc.CreateElement("MyNode");
XmlText myText = xmlDoc.CreateTextNode(myValue.replace("""","""))
myNode.AppendChild(myText)
xmlDoc.AppendChild(myNode);
xmlDoc.Save("c:/SampleXmlFile.xml");
//Open the saved xml file as text and update the &quot; to "
System.Text.StringBuilder newFile = new System.Text.StringBuilder();
string tempString = "";
string []fileString = File.ReadAllLines("c:/SampleXmlFile.xml");
foreach(string line in fileString)
{
if (line.Contains("&quot;"))
{
tempString = line.Replace("&quot;",""");
newFile.AppendLine(tempString);
continue for;
}
}
File.WriteAllText("c:/SampleXmlFile.xml", newFile.ToString());
The workaround here is that after I saved the xml file i reopen it again using File object and replace the double encoded value
Tuesday, September 6, 2011
SOA - Service Oriented Architecture
What is SOA
Service Oriented Architecture (SOA). Is a group of services accessible in public network.
When and why was SOA created?
SOA was already there since 1990s and the concept of SOA was created in order to integrate business intelligence across platform. SOA also is virtual location, meaning services can be located anywhere on the cloud. Since the location is transparent when implementing SOA, basically the deployment time frame will also be optimize to a certain degree since they will simply map their application to the defined web service. Web Service is application for SOA.
Why we need SOA now? Why not before?
Chances are.. back in the days the idea of sharing business intelligence is not really into practice due to several factors that holds company to share their business intelligence. But as business matures the technology evolve into difference level where everything is almost possible.
Before, the ways of payment is done via over the counter. So at the end of the day, people needs to go to bank to deposit the money. With the help of technological advancement, we can now pay or deposit our money with out actually going to the bank. This is also being applied between online store and the bank where every transaction of the user will be automatically deposit to the account of the online store owner.
SOA and Cloud
The relationship between SOA and Cloud is that cloud offers virtualization such that services were provided to the consumer such as infrastructure, hardware resource such as servers, software as s service, and other device on demand.
Software-as-a-Service
Software-as-a-Service (SaaS) is a very good example of SOA for cloud computing. Before implementing SaaS/SOA you have to extremely consider the following pros and cons:
Potential Pros:
- Automatic updates. You will always be getting the latest version of the software, with no work required. But these features are only valuable if you can leverage them to create value. Does your organization have the agility to improve processes and services, train users, and really get some value out of the upgrades?
- Fewer compatibility issues. You’ll have less to worry about in terms of compatibility issues. As long as you run a standard web browser, it’s likely you’ll be able to use the service.
- No installs. You won’t have to worry about installing the software on multiple machines or automating this with installation packages.
- Small upfront costs. You’ll be able to space payments out over time (regular monthly fees) and minimize the large upfront capital investments.
- Reduced hardware expense. As the amount of SaaS reaches critical mass for an organization, there comes a point where the server/workstation refresh rate slows.
Potential Cons:
- Online connectivity is required to use the service. (No catching up on email in an airplane, unless the service specifically supports a download/upload.)
- Data. Someone else is responsible for your data. This can be a great thing if you haven’t a clue how to manage your data, but if you collect highly sensitive information you’ll need to scrutinize your potential vendors about their practices. This includes security, back-up, and recovery.
- Up-time and availability. Someone else is responsible for making sure the software works everyday. Again, this is a double-edged sword and you’ll want to set expectations with your service providers (and validate them).
- Limited customization options are available through most services. And even if they are offered, you could run the risk of finding issues when those automatic upgrades occur. Tread carefully on customization paths…
Other Saas issues for consideration:
- Single-sign on. Does the system support integration with your existing user management service or will your users need to remember yet another set of login information?
- Ongoing payments required. Just like the difference between renting a home and owning one, ongoing payments are required to keep the service available. Unlike software you purchase and host yourself, you won’t have the option to stay status quo if funds are running low.
- Integration with other services. Is it important that you are able to pull accounting and CRM data into your email or intranet sites? How about make your CRM system and accounting system talk together? How about that time tracking system? These types of integrations might be easier or more difficult, depending on the services you choose and how you choose to manage your data.
Sources:
* http://www.simonstapleton.com/wordpress/2008/06/19/whats-this-software-as-a-service-saas-all-about-a-laymans-view-and-implications-for-technical-professionals/
* http://www.bridging-the-gap.com/pros-and-cons-of-software-as-a-service-models/
Service Oriented Architecture (SOA). Is a group of services accessible in public network.
When and why was SOA created?
SOA was already there since 1990s and the concept of SOA was created in order to integrate business intelligence across platform. SOA also is virtual location, meaning services can be located anywhere on the cloud. Since the location is transparent when implementing SOA, basically the deployment time frame will also be optimize to a certain degree since they will simply map their application to the defined web service. Web Service is application for SOA.
Why we need SOA now? Why not before?
Chances are.. back in the days the idea of sharing business intelligence is not really into practice due to several factors that holds company to share their business intelligence. But as business matures the technology evolve into difference level where everything is almost possible.
Before, the ways of payment is done via over the counter. So at the end of the day, people needs to go to bank to deposit the money. With the help of technological advancement, we can now pay or deposit our money with out actually going to the bank. This is also being applied between online store and the bank where every transaction of the user will be automatically deposit to the account of the online store owner.
SOA and Cloud
The relationship between SOA and Cloud is that cloud offers virtualization such that services were provided to the consumer such as infrastructure, hardware resource such as servers, software as s service, and other device on demand.
Software-as-a-Service
Software-as-a-Service (SaaS) is a very good example of SOA for cloud computing. Before implementing SaaS/SOA you have to extremely consider the following pros and cons:
Potential Pros:
- Automatic updates. You will always be getting the latest version of the software, with no work required. But these features are only valuable if you can leverage them to create value. Does your organization have the agility to improve processes and services, train users, and really get some value out of the upgrades?
- Fewer compatibility issues. You’ll have less to worry about in terms of compatibility issues. As long as you run a standard web browser, it’s likely you’ll be able to use the service.
- No installs. You won’t have to worry about installing the software on multiple machines or automating this with installation packages.
- Small upfront costs. You’ll be able to space payments out over time (regular monthly fees) and minimize the large upfront capital investments.
- Reduced hardware expense. As the amount of SaaS reaches critical mass for an organization, there comes a point where the server/workstation refresh rate slows.
Potential Cons:
- Online connectivity is required to use the service. (No catching up on email in an airplane, unless the service specifically supports a download/upload.)
- Data. Someone else is responsible for your data. This can be a great thing if you haven’t a clue how to manage your data, but if you collect highly sensitive information you’ll need to scrutinize your potential vendors about their practices. This includes security, back-up, and recovery.
- Up-time and availability. Someone else is responsible for making sure the software works everyday. Again, this is a double-edged sword and you’ll want to set expectations with your service providers (and validate them).
- Limited customization options are available through most services. And even if they are offered, you could run the risk of finding issues when those automatic upgrades occur. Tread carefully on customization paths…
Other Saas issues for consideration:
- Single-sign on. Does the system support integration with your existing user management service or will your users need to remember yet another set of login information?
- Ongoing payments required. Just like the difference between renting a home and owning one, ongoing payments are required to keep the service available. Unlike software you purchase and host yourself, you won’t have the option to stay status quo if funds are running low.
- Integration with other services. Is it important that you are able to pull accounting and CRM data into your email or intranet sites? How about make your CRM system and accounting system talk together? How about that time tracking system? These types of integrations might be easier or more difficult, depending on the services you choose and how you choose to manage your data.
Sources:
* http://www.simonstapleton.com/wordpress/2008/06/19/whats-this-software-as-a-service-saas-all-about-a-laymans-view-and-implications-for-technical-professionals/
* http://www.bridging-the-gap.com/pros-and-cons-of-software-as-a-service-models/
Thursday, July 21, 2011
How to display javascript message after postback from server control
ScriptManager.RegisterStartupScript is a method that would let you add a script block from server side code (let say) show alert message of javascript.
ScriptManager class belongs to System.Web.UI namespace.
RegisterStartupScript method have 5 parameters.
e.g: (Page, Type, ID, JavascriptCode, IsWriteScriptBlock)
Page: This is the instance of your web page
Type: This is the type of the control, use typeof for C# and GetType() for VB
JavascriptCode: This is the javascript like a lert("hello");
IsWriteScriptBlock: Its a boolean value if the value is true the value you have written in your JavascriptCode parameter will be wrapped with block.
How to use this:
In your code behind "i am using C#" you have
protected void SaveButton_Click(object sender, System.EventArgs e)
{
//code to save the data
//....
ScriptManager.RegisterStartupScript(this.Page, typeof(this), "testScrpt", "a lert('hello');", true);
}
Result:
if your last parameter is false the result would be:
a lert('hello');
I know it's very basic but for those who are not aware of this please feel free to test it. Enjoy coding... :)
ScriptManager class belongs to System.Web.UI namespace.
RegisterStartupScript method have 5 parameters.
e.g: (Page, Type, ID, JavascriptCode, IsWriteScriptBlock)
Page: This is the instance of your web page
Type: This is the type of the control, use typeof for C# and GetType() for VB
JavascriptCode: This is the javascript like a lert("hello");
IsWriteScriptBlock: Its a boolean value if the value is true the value you have written in your JavascriptCode parameter will be wrapped with block.
How to use this:
In your code behind "i am using C#" you have
protected void SaveButton_Click(object sender, System.EventArgs e)
{
//code to save the data
//....
ScriptManager.RegisterStartupScript(this.Page, typeof(this), "testScrpt", "a lert('hello');", true);
}
Result:
if your last parameter is false the result would be:
a lert('hello');
I know it's very basic but for those who are not aware of this please feel free to test it. Enjoy coding... :)
Labels:
C#,
javascript,
schools,
serviam,
serviam club
Subscribe to:
Posts (Atom)
