Tuesday, May 06, 2008

Read Write and Search XML Document in ASP.NET

You often need to read, write or search some phrase in an XML document and you can use XmlDocument or any class among a lot present in .NET framework but what
if you wish to bind your business objects
the list of business objects to the XmlDocument.

You can use the code below to do this.

What you need to do for this is to keep the name of properties of your business objects same as the name of attributes are present in the XML file you wanna load.

This class make use of XmlReader and XmlWriter base classes provided by .NET framework.

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Xml;
using System.Reflection;
using System.IO;

///
/// XMLDataHelper provides way to access nodes and bind them directly to custom objects.
/// Also Save XMLFragment at the end of the Xml File
///

public class XMLDataHelper : IDisposable
{
#region Variables

private static string _baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
private static string _documentDirectory = _baseDirectory + "App_Data/";

protected string _query;
protected XmlReader xmlReader;
protected XmlWriter xmlWriter;
#endregion

#region constructors
public XMLDataHelper()
{
string xmlFile = ConfigurationManager.AppSettings["XmlFileName"].ToString();
xmlReader = XmlReader.Create(xmlFile);
}

public XMLDataHelper(string xmlFile)
{
xmlReader = XmlReader.Create(xmlFile);
}
public XMLDataHelper(string xmlFile, string xmlFileForWriter)
{
xmlReader = XmlReader.Create(xmlFile);
xmlWriter = XmlWriter.Create(xmlFileForWriter);

}
#endregion

#region Load Object
public T LoadObject(string nodeName, Dictionary attrFieldsLookUp) where T : new()
{
T obj = new T();
if (string.IsNullOrEmpty(nodeName))
{
throw new Exception("Node not specified.");
}
bool IsRequestedItem = true;
PropertyInfo[] objPropInfo = obj.GetType().GetProperties();
while (xmlReader.ReadToFollowing(nodeName))
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.NodeType != XmlNodeType.Document)
{
XmlReader nodeXmlReader = xmlReader.ReadSubtree();
while (nodeXmlReader.Read())
{
IsRequestedItem = false;
foreach (string key in attrFieldsLookUp.Keys)
{
if (attrFieldsLookUp[key.ToUpper()] == nodeXmlReader.GetAttribute(key))
{
IsRequestedItem = true;
}
else
{
IsRequestedItem = false;
break;
}
}
if (IsRequestedItem)
{
GetObjectFromReaderNode(ref obj, ref nodeXmlReader, ref objPropInfo, true, nodeName);
}
}
}
}
if (xmlReader.ReadState != ReadState.Closed)
{
xmlReader.Close();
}
return obj;
}
#endregion

#region GetObjectFromReaderNode
private void GetObjectFromReaderNode(ref T obj, ref XmlReader nodeXmlReader, ref PropertyInfo[] objPropInfo, bool AreElementsReq, string nodeName)
{
Dictionary xmlFileValues = new Dictionary();
while (nodeXmlReader.MoveToNextAttribute())
{
xmlFileValues.Add(nodeXmlReader.Name.ToUpper(), nodeXmlReader.Value);
}
foreach (PropertyInfo pi in objPropInfo)
{
if (pi.Name == "DEPTH")
{
pi.SetValue(obj, (object)(nodeXmlReader.Depth + 1), null);
}
else
{
string currAttrVal;
if (xmlFileValues.TryGetValue(pi.Name.ToUpper(), out currAttrVal))
{
if (pi.PropertyType == typeof(Boolean))
{
pi.SetValue(obj, Convert.ToBoolean(currAttrVal.ToLower()), null);
}
else
{
pi.SetValue(obj, (object)currAttrVal, null);
}
}
}
}
if (AreElementsReq)
{
bool firstOccur = true;
while (xmlReader.Read() && firstOccur)
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.NodeType != XmlNodeType.Document)
{
string elementName = nodeXmlReader.Name;
// To Stop Retrieving Inner Elements value
if (elementName == nodeName)
{
firstOccur = false;
}
string currElementVal;
foreach (PropertyInfo pi in objPropInfo)
{
if (pi.Name.ToUpper() == elementName.ToUpper())
{
pi.SetValue(obj, (object)nodeXmlReader.ReadElementString(), null);
}
}
}
}
}
}
#endregion

#region LoadList
public List LoadList(string nodeName, bool includeElement) where T : new()
{
T obj = new T();
List retList = new List();
if (string.IsNullOrEmpty(nodeName))
{
throw new Exception("Node not specified.");
}
bool IsRequestedItem = true;
PropertyInfo[] objPropInfo = obj.GetType().GetProperties();
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.NodeType != XmlNodeType.Document)
{
if (xmlReader.Name == nodeName)
{
obj = new T();
GetObjectFromReaderNode(ref obj, ref xmlReader, ref objPropInfo, includeElement, nodeName);
retList.Add(obj);
}
}
}
if (xmlReader.ReadState != ReadState.Closed)
{
xmlReader.Close();
}
return retList;
}
#endregion

#region SaveXmlFragment
// Summary:
// To Save XmlFragment at the end of the file
public void SaveXmlFragment(string rawXmlFragment, string rootItem)
{
try
{
using (xmlReader)
{
while (xmlReader.Read())
{
if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.Name == rootItem)
{
xmlWriter.WriteStartElement(rootItem);
xmlWriter.WriteRaw(xmlReader.ReadInnerXml());
xmlWriter.WriteRaw(rawXmlFragment);
xmlWriter.WriteEndElement();
}
else if (xmlReader.NodeType == XmlNodeType.Comment || xmlReader.NodeType == XmlNodeType.Text || xmlReader.NodeType == XmlNodeType.Whitespace)
{

}
else
{
xmlWriter.WriteNode(xmlReader, true);
}
}
xmlWriter.Flush();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
xmlReader.Close();
xmlWriter.Close();
FileInfo fi = new FileInfo(_documentDirectory + "SiteData.xml");
File.Copy(_documentDirectory + "_tempSiteData.xml", fi.FullName, true);
}
}
#endregion

#region Search Document
// Summary:
// To Save XmlFragment at the end of the file
public SortedDictionary> SearchDocument(string searchText, string nodeName, string propertyNameToLookFor) where T : new()
{
List searchWords = new List();

string[] allWords = searchText.Split(' ');

for (int i = 0; i <>> retDictionary = new SortedDictionary>();

T obj = new T();

PropertyInfo[] piAll = obj.GetType().GetProperties();

List retList = this.LoadList(nodeName, true);

foreach (T item in retList)
{
string content = "";
int relevance = 0;
foreach (PropertyInfo pi in piAll)
{
if (pi.Name == propertyNameToLookFor)
{
content = Convert.ToString(pi.GetValue(item, null));
}
}
string[] contentSplitted = content.Split(' ');
foreach (string word in searchWords)
{
for (int i = 0; i <> relCorrList = new List();
relCorrList.Add(item);
retDictionary.Add(relevance, relCorrList);
}
else
{
retDictionary[relevance].Add(item);
}
}
}
return retDictionary;
}
#endregion

#region IDisposable Members
public void Dispose()
{
if (xmlReader.ReadState != ReadState.Closed)
{
xmlReader.Close();
xmlWriter.Close();
}
}

#endregion


}

if you are getting it difficult to understand or have some queries you can put a reply or mail me at
shashank.abes at gmail.com

Some Useful Sql Server Queries

Some Useful Sql Server Queries

Get Number Of Days in a Month:

SQL Query to get No of Days in a month:-

SELECT DAY(DATEADD(MONTH, 1, GETDATE()) - DAY(DATEADD(MONTH, 1, GETDATE())))

Reading XMl from Sql Server

DECLARE @FileName varchar(255)

DECLARE @ExecCmd VARCHAR(255)

DECLARE @y INT

DECLARE @x INT

DECLARE @FileContents VARCHAR(8000)

CREATE TABLE #tempXML(PK INT NOT NULL IDENTITY(1,1), ThisLine VARCHAR(255))

SET @FileName = Full Path To Xml \General.xml'

SET @ExecCmd = 'type ' + @FileName

SET @FileContents = ''

INSERT INTO #tempXML EXEC master.dbo.xp_cmdshell @ExecCmd

SELECT @y = count(*) from #tempXML

SET @x = 0

WHILE @x <> @y

BEGIN

SET @x = @x + 1

SELECT @FileContents = @FileContents + ThisLine from #tempXML WHERE PK = @x

END

SELECT @FileContents as FileContents

DROP TABLE #tempXML

Grouping Records in Sql Server 2005

declare @NO_OF_PARTITION int

set @NO_OF_PARTITION = 10

SELECT c.First_Name, c.Last_Name , C.DIVISION_ID

,NTILE(@NO_OF_PARTITION)

OVER(PARTITION BY DIVISION_ID ORDER BY DIVISION_ID ASC) AS 'GROUP_ID'

FROM EMPLOYEE C

WHERE division_id = 2

ORDER BY DIVISION_ID ASC

Replacement to IN and NOT IN from INTERSECT and EXCEPT

SELECT EMPLOYEE_ID FROM EMPLOYEE

INTERSECT

SELECT EMPLOYEE_ID FROM LEAVE_DETAILS

SELECT EMPLOYEE_ID FROM EMPLOYEE

EXCEPT

SELECT EMPLOYEE_ID FROM LEAVE_DETAILS

Using NTILE to tile (group) your records

SELECT c.First_Name, c.Last_Name , C.DIVISION_ID

,NTILE(2)

OVER(PARTITION BY DIVISION_ID ORDER BY DIVISION_ID ASC) AS 'GROUP_ID'

FROM EMPLOYEE C

WHERE EMPLOYEE_ID < 13

ORDER BY DIVISION_ID ASC

Get Serial No. with the query result (ROW_NUMBER function SQL Server 2005)

SELECT ROW_NUMBER() OVER (ORDER BY DIVISION_ID ASC) AS ROWID, * FROM EMPLOYEE

Using Pivot Keyword SQL Server 2005

CREATE TABLE dbo.SalesByQuarter
(
Y INT,
Q INT,
sales INT,
PRIMARY KEY (Y,Q)
)
GO

INSERT dbo.SalesByQuarter(Y,Q,Sales)
SELECT 2003, 2, 479000
UNION SELECT 2003, 3, 321000
UNION SELECT 2003, 4, 324000
UNION SELECT 2004, 1, 612000
UNION SELECT 2004, 2, 524000
UNION SELECT 2004, 3, 342000
UNION SELECT 2004, 4, 357000
UNION SELECT 2005, 1, 734000
GO

SELECT Y,
[1] AS Q1,
[2] AS Q2,
[3] AS Q3,
[4] AS Q4
FROM
(SELECT Y, Q, Sales
FROM SalesByQuarter) s
PIVOT
(
SUM(Sales)
FOR Q IN ([1],[2],[3],[4])
) p
ORDER BY [Y]
GO

DROP TABLE dbo.SalesByQuarter
GO

Saturday, April 05, 2008

Generic List Predicates

Have you ever considered of searching on a list based upon a single value, for example we have a List and Employee contains a Property names Name and EmpCode.

There are many ways to search for it, we can walk through a foreach loop, or call our database, or whatsoever But we also have functions called Find and FindAll that expects a function the returns a bool value.

Now how we can use it. Suppose we are having a list of Employees say :

List lstEmployee

and we want to search an employee that contains EmpCode = 0.

We can write a function like:

int _empCode = 4;

Employee empWithCode = lstEmployee.FindAll(new Predicate(GetSingleEmployeeForCode));

private void GetSingleEmployeeForCode(Employee emp)

{

if (emp.EmpCode == _empCode)

    {

    return true;
    }

return false;

}

This will return us the employee with EmpCode 4.

Now how can we search for items that may have same value for different objects in list.

We have function like :

List maleEmpList;

maleEmpList = lstEmployee.FindAll(new Predicate(GetMaleEmployees));

private void GetMaleEmployees (Employee emp)

{

if (emp.Gender == "Male")

    {

    return true;
    }

return false;

}

How to perform Sort operation in List Generic List

Today I am coming with a small but efficient code for performing Sort operation in List. I am not going to explain it in much details as the code is

self understandable.

List braList;

braList = _branManager.GetBranchList();

braList.Sort

(

delegate(Branch braA, Branch braB)

{

if (CompanySortDirection == SortDirection.Ascending)

{

return braA.BranchCode.CompareTo(braB.BranchCode);

}

else// if (CompanySortDirection == SortDirection.Descending)

{

return braB.BranchCode.CompareTo(braA.BranchCode);

}

}

);

Depending upon the Sort Direction the list get sorted.

Friday, March 21, 2008

Use of Generics with C#

Its a long time when I last posted...

Now I am coming up with a brief but self explanatory article on C# Generics that will explain use of generics to less experienced persons in C#.

Before continuing to this post I would like to say if you are not using the concept of objects and classes (or say OOPS principles) in your development than the principle of Generics is not going to help you much.

However, what are Generics?

In a lot of articles you will get the Generics are similar to C++ Templates. Yes it is. The concept is same as C++ Templates but the internal implementation and advantage is the place where both of these differs slightly.

Basically Generics is to do once and use multiple concept.

Now we will write a simple example to let you know about the Generic functions:

Say we want to write a function where we will pass any object:

The function definition will look like this:

public string GetStringRepresentation(T t, string propertyNameToLookFor) where T : new()

{

return "";

}

Now here we are declaring that our first parameter T t is a generic Type.

Now what we can do with this. To use this lets take a look on to the enhanced function below:

public string GetStringRepresentation(T t, string propertyNameToLookFor) where T : new()

{

t = default(T); // specifying the default value to the coming type

return t.ToString();

}

Role of default keyword in generics:

The default keyword let us specify the initial value for the coming type if it is int the default value will go to 0, if the coming type is string it will be assigned to “” or if it is an object the default value will go to null.

For more information follow the link.


Putting constraints on the coming T types in a function:

Suppose you want to put some constraints on the parameter T so that you can look for

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection;

namespace GenericTest

{

public interface IConstraint

{

void Constraints();

}

public class DummyClass : IConstraint

{

#region IConstraint Members

public void Constraints()

{

// Constraint Applied

}

#endregion

}

public class TypeTProceesing

{

public T ProcessT() where T : IConstraint, new()

{

T t = new T();

t.Constraints(); // As we are putting constraint on the

// parameter T that it will be

// implementing interface IConstraint

// That's why we are able to call the

// function Constraints() here.

return t;

}

}

}

If you have any query regarding how to utilize the concepts of Generics

Let me know as a reply for this post or contact me at

Shashank.abes@gmail.com


Wednesday, April 25, 2007

Basics of NHibernate

NHibernate: An Object to Relational Mapping Tool.



This post is to just let you know how to start working with NHibernate a tool that let you save your real world objects directly to your relational database.
It handles persisting plain .NET objects to and from an underlying relational database. Given an XML description of your entities and relationships, NHibernate automatically generates SQL for loading and storing the objects.

For detailed description and downloading NHibernate please visit the site:
http://www.hibernate.org
However the following lines let you know how you can start working with NHibernate.
The environment that I am choosing is .NET 2003, SQL Server 2000, NHibernateContrib-1.0.4.0.zip, Language : C#

First create a website and add the reference of NHibernate.dll found under the folder NHibernateContrib-1.0.4.0\bin\

Add reference of NHibernate.dll and add the rest of the dlls in your projects bin directory.

So now you are able to add NHibernate code but remember to build to check whether you are using the right version of NHibernate or not…..

Ok, Now lets start working with a class whose object you want to store in your database.

I am naming this class as Cat.
FIRST PERSISTENT CLASS : CAT

using System;

namespace testa
{
///
/// Summary description for Cat.
///

public class Cat
{
private string id;
private string name;
private char sex;
private float weight;

public string Id
{
get
{
return id;
}
set
{
id = value;
}
}
public string Name
{
get
{
return name;
}
set
{
name = value;
}
}
public char Sex
{
get
{
return sex;
}
set
{
sex = value;
}
}
public float Weight
{
get
{
return weight;
}
set
{
weight = value;
}
}

public Cat()
{
//
// TODO: Add constructor logic here
//
}
}
}

This is a normal C# class with some properties whose object you want to store to your database.

MAPPING THE CAT
Create an xml file but remember to put it in the same directory where your class resides and name it Cat.hbm.xml. The content of Cat.hbm.xml will look like this:

Do remember to make the Cat.hbm.xml an embed reource in your application by clicking on the Cat.hbm.xml and pushing F4 in your keyboard and then choose Build Action as: Embedded Resource

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.0" namespace="testa" assembly="testa">
<class name="Cat" table="Cat">
<id name="Id">
<column name="CatId" sql-type="char(30)" not-null="true" />
<generator class="uuid.hex" />
</id>
<property name="Name">
<column name="Name" length="16" not-null="true" />
</property>
<property name="Sex" />
<property name="Weight" />
</class>
</hibernate-mapping>


The table cat in the database will look like this:
Column Type
CatId char(32)
Name nvarchar(16)
Sex char(1)
Weight float

Meanwhile something about NHibernate’s ISession. Its an interface that let you store and retrieve objects from the database.
To get ISession from the ISessionFactory:

ISessionFactory sessionFactory =
new Configuration().Configure().BuildSessionFactory();

An ISessionFactory is usually only built once, e.g. at startup inside Application_Start event handler. This also means you should not keep it in an instance variable in your ASP.NET pages, but in some other location. Furthermore, we need some kind of Singleton, so we can access the ISessionFactory easily in application code. The approach shown next solves both problems: configuration and easy access to a ISessionFactory.

We will do this by Impleting a helper calss that will take care for all the Sessions open for the applications:
Implementing the NHibernate Helper Class:

using System;
using System.Web;
using NHibernate;
using NHibernate.Cfg;

namespace testa
{
///
/// Summary description for NHibernateHelper.
///

public sealed class NHibernateHelper
{
private const string CurrentSessionKey = "nhibernate.current_session";
private static readonly ISessionFactory sessionFactory;

static NHibernateHelper()
{
sessionFactory = new Configuration().Configure().BuildSessionFactory();
}

public static ISession GetCurrentSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;

if (currentSession == null)
{
currentSession = sessionFactory.OpenSession();
context.Items[CurrentSessionKey] = currentSession;
}
return currentSession;
}

public static void CloseSession()
{
HttpContext context = HttpContext.Current;
ISession currentSession = context.Items[CurrentSessionKey] as ISession;

if (currentSession == null)
{
return;
}

currentSession.Close();
context.Items.Remove(CurrentSessionKey);
}

public static void CloseSessionFactory()
{
if (sessionFactory != null)
{
sessionFactory.Close();
}
}
}
}

Now if we have all the sessions available we can use it for persisting our objects.

Make a webform from where you want to save your objects.
I called it CallToHibernate.aspx and in the Codebehind class use the following code.

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using NHibernate;
using NHibernate.Cfg;

namespace testa
{
///
/// Summary description for CallToHibernate.
///

public class CallToHibernate : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
ISession currentSession = NHibernateHelper.GetCurrentSession();
ITransaction tx = currentSession.BeginTransaction();

Cat myCat = new Cat();

myCat.Name = "Nina";
myCat.Sex = 'F';
myCat.Weight = 32.23f;

// To persist data to the database
currentSession.SaveOrUpdate(myCat); // or call only the Save method
/* To load data based upon the identifier.
Use the currentSession.Load(object type, object identifier) method.
* */
tx.Commit();

NHibernateHelper.CloseSession();
}

#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}

///
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
///

private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);

}
#endregion
}
}


Now just open your browser and call the CalltoHibernate.aspx page and see the database. You have a Cat in your database named Nina.

This level of abstraction is really appreciable in real world applications.

For any query mail me at
shashank@bnkinfotech.com

Monday, April 23, 2007

Background Worker Class in .NET

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

and here is an example how you can do this:

Step 1: Create an instance of BackgroundWorker class:

private BackgroundWorker bw = new BackgroundWorker();

Step 2: Define DoWorkEventHandler and RunWorkerCompleted events before Page_Render events :

protected override void OnPreLoad(EventArgs e)
{
bw.DoWork += new DoWorkEventHandler(bw_DoWork);

bw.RunWorkerAsync();

bw.RunWorkerCompleted += new
RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);

}

void bw_DoWork(object sender, DoWorkEventArgs de)
{
// Do your background work here
}

void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
BackgroundWorker bgworker = sender as BackgroundWorker;
// Finalization of your backgroundworker
}

Step 4: Also set Async="true" on your aspx page.

Thats it your background worker instance is ready to work.
To read more about BackGroundWorker class go to this link

Monday, April 02, 2007

Apply themes to your ASP.NET Pages

So you want to apply themes in your ASP.NET pages.......
The simplest way to do so is to write the following code in your Page_PreInit function like this:

protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme = "StyleShhetThemeName";
}

So you have done....

Wednesday, March 21, 2007

Implementing Web based Chat System in ASP.NET

So do you want to develop a web based chat application.
First of all I want to tell you something about
COMET.

So what is Comet?

Its a technology to push the data to Client from the Server in a Web Environment.
However a general web based application supports request/response model that is first the client requests than the server gives the response.
But we need the opposite of this.......................Server response without the client's request. There are various ways you can do this thing and a lot of implementation are
here

Tuesday, March 20, 2007

Thinking about Open Source Content Management in ASP.NET

Thinking about Open Source Content Management in ASP.NET:

If you are thinking to have a versatile, User Friendly, Powerful, Feature Rich, Extensible as well as Open Source Content Management then you are looking for:

DotNetNuke

Learn more about DotNetNuke:
http://www.dotnetnuke.com/


View what you can do with DotNetNuke even more than this...at the bottom of this link