Friday, July 27, 2012

NHibernate Tutorial in .Net With Example For Beginners


NHibernate is an open source Object-Relational Mapping (ORM) tool for the .Net platform. Here each row in the database acts as an object. If we write a sql query to get data from database, it gives list of rows. In nhibernate, we get list of objects insted of rows. Working with nhibernate is very simple. All We need to know is just how to configure the settings. Here i am trying to explain this tutorial from the scratch. Follow the below steps carefully.

Step1: The following are some Requirements to work with Nhibernate
1.Microsoft Visual Studio 2008 or greater
2. SQL Server Management Studio

Note: I am assuming that you already have the above two installations.

Step2: We need Nhibernate library files. You can download these files from following source.


Step3: After downloading Nhibernate library, go to Required_Bins folder

       Path: NHibernate-3.3.1.GA-bin-->Required_Bins

       After opening Required_Bins you will see nhibernate-configuration.xmlnhibernate-mapping.xml files. Copy these two files and paste it into C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas folder.





Step4: Now we need to connect the database. Do the following steps.

Step 4.1: Open the visual studio and right click on view and select server explorer.


Step 4.2: After choosing server explorer you will see the following window. Then right click on Data Connections and select add connection.


Step 4.3: After choosing add connection, you will see the following window. Then select the Microsoft SQL Server and uncheck the "Always use this selection" check box and finally click on continue button.



Step 4.4: After choosing continue button you will see the following window.


Step 4.5: Here you have to fill server name. To get the server name, see next tab below the Data Coonections. Inside Servers root , list of servers will be there.In your system the name may be different.I am showing server name in my system. See the following window.

Step 4.5: Enter your server name.


Note: You should use your server name.

Step 4.6: Select "Use SQL Server Authentication" radio button and fill your username and password. and click ok.


Step 4.7: After choosing ok you will see the following database. 

Step 4.8: So expand the database and right click on tables and select "Add New Table". Then a window will be opened to enter the table fields. In this tutorial i want to use employee table. So fill the details as follows.


Step 4.9: select the first row and set the primary key by clicking on the key symbol.


step 4.10: Again select the empId column in table, and below the table you will see column properties, In that Expand the Identity Specification tab, and change isIdentity to yes.



step 4.11: After changing, Save the table name with Employees.

Now our database part is done!!. 

Step 5: Come to the visual studio. Create a new Project.Then select console application and type the project name as NhibernateTutorial.


Step 6: Right click on the project and click on Add and select class. Then give the class name as employee.



Step 7: Create variables and methods exactly same as below. Here each variable represents a column in the Employee table. So it is better to create field names exactly same as database including capital and small letters. Here you must use virtual keyword. Otherwise it will give error.


Step 8: After creating entity class,we need to write hibernate mapping file. This is an xml file. To create this, right  click on the project and click on Add and select new Item.


Step 9: After choosing new Item,you will see the following window. So select on data which is available at right side and select XML file, and write file name as Employee.hbm.xml as below. 


Step 10: Write the configuration detais as follows.

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="NhibernateTutorial" namespace="NhibernateTutorial">
  <class name="NhibernateTutorial.Employee,NhibernateTutorial" table="Employees">
    <id name="empId" column="empId" type="Int32" unsaved-value="0">
      <generator class="native">
      </generator>
    </id>
    <property name="empName" column="empName" type="String" not-null="true"></property>
    <property name="city" column="city" type="String" not-null="true"></property>
  </class> 
</hibernate-mapping>

Note: You should use your assembly name and namespace name in the above mapping xml.

Explanation: 

Hibernate-mapping tag: It is the root tag for nhibernate mapping xml. It contains three attributes. They are

xmlns: It represents xml namespace. So after writing "xmlns=" in xml file, if we press (ctrl+space bar) it will show list of options from that we can select the urn:nhibernate-mapping-2.2 value.

assembly: It represents the assebly name of your project. You can get this name by right clicking on the project and select properties. You will see the following window.



namespace: It represents the namespace of your project.

Class tag: It represents an entity class, which is the equivalent representation of the table in database. It will take the follwoing attributes.

name: Name attribute takes two parameters. First one is class name and the second one is assembly name.

table: It represents the table name in the database.


Id tag: It represents the primary key in the table.

name: It represents field name in the entity class which is equivalent to the column name in the table.

column: It represents column name in the corresponding table.

type: It represents data type of the field name in entity class which is equivalent to the data type of corresponding column in the database table.
   
unsaved-value: unsaved-value is used to differentiate whether we are going to insert the data or update the data. Here we are setting  it to zero. So if the value is zero then nhibernate assumes that it is a new record. So that it will insert the data. If it is a non zero, then nhibernate assumes that it is an existing record. So it will perform update operation.

generator tag: It represents whether we have to fill the field value or database fills.

class: It represents who will take care of filling the primary key field value. Here the "native" represents database will take care of filling the primary key field.

property tag: It represents the field name in entity class which is equivalent to colum name in the database table.

Step 11: After writing the mapping details, right click on the Employee.hbm.xml file and click on the properties and change the Build Action to embedded resource.


Step 12:  Now we will create a class to get employee data using nhibernate from database. Before creating that class, we need to add some nhibernate library files. It can be done as follows.

Step 12.1: Right click on the References and select Add Reference.


Step 12.2: Then you will see the following window. From this you can select Required_Bins folder from NHibernate-3.3.1.GA-bin, which you downloaded from our website. The Required_Bins folder contains NHibernate.dll. So select that NHibernate.dll and click ok.



Step 13: Now right click on the project and create a new class and name the class as NhibernateDataProvider. Write the follwoing content in the NhibernateDataProvider class.


NhibernateDataProvider.cs Class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Cfg;

namespace NhibernateTutorial
{
    class NhibernateDataProvider
    {
       
        public Employee getEmployeeById(int employeeId)
        {
            ISessionFactory sessionFactory = new Configuration().Configure().BuildSessionFactory();

            ISession session = sessionFactory.OpenSession();
                  
            return session.Get<Employee>(employeeId);
        }
        
    }
}


Step 14: Finally we call the methods in the main method. So go to program.cs and write the following code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NhibernateTutorial
{
    class Program
    {
        static void Main(string[] args)
        {
            NhibernateDataProvider obj = new NhibernateDataProvider();
            Console.WriteLine(obj.getEmployeeById(2).empName);
        }
    }
}

Note: ( Please fill some data in employee table before executing the program).

Step 15: Now the last step is to set up configuration file. This is an xml file. so right click on the project, and select new Item and then click on data and select the xml file. Save the file as hibernate.cfg.xml.



Step 16: Write the following code in it.

hibernate.cfg.xml :

<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=SL-PN-LT-0064;User ID=sa;Password=mysql@123</property>
    <property name="show_sql">false</property>
    <mapping assembly="NhibernateTutorial"/>
  </session-factory>
</hibernate-configuration>

Note: 
1.Here when writing xmlns, if you press (ctrl+space bar) it will give list of options. From that you can select, the value "urn:nhibernate-configuration-2.2"

2. When writing coonection string, you should use your connection string. This connection string you can get by right cliking on the database connection in the visual studion and select properties. From properties window you can copy the connection string and paste in the xml file.

3. Use you assembley name when writing assembly.

Step 17: Right click on the hibernate.cfg.xml and select properties. Then change the Copy to output directory option to "copy always".




Step 18: Finally Run the program.cs file.

Note: ( Please fill some data in employee table before executing the program).
               Here i explained how to work with nhibernate by giving simple example. So if you get this, you can improve your knowledge by reading relationships and mappings in nhibernate.

http://horoscope.vikianswers.com/

Friday, July 20, 2012

JQuery or Ajax Autocomplete Example

JQuery or Ajax Autocomplete Example:

      The autocomplete can be used to add dynamic behaviour to the text box. If i type a character in the text box, the related words for that character we can display as a suggestion. We can set several options like after how many characters results should be displayed,length of the suggestion box, width of the suggestion box. We can limit the number of suggestions to display. The following example shows a list of suggested cities when you enter a character. Follow the below steps to use Jquery autocomplete program.

Step 1: The following three files are needed in this program. They are

1. jquery-ui-1.8.13.custom.css
2. jquery.js
3. jquery-ui-1.8.13.custom.min.js

The above three files you can download from the following source.


Step2: The above folder contains AutoCompleteDemo.html. If you run that page, you will see the following page.






Thursday, July 19, 2012

How to use Google map api tutorials with examples

Google map api tutorials with examples:

        Google map API is used  for several applications like marking a place on google map , making a path between two places,finding the directions  between two plces and many. Here i am explaining two examples.



                         To work with Google map API we need to have the API key. We can get this key by registering the following website.

Step 1: Register in the below website to get the API key.

https://developers.google.com/maps/documentation/javascript/tutorial#api_key

Note: If you go through the above website, it will give several instructions for getting API key. Follow those instructions.

Step 2: Copy the below code into a notepad and save with Any_Name.html. But use your Google map  API Key in place of  "USE_YOUR_KEY".

Example Code1 to Make a Mark on a Particular Place:

<!---------Add a Marker To Google Map--------------->

<!DOCTYPE html>
<html> 
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />


<style type="text/css">

html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#display_here { height: 100% }

</style>

<script type="text/javascript"      src="

http://maps.googleapis.com/maps/api/js?key=USE_YOUR_KEY&sensor=false"></script>   


<script type="text/javascript">
      var map;
function initialize() {


    var latlng = new google.maps.LatLng(17.3667, 78.4667);
    var myOptions = {
        zoom: 8,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP

    };

    map = new google.maps.Map(document.getElementById("display_here"), myOptions);

    var marker = new google.maps.Marker
    (
        {
            position: new google.maps.LatLng(17.3667, 78.4667),
            map: map,
            title: 'Click me'
        }
    );
    var infowindow = new google.maps.InfoWindow({
        content: 'Location info:<br/>Country Name:<br/>LatLng:'
    });
    google.maps.event.addListener(marker, 'click', function () {
        // Calling the open method of the infoWindow
        infowindow.open(map, marker);
    });
}

</script> 
</head>
 
<body onload="initialize()">
<div id="display_here" style="width:100%; height:100%"></div>
</body>


</html>



Output: If you run that html, you will see the following output. (You should have good internet connection)




Explanation:

In the above example, google.maps.LatLng(latitude,longitude) will take latitude and longitude of a place as parameters. Zoom property can be used to increase or decrease the size of the google map image. The google.maps.Map() method will take two parameters HTML ID and Options. Here HTML ID tells where to display google map image. The google.maps.Marker() can be used to mark a place on the google map. Here we can set the position of the marker and title. The google.maps.event.addListener() method can be used to add events to a marker.


 Example Code2 to Make a Path Between Two Places:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />


<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#display_here { height: 100% }
</style>

<script type="text/javascript" src="
http://maps.googleapis.com/maps/api/js?key=USE_YOUR_KEY&sensor=false"></script>   
<script>
  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var hyderabad = new google.maps.LatLng(17.3667, 78.4667);
    var mapOptions = {
      zoom:14,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: hyderabad
    }
    map = new google.maps.Map(document.getElementById("display_here"), mapOptions);
    directionsDisplay.setMap(map);
  }

  function calcRoute() {
    var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
  }
</script>


</head>

<body onload="initialize()">
<div>
<b>Origin: </b>
<select id="start" onchange="calcRoute();">
  <option value="hyderabad, in">hyderabad</option>
  <option value="pune, in">pune</option>
  <option value="chennai, in">chennai</option>
  <option value="delhi,in">delhi</option>
  <option value="goa">goa</option>
</select>

<b>Destination: </b>
<select id="end" onchange="calcRoute();">
  <option value="bangalore, in">bangalore</option>
  <option value="mumbai, in">mumbai</option>
  <option value="calcutta, in">calcutta</option>
    <option value="vizag">vizag</option>
</select>
</div>
<div id="display_here" style="top:30px;"></div>
</body>
</html>

 Output: If you run that html, you will see the following output. (You should have good internet connection)


 Explanation:

       In the above example we need minimum two places to draw a path between them. Here google.maps.DirectionsService().route() will take care of creating path between two places.

Note: use your Google map API Key in place of "USE_YOUR_KEY".

How to Debug nhibernate.hql.ast.antlr.querysyntaxexception?

How to Debug nhibernate.hql.ast.antlr.querysyntaxexception:

    This error may occur, when we have syntactical errors in the query when working with HQL. The following example explains how to resolve this issue.

You may get error, if you write as below:

select * from Employee;

(or)

select e.* from Employee e;

(or)

select from Employee;


Correct Syntax:

select e from Employee e;

Monday, July 16, 2012

How To Stop Receiving Airtel Flash Messages?

How To Stop Receiving Airtel Flash Messages:

   I recently bought an Airtel sim. I am getting flash messages on the screen continuously. To stop this, We  can do the following steps.

Solution:

Step1: Go to Airtel Live!

Step2: Click on Airtel Now

Step3: Click on Start/Stop

Step4: Click on Stop

Thursday, July 12, 2012

Difference between string and stringbuffer in java with example?

Difference between string and stringbuffer in java with example:

   The main difference between String and StringBuffer is, String objects are immutable and StringBuffer objects are mutable. Here Immutable means we can not change the contents of an object. Consider the following example.

Example for String Immutable:

String name1="Hello";   //Hello will be stored in name1

String name2="World";    //World will be stored in name2

name1=name1+name2; //Trying to add something to Hello

System.out.println(name1);

Output:

HelloWorld

             In the above example we said that String objects are immutable, but the content of name1 is changed from Hello to HelloWorld. It is little surprising right?,Here the reason is when we are trying to add two strings a new object is created. Here the new object is HelloWorld. In place of Hello the HelloWorld will be replaced. This will be done internally. We can not notice that.

Example for StringBuffer mutable:

StringBuffer name1=new StringBuffer("Hello"); //Hello will be stored in name1
StringBuffer name2=name1; // We are assigning Hello to name2 also
 name2.append("World"); // We are adding an World to Hello
System.out.println(name1);
System.out.println(name2);


Output:

HelloWorld
HelloWorld

                   In the above example we  are trying to change the contents of name2. Here we are adding World to name2.  When displaying name1, it should print Hello and when displaying name2 it should print HelloWorld. But Cleary Observe, In the above example both name1 and name2 are printing HelloWorld only. Here the reason is, both name1 and name2 are sharing the same object. When we change the content of an object, the same object will be changed. Here new object will not be created.

Nunit can not load file or badimage error?

            This error may occur if we dont have a proper configuration of a project. So right click on the project and select properties, then properties window will be opened as follows.Then click on build you will see the window like this.


Note: Change the Platform target to Any CPU. Your problem will be solved

How to Use Time in C# With Example?

Working With Time in C# Example:

We can use TimeSpan Class to work with time in C#. By using this class we can add two times,we can subtract two times. We can format the time according to hours,minutes,seconds and milliseconds.

Example:
class TimeExample
{
static void Main(string[] args)
{
          /*----------Working With Tim e--------------------*/
TimeSpan time1 = new TimeSpan(1,1,30,30); //Parameters are days,hours,mins,secs
Console.WriteLine("Time With Our Values: "+time1);
TimeSpan time2 = new TimeSpan(1, 30, 30); //Parameters are hours,mins,secs
Console.WriteLine("Time With Our Values: " + time2);
           /*-----------Add Two Times----------------*/
TimeSpan span1 =new TimeSpan(2,3,20); //It is 02:03:20 hr:min:sec
TimeSpan span2 = new TimeSpan(5, 3, 20); //It is 05:03:20 hr:min:sec
TimeSpan span3 = span1.Add(span2); //It is 07:06:40
Console.WriteLine("After Adding two Times: "+span3);
}
}

Output:

How to Use Date and Time in C# With Example?

Working With Date in C# Example:

 We can use DateTime Class in C# to work with date and time. From that we can get today's date. If we want yesterday's date we can add -1 to current date. If we want tomorrow's date we can simply add 1 to the current date. The following example illustrates how to work with date and time in c#.

Example Code:
  
class DateAndTimeExample
{
static void Main(string[] args)
{
   /*----------Working With Date--------------------*/
       
DateTime value = new DateTime(2012,2, 25);
Console.WriteLine("Date With Our Values:"+value); //It will print date with our values
Console.WriteLine("Today's Date:" + DateTime.Today);
Console.WriteLine("Tomorrow Date:" + DateTime.Today.AddDays(1));
Console.WriteLine("Yesterday Date:" + DateTime.Today.AddDays(-1));
}
}
Output: