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

Thursday, March 15, 2007

Simplest Way to perform Database operations in ASP.NET

This is the simplest way to perform Database operation using C#.NET for beginners.
This function just give you the step by step explanation to perform the database operations. However the best way to perform db operations is to build a business logic and dbOperations layer seperately but for beginners who wants to know how to perform database operations this is the best approach to learn.


private void SaveDataToDB() // Function to perform db operation
{
/* Putting your connection string inside web.config will make the easy transportation of your code without recompilation. you just need to write your connection string once and use it through out your project. Also changing the connection string doesn't need the code compilation however if you will put your connection code in CS file (in the code) you need to recompile the code each time you will migrate from one server to another.
*/

/* Reading Connection String from your configuration settings */
string conn = System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"].ToString();
/*
Or you can specify your connection string directly here.
*/
string query = @"insert into TABLE_BASIC_INFO
(LAST_NAME, FIRST_NAME, EMAIL_ID, NO_OF_CORRECT_ANS, DATE_OF_TEST)
values ('" + tbLastName.Text + "', '" + tbFirstName.Text + "', '" + tbEmailID.Text + "', " +
int.Parse(Session["ScoreQuestionDetail"].ToString())+ ",'" + System.DateTime.Now.ToShortDateString () + "')";

SqlConnection mySqlConnection = new SqlConnection(conn); // New SQLConnection Object
SqlCommand sqlComm = new SqlCommand(query, mySqlConnection);
try
{
mySqlConnection.Open ();
sqlComm.ExecuteNonQuery(); // Performing query to the database
mySqlConnection.Close();
}
catch (SqlException se)
{
Response.Write("Currently Facing Problem with Server " + "
" + se.ToString());
}

// Response.Write("Somewhat Problem with dbOperation "+se.ToString());
}

Tuesday, February 20, 2007

Writing your own JSP Tag Library

Writing your own JSP Tag Library:
This is not too hard to write your own custom tag libraries that can be reused over and over also it is simple enough to do so. Just go step by step and do as said in the tutorial. I have used Tomcat Server so the directory structure may need to be changed.

Step 1:
Write a file with .tld extension that will explain the feature of your tag that you are going to build and place it in tld folder under WEB-INF directory and Name it whatever you want. An example bnk.tld file is :


*********************** Bnk.tld *************************

<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"
"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>BNKTagLib</shortname>
<info>BNK Tag library</info>
<tag>
<name>Repeater</name>
<tagclass>BNK.TAGS.Repeater</tagclass>
<bodycontent>empty</bodycontent>
<info>
This is a simple BNK tag.
</info>
<!-- Optional attributes -->
<!-- personalized name -->
<attribute>
<name>sqlQuery</name>
<required>true</required>
<rtexpvalue>false</rtexpvalue>
</attribute>
<attribute>
<name>cssClass</name>
<required>false</required>
<rtexpvalue>false</rtexpvalue>
</attribute>
</tag>
</taglib>

********************* Bnk.tld **********************

Step 2:

Create a java file that will explain the function as you want by your tag. For example my tag will create a table that will display all the information returned by a query.
And the query is the parameter passed to my tag with the class applied to the tag. These classes need to be placed within the classes subfolder of WEB-INF directory.

********************* Repeater.java **********************
The Repeater.java file will look like this:


package BNK.TAGS;

import javax.servlet.jsp.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.tagext.*;
import javax.servlet.ServletResponse;
import java.sql.*;
import BNK.TAGS.DataAccess;

public class Repeater extends TagSupport
{

private String sqlQuery;
private String cssClass;
/*
Getter Setter for the attributes
*/
public String getSqlQuery()
{
return this.sqlQuery;
}
public void setSqlQuery(String query)
{
this.sqlQuery = query;
}

public String getCssClass()
{
return this.cssClass;
}
public void setCssClass(String css)
{
this.cssClass = css;
}




public int doStartTag() throws JspTagException
{
getSqlQuery();
DataAccess da = new DataAccess(this.sqlQuery);

//DataAccess.DataAccessClassName();
//da.sqlQuery = this.sqlQuery;
ResultSet rs = da.DataAccessQueryFunction();

JspWriter out = pageContext.getOut();
try
{

if (rs != null)
{
int i = 1;

out.println("<table cellpadding='2' border='1' cellspacing='0'" + "class=" + "'"+ cssClass +"'" + ">");

while (rs.next())
{

out.println("<tr>");

out.println("<td>");
out.println(rs.getString("SKILL_ID"));
out.println("</td>");

out.println("<td>");
out.println(rs.getString("SKILL_NAME"));
out.println("</td>");

out.println("</tr>");
i ++;
}

out.println("</table>");
}
else
{
out.println(rs);
}
}
catch (Exception ex)
{
throw new JspTagException("All is not well in the world." + ex.toString() );
}
// Evaluate the body if there is one
return SKIP_BODY;
}

/**
* doEndTag is called by the JSP container when the tag is closed
*/
public int doEndTag(){
try {
//JspWriter out = pageContext.getOut();
//out.println("</table>");
} catch (Exception ex){
throw new Error("All is not well in the world.asdasd");
}
return SKIP_BODY;
}
}
********************* Repeater.java **********************



Also I have used a reference to the DataAccess class that will provide the interface to perform queries to the database and will return a ResultSet containing the result.
This is also need to be placed in the same directory where we put our Repeater.java file.

********************* DataAccess.java *********************
package BNK.TAGS;

import java.sql.*;

public class DataAccess
{
private static String URL = "jdbc:mysql://localhost:3306/Testing?autoReconnect=true";
private static String user = "userName";
private static String password = "password";

public ResultSet results = null;
public String error = "";
public String sqlQuery = "";

public DataAccess(String sql)
{
this.sqlQuery = sql;
}

public ResultSet DataAccessQueryFunction()
{
error += sqlQuery;
try
{
Class.forName ("com.mysql.jdbc.Driver").newInstance();
}

catch (Exception e)
{

}
finally
{
}
try
{
Connection connection = DriverManager.getConnection(URL, user, password);


Statement statement = connection.createStatement();

results = statement.executeQuery(this.sqlQuery);
}
catch (SQLException e)
{
System.err.println("Exception " +e.toString());
error += "<br />" + e.toString();
}

return results;
}
}



********************* DataAccess.java *********************

Step 3:
Calling the tag………………

<%@page contentType="text/html"%>
<%@page pageEncoding="UTF-8"%>

<%--
The next line calls our bnk.tld file so that the repeater control will be available here.
--%>

<%@ taglib uri="/WEB-INF/tld/bnk.tld" prefix="bnk" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>BNK Sample Tag Library</title>
</head>
<body>

<h1> BNK Sample Tag Library </h1>

<bnk:Repeater sqlQuery = "select * from tablename" cssClass="tableClass" />

</body>
</html>

Just watch the output on your web page.

So now you can use this tag wherever required.
Isn’t it simple enough !

Tuesday, February 13, 2007

Javascript window_onbeforeunload Event

<script language=javascript for=window event=onbeforeunload>
return window_onbeforeunload()
</script>
<script>
function window_onbeforeunload()
{
var a = alert('You are about to close this window!');
if(a)
{
window.open(window.location,"_blank");
}
else
{
window.open(window.location,"_blank");
}
}
</script>

In this way you can process any Javascript code just before the browser will get closed.

Friday, February 09, 2007

shashank's Work

1. Betting System for Mindshift Technologies

Duration - 5 Weeks

Front End - ASP.NET 2.0 (using C#)

Database - MS Sql Server 2000

Client - Mindshift Technologies

Project Description: It was a betting system for Mindshift Technologies, in which their employees can bet on the pools created by the administrator and can view the pool results.

Link:http://dev.bnkinfotech.com/Mindshift

2. Kikora Educational Software

Duration - 8 Weeks

Front End - JSP

Database - My Sql

Group - 3 People

Project Description: It was an online mathematical testing system for relatively small children in which the random exercise generation was based upon the input algorithms.

Link:http://delhi.conversationtech.com:8083/Kikora

3. XML File Editing Tool for Arora Board Review

Duration - 4 Weeks

Front End - ASP.NET using C#

Client - Arora Board Review

Project Description: It was an online XML File editing tool that let the user update the XML file.

4. HFT Music Bulk Mailing System

Duration - 3 Weeks

Front End - ASP.NET using C#

Database - MS Sql Server 2000

Client - HFT Music

Project Description: It was a mailing system to send bulk mail at once. It was getting the email address of subscribers through database and send them all the mail.

5. EXTOP for World Bank Publication

Duration - 40 Weeks

Front End - ASP.NET using C#

Database - Oracle 9i

Client - World Bank Publication

Project Description: It was the conversion of an existing workflow management system (in Tickle) of Worldbank Publication house that we converted into ASP.NET version.

6. Dot Net Nuke Skinning Work to provide CMS to the Clients

a. BNK Infotech Pvt. Ltd. Website (http://www.bnkinfotech.com)

b. Global Strategy Project website (demo at http://dev.bnkinfotech.com/gsp/)

c. Skin for Devcomm site of Worlbank (demo at http://dev.bnkinfotech.com/devcomm/)

d. Skin for Outreach site of Worlbank (demo at http://dev.bnkinfotech.com/devoutreach/)

e. Skin for PS Energy Website (demo at http://dev.bnkinfotech.com/PSEnergyF/)

f. Skin for Logsup Website (demo at http://dev.bnkinfotech.com/Logsup /)

g. Skin for Earthday Network Website (demo at http://dev.bnkinfotech.com/earthday/)

h. Skin for Integrated Business Technologies Website (demo at http://dev.bnkinfotech.com/IBT/)

Hi from shashank

Hi! I am Shashank Mishra.