Interview Question of .NET
|
|
comments (0)
|
Cookies
Definition: – A cookie is information that a Website puts on your hard disk so that it can remember something about you at a later time. (More technically, it is information for future use that is stored by the server on the client side of a client/server communication.)
In short, Cookie is client’s information for particular site stored on client’s PC.
Typically, a cookie records your preferences when using a particular site. Using the Web’s Hypertext Transfer Protocol (HTTP), each request for a Web page is independent of all other requests. For this reason, the Web page server has no memory of what pages it has sent to a user previously or anything about your previous visits. A cookie is a mechanism that allows the server to store its own information about a user on the user’s own computer.
Procedure:- following are steps show how cookies works
When you visit some site, server for that site stores information (user name or simply physical address of user’s pc) in 1 text file. For that, that site may ask you to fill details about yourself or it can simple fetch physical address of your computer.Server sends this file to client with web page and that file is saved in client’s pc.Now when user visits that website again, that cookie file is also sent to server with the web page request. From that file, website’s sever can identify that particular user and do further procedures (Ex. Prepare customized webpage for that user) using that information.
Session
Definition: – A session is information of user that a Website puts on its temporary memory so that it can remember something about you when you are visiting that site. (More technically, it is information for future use that is stored by the server on the server side of a client/server communication.)
In short, Session is client’s information for particular site stored on Server’s temporary memory. The period of time a user interfaces with an application. The user session begins when the user accesses the application and ends when the user quits the application The number of user sessions on a site is used in measuring the amount of traffic a website gets. The site administrator determines what the time frame of a user session will be (e.g., 30 minutes). If the visitor comes back to the site within that time period, it is still considered one user session because any number of visits within those 30 minutes will only count as one session. If the visitor returns to the site after the allotted time period has expired, say an hour from the initial visit, then it is counted as a separate user session. Contrast with unique visitor, hit, click-through and page view, which are all other ways that site administrators measure the amount of traffic a Web site gets. Example:- When you visit www.gmail.com , you have to enter your account ID and password first. That information is verified on server and stored on server in session until that user is logged on.
What is the difference between session and cookie?
If you set the variable to “cookies”, then your users will not have to log in each time they enter your community. The cookie will stay in place within the user’s browser until the user deletes it.
But Sessions are popularly used, as the there is a chance of your cookies getting blocked if the user browser security setting is set high.
If you set the variable to “sessions”, then user activity will be tracked using browser sessions, and your users will have to log in each time they re-open their browser. Additionally, if you are using the “sessions” variable, you need to secure the “sessions” directory, either by placing it above the web root or by requesting that your web host make it a non-browsable directory.
The Key difference would be cookies are stored in your hard disk whereas a session aren’t stored in your hard disk. Sessions are basically like tokens, which are generated at authentication. A session is available as long as the browser is opened.
1) session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. there is no way to disable sessions from the client browser.
2) session and cookies differ in type and amount of information they are capable of storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store String objects
Explain the access specifiers Public, Private, Protected, Friend, Internal, Default?
The main purpose of using access specifiers is to provide security to the applications. The availability (scope)of the member objects of a class may be controlled using access specifiers.
1. PUBLIC
As the name specifies, it can be accessed from anywhere. If a member of a class is defined as public then it can be accessed anywhere in the class as well as outside the class. This means that objects can access and modify public fields, properties, methods.
2. PRIVATE
As the name suggests, it can't be accessed outside the class. Its the private property of the class and can be accessed only by the members of the class.
3. FRIEND/INTERNAL
Friend & Internal mean the same. Friend is used in VB.NET. Internal is used in C#.Friends can be accessed by all classes within an assembly but not from outside the assembly.
4. PROTECTED
Protected variables can be used within the class as well as the classes that inherites this class.
5. PROTECTED FRIEND/PROTECTED INTERNAL
The Protected Friend can be accessed by Members of the Assembly or the inheriting class, and ofcourse, within the class itself.
6. DEFAULT
A Default property is a single property of a class that can be set as the default. This allows developers that use your class to work more easily with your default property because they do not need to make a direct reference to the property. Default properties cannot be initialized as Shared/Static or Private and all must be accepted at least on argument or parameter. Default properties do not promote good code readability, so use this option sparingly.
Whats the difference between Classic ASP and ASP.NET?
Major difference: Classic ASP is Interpreted. ASP.NET is Compiled. If code is changed, ASP.NET recompiles, otherwise does'nt.
Other differences: ASP works with VB as the language. ASP.NET works with VB.NET & C# as the languages (Also supported by other languages that run on the .NET Framework).
ASP.NET is the web technology that comes with the Microsoft .NET Framework. Themain process in ASP.NET is called aspnet_wp.exe that accesses system resources. ASP.NET was launchedin 2002 with version 1.0. Subsequent versions are 1.1 and version 2.0. ASP.NET is built upusing thousands of objects, ordered in the System namespace. When an ASP.NET class is compiled, itscalled an assembly.
In Classic ASP, complex functionalities are achieved using COM components, that are nothingbut component objects created using VB 6, C++ etc, and are usually in a DLL format. Thesecomponents provide an exposed interface to methods in them, to the objects that reference thesecomponents. Last version of classic ASP is version 3.0. ASP has 7 main objects - Application, ASPError, ObjectContext, Request, Response, Server, Session.
Dynamically setting the "editoption" 'value' field for a select box in jqgrid with AJAX call
|
|
comments (1)
|
<script type="text/javascript">
$(function() {
var data1 = '';
var tmp = 'Select:Select Course;';
$.ajax({
type: "POST",
url: "AddAEP.aspx/GetCourses",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
data1 = msg.d.split(";");
for (var i = 0; i <= data1.length - 1; i++) {
tmp = tmp + data1[i] + ";";
}
tmp = tmp.substring(0, tmp.length - 1);
}
});
$("#InstructorGrid").jqGrid({
url: '../Handler/InstructorHandler.ashx',
datatype: 'json',
height: 300,
width: 1000,
colNames: ['InstructorID', 'Date', 'CourseName', 'CourseNumber', 'Instructor', 'Comments', 'Actions'],
colModel: [
{ name: 'InstructorID', index: 'InstructorID', width: 100, sortable: false, hidden: true },
{ name: 'Date', width: 100, sortable: false, editable: true, editrules: { required: true, date: true, datefmt: 'd-M-Y'} },
{ name: 'CourseName', width: 150, editable: true, editrules: { required: false }, edittype: "select", formatter: "select", editoptions: { value: tmp} },
{ name: 'CourseNumber', width: 100, editable: true, editrules: { required: false }, edittype: "select", editoptions: { dataUrl: "../Handler/Select.txt"} },
{ name: 'Instructor', width: 100, editable: true, editrules: { required: false }, edittype: "select", editoptions: { value: "UserHandler.ashx/GetAllUserName1"} },
{ name: 'Comments', width: 250, editable: true, edittype: "textarea", editoptions: { rows: "5", cols: "30"} },
{ name: 'Actions', width: 100 }
],
rowNum: 25,
rowList: [25, 35, 45],
pager: '#InstructorGridPager',
//sortname: 'StudentID',
viewrecords: true,
mtype: "GET",
editurl: '../Handler/InstructorHandler.ashx',
gridview: true,
sortorder: 'asc',
caption: 'Instructor',
//loadComplete: function(data) {
// alert("safdewrfe");
//$("#InstructorGrid").setColProp('CourseName', { editoptions: { value: "A:A"} });
//},
col: {
caption: "Show/Hide Columns",
bSubmit: "Submit",
bCancel: "Cancel"
}
});
$("#InstructorGrid").jqGrid('navGrid', '#InstructorGridPager', { edit: true, add: true, del: true });
options = { autosearch: true };
$("#InstructorGrid").filterToolbar(options);
});
</script>
WebMethod:
[WebMethod ]
public static string GetCourses()
{
string Users = "";
string connectionString = SQLHelper.getConnetionString();
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
//command.CommandText = "User_GETAllUser";
command.CommandText = "SELECT CourseTitle FROM CourseCatalog";
//command.CommandType = CommandType.StoredProcedure;
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
string user;
while (dataReader.Read())
{
user = Convert.ToString(dataReader["CourseTitle"]);
Users += user + ":" + user + ";";
}
Users = Users.Substring(0, Users.Length - 1);
}
}
return Users;
}
JQuery Flot Charts with Time Series
|
|
comments (0)
|
Flot is an awesome library to produce the simple charts based on the great JQuery.
Using the date/time data (e.g. X-axis data type) is a little difficult to get working right but after exchanging the emails with the developer of the Flot library, I got it right and this solution I couldn’t find anywhere on Google/Bing.
Here’s the code snippet and I hope this helps.
This example uses our OLD json-based asmx ASP.Net service (sorry, I didn’t need to use WCF).
You may have to tweak this code to suite your needs.
1: function LoadCharts() {
2: $.ajax({
3: type: "POST",
4: contentType: "application/json; charset=utf-8",
5: url: "SomeService.asmx/ChartData",
6: data: "{dataFor: 'blah'}",
7: success:
8: function(msg) {
9: ProcessCharts($.evalJSON(msg).d);
10: },
11: error:
12: function(XMLHttpRequest, textStatus, errorThrown) {
13: alert(XMLHttpRequest.responseText);
14: }
15: });
16: }
17:
18: function ProcessCharts(tables) {
19: var plot0, plot1, plot2;
20: //Assume I've 3 tables in the result.
21: $(tables).each(function(i) {
22: var data = tables[i].Data;
23: var plotData = [];
24: var offset = new Date().getTimezoneOffset() * 60 * 1000;
25:
26: //TODO: find a simple better way in jquery to do this.
27: for (var j = 0; j < data.length; j++) {
28: var d = data[j].Date; //my case the date is 20090101 format
29: d = d.substr(4, 2) + "/" + d.substr(6, 2) + "/" + d.substr(0, 4);
30: var date = new Date(d).getTime() - offset;
31: tables[i].Data[j].Date = date;
32:
33: plotData.push([date, data[j].Val]);
34: }
35: var previousPoint = null;
36: var lbl = "";
37: var options = {
38: colors: ['#123658', '#000000'],
39: series: {
40: lines: { show: true, lineWidth: 2 },
41: points: {
42: show: true
43: }
44: },
45: shadowSize: 5,
46: grid: {
47: hoverable: true,
48: clickable: false,
49: borderWidth: 1,
50: backgroundColor: '#ddf0ff'
51: },
52: legend: {
53: show: false
54: //"nw"
55: },
56: xaxis: {
57: mode: "time",
58: timeformat: "%m/%d/%y",
59: minTickSize: [1, "day"]
60: }
61: };
62: var InitChart = function() {
63:
64: $("#Chart" + i).remove();
65:
66: return $.plot($("#Chart" + i),
67: [{ data: plotData, label: lbl }],
68: options
69: );
70: }
71: //I've more tables in my case so change this code as per your need
72: switch (i.toString()) {
73: case "0":
74: lbl = "Label1";
75: plot0 = InitChart();
76: break;
77: default:
78: break;
79: }
80:
81: $("#Chart" + i).bind("plothover", function(event, pos, item) {
82: if (item) {
83: if (previousPoint != item.datapoint) {
84: previousPoint = item.datapoint;
85:
86: $("#tooltip").remove();
87: var x = item.datapoint[0], y = item.datapoint[1];
88:
89: var d = new Date();
90: d.setTime(x + offset);
91:
92: showTooltip(item.pageX, item.pageY, "Total " + item.series.label + " of " + d.toDateString() + " is " + addCommas(y));
93: }
94: }
95: else {
96: $("#tooltip").remove();
97: previousPoint = null;
98: }
99: });
100: });
101:
102: }
103:
104: function showTooltip(x, y, contents) {
105: $('<div id="tooltip">' + contents + '</div>').css({
106: 'absolute',
107: display: 'block',
108: "z-index": 10,
109: top: y + 5,
110: left: x + 5,
111: border: '1px solid #e17009',
112: padding: '3px',
113: 'background-color': '#fee',
114: opacity: 0.70,
115: margin: '5px',
116: 'font-size': '10px'
117: }).appendTo("body").fadeIn(200);
118: }
Introduction to JSON
|
|
comments (0)
|
Introduction
As we know Ajax is a web development technology that makes the server responses faster by enabling the client-side scripts to retrieve only the required data from the server without retrieving a complete web page on each request, which will minimize the data transferred from the server.
These requests usually retrieve xml formatted response, the xml responses are then parsed in the JavaScript code to render the results. Which complicate the JavaScript code
The idea of JSON (JavaScript Object Notation) is to make the response a specific data structure that can be easily parsed by the JavaScript code.
Advantages
1- lightweight data-interchange format
2- Easy for humans to read and write
3- Easy for machines to parse and generate
4- JSON can be parsed trivially using the eval() procedure in JavaScript
5- JSON Supports: ActionScript, C, C#, ColdFusion, E, Java, JavaScript, ML, Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Lua.
.
Syntax
The JSON Syntax is the convention which you will use it to generate data, it’s near to the C family language, so it can be parsed easily in the C family languages.
For objects start the object with “{“ and end it with “}”
object
{}
{ members }
· For members (properties), use pairs of string : value and separate them by commas
members
string : value
members , string : value
· For arrays put the arrays between []
array
[]
[ elements ]
· For elements put the values directly separated by commas
elements
value
elements , value
· Values can be string, number, object, array, true, false, null
EXAMPLESJSON
{"menu": {
"id": "file",
"value": "File:",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"} ]
}
}}
XML<menu id="file" value="File" > <popup> <menuitem value="New" onclick="CreateNewDoc()" /> <menuitem value="Open" onclick="OpenDoc()" /> <menuitem value="Close" onclick="CloseDoc()" /> </popup></menu>
Server side codeThe following code will be generated in the server side to retrieve the server time, and in one step in the client side it will be rendered to JavaScript
Java <%@ page language="java" import="java.util.*" %>
<%Date date = new Date(); %>alert("The server time is: <%Úte%>");
<SPAN style="mso-tab-count: 1"> ASP.NET<%@ page language="C#" %> alert("The server time is: <%=System.Date.Now.ToString()%>");
PHPalert("The server time is: <?=time()?>");
Client Side JavaScript//XMLHttpRequest completion function
var myOnComplete = function(responseText, responseXML){eval(responseText);}
http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=11
Tutorial on NHibernate and FluentNhibernate
|
|
comments (0)
|
This tutorial will be well-understood with a project , that can be downloaded from here
Background :In the past we all have spent a considerable amount of time writing a data access layer for our application. The overall time spent developing data access code could easily be 30% of the overall time used to implement the solution. There is one problem with this fact. Data access code is nothing special, nothing that adds business value to your application. (Nearly) every business application needs some kind of data access. So why would we continue to spend such a huge amount of time writing boring data access code?
NHibernate can and will take away the burden of our shoulders. Never again you will have to write and maintain stored procedures. Never again you will deal with ADO.NET and the like. When using a modern ORM tool you can concentrate on the core elements of an application, the ones that provide real business value. You can concentrate on the model of the business domain and the business rules there in. But this is enough for now. Let’s start to introduce NHibernate and its sister Fluent NHibernate. To make this introduction a little bit more realistic let’s first find an interesting domain. The domain should be well known to most of you people. What else could be a better fit that an order entry system? At the same time – to not make things too complicated – I have to define a rather simplistic order entry system. So let’s start.
Object Model first approach :One important change to consider when you develop a so called green-field application (a new application) is that you normally start with the object model of the domain for which you want to develop the application. In the past most of the time the data model was developed first. So you started with the entity relationship diagram (ERD). On top of that the application was then built. But in this article we want to first concentrate on the object model and let the database schema be generated automatically by NHibernate based on the object model. Don’t misunderstand me; I am not saying that one cannot use NHibernate to develop applications the other way around. NHibernate is also able to deal with the situation where there already is an existing data model and one has to build an application on top of this.
Mapping the domain model :Once we have our domain model in place we want to be able to store the state (of this model) in some place. Very often this is done by using a relational database management system (RDBMS) like SQL Server, Oracle, IBM DB2 or MySql to name just a few. When you are using NHibernate it doesn’t really matter which database product you’re going to use since NHibernate supports most of the well known database products. Your application will not be tied to a specific database.
NHibernate in a Nutshell :
NHibernate is an Object-relational mapping (ORM) solution for the Microsoft .NET platform,it provides an easy way to use framework for mapping an object-oriented domain model to a traditional relational database. NHibernate is a .NET based object persistence library which helps to persist our .NET objects to and from an underlying relational database. Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.
“If we use an RDBMS to store our data (or state) then the data is stored in tables. Thus we have to map our object model to corresponding tables in the database. This mapping doesn’t necessarily have to be one to one (and most often it is not). That is we do not always have mapping where one object maps to one table. Very often the content of one table maps to different object.”
FluentNHibernate in a Nutshell :
To be formal – “Fluent NHibernate provides a way for you no longer need to write the standard NHibernate mapping file (. Hbm.xml), but you can use the C # mapping file to write. Doing so, facilitate the reconstruction of our code to provide the code readability, and streamlining the project code.”
The greatest advantage of FluentNHibernate is – the mapping is type-safe since it is not based on strings.
In the past the mapping between the object model and the underlying database has been mainly done by defining XML documents.
Fluent NHibernate canceled the xml file.
Why needs to replace the XML file?
a. XML is not real-time compiled. When your XML configuration file has errors, you can see only in the run-time what went wrong.
b. XML is very cumbersome. Indeed, in the NHibernate configuration file, xml node is very simple, but still can not cover up the cumbersome nature of XML file itself.
c. Repeat mapping file attributes set. For example, in xml, we need to set for each string type fields are not allowed to be empty, the length is greater than 1000, int type had to have a default value is -1, the end of the xml configuration file so you will find a lot of repetition work.
one can define the mappings in C# which is a full blown programming language and not only a data description language as XML is. This fact opens the door for many – previously unthinkable – possibilities since the mapping can now contain logic.
Step By Step Approach:
Now we will build a very simple web application which will store, update, read and delete Car data using NHibernate and FluentNhibernate.
Step 1:
From the VS editor we will create a new web application. We will add reference of NHibernate and FluentNhibernate from here……
Step 2:
We will create a new class file by giving a name “Tables.cs”. In this class file we will add all the classes that we planned to map to the Database. At first we will create a very simple class named “Car” with properties (all class should contain property)
public class Core
{
public virtual int Id { get; set; }
}
public class Car : Core
{
public virtual string Title { get; set; }
public virtual string Description { get; set; }
}
Step 3:
Ok, so now we have to tell NHibernate how to map our entities to the database. We’re going to use the FluentNHibernate interface to do this, so all configuration is in code. We will create another class such as CarMap that inherits ClassMap<Car>. This is what lets FluentNHibernate know to use these mappings with the Car class we’ve just defined. If we look at the configuration, it’s saying what’s the Id field. Handily called Id in this example. NHibernate has the ability to generate auto Ids and there are many options which are beyond our scope here. Lets have look to the code below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Mapping;
namespace NHibernateTutorial
{
public class CarMap : ClassMap<Car>
{
public CarMap()
{
LazyLoad();
Id(x => x.Id);
Map(x => x.Title).Not.Nullable().Length(100);
Map(x => x.Description);
Table(“Car”);
}
}
}
With this statement we define the mapping of the property Title which is mandatory and thus cannot be null. We also tell the system that its maximal length is 100 characters. If we do not explicitly define the name of the column in the corresponding table on the database will be the same as the name of the mapped property. In our case this is Title. Of course this can be changed anytime by using the appropriate syntax.
You might wonder what the LazyLoad() means. A Lazy Load interrupts this loading process for the moment, leaving a marker in the object structure so that if the data is needed it can be loaded only when it is used. I recommend you to read this Article1 & Article2 to know more about lazy loading.
LazyLoad() is an optional field.
Step 4:
Now the challenge appears- we need to tell NHibernate how to connect to the database.
At First We have to choose the Database. Here I have used SQLEXPRESS 2008 which is provided with VS 2010. Here I have created a database named ”nhub”. We will access this database through Server Explorer of the VS Editor.
Here is the place where we will apply our business logic and reduce the number and necessity of writing cumbersome stored procedures.
When we impose CRUD on RDBMS through NHibernate, all the operations is held by the NHibernate Session (Nhibernate session is different from ASP.NET session and they are totally different). It may be easier to think of a session as a cache or collection of loaded objects relating to a single unit of work. NHibernate can detect changes to the objects in this unit of work..To handle these sessions we will use some interfaces that comes form NHibernate.These interfaces are the main point of dependency of application business/control logic on NHibernate.
Five basic Interfaces used as shown in the figure below; where IQuery and ICriteria performs the same operation.
ISession interface
1. The ISession interface is the primary interface used by NHibernate applications, it exposes NHibernates methods for finding, saving, updating and deleting objects.
2. An instance of ISession is lightweight and is inexpensive to create and destroy. This is important because your application will need to create and destroy sessions all the time, perhaps on every ASP.NET page request. NHibernate sessions are not thread safe and should by design be used by only one thread at a time. The NHibernate notion of a session is something between connection and transaction.
3. We sometimes call the ISession a persistence manager because it’s also the interface for persistence-related operations such as storing and retrieving objects. Note that a NHibernate session has nothing to do with an ASP.NET session.
ISessionFactory interface
1. The application obtains ISession instances from an ISessionFactory. Compared to the ISession interface, this object is much less exciting.
2. The ISessionFactory is certainly not lightweight! It’s intended to be shared among many application threads. There is typically a single instance of ISessionFactory for the whole application-created during application initialization, for example. However, if your application accesses multiple databases using NHibernate, you’ll need a SessionFactory for each database.
3. The SessionFactory caches generated SQL statements and other mapping metadata that NHibernate uses at runtime.
4. It can also hold cached data that has been read in one unit of work, and which may be reused in a future unit of work or session. This is possible if you configure class and collection mappings to use the second-level cache.
ITranscation interface
1. The ITransaction interface, next to the ISession interface. The ITransaction interface is an optional API. NHibernate applications may choose not to use this interface, instead managing transactions in their own infrastructure code.
2. A NHibernate ITransaction abstracts application code from the underlying transaction implementation-which might be an ADO.NET transaction or any kind of manual transaction-allowing the application to control transaction boundaries via a consistent API. This helps to keep NHibernate applications portable between different kinds of execution environments and containers.
IQuery and ICriteria interfaces
1. The IQuery interface gives you powerful ways of performing queries against the database, whilst also controlling how the query is executed.
2. It is the basic interface used for fetching data using NHibernate. Queries are written in HQL or in the native SQL dialect of your database. An IQuery instance is lightweight and can’t be used outside the ISession that created it. It is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.
3. The ICriteria interface is very similar; it allows you to create and execute object-oriented criteria queries.
Now, I will discuss some points from my written code for configuring the FluentNibernate . We have create a class called ModelClass:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
namespace ModelClass
{
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
InitializeSessionFactory();
return _sessionFactory;
}
}
private static void InitializeSessionFactory()
{
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(
@”Server=fire-3\sqlexpress;Database=nhub;Trusted_Connection=True;”)
.Mappings(m =>
m.FluentMappings
.AddFromAssemblyOf<Car>())
.ExposeConfiguration(cfg => new SchemaExport(cfg)
.Create(true, true))
.BuildSessionFactory();
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
}
There’s quite a bit going on here. .Database(MsSqlConfiguration.MsSql2008 is where we tell NHibernate to use the SQL Server driver, there are numerous others, including MySql and SQLLite which are the popular one’s I’m aware of. The .ConnectionString is obvious we’re connecting to the database we defined above.
The next bit is optional .ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true,true)) tells NHibernate to actually create the tables in the database if they’re not there. We don’t really want to leave this on otherwise eachtime we run our app it’ll drop the tables with all our Cars in them and recreate them. the Create(true,true) also refers to whether to show the SQL generated to drop the tables, which we’ve turned on so we can see it work its magic.
Finally we BuildSessionFactory() which will build the session factory and we assign it to a static variable so as to only use one Session for the lifetime of our application
Step 5:
All configuration is completed so far, now we will create a very simple webpage that prompt a user to create a table name “Car” for the first time if the table does not exist and then insert data into “Car” table.
We create a page just like below
<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<p> Add Car</p>
<table>
<tr>
<td>
Title
</td>
<td>
<asp:TextBox ID=”txtTitle” runat=”server”></asp:TextBox>
</td>
<td>
Description
</td>
<td>
<asp:TextBox ID=”txtDesc” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID=”btnSave” runat=”server” Text=”Save” onclick=”btnSave_Click” />
</td>
</tr>
</table>
<asp:Label ID=”lblsatat” runat=”server” Text=”" ForeColor=”#FF5050″></asp:Label>
</asp:Content>
Step 6:
Now in the “ModelClass.cs” we will add this piece of code to add Car to the “Car” table.
public static void Add<T>(T entity)
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Save(entity);
transaction.Commit();
session.Flush();
session.Close();
}
}
We will add an event in the Page Class which will fire when the Save button is clicked
protected void btnSave_Click(object sender, EventArgs e)
{
Create(txtTitle.Text.ToString(), txtDesc.Text.ToString());
}
}
Notice we’re using the Session we just new up a Car class simply give it a name and then session.Save(entity) but note that it doesn’t actually get added to the database until you Commit the Transaction.
There’s a simple order here:
Open SessionBegin TransactionDo SomethingCommit the TransactionClose the transactionClose the SessionNow because we have a using statement we’re automatically calling Dispose on the Transaction and the session. The session.save(entity) figures out the appropriate SQL to generate for us.
Step 7:
This time we will recreate the “Car” class and create another class “Manufacturer”. We will assume that A Car has a Manufacturer and it is a One to Many relation.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using NHibernate;
using NHibernate.Linq;
namespace NHibernateTutorial
{
public class Core
{
public virtual int Id { get; set; }
}
public class Car : Core
{
public virtual string Title { get; set; }
public virtual string Description { get; set; }
public virtual Manufaturer ManuFacturedBy { get; set; }
}
public class Manufaturer : Core
{
public virtual string Name { get; set; }
}
}
Step 9:
We have to Map the classes again like below -
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FluentNHibernate.Mapping;
namespace NHibernateTutorial
{
public class CarMap : ClassMap<Car>
{
public CarMap()
{
Id(x => x.Id);
Map(x => x.Title).Not.Nullable().Length(100);
Map(x => x.Description);
References(x => x.ManuFacturedBy).Column(“ManufacturerID”).Not.LazyLoad();
Table(“Car”);
}
}
public class ManufaturerMap : ClassMap<Manufaturer>
{
public ManufaturerMap()
{
Id(x => x.Id);
Map(x => x.Name);
Table(“Manufacturer”);
}
}
}
Step 10:
We will write the following code to save data now-
public void Create(string carTitle, string carDesc)
{
Car cr = new Car();
cr.Title = carTitle;
cr.Description = carDesc;
cr.ManuFacturedBy = new Manufaturer { Name = this.txtMan.Text.ToString() };
ModelCode.Add<Manufaturer>(cr.ManuFacturedBy);
ModelCode.Add<Car>(cr);
}
Here, “cr.ManuFacturedBy = new Manufaturer { Name = this.txtMan.Text.ToString() }” is initaing the “Car” object with “Manufacturer” object. While saving data we have to save the manufacturere object first then Car object.
Step 11:
Now we will retrieve data from the database. to show the data we first add a GridView named “gdvShowCar” to a newly created Webform “ShowCar.aspx”.
Now we will add a method named “Get” in out ModelCode class.
public static IList<T> Get<T>()
{
IList<T> centers;
using (ISession session = OpenSession())
{
centers = session.CreateCriteria(typeof(T))
.List<T>();
}
return centers;
}
This method will return a list to us. the CreateCriteria() take a class which will be queried as a parameter and return an ICriteria Object.
Now in “ShowCar.aspx.cs” we will write -
public partial class ShowCar : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
LoadData();
}
public void LoadData()
{
IList<Car> Icar = ModelCode.Get<Car>();
var cars = from car in Icar select new { car.Title, car.Description };
gdvShowCar.DataSource = cars;
gdvShowCar.DataBind();
}
}
This code will fill the griedview with data.
Step 12:
Now we will update data . we will first create a page named ”UpdateCar”. there we will create a drop down list of Car’s name. We will select a name from the list and update data according to this particular Car name.
<%@ Page Title=”" Language=”C#” MasterPageFile=”~/Site.Master” AutoEventWireup=”true” CodeBehind=”UpdateCar.aspx.cs” Inherits=”NHibernateTutorial.UpdateCar” %>
<asp:Content ID=”Content1″ ContentPlaceHolderID=”HeadContent” runat=”server”>
</asp:Content>
<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>
<p> Update Car</p>
<table>
<tr>
<td>
Title
</td>
<td>
<asp:DropDownList ID=”ddlCarTitle” runat=”server” AutoPostBack=”True”></asp:DropDownList>
</td>
<td>
Description
</td>
<td>
<asp:TextBox ID=”txtDesc” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
Manufacturer Name:
</td>
<td>
<asp:TextBox ID=”txtMan” runat=”server”></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID=”btnSave” runat=”server” Text=”Save” onclick=”btnSave_Click” />
</td>
</tr>
</table>
</asp:Content>
we did not bind data to the dropdownlist yet. To do that we will simply call the “Get” method fromModelCode class.
we can write -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
initData();
}
}
public void initData()
{
IList<Car> cars = ModelCode.Get<Car>();
ddlCarTitle.DataSource = cars.ToList();
ddlCarTitle.DataTextField = “Title”;
ddlCarTitle.DataValueField = “Id”;
ddlCarTitle.DataBind();
}
The DropDownList is filled with data now. Next, we have to Load our text boxes with appropriate data. For this we will create an overloaded method of “Get” inside the “DataModel” class. this method may looks like below -
public static IList<T> Get<T>(string property, object value)
{
IList<T> centers;
using (ISession session = OpenEngineSession())
{
centers = session.CreateCriteria(typeof(T))
.Add(Restrictions.Eq(property, Convert.ToInt32(value)))
.List<T>();
}
return centers;
}
the eq() searches a match for the (property,value) pair and return a List. It works like traditional WHERE clause with a SELECT statement.
Now we will create an method in the page class named “LoadCarInfo” this method will load data on form when the DropDownList of Name is being populated.
public void LoadCarInfo()
{
var inv = ModelCode.Get<Car>(“Id”, this.ddlCarTitle.SelectedItem.Value.ToString());
if (inv.Count > 0)
{
txtDesc.Text = inv[0].Description;
txtMan.Text = inv[0].ManuFacturedBy.Name;
}
}
Now , time to UpDate data. This very similar to “Add” in the ModelCode class.
We will add another method to “ModelCode”. It is very easy and understandable.
public static void Update<T>(T entity)
{
using (ISession session = OpenSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Update(entity);
transaction.Commit();
session.Flush();
session.Close();
}
}
So now we can call this “Update” from our Page Class as before-
protected void btnSave_Click(object sender, EventArgs e)
{
var inv = ModelCode.Get<Car>(“Id”, this.ddlCarTitle.SelectedItem.Value.ToString())[0];
inv.Description = txtDesc.Text;
inv.ManuFacturedBy.Name = txtMan.Text;
ModelCode.Update<Manufaturer>(inv.ManuFacturedBy);
ModelCode.Update<Car>(inv);
}
Step 13:
Now we will Delete data. We will add another method in “ModelCode”.
public static void Remove<T>(T entity)
{
using (ISession session = OpenEngineSession())
using (ITransaction transaction = session.BeginTransaction())
{
session.Delete(entity);
transaction.Commit();
session.Flush();
session.Close();
}
}
Conclusion:
Here I have tried to given some basic CRUD operation using NHibernate and FluentNHibernate. Many thing is left and overlooked intentionally because the limitation of my scope. Actually It takes time to be expert and skilled with these technology.
DownLoad FullCode.