Oshyn Home Page
  • expertise
    • Overview
    • Contact Us |
    • Latest work: www.miramax.com
  • solutions
    • Overview
    • Content Management
      • Common Issues
      • Choosing a CMS
      • Training
      • Drupal Development
      • Jahia Integration
      • Sitecore Consulting
      • Open Text Web Solutions RedDot CMS
      • EPiServer CMS Consulting
    • E-commerce
    • SOA
    • Portals & Collaboration
    • Web Strategy
    • Mobile Platforms
    • Social Media
    • Contact Us |
    • Latest work: www.miramax.com
  • work
    • Overview
    • Client Quotes
    • Contact Us |
    • Latest work: www.websense.com
  • resources
    • Overview
    • News & Events
    • Newsletters
    • Blog
    • White Papers
    • Success Stories
    • Press Kit
    • Contact Us |
    • Latest work: www.disneydvd.com
  • partners
    • Overview
    • Agency Partner Program
    • Technology Partners
    • Contact Us |
    • Latest work: www.nea.org
  • company
    • Overview
    • Contact
    • Careers
    • Leadership Team
    • News & Events
    • Social Responsibility
    • Contact Us |
    • Latest work: www.icon4x4.com
Why is Persistence Layer Important Plus a Quick NHibernate Sample
  • Tweet
Tuesday, November 17, 2009  /   Juan Pablo Albuja Juan Pablo Albuja
close

Juan Pablo Albuja


During his 5 years in software development, Juan Pablo Albuja has performed work for clients in the Software, Insurance, Media Digital, and Higher Education industries. His expertise ranges from software development to innovative web technologies with particular expertise in CMS (Content Management Systems), like Jahia, RedDot, LiveServer (DS), Joomla, and system integration with a particular focus on Java technologies. In addition, Juan Pablo has a high experience with the configuration of automatic deployments process based on Hudson, installations, and configuration of search engines like Verity and OpenText Common Search.

Why is Persistence Layer Important Plus a Quick NHibernate Sample

Let’s investigate the importance of the use of persistence layers between applications and databases. The idea is to show the benefits and functions of persistence layers with a simple example built in NHibernet for .Net applications.

The idea of the persistence layer is to encapsulate databases access routines. This allows applications to work with a set of objects (Data Objects) that read and save their state to a database; therefore applications do not need to have it in their source code SQL statements. The big advantage of persistence layers is to avoid the direct communication between applications and relational databases. A big problem can exist if you do not have a persistence layer because if the database engine is updated or replaced, changes to the http://www.redhat.com/docs/manuals/rhea/RHEA-5.0-Manual/developer-guide/ch-persistence.html Persistence and Data Objectsapplication source code are required to make it work with the updated database engine.

Following is an example of how to use NHibernate to achieve that separation between applications and relational databases. NHibernate is .Net persistence library for relational databases that can be used in web and console applications to access relational databases. The following example is build for a web application in Visual Studio 2008 with SQL Server 2005:

Project Setup

  1. Please download the last distribution of NHibernate here.
  2. Open your Visual Studio and create a .Net Web Application project in C# and named it as "NHibernateSample".
  3. For simplicity, let's create a Persistence project adding to the recently created project that is going to contain the model and the persistence.
  4. In the NHibernateSample project, add a reference to the Persistence project.
  5. The Persistence project is going to use Nhibernate, for that reason, add following references: NHibernate.dll, NHibernate.ByteCode.LinFu.dll and LinFu.DynamicProxy.dll.

Database Setup

For this part, I am assuming that you already have SQL Server 2005 installed.

  1. Open SQL Server Management Studio and create new database named as "NHibernateDatabase".
  2. Run the following query to create the table users:

    use NHibernateDatabase
    go
    CREATE TABLE users (
    LogonID nvarchar(20) NOT NULL default '0',
    Name nvarchar(40) default NULL,
    Password nvarchar(20) default NULL,
    EmailAddress nvarchar(40) default NULL,
    LastLogon datetime default NULL,
    PRIMARY KEY (LogonID)
    )
    go

NHibernate Configuration

Now is time to do the lasts configurations in order to use NHibernate.

  1. Create a .NET class in the project Persistence that is going to represent the table Users in .NET.

    using System;

    namespace Persistence
    {

    ///
    /// Summary description for User
    ///

    public class User
    {
    private string id;
    private string userName;
    private string password;
    private string emailAddress;
    private DateTime lastLogon;

    public User()
    {
    }

    public virtual string Id
    {
    get { return id; }
    set { id = value; }
    }

    public virtual string UserName
    {
    get { return userName; }
    set { userName = value; }
    }

    public virtual string Password
    {
    get { return password; }
    set { password = value; }
    }

    public virtual string EmailAddress
    {
    get { return emailAddress; }
    set { emailAddress = value; }
    }

    public virtual DateTime LastLogon
    {
    get { return lastLogon; }
    set { lastLogon = value; }
    }
    }
    }
  2. Add to the Persistence Project the following mapping file named Users.hbm.xml:
    <?xml version="1.0" encoding="utf-8" ?>
    <hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" >
    <class name="Persistence.User, Persistence" table="users">
    <id name="Id" column="LogonId" type="String" length="20">
    <generator class="assigned" />
    </id>
    <property name="UserName" column="Name" type="String" length="40"/>
    <property name="Password" type="String" length="20"/>
    <property name="EmailAddress" type="String" length="40"/>
    <property name="LastLogon" type="DateTime"/>
    </class>
    </hibernate-mapping>
  3. Right click over the file "User.hbm.xml", properties, and change the Build Action to Embedded Resource.
  4. Open the web.config file of the web project and add the following:
  5. <?xml version="1.0"?>
    <configuration>
    <configSections>
    <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
    </configSections>
    <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.isolation">ReadUncommitted</property>
    <property name="show_sql">true</property>
    <!-- SQLServer -->
    <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Server=localhost;initial catalog=nhibernatedatabase;Integrated Security=SSPI</property>
    <property name="default_schema">NHibernateDatabase.dbo</property>
    <property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>
    <mapping assembly="Persistence"/>
    <!-- MySQL -->
    </session-factory>
    </hibernate-configuration>
    </configuration>

NHibernate Use

  1. Create class called "TestNHibernate.cs" in the Persistence Project to use NHibernate.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using NHibernate;
    using NHibernate.Cfg;

    namespace Persistence
    {

    public class ConfigurationObject
    {

    public ConfigurationObject()
    {

    Configuration cfg = new Configuration();
    cfg.AddAssembly("Persistence");


    ISessionFactory factory = cfg.BuildSessionFactory();
    ISession session = factory.OpenSession();
    ITransaction transaction = session.BeginTransaction();

    //Use
    User newUser = new User();
    newUser.Id = "test";
    newUser.UserName = "test";
    newUser.Password = "abc123";
    newUser.EmailAddress = "test@cool.com";
    newUser.LastLogon = DateTime.Now;

    // Save
    session.Save(newUser);

    // Comit
    transaction.Commit();
    session.Close();

    }

    }

    }
  1. Create a class in the NHibernatSample project to call the configuration object.
    TestNHibernate co = new TestNHibernate ();

The interesting part of persistence is that if we change the database, we just need to change the configuration file located in web.config in order to point to the updated database. Notice that in the code we do not have any SQL statement,because NHibernate is working as the persistence layer that transform calls to the object update to SQL Statements.

  • Share
  • Facebook    0
  • Twitter    0
Trackback Link
http://www.oshyn.com/BlogRetrieve.aspx?BlogID=2583&PostID=100458&A=Trackback
Trackbacks
Post has no trackbacks.

blog comments powered by Disqus

Pages: Previous Next

TwitterFacebookLinkedIn

Blog Authors

Christian Burne Christian Burne
question button image

 



Captcha Image

question button image
Subscribe Subscribe Subscribe Subscribe Subscribe
OTHER CATEGORIES
  • ALL

  • General

  • Web Content Management

  • Sitecore CMS

  • Open Text

  • Jahia

  • Drupal

  • EpiServer

  • SOA

  • Social Media and Mobile

  • Software Development

  • Visit Bloggers Profiles

RELATED POSTS
  • Jira new plugin: Bonfire for Agile Testing
  • Google App Inventor: An Android Mobile App Developer for Everyone
  • Agile Testing and Test Management
  • .Net Source Code Quality Tools – Part 3: Analyzing Code
  • Using WMDRM on your Application – Part 2
  • .Net Source Code Quality Tools – Part 2: Configuring the Build
  • Using WMDRM on your Application – Part 1
  • .Net Source Code Quality Tools – Part 1: Setup
  • ClickOnce Deployment - Creating a Custom Installer
  • Build Automation for Windows Presentation Framework (WPF) and Silverlight Applications

WHITE PAPERS
    ajax rotator

    Web Content Management, Social Media, Content: Three Kings for Your Website Web Content Management, Social Media, Content: Three Kings for Your Website (846 KB)
    Companies pursuing online marketing success, including Social Media, can increase the power of their online presence with right strategy and technology to maximize online visibility and engagement. Download this FREE white paper on the WCM, Social Media, and Content triad.

    Drupal Performance Tuning Drupal Performance Tuning (1213 KB)
    In this Free White Paper Oshyn evaluates Drupal Performance Tuning, sharing the results of testing response time and Requests Per Second (RPS) that a server can hold before the response rate becomes unacceptable. In this paper you will learn about optimizing performance of a website through changes to settings and the server.

    Enterprise Drupal: Social Media, Mobile, and Rich Media in your Website Enterprise Drupal: Social Media, Mobile, and Rich Media in your Website (1015 KB)
    In this free WCM white paper, Oshyn examines advanced Drupal capabilities: Multisite Environment, Access Control and Security, Enhanced User Profiles, Custom Breadcrumbs, Mobile Support, Podcasts, Advanced Multimedia, Locations and Maps, Internationalization and Locale based content, Events and Scheduled Tasks, Rules Actions and E-Commerce Solutions.

    Drupal Multilingual Drupal Multilingual (636 KB)
    There are several multilingual installation methods for Drupal. In this free white paper Oshyn evaluates and recommends several methods of using Drupal Open Source CMS to manage websites in multiple languages.

    Drupal Social Media Drupal Social Media (1297 KB)
    Looking for an Open Source CMS to for “Social Media Optimization” of your website? Download this free white paper, “Drupal and Social Media”, to learn about the extensive Social Media this Open Source CMS offers to create a dynamic and engaging website and online community.

    Drupal Multisite Options Drupal Multisite Options (427 KB)
    There are several multisite installation methods for Drupal. In this free white paper Oshyn evaluates and recommends several methods of using Drupal Open Source CMS to manage multiple sites.

    Open Source CMS: Is It Right for your Organization Open Source CMS: Is It Right for your Organization (496 KB)
    In this free white paper, “Open Source CMS: Is It Right for your Organization?” we share an in-depth look at the pros and cons of using Open Source Content Management Systems (CMS) or Open Source Web Content Management (WCM) platforms. Oshyn helps clients select CMS/WCM solutions based on the specific requirements of each client.

    Affiliate Content Sharing in a CMS/WCM World Affiliate Content Sharing in a CMS/WCM World (273 KB)
    The Content Editors at your company have created GREAT content! Now how do you share it? In this Free white paper learn several methods for using a Content Syndication tool to automatically repurpose content and how Content Sharing can generate business value.

    Sitecore and Social Media - An Interactive Web Content Management Platform Sitecore and Social Media - An Interactive Web Content Management Platform (898 KB)
    Social Media has revolutionized how people interact with business. In this white paper Oshyn’s Lead Sitecore Developer, Prasanth Nittala, discusses key points from the perspectives of marketing and Web development that make Sitecore a compelling choice for engaging in Social Media via your website. This Sitecore white paper draws from Oshyn’s expertise as a certified Sitecore partner, helping organizations understand the distinct capabilities offered by Sitecore CMS.

    The Business Case for Leveraging Open Text Web Solutions Delivery Manager The Business Case for Leveraging Open Text Web Solutions Delivery Manager (451 KB)
    This free white paper explores the evolving needs of small and medium size businesses and explains how the Open Text Web Solutions Delivery Manager (formerly RedDot LiveServer) can help businesses build their brand, reputation, and client base. This white paper examines strategies, key points and tips to leverage the features available in Open Text Web Solutions (RedDot CMS) to achieve an impactful user experience and to maximize visitor engagement through a reliable and powerful implementation.

    Open Text Best Practices: Part One Open Text Best Practices: Part One (763 KB)
    Authored by Oshyn Senior Consultant, Adaeze Okorie, this free CMS white paper draws from Oshyn’s vast experience as an Open Text Certified Partner, in helping organizations define strategies to meet business goals while implementing Open Text Web Solutions (RedDot CMS). Specifically in this free white paper Adaeze Okorie discusses strategies, key points and tips to leverage the features available in Open Text Web Solutions (RedDot CMS) to achieve an effective, reliable and robust implementation.

    Improving the ROI of Business Software: Service Oriented Architecture from a Business Perspective Improving the ROI of Business Software: Service Oriented Architecture from a Business Perspective (398 KB)
    Software selection and technology decision making should no longer be left to the IT department alone. By gaining an understanding of Service-Oriented Architecture, business people outside of the IT department will be better positioned to maximize the ROI of the company's technology platforms. Download this free white paper to learn more.

    Getting Over Social Media Marketing Paralysis for B2B Getting Over Social Media Marketing Paralysis for B2B (2254 KB)
    Many companies are well aware that Social Media has become critically important to engaging audiences and promoting online "presence" while some wonder how to approach their C-level executives and prove that it is not all hype. With so many ways to engage in Social Media, how can they get buy-in and begin execution with so many different venues and tools available? Staying on the sidelines and becoming a latecomer might make it more difficult to create a convincing "social" presence. Put the ove

    Performance Tuning Open Text Web Solutions Management Server and Delivery Server Performance Tuning Open Text Web Solutions Management Server and Delivery Server (235 KB)
    If you've made an investment in Open Text Web Solutions (formerly RedDot) Web Content Management products, you’ve undoubtedly experienced performance issues. While every CMS requires tuning, Open Text Web Solutions - RedDot is especially susceptible to mis-configuration and poor performance as the out-of-the-box installation comes untuned and ready for Development Environments only. In this FREE white paper we share performance tuning expertise as an Open Text Certified Partner that has optimize

    The Business Case for Leveraging Open Text Web Solutions Within Higher Education The Business Case for Leveraging Open Text Web Solutions Within Higher Education (430 KB)
    Academic institutions have a long reputation for being slower to adopt new technologies for their audiences. However, many schools are taking serious steps in improving the online experience they are providing. This white paper explores the unique needs of the higher education market, applying new tools & trends and specifically how the Open Text Web Solutions’ Delivery Manager (formerly known as RedDot LiveServer) can be leveraged to achieve those goals.

    SEO Best Practices within a Content Management System SEO Best Practices within a Content Management System (712 KB)
    In this free white paper, we share Search Engine Optimization (SEO) tips and best practices to follow when implementing a Content Management System (CMS). Certain features and functionality will help your content editors make website changes faster while minimizing the risk of human error. Download this free white paper to learn strategies to improve search engine rankings.

    Best Practices for Sitecore CMS Best Practices for Sitecore CMS (1121 KB)
    Sitecore CMS is an extensive Web Content Management (WCM) platform for the mid-market. It offers reduced IT expenditures, a streamlined content lifecycle, and a return of content control to the subject matter experts. The newest incarnation of Sitecore CMS version 6.0 is a mature product that incorporates standard social media components such as wikis, blogs, RSS syndication and “e-mail a friend” features.

    Optimizing SEO in your CMS (WCM) Optimizing SEO in your CMS (WCM) (3108 KB)
    Oshyn's Christian Burne spoke in depth about SEO in CMS at the Gilbane San Francisco Conference on June 3rd, 2009. Christian discussed the pressues of keyword competition and how the CMS can add tremendous power to climbing Google SERPs and other search engine rankings. The presentation was later part of a featured article on CMSWire. We've made the presentation available in PDF format. Download now to learn more about strategies for using your CMS to optimize SEO.

    The Best CMS for You: Tips on How to Select Your Next CMS The Best CMS for You: Tips on How to Select Your Next CMS (909 KB)
    As websites continue to grow in size, features and functionality, the visitors to these websites are also becoming more demanding and have higher expectations than ever before. Companies who committed valuable time and resources to web strategies just five years ago are finding they must re-evaluate and explore new options as their content, features and online offerings must keep pace with the constant and rapid movement in the digital marketplace. For many of these companies, there is a strong.

    Oshyn Sample Voluntary Product Accessibility Template (VPAT) Oshyn Sample Voluntary Product Accessibility Template (VPAT) (741 KB)
    Section 508 requires that when federal government and agencies procure, develop, and maintain or use electronic and information technology (EIT), they must ensure that it is accessible and in compliance with Section 508 standards developed by the Architectural and Transportation Barriers Compliance Board (Access Board). Oshyn understands these requirements and has delivered reports like these countless times.

    Sitecore CMS Implementation Best Practices Sitecore CMS Implementation Best Practices (481 KB)

    TwitterFacebookLinkedInAlltopFeatured in Alltop
    Oshyn, Inc.17785 Center Court Drive N Cerritos, CA 90703    1.888.483.1770 newbusiness@oshyn.com
    2012 Copyright Oshyn. All rights reserved.
    • View Mobile Version
    • Terms of Use
    • Privacy Policy
    • Contact Us