Silverlight Authors: Automic Blog, Michael Kopp, AppDynamics Blog, Kaazing Blog, Steven Mandel

Related Topics: Silverlight, Microsoft Cloud, Machine Learning

Silverlight: Blog Feed Post

Silverlight 3 RTM and .NET RIA Services wirth NHibernate

I think NHibernate is an excellent example of the vibrant open source community on .NET that I’d like to support

   1: static ISessionFactory SessionFactory = CreateSessionFactory();
   2: static ISessionFactory CreateSessionFactory()
   3: {
   4:     return Fluently.Configure()
   5:       .Database(
   6:         MsSqlConfiguration.MsSql2005
   7:         .ConnectionString(c => c
   8:             .Is(ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString)
   9:             )
  10:       )
  11:       .Mappings(m =>
  12:        m.FluentMappings.AddFromAssemblyOf<SuperEmployeeDomainService>())
  13:        .BuildSessionFactory();
  15: }

Next, let’s look at the mapping class.. this shows how the data from the database are mapped into a .NET Class. 

   1: public class SuperEmployeesMap : ClassMap<SuperEmployee>
   2: {
   3:     public SuperEmployeesMap()
   4:     {
   5:         WithTable("SuperEmployees");
   6:         Id(x => x.EmployeeID);
   7:         Map(x => x.Name);
   8:         Map(x => x.Gender);
   9:         Map(x => x.Issues);
  10:         Map(x => x.LastEdit);
  11:         Map(x => x.Origin);
  12:         Map(x => x.Publishers);
  13:         Map(x => x.Sites);
  14:     }
  15: }

And here is the type I map the data into.  Notice this has the validation attributes for RIA Services to do the validation on the client and server. 

   1: public class SuperEmployee
   2: {
   3:         [Key]
   4:         [ReadOnly(true)]
   5:         public virtual int EmployeeID {get; set;}
   7:         [RegularExpression("^(?:m|M|male|Male|f|F|female|Female)$", 
   8:             ErrorMessage = "Gender must be 'Male' or 'Female'")]
   9:         public virtual string Gender { get; set; }
  11:         [Range(0, 10000,
  12:             ErrorMessage = "Issues must be between 0 and 1000")]
  13:         public virtual Nullable<int> Issues { get; set; }
  15:         public virtual Nullable<DateTime> LastEdit { get; set; }
  17:         [Required]
  18:         [StringLength(100)]
  19:         public virtual string Name { get; set; }
  21:         public virtual string Origin { get; set; }
  23:         public virtual string Publishers { get; set; }
  25:         public virtual string Sites { get; set; }
  26:     }


That’s the bulk of the NHibernate specific code.    Now let’s look at the DomainService..

   1: [EnableClientAccess()]
   2: public class SuperEmployeeDomainService : NHibernateDomainService
   3: {
   4:     public SuperEmployeeDomainService() :
   5:         base(SessionFactory) { }

First, in line 2, notice I have factored some of the plumbing code into a base class.  This is very simple (not production ready) example.. we will look it in more detail later. Then we return the static SessionFactory the the base class.  The SessionFactory is static such that it is created only once per AppDomain rather than on each request.

   1: public IQueryable<SuperEmployee> GetSuperEmployees()
   2: {
   3:     return Session.Linq<SuperEmployee>()
   4:             .Where(e => e.Issues > 10);
   5: }

Here we use NHibernate Linq to return an IQueryable that RIA Services can use to do paging, filtering, etc. 

Then we have Insert and Update which are very basic..

   1: public void InsertSuperEmployee(SuperEmployee superEmployee)
   2: {
   3:     Session.Save(superEmployee);
   4: }
   6: public void UpdateSuperEmployee(SuperEmployee currentSuperEmployee)
   7: {
   8:    Session.Update(currentSuperEmployee);
   9: }

Now, let’s take a look at the NHibernateDomainService base class… Again this is very basic, just to show the concepts..

   1: public class NHibernateDomainService : DomainService
   2: {
   4:     protected ISession Session;
   6:     public NHibernateDomainService(ISessionFactory sessionFactory)
   7:     {
   8:         this.Session = sessionFactory.OpenSession();
   9:     }
  12:     protected override void Dispose(bool disposing)
  13:     {
  14:         Session.Dispose();
  15:         base.Dispose(disposing);
  17:     }
  18:     protected override void ExecuteChangeSet(ChangeSet changeSet)
  19:     {
  20:         using (var trans = Session.BeginTransaction())
  21:         {
  22:             base.ExecuteChangeSet(changeSet);
  23:             trans.Commit();
  24:         }
  25:     }

Notice in the constructor we create the Session… then we close the session in the Dispose() method. 

The interesting bit is handling the ChangeSet… Notice we use a transaction to wrap the calls to our update\create methods.  This ensures that if their is any failure we roll back the changes (this is the contract for DomainService)…

Now, because we plug into the DomainService pattern, we get our silverlight client with paging, filtering, etc


…and validated editing.



But we also get ASP.NET support via the DomainDataSource as in this example from the sitemap.aspx

   1: <asp:DomainDataSource runat="server" ID="SitemapDataSource" 
   2:     DomainServiceTypeName="MyApp.Web.SuperEmployeeDomainService" 
   3:     SelectMethod="GetSuperEmployees" />


And we get a REST based interface via the Astoria support for DomainService.



And we get ASP.NET Dynamic Data Support, again with paging, filtering,


and validating editing.


And all the other presentation tiers..


Wow, pretty cool..

For more on NHibernate, check out Ayende’s blog

For more NHibernate and DomainService, check out Chris van de Steeg’s blog post ASP.NET MVC, DynamicData, Domain-/RiaServices, Unity and NHibernate: Part 1

Read the original blog entry...

More Stories By Brad Abrams

Brad Abrams is currently the Group Program Manager for the UI Framework and Services team at Microsoft which is responsible for delivering the developer platform that spans both client and web based applications, as well as the common services that are available to all applications. Specific technologies owned by this team include ASP.NET, Atlas and Windows Forms. He was a founding member of both the Common Language Runtime, and .NET Framework teams.

Brad has been designing parts of the .NET Framework since 1998 when he started his framework design career building the BCL (Base Class Library) that ships as a core part of the .NET Framework. He was also the lead editor on the Common Language Specification (CLS), the .NET Framework Design Guidelines, the libraries in the ECMA\ISO CLI Standard, and has been deeply involved with the WinFX and Windows Vista efforts from their beginning.

He co-authored Programming in the .NET Environment, and was editor on .NET Framework Standard Library Annotated Reference Vol 1 and Vol 2 and the Framework Design Guidelines.

IoT & Smart Cities Stories
The platform combines the strengths of Singtel's extensive, intelligent network capabilities with Microsoft's cloud expertise to create a unique solution that sets new standards for IoT applications," said Mr Diomedes Kastanis, Head of IoT at Singtel. "Our solution provides speed, transparency and flexibility, paving the way for a more pervasive use of IoT to accelerate enterprises' digitalisation efforts. AI-powered intelligent connectivity over Microsoft Azure will be the fastest connected pat...
There are many examples of disruption in consumer space – Uber disrupting the cab industry, Airbnb disrupting the hospitality industry and so on; but have you wondered who is disrupting support and operations? AISERA helps make businesses and customers successful by offering consumer-like user experience for support and operations. We have built the world’s first AI-driven IT / HR / Cloud / Customer Support and Operations solution.
Codete accelerates their clients growth through technological expertise and experience. Codite team works with organizations to meet the challenges that digitalization presents. Their clients include digital start-ups as well as established enterprises in the IT industry. To stay competitive in a highly innovative IT industry, strong R&D departments and bold spin-off initiatives is a must. Codete Data Science and Software Architects teams help corporate clients to stay up to date with the mod...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...
Druva is the global leader in Cloud Data Protection and Management, delivering the industry's first data management-as-a-service solution that aggregates data from endpoints, servers and cloud applications and leverages the public cloud to offer a single pane of glass to enable data protection, governance and intelligence-dramatically increasing the availability and visibility of business critical information, while reducing the risk, cost and complexity of managing and protecting it. Druva's...
BMC has unmatched experience in IT management, supporting 92 of the Forbes Global 100, and earning recognition as an ITSM Gartner Magic Quadrant Leader for five years running. Our solutions offer speed, agility, and efficiency to tackle business challenges in the areas of service management, automation, operations, and the mainframe.
The Jevons Paradox suggests that when technological advances increase efficiency of a resource, it results in an overall increase in consumption. Writing on the increased use of coal as a result of technological improvements, 19th-century economist William Stanley Jevons found that these improvements led to the development of new ways to utilize coal. In his session at 19th Cloud Expo, Mark Thiele, Chief Strategy Officer for Apcera, compared the Jevons Paradox to modern-day enterprise IT, examin...
With 10 simultaneous tracks, keynotes, general sessions and targeted breakout classes, @CloudEXPO and DXWorldEXPO are two of the most important technology events of the year. Since its launch over eight years ago, @CloudEXPO and DXWorldEXPO have presented a rock star faculty as well as showcased hundreds of sponsors and exhibitors! In this blog post, we provide 7 tips on how, as part of our world-class faculty, you can deliver one of the most popular sessions at our events. But before reading...
DSR is a supplier of project management, consultancy services and IT solutions that increase effectiveness of a company's operations in the production sector. The company combines in-depth knowledge of international companies with expert knowledge utilising IT tools that support manufacturing and distribution processes. DSR ensures optimization and integration of internal processes which is necessary for companies to grow rapidly. The rapid growth is possible thanks, to specialized services an...
At CloudEXPO Silicon Valley, June 24-26, 2019, Digital Transformation (DX) is a major focus with expanded DevOpsSUMMIT and FinTechEXPO programs within the DXWorldEXPO agenda. Successful transformation requires a laser focus on being data-driven and on using all the tools available that enable transformation if they plan to survive over the long term. A total of 88% of Fortune 500 companies from a generation ago are now out of business. Only 12% still survive. Similar percentages are found throug...