NHibernate 3.2 Mapping by Code: Component Mapping

12 Oct 2011

Component mapping in NHibernate 3.2 Mapping by code provides a very flexible way. You can have multiples static method for returning Action<IComponentMapper<Address>> for the same component class. So that you can reuse it in different place with more customization.

In this example, we have Veteran class and Address class as a component.

 

Entity class files

Address.cs

  public class Address
  {
    public virtual string HouseNo { get; set; }
    public virtual string Street { get; set; }
    public virtual string Commune { get; set; }
    public virtual string District { get; set; }
    public virtual string Province { get; set; }
  }

Veteran.cs

  public class Veteran
  {
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Address Address { get; set; }
  }

Entity mapping class files

AddressMap.cs

  public class AddressMap
  {
    public static Action<IComponentMapper<Address>> Mapping()
    {
      return c =>
               {
                 c.Property(p => p.HouseNo);
                 c.Property(p => p.Street);
                 c.Property(p => p.Commune);
                 c.Property(p => p.District);
                 c.Property(p => p.Province);
               };
    }
  }

VeteranMap.cs

  public class VeteranMap : ClassMapping
  {
    public VeteranMap()
    {
      Id(p=>p.Id, map=>map.Generator(Generators.GuidComb));
      Property(p=>p.Name);
      Component(p=>p.Address, AddressMap.Mapping());
    }
  }

3 responses so far

What is the most popular programming language?

04 Oct 2011

The data from langpop.com and IEEE Spectrum magazine released on Oct 2011 about the popularity of programming languages recently.

Popular Programming Languages

Popular Programming Languages

No responses yet

NHibernate 3.2 Mapping by Code – Enforce Referential Integrity

28 Sep 2011

In the previous post, I show an example of a simple parent/child mapping by code in NHibernate 3.2. In this article, I will show how to enforce referential integrity in way the that deleting a parent record will yield to child record deletion as well.

The data model is exactly the same as previous post. The different is mapping technique.

ProvinceMap.cs

  public class ProvinceMap : ClassMapping
  {
    public ProvinceMap()
    {
      Id(p=>p.Id, map=>map.Generator(Generators.Assigned));
      Property(p => p.Code, map =>
                              {
                                map.Length(3);
                                map.NotNullable(true);
                              });
      Property(p=>p.Name);

      Bag(p => p.Districts, map =>
                              {
                                map.Key(k =>
                                          {
                                            k.Column("ProvinceId");
                                            k.OnDelete(OnDeleteAction.Cascade);
                                          });
                                map.Cascade(Cascade.All);
                                map.Inverse(true);
                              }, ce => ce.OneToMany());
    }
  }

DistrictMap.cs

  public class DistrictMap : ClassMapping
  {
    public DistrictMap()
    {
      Id(p=>p.Id, map=>map.Generator(Generators.Assigned));
      Property(p=>p.Name);
      ManyToOne(p=>p.Province, map=>map.Column("ProvinceId"));
    }
  }

NUnit Test

    [Test]
    public void Referential_integrity_should_work()
    {
      var province = new Province() {Id = 1, Code = "BMC", Name = "Banteay Meanchey"};
      var districtA = new District() {Id = 101, Name = "AA", Province = province};
      var districtB = new District() {Id = 102, Name = "BB", Province = province};

      province.Districts.Add(districtA);
      province.Districts.Add(districtB);

      using(var tx=NhSession.BeginTransaction())
      {
        NhSession.Save(province);
        tx.Commit();
      }

      var provinceBMC = NhSession.Get(province.Id);
      Assert.AreEqual("BMC", provinceBMC.Code);
      Assert.AreEqual(2, provinceBMC.Districts.Count);

      using(var tx = NhSession.BeginTransaction())
      {
        NhSession.Delete(provinceBMC);
        tx.Commit();
      }

      var queryDistrictA = NhSession.Get(districtA.Id);
      Assert.IsNull(queryDistrictA);
    }

 

5 responses so far

NHibernate 3.2 Mapping by Code – Basic Mapping

27 Sep 2011

NHibernate 3.2 is coming with default mapping interface that based on ConfORM interface NOT Fluent NHibernate interface. Since its released, there is little document on how to manage mapping by code with this new interface. So this post will contribute to the short.

I have a simple schema as follow:

I have these files to show you.

  1. App.Config, configuration file
  2. ApplicationContext.cs, manage NHibernate configuration and SessionFactory
  3. Province.cs, District.cs, a domain model as depicted in the figure above
  4. ProvinceMap.cs, DistrictMap.cs, a class-by-class mapping
  5. SchemaTest.cs, a drop and create schema for testing
  6. A full source code will be uploaded later while tutorial is completed
App.Config


  
    
  
  
    
  

ApplicaionContext.cs
  public class ApplicationContext
  {
    public static Configuration NHConfiguration { get; set; }
    public static ISessionFactory SessionFactory { get; set; }

    public static void AppConfigure()
    {
      #region NHibernate configuration

      NHConfiguration = ConfigureNHibernate();

      SessionFactory = NHConfiguration.BuildSessionFactory();

      #endregion
    }

    private static Configuration ConfigureNHibernate()
    {
      var configure = new Configuration();
      configure.SessionFactoryName("BuildIt");

      configure.DataBaseIntegration(db =>
      {
        db.Dialect();
        db.Driver();
        db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
        db.IsolationLevel = IsolationLevel.ReadCommitted;

        db.ConnectionStringName = "NH3";
        db.Timeout = 10;

        // enabled for testing
        db.LogFormattedSql = true;
        db.LogSqlInConsole = true;
        db.AutoCommentSql = true;
      });

      var mapping = GetMappings();
      configure.AddDeserializedMapping(mapping, "NHSchemaTest");
      SchemaMetadataUpdater.QuoteTableAndColumns(configure);

      return configure;
    }

    private static HbmMapping GetMappings()
    {
      var mapper = new ModelMapper();

      mapper.AddMappings(Assembly.GetAssembly(typeof(ProvinceMap)).GetExportedTypes());
      var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

      return mapping;
    }
  }
Province.cs
  public class Province
  {
    public Province()
    {
      Districts = new List();
    }

    public virtual long Id { get; set; }
    public virtual string Code { get; set; }
    public virtual string Name { get; set; }
    public virtual IList Districts { get; set; }
  }
District.cs
  public class District
  {
    public virtual long Id { get; set; }
    public virtual string Name { get; set; }
    public virtual Province Province { get; set; }
  }
ProvinceMap.cs
  public class ProvinceMap : ClassMapping
  {
    public ProvinceMap()
    {
      Id(p=>p.Id, map=>map.Generator(Generators.Assigned));
      Property(p => p.Code, map =>
                              {
                                map.Length(3);
                                map.NotNullable(true);
                              });
      Property(p=>p.Name);

      Bag(p => p.Districts, map => map.Key(k => k.Column("ProvinceId")), ce => ce.OneToMany());
    }
  }
DistrictMap.cs
  public class DistrictMap : ClassMapping
  {
    public DistrictMap()
    {
      Id(p=>p.Id, map=>map.Generator(Generators.Assigned));
      Property(p=>p.Name);
      ManyToOne(p=>p.Province, map=>map.Column("ProvinceId"));
    }
  }
SchemaTest.cs
  public class SchemaTest
  {
    [Test, Explicit]
    public void Create()
    {
      ApplicationContext.AppConfigure();
      new SchemaExport(ApplicationContext.NHConfiguration).Create(false, true);
    }

    [Test, Explicit]
    public void Drop()
    {
      ApplicationContext.AppConfigure();
      new SchemaExport(ApplicationContext.NHConfiguration).Drop(false, true);
    }
  }

5 responses so far

Cyberbullying

12 Sep 2011

Indeed I found an interesting article from Computer Magazine dated September 2011 about Cyberbullying. This is a research achievement from MIT Media Lab to create a novel social network software that can prevent  from bullying.

As you know well, social network has a major impact on the Internet usage today for teenager and adult. It is a place to connect people, make friend or even more. However, some gangs or a group of people may take advantage of it to bully a kid, for example. So that that kid may feel scare, isolated, or s/he bans him/herself from using the Internet.

The full article is shown here (Let’s Gang Up on Cyberbullying) . It is for education purpose. If it is a copyright issue please let me know I’ll remove it.

No responses yet

Search Engines Fill in the Blank

02 Sep 2011

Search Engines Fill in the Blank

Search Engines Fill in the Blank

Here is the simple research I quoted from IEEE Spectrum Sept on page 58. The author found the smart guess behavior of the two giant search engines. However, the data from what I test is not the same as what the author wrote. It’s probably because of the search engines have changed their algorithm or the search result differs from one location to another.

2 responses so far

Wi-Fi Question of the Day

20 Jul 2011

Please try to choose the one correct answer.

What is a disadvantage of using a Wi-Fi network as a high-availability production network?

A.  Attacks against the 802.11 protocol can be detected, but not prevented.
B.  The only method of troubleshooting a Wi-Fi network is verifying configuration parameters.
C.  Reliable site surveys cannot be performed in some environments.
D.  WLAN switches/controllers cannot be installed in a redundant configuration.

 

The correct answer is A

Explanation: Attacks against an 802.11 network such as a deauthentication attack are detectable but cannot be prevented by WIPS or any other device. WLAN implementation troubleshooting can be done using analyzers, site survey tools, and client utilities in most cases. A site survey can be reliably performed in any environment; however, it is possible for a site survey to reveal that the environment is not reliable. WLAN switches and autonomous APs can be installed in a redundant (failover) configuration for high availability environments.

Credit: CWNP Wi-Fi Question of the Day

No responses yet

Google and Facebook by the Numbers

06 Jun 2011

I found an interesting article on the IEEE Spectrum magazine dated this June 2011. It is hard to make a comparison between Facebook and Google.

Description Google Facebook
Establishment 1998 2004
Usage 1 billion search requests each day 600 million active users (25 minutes)
Localization 40 languages 76 languages
Average Employee Age 30 31
Number of employee 30 000 employees 2 000 employees
Number of patents 620 U.S. patents 8 U.S. patents
Market Valuations (Q1 2011) US$ $175 billion $65 billion

 

No responses yet

Selenium Grid

22 Apr 2011

Selenium Grid Architecture

Selenium Grid Architecture

Selenium is a fantastic web application testing package that comes with different form factors such as Selenium IDE, Selenium Remote Control (RC), Selenium WebDriver and finally Selenium Grid. It highly depends on quality assurance to choose whichever appropriated. This article we see Selenium Grid as it is a good example of distributed systems.

What is Selenium Grid actually?

In distributed systems, Cloud computing is usually running on homogeneous platform while Grid computing is running heterogeneous platform. Similarly, Selenium Grid is running on different (heterogeneous) platform, support various programming languages, support multiples unit test framework, and more importantly is cross browsers.

Continue Reading »

No responses yet

Performance of ReentrantLock and Synchronized

19 Apr 2011

ReentrantLock and Synchronized

ReentrantLock and Synchronized

Synchronized keyword is famous in locking shared variables to be modified by only one thread at the specific time. However, it has performance issue while multiple threads are trying to contend for accessing shared variables. JDK 5.0 is redesigned memory model that makes it truly cross platform for multithread environment. JDK 5.0 adds java.util.concurrent package that supports various optimized concurrency tools.

In this article, I present the performance of ReentrantLock and Synchronized. Actually, the performance has been reveal in Java theory and practice: More flexible, scalable locking in JDK 5.0. However, that article did not show the source code of how to do it.

Prerequisite

Continue Reading »

5 responses so far