Exploring the NHibernate Ecosystem Steve Bohlen Blog:

Slides:



Advertisements
Similar presentations
Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
Advertisements

Dr. Leo Obrst MITRE Information Semantics Information Discovery & Understanding Command & Control Center February 6, 2014February 6, 2014February 6, 2014.
Yukon – What is New Rajesh Gala. Yukon – What is new.NET Framework Programming Data Types Exception Handling Batches Databases Database Engine Administration.
.NET 3.5 SP1 New features Enhancements Visual Studio 2008 SP1 New features Enhancements Additional features/enhancements.

INTRODUCTION TO ASP.NET MVC AND EXAMPLE WALKTHROUGH RAJAT ARYA EFECS - OIM DAWG – 4/21/2009 ASP.NET MVC.
1.  Understanding about How to Working with Server Side Scripting using PHP Framework (CodeIgniter) 2.
St Louis Day of.NET 2011 Refactoring to a SOLID Foundation Steve Bohlen Senior Software Engineer SpringSource/VMware Blog:
.NET Database Technologies: Open-Source Frameworks.
St Louis Day of.NET 2011 Taming Dependency Chaos with Inversion of Control Containers Steve Bohlen Senior Software Engineer SpringSource/VMware
Michael Paladino Lead Application Developer EagleOne.
DEV392: Extending SharePoint Products And Technologies Through Web Parts And ASP.NET Clint Covington, Program Manager Data And Developer Services - Office.
Kansas City Developer Conference 2011 Unit Testing Patterns and Anti-Patterns Steve Bohlen Blog:
Microsoft ® Official Course Interacting with the Search Service Microsoft SharePoint 2013 SharePoint Practice.
Chapter 14: Advanced Topics: DBMS, SQL, and ASP.NET
Session-02.
St Louis Day of.NET 2011 Unit Testing Patterns and Anti-Patterns Steve Bohlen Senior Software Engineer SpringSource/VMware Blog:
A tour of new features introducing LINQ. Agenda of LINQ Presentation We have features for every step of the way LINQ Fundamentals Anonymous Functions/Lambda.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
Windows.Net Programming Series Preview. Course Schedule CourseDate Microsoft.Net Fundamentals 01/13/2014 Microsoft Windows/Web Fundamentals 01/20/2014.
Training Course 2 User Module Training Course 3 Data Administration Module Session 1 Orientation Session 2 User Interface Session 3 Database Administration.
Doing Something Useful with Enterprise Library 3.0 Benjamin Day Level: Intermediate.
DEVELOPMENT QA REPORTS A Series of Reports to Enforce Compliance with Your PeopleSoft Development Standards Leandro Baca.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
Database Technical Session By: Prof. Adarsh Patel.
Windows Azure Tour Benjamin Day Benjamin Day Consulting, Inc.
Chemical Toxicity and Safety Information System Shuanghui Luo Ying Li Jin Xu.
.NET Framework Danish Sami UG Lead.NetFoundry
Copyright © 2005 Finetix LLC All Rights Reserved 0 SpringFramework.Net Developer Session Chris Donnan The Peer Frameworks Series -.Net and Java.
AUTOMATION OF WEB-FORM CREATION - KINNERA ANGADI – MS FINAL DEFENSE GUIDANCE BY – DR. DANIEL ANDRESEN.
OVERVIEW ON HOW ENTITY FRAMEWORK CODE FIRST CAN EASE THE DEVELOPMENT PROCESS Entity Framework Code First 11/19/2013 Joe Walling Copyright Walling Info.
Intoduction to NHibernate. Agenda Overview of NHibernate Models and Mappings Configuration Sessions and Transactions Queries.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
Intoduction to NHibernate. Agenda Overview of NHibernate Models and Mappings Configuration Sessions and Transactions Queries.
AUC Technologies LINQ (Language Integrated Query) LINQ Presented By : SHAIKH SHARYAR JAVED Software Engineer (Daedalus Software Inc.) Technology Teacher.
Intoduction to NHibernate. Agenda Overview of NHibernate Models and Mappings Configuration Sessions and Transactions Queries.
Fall CIS 764 Database Systems Engineering L18.2 : Object Relational Mapping … ….Object persistence.
Virtual techdays INDIA │ 9-11 February 2011 Caching Enhancement in ASP.NET 4.0 Abhijit Jana │ Consultant, Microsoft
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
All information's of PLINQO in this Document, I got it from: So, you could visit the link above to research.
Hibernate Basics. Basics What is persistence? Persistence in Object Oriented Applications? Paradigm Mismatch.  The Problem of Granularity.  The Problem.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Simplifying the Code First Approach in the Entity Framework Dhananjay Kumar Infragistics Consultant Microsoft MVP
Introduction – ORM, Helloworld Application
Introduction to JavaScript MIS 3502, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 2/2/2016.
Sean Chambers.  ORM stands for Object Relational Mapper  Maps your POCO (plain old clr objects) to your relational model using XML config  Relieves.
 Who I am  What is NHibernate? ◦ Object Relational Mapper ◦ A framework for building advanced frameworks ◦ Ported from Java ◦ A wide NHibernate ecosystem.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
Data Access Methodologies: When to choose what (ADO.NET, Entity Framework, WCF Data Services) Wriju Ghosh Lead Partner Consultant, Microsoft.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Fall CIS 764 Database Systems Engineering L11: Object Relational Mapping … (a) ORM, Object persistence (b) Pets sequence.
October 2014 HYBRIS ARCHITECTURE & TECHNOLOGY 01 OVERVIEW.
ArcGIS for Server Security: Advanced
EF Relations Object Composition
What’s new in Entity Framework Core 2.0
A very brief introduction
Hands on LINQ to SharePoint
ADO.NET Entity Framework
ADO.NEXT Advances in Data Access for 2008
Java Data Persistence Using Hibernate
The Re3gistry software and the INSPIRE Registry
SharePoint data access and LINQ to SharePoint
Building event-driven, long-running apps with Windows workflow
Entity Framework Core (EF Core)
ASP.NET 4.0 State Management Improvements – Deep Dive
Pablo Castro Software Architect Microsoft Corporation
Implementing Entity Framework with MVC Jump Start
Quiz Points 1 Rules Raise your hand if you know the question
Presentation transcript:

Exploring the NHibernate Ecosystem Steve Bohlen Blog:

Steve Bohlen Nearly 20 years developing software LISP, Pascal, C/C++, VB, VB.NET, C# Co-Founder, NYC Alt.Net User Group Contributor: various OSS projects blog:

Oredev2009: Efficiency Relational Persistence Object Relational Mapping with NHibernate Persistence Framework NHibernate-based Frameworks NHibernate Add-ins

Coming Up: A Tour

…Not a Deep Dive

Mapping the Universe

NHibernate Core External NHContrib NH Spatial NH Burrow NH Linq FluentNH Castle ActiveRecord NH Validator NH Proxy Gen Rhino Tools Castle NH Facility uNHAddins NH Caches NH Mapping Attributes NH Shards NH Search Castle ActiveWriter JetDriver Lambda Extensions NH Prof

Non-Relational Data Sources Mapping, Configuration, and Query Infrastructure and Frameworks Relational Data Sources NHibernate Core NHSpatial NHSearch NH LINQ FluentNH Castle ActiveRecord NH Validator JetDriver Rhino Tools Castle NH Facility NHBurrow NH Attribute Mapping uNHAddins NH Caches Lambda Extensions

NHibernate Implementation Framework (plus a lot more)

A Complete Infrastructure Stack  Unit-of-Work Abstraction  IoC Container Convenience Services Assumes Castle Windsor  NH Session lifecycle management for ASP.NET apps  Conversation-per-Business-Transaction  NHRepository implementation  Multiple, concurrent DB support  Lots more

Rhino IRepository public interface IRepository { // Methods long Count(); long Count(DetachedCriteria criteria); T Create(); DetachedCriteria CreateDetachedCriteria(); DetachedCriteria CreateDetachedCriteria(string alias); void Delete(T entity); void DeleteAll(); void DeleteAll(DetachedCriteria where); object ExecuteStoredProcedure(string sp_name, params Parameter[] parameters); ICollection ExecuteStoredProcedure (Converter converter, string sp_name, params Parameter[] parameters); bool Exists(); bool Exists(DetachedCriteria criteria); ICollection FindAll(params ICriterion[] criteria); ICollection FindAll(Order order, params ICriterion[] criteria); ICollection FindAll(Order[] orders, params ICriterion[] criteria); ICollection FindAll(DetachedCriteria criteria, params Order[] orders); ICollection FindAll(string namedQuery, params Parameter[] parameters); ICollection FindAll(int firstResult, int numberOfResults, params ICriterion[] criteria); ICollection FindAll(DetachedCriteria criteria, int firstResult, int maxResults, params Order[] orders); ICollection FindAll(int firstResult, int numberOfResults, Order selectionOrder, params ICriterion[] criteria); ICollection FindAll(int firstResult, int numberOfResults, string namedQuery, params Parameter[] parameters); ICollection FindAll(int firstResult, int numberOfResults, Order[] selectionOrder, params ICriterion[] criteria); T FindFirst(params Order[] orders); T FindFirst(DetachedCriteria criteria, params Order[] orders); T FindOne(params ICriterion[] criteria); T FindOne(DetachedCriteria criteria); T FindOne(string namedQuery, params Parameter[] parameters); FutureValue FutureGet(object id); FutureValue FutureLoad(object id); T Get(object id); T Load(object id); ICollection ReportAll (ProjectionList projectionList); ICollection ReportAll (DetachedCriteria criteria, ProjectionList projectionList); ICollection ReportAll (ProjectionList projectionList, params ICriterion[] criterion); ICollection ReportAll (ProjectionList projectionList, params Order[] orders); ICollection ReportAll (ProjectionList projectionList, bool distinctResults); ICollection ReportAll (string namedQuery, params Parameter[] parameters); ICollection ReportAll (DetachedCriteria criteria, ProjectionList projectionList, params Order[] orders); ICollection ReportAll (ProjectionList projectionList, Order[] orders, params ICriterion[] criteria); ProjT ReportOne (DetachedCriteria criteria, ProjectionList projectionList); ProjT ReportOne (ProjectionList projectionList, params ICriterion[] criteria); T Save(T entity); T SaveOrUpdate(T entity); T SaveOrUpdateCopy(T entity); void Update(T entity); }

Abstractions, Tools, and a WHOLE lot more!

uNhAddins: a Smörgåsbord! NH UserTypes NH Event Listeners Inflector NH Session Abstraction Query Pagination Tolerant Query Cache Conversation- Per-Business Transaction NH Audit Event Listeners IoC Container Abstraction Castle Windsor Adapter Spring.NET Adapter Ninject Adapter NH Session Mgt for WCF NH Session Mgt for WPF Validation Abstraction NH Validator Adapter Data Annotations Adapter Castle Validator Adapter Validation Ent. Application Block Adapter

Efficient Database Caching

Cache Providers  MemCache Implementation for MemCached  Prevalence Bamboo.Prevalence engine  SharedCache Inspired by MemCached but 100% managed code (C#)  Velocity Microsoft’s Distributed Caching Engine (CTP2)  SysCache ASP.NET Cache Provider  SysCache2 ASP.NET Cache Provider ○ with SQLServer call-back-invalidate support

Simpler Data Access

ActiveRecord Example [ActiveRecord] public class Category : ActiveRecordBase { [PrimaryKey] public int Id { get; set; } [Property] public string Name { get; set; } [BelongsTo("parent_id")] public Category Parent { get; set; } [HasMany] public IList<Category> SubCategories { get; set; } }

Integrated Validation Framework

Using NHValidator 1. Get and Build it (NHContrib) 2. Add References 3. Register Event Listeners in code or hibernate.cfg.xml file 4. Off and Running!

Let’s Look at Some Code!

Death to String-Literals!!!!

Using NHLambdaExtensions 1. Download the Assembly (googlecode) Add Reference to Assembly 2. Off and Running!

LambdaExtensions In Action session.CreateCriteria<Customer>().Add(Restrictions.Eq(“Firstname”, “Steve”).List<Customer>(); session.CreateCriteria<Customer>().Add<Customer>(c => c.Firstname == “Steve”).List<Customer>();

One Query Language to Rule Them All!

Using NHLINQ 1. Download the Assembly (sourceforge) v1.0  NH 2.1GA release 2. Add Reference to Assembly 3. Off and Running!

NHLINQ in Action using (var session = sessionFactory.OpenSession()) { using (var tx = session.BeginTransaction()) { var customers = session.Linq<Customer>().Where(c => c.Firstname == “Steve”); foreach (var customer in customers) { Console.WriteLine(customer.Firstname); } tx.Commit(); } }

Stateful NHibernate Session Management for ASP.NET WebForms

Using Burrow 1. Get it and Build it (NHContrib) 2. Add References 3. Add NHibernate.Burrow config section to web.config 4. Add Burrow HTTP Module to your web.config

Modify web.config for Burrow

Register Burrow HTTPModule

Burrow Conversation Pattern BurrowFramework bf = new BurrowFramework(); bf.CurrentConversation.SpanWithPostBacks(TransactionStrat egy.BusinessTransaction); //do a bunch of work in a bunch of postbacks BurrowFramework bf = new BurrowFramework(); bf.CurrentConversation.FinishSpan(); //commit to DB… bf.CurrentConversation.GiveUp(); //…or abandon!

Spatial Queries

Understanding Spatial Data Latitude / Longitude Coordinate Systems (Spatial Reference ID) SRID Projections

Supported Spatial Engines  MS SQLServer 2008 Includes SQLServer 2008 Express!  MySQL  PostGIS (PostGre-based)  Oracle (work-in-progress)

Using NH Spatial 1. Get and Build it (NHContrib) 2. Add References (GeoAPI, Spatial, etc.) 3. Change Dialect in hibernate.cfg.xml 4. Optional: add support for spatial metadata to the Configuration instance before building SessionFactory 5. Map properties as ‘Geometry Type’ 6. Off and Running!

NHSpatial: Dialect NHibernate.Driver.SqlClientDriver Server=(local);initial catalog=nhibernate;Integrated Security=SSPI 10 false NHibernate.Spatial.Dialect.MsSql2008SpatialDialect, NHibernate.Spatial.MsSql2008 true 60 true 1, false 0, yes 'Y', no 'N' NHibernate.ByteCode.LinFu.ProxyFactoryFactory,NHibernate.ByteCode.LinFu

Add Spatial Metadata Classes Configuration cfg = new Configuration(); cfg.Configure(); Metadata.AddMapping(cfg, MetadataClass.GeometryColumn); Metadata.AddMapping(cfg, MetadataClass.SpatialReferenceSystem); var sessionFactory = cfg.BuildSessionFactory(); //rest of your app here!

Add Geometry Type + Mapping using GeoAPI.Geometries public class MyThing { public virtual IGeometry Geometry {get;set;} //more of our class } <!-- short version --> <property name="Geometry" column="the_geom" type = "NHibernate.Spatial.Type.GeometryType, NHibernate.Spatial" /> <!-- long version --> <property name="Geometry" column="the_geom"> <type name = "NHibernate.Spatial.Type.GeometryType, NHibernate.Spatial"> <param name="srid">4326</param> <param name="subtype">POLYGON</param> </type> </property>

Perform Spatial Queries var country = session.CreateCriteria<Country>().Add(SpatialExpression.Contains("Boundaries", new Point(-70.40, ))).UniqueResult<Country>(); IList<Town> towns = session.CreateCriteria<Town>().Add(SpatialExpression.Filter("Boundaries", new Envelope(-70, -68, -32, -34))).Add(Restrictions.Not(SpatialExpression.Contains("Bounda ries", new Point(-70.40, )))).List<Town>();

Querying Unstructured Text Indices

The Power of Lucene.NET  Databases are efficient and querying relational data  Databases are inefficient at querying unstructured text  Better tools exist to do that Lucene.NET ○ A port of the Lucene project to.NET ○ High-performance indexed searching of text content

NHibernate Search NHibernateQuery Lucene.NET Document Index Relational Database Select all Customers who have more than 10 orders and whose comments on their Invoices contain the word “’dissatisfied”

Using NHSearch 1. Get and build it (NHContrib) 2. Add References 3. Add index-related properties to hibernate.cfg.xml 4. Register Ins, Upd, Del event listeners to trigger updates to index on change 5. Add attributes to your classes to indicate what should be indexed 6. Off and Running!

Modify Configuration File NHibernate.Driver.SqlClientDriver Server=(local);initial catalog=nhibernate;Integrated Security=SSPI 10 false NHibernate.Dialect.MsSql2000Dialect true 60 true 1, false 0, yes 'Y', no 'N' NHibernate.ByteCode.LinFu.ProxyFactoryFactory,NHibernate.ByteCode.LinFu NHibernate.Search.Store.FSDirectoryProvider, NHibernate.Search c:\MyIndex event

Register Event Listeners //register in code var cfg = new Configuration(); cfg.SetListener(NHibernate.Event.ListenerType.PostUpdate, new FullTextIndexEventListener()); cfg.SetListener(NHibernate.Event.ListenerType.PostInsert, new FullTextIndexEventListener()); cfg.SetListener(NHibernate.Event.ListenerType.PostDelete, new FullTextIndexEventListener());

Add Attributes for Index Engine public class Document { [DocumentId] public virtual int Id { get; set; } [Field(Index.Tokenized, Store=Store.Yes)] public virtual string Title { get; set; } [Field(Index.Tokenized)] public virtual string Body { get; set; } }

Perform Indexed Queries using (var session = sessionFactory.OpenSession()) { using(var textsearch = Search.CreateFullTextSession(session)) { using (var tx = session.BeginTransaction()) { var results = textsearch.CreateFullTextQuery (“Title:Oredev").SetMaxResults(10).List (); }

Mapping and Configuration without XML

Using FluentNHibernate 1. Get it ( ) 2. Add References 3. Off and Running!

Sample Classes

XML Mappings

Fluent Mappings public class CustomerMap : ClassMap<Customer> { public CustomerMap() { Id(c => c.Id).Column("CustomerId"); Map(c => c.Firstname); Map(c => c.Lastname); HasMany<Order>(c => c.Orders).Table("Order").KeyColumn("CustomerId").Inverse().Generic(); } }

XML Configuration NHibernate.Driver.SqlClientDriver Server=(local)\sqlserver2005;initial catalog=FluentNHibernateDemo;user=sa;password=password 10 true NHibernate.Dialect.MsSql2005Dialect true 60 true 1, false 0, yes 'Y', no 'N' NHibernate.ByteCode.Castle.ProxyFactoryF actory, NHibernate.ByteCode.Castle

Fluent Configuration sessionFactory = Fluently.Configure().Database(FluentNHibernate.Cfg.Db.MsSqlConfiguration.Ms Sql2005.ConnectionString(CONNSTRING).AdoNetBatchSize(10).ProxyFactoryFactory <NHibernate.ByteCode.Castle.ProxyFactoryFactory>().UseOuterJoin()).Mappings(m => m.FluentMappings.AddFromAssemblyOf<CustomerMap>()).BuildSessionFactory();

Convention Mapping  Enables Fluent NHibernate to ‘infer’ your mappings from your objects  Uses conventions Baked into FNH Overrides provided by yourself Identity field convention Many-to-many intermediate table convention Foreign-key id column convention Many, many more

Production-Class Profiling for ORMs

Metrics, Analysis, Recommendations

Summary  If you’re doing your data-access by hand… YOU’RE DOING IT WRONG  If you’re doing the rest of the stuff you saw here today by hand… YOU’RE DOING IT WRONG  NHibernate has one of the richest ecosystems of extensions, frameworks, and tools of any.NET technology, OSS or otherwise… LEARN TO LEVERAGE THEM for EFFICIENCY

*NHibernate GA Released!*  November 1, 2009  Probably the final 2.x release before 3.0  Primarily bug-fix, no breaking changes  Most of these tools will work with Most will need to be recompiled against the new release before use ○ Binary dependency on NH assemblies  HORNGET.NET is your friend here!

Resources  NHForge  NHContrib  uNhAddins  NHProf  HornGet.NET

~fini~