Fluent Nhibernate Made Easy

fluent-nhibernate

Progressing from using NHibernate to Fluent NHibernate is a practical way of not using XML files. For people like me, who are not very comfortable using XML files, Fluent NHibernate gives the opportunity to map your domain class entities through traditional C# classes. So lets start by specifying the requirements to complete this tutorial:

Requirements for this Tutorial:

  • NuGet Package Manager (unless you already have Fluent NHibernate)
  • Visual Studio 2010
  • MS SQL 2005 or 2008

Note: If you have never used NHibernate at all, I suggest you start from my previous tutorial NHibernate made easy

This tutorial will be very similar the the previous one, however it will include all changes required to use Fluent NHibernate rather than NHibernate. Continue reading

Nhibernate simple Select, Insert, Update and Delete

nhibernate

Nhibernate is one of the many Object-Relational Mapping (ORM) tools for the .NET platform.

A very quick description of ORM:

ORM is the process of mapping objects to database relations without the requirement of writing SQL statements (such as SELECT, INSERT, UPDATE, DELETE, JOIN, etc etc) generally through the use of XML files.

Nhibernate eliminates the requirement of using ADO.NET, Linq, etc and thus is the back bone of the Data Access Layer (in nThier Architectures).

Requirements for this Tutorial:

This tutorial will be split in 12 steps:

Step 1:- Create a 2-Thier Project

Step 2:- Install Nhibernate

Step 3:- Define Business Objects (Domain Folder)

Step 4:- Define the Mapping (Mappings Folder)

Step 5:- Setting XML Schema

Step 6:- Configure Nhibernate

Step 7:- Create ISessionFactory

Step 8:- Create Table from Schema and Test Connection

Step 9:- Create Repositories

Step 10:- Define Method from Repositories

Step 11:- Testing Add, Update, Delete Method

Before we continue, I want to add that “I know this is a very long and mostly text based tutorial” but I have searched the internet sooo much for a decent working tutorial without errors and complications that this post here should cover it ALL … I also did it again while writing it to make sure no errors are found. So, hold on and read through… EVERYTHING should be there 🙂

So, lets begin …

Continue reading

Simple MVC and Razor with Database Connection for Simple Insert, Update and Delete.

Model View Controller

If you are new in MVC (Model View Controller) then this tutorial is the ideal for you. I had issues in finding one single tutorial with all my questions so I decided to put one together myself. This tutorial might seem long however, most of the tutorials is full of images to help you visualize better so in order words, it is not as long as it might look like on your scroll bar 😉 Goodluck and hope you find no issues… if you do, feel free to leave a comment and I will be glad to help where possible.

Continue reading

Error: system.data.entity.edm.edm entitytype entity type has no key defined

Cause: 

No Primary Key is defined. Visual Studio generally looks out for an entityproperty int ID or similar and set it as a primary key. However, if our primary key is something like “Username” then we need to specify which one it is.

 

Solution:

Include the namespace:

using System.ComponentModel.DataAnnotations;

Before your Primary Key add the following attribute:

[Key]

 


Detect if browser is on iphone or ipad in C#

USING C#

if ((Request.ServerVariables[“HTTP_USER_AGENT”].Contains(“iPad”))

{

//Do Something for iPad

}

else if((Request.ServerVariables[“HTTP_USER_AGENT”].Contains(“iPhone”)))
{

//Do Something for iPone

}

 

USING JAVASCRIPT

if (navigator.userAgent.match(/iPad/i) == “iPad”))

{

//Do Something for iPad

}

else if(navigator.userAgent.match(/iPhone/i) == “iPhone”)
{

//Do Something for iPone

}

JavaScript Get Server Time

I once needed to check time on both server side and in JavaScript, but my problem was that the server was not in the same location I was testing my website so the JavaScript time and Server time in code behind did not match. Below is an easy way I used to go around this issue:

 

HTML PAGE / JavaScript:

<script type=”text/javascript”>

$(document).ready(function() {

var d = new Date();
var dateFromServer = $(‘#<%= lbl_serverTime.ClientID %>’).html(); //Get Time from Label which is loaded from Server (through Code Behind)
var time = dateFromServer.substring(11); //Takes only the time in hh:mm:ss format
var n = (d.getMonth()+1) + “/” + d.getDate() + “/” + d.getFullYear() + ” ” + time ;  //puts it together in MM/dd/yyyy hh:mm:ss format
var dateNow = new Date(n); //Created new date from Server Time

alert(dateNow);

});

</script>

 

<asp:Label ID=”lbl_serverTime” runat=”server” Text=””></asp:Label>

 

CODE BEHIND:

//Copy the method Page_Init in your code behind or add it to your Page_Init Method

protected void Page_Init(object sender, EventArgs e)
{

try
{

lbl_serverTime.Text = DateTime.Now.ToString(); //Sets Label to DateTime which is taken from Server

}
catch (Exception ex)

{

throw ex;

}

}

Javascript pass arguments to WebMethod in C#

So, as we all know WebMethod generally cannot access any other parts of the code since it is normally a static and a web method. Therefore I found a quick and silly idea to get around with this. I have set labels hiden in the page and I’m passing their content as an argument when calling the WebMethod. This is done as shown below through Ajax Calls:

HTML PAGE:

<script type=”text/javascript”>

$(document).ready(function() {

$.ajax({
type: “POST”,
url: “default.aspx/GetMyWebMethod”,
data: “{arg1:'” + $(‘#<%= lbl_myFirstArgument.ClientID %>’).html() + “‘,arg2:'” + $(‘#<%= lbl_mySecondArgument.ClientID %>’).html() + “‘}”,

contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: function(msg) {
//Do something on success
}

});

});

</script>

 

<div style=”display: none”>

<asp:Label ID=”lbl_myFirstArgument” runat=”server” Text=””></asp:Label>
<asp:Label ID=”lbl_mySecondArgument” runat=”server” Text=””></asp:Label>

</div>

 

CODE BEHIND:

//We will fill the content of the labels in the Page_Init in order to be ready on document.ready(function() {} );

protected void Page_Init(object sender, EventArgs e)
{

lbl_myFirstArgument.Text = DateTime.Now.toString();

lbl_mySecondArgument.Text = “Write Something here or get something dynamically from Database to pass to WebMethod”;

}

[WebMethod]
public static void GetMyWebMethod(string arg1, string arg2)
{

//You Can do something with arg1 and arg2 

}

 

That’s All !!!! Please feel free to comment or give suggestions on quick and easy alternatives 🙂

Error: Unable to create type ‘telerik:RadPanelBar’. Could not load file or assembly ‘System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. The system cannot find the file specified.

When I converting my project from Visual Studio 2008 to Visual Studio 2010 I was getting this error in my webpage:

Unable to create type ‘telerik:RadPanelBar’. Could not load file or assembly ‘System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. The system cannot find the file specified.

After searching and reading quite a fair bit on the net, I thought it might be that I have a version of the dll that is not compatibile with NET4.0 so I visited telerik.com accessed my account, downloaded the latest “RadControls for ASP.NET AJAX”, installed it and copied the generated Telerik.Web.UI.dll from the folder bin35 into my project bin and rebuilt. This made the error go! Please, keep in mind that even though I converted to VS 2010, I was still running on NET3.5, if you are running on version NET4.0 make sure to copy the dll from bin40 if available.

 

 

 

Confirm Message from Code Behind /

So, I needed to create some sort of confirm message box to present the user however I needed it to be all generated from the code behind. Below is an example of how this is done:

protected void Page_Load(object sender, EventArgs e)
{

string parameter = Request[“__EVENTARGUMENT”];
if (string.Equals(“confirmed”, parameter, StringComparison.InvariantCultureIgnoreCase))
{

//Call method to use if user clicks YES

}

//OR  – They both do the same thing however when the above doesnt work, use the following:

if (!string.IsNullOrEmpty(Request[“__EVENTARGUMENT”]) && Request[“__EVENTARGUMENT”].ToLower().Equals(“confirmed”))
{

//Call method to use if user clicks YES

}

}

And finally wherever you need to send the confirm message, lets say in a normal method:

public void AskConfirmation()

{

 ScriptManager.RegisterStartupScript(this, this.GetType(),”temp”, “if(confirm(‘Are you sure ?’)) __doPostBack(‘ ‘, ‘confirmed’);”, true);

//If the user clicks yes, the method called in the PageLoad will be fired

}

Thats All 🙂 enjoy