Tag: .NET

.NET environment automation with Powershell

In the upcoming series of short posts, I would like to describe how some common developer tasks in .NET ecosystem can be automated via Powershell.

The list follows:
Create a website on IIS, including creation and usage of self-signed certificate
– Setting Sql Server authentication mode and creating database logins
– Creating a database based on Visual Studio Database Project
– Executing Sql queries
– Calling REST APIs

Advertisements

Passing complex objects to ASP.NET MVC action using HTTP GET method via jQuery ajax

Sometimes, you might encounter a minor issue in ASP.NET MVC: via AJAX, you can easily pass whatever object you want to your POST action, but doing so with GET endpoint is not so obvious. Plain object would work, but once it starts to be more complex, containing nested objects, everything breaks down and nested objects properties are never filled in.

As an example, consider this jQuery bit:

var obj= { prop1: "val1", nested: { prop2: "val2" } };
$.ajax({
    type: "GET",
    data : obj
})

This is what it sends to the server:

prop1=val1&nested%5Bprop2%5D=val2

or, unencoded:

prop1=val1&nested[prop2]=val2

It seems like array syntax is not welcomed by MVC. What IS welcomed then? Turns out, dot member access is parsed quite nicely – all we need to do is to replace foo[bar] with foo.bar in case of non-numeric array index. The sample code, adapted from the following StackOverflow answer http://stackoverflow.com/a/17580574/76176 is like this:

var obj = { prop1: "val1", nested: { prop2: "val2" } };
var data = $.param(obj).replace(/%5b([^0-9].*?)%5d/gi, '.$1');
$.ajax({
    type: "GET",
    data : data
})

Which produces the following result, happily consumed by MVC:

prop1=val1&nested.prop2=val2

ASP.NET performance measurements on desktop Windows

Proper benchmarking has always been hard – it is trivial to get some numbers, but not so if you are trying to receive relevant ones, that is, results describing the behaviour of the system under test rather than some of auxiliary setup.

One example is testing ASP.NET web sites performance on a developer machine running Windows. It is very easy to achieve pretty low results compared to other systems like Apache, and the outcome is tempting to make far-reaching conclusions about platform’s performance. For a less obvious example, blog post I’ve stumbled upon recently compared the performance of Web API project using synchronous and asynchronous code, having threaded solution blown out of water by the magnitude of ten.

However, such results do not signify a weakness of Windows/IIS/ASP.NET platform in general due to the simple fact that IIS running on non-server Windows is limited to pretty small number (3 or 10) of concurrent web requests, which naturally limits throughput of a web application quite heavily if the request processing time is not too small. It might not be a bottleneck if your requests are done in 50 ms or so, but if the idea is to simulate a long call to an external web service, then the results stop to be realistic very soon.

How to get the real data then? Of course one way is to use Windows Server machine for performance testing. However, it might present less than optimal feedback cycle when you want to work in a measure – adjust – measure loop. Then another solution might be to use self-hosting capabilities present for a long time in Web API and recently included in ASP.NET MVC as well. In my experience, such hosts are quite quick and do not have any artificial limitations even on desktop Windows.

First steps in NHibernate development. Mapping

I continue my NHibernate development posts. In the previous post I showed the necessary steps to set up the framework, but there was nothing really useful above that. Now it’s time to go further to mapping files.

Mapping files define the relationship between the domain model classes and database tables. The first question that comes to mind is where to start: you can design your database tables first and create classes after that, or start with domain model and then define the database. For most greenfield projects I would recommend to start prototyping your application with classes first, and then gradually pay more and more attention to the database issues (you’ll definitely need this at the deploy time and later on).

Let’s start with the following example: imagine you are developing an online game and need to persist some information into the database.  Take the project we’ve created in the previous post and add Player class with Name and Rating properties:

    class Player
    {
        public virtual int Id { get; set; }

        public virtual string Name { get; set; }

        public virtual int Rating { get; set; }
    }

Notice we need the unique identifier property in a class; some other options are possible but generally are more cumbersome to work with. Also, all the properties are marked with virtual keyword. I’ll discuss the reasons for this requirement in future posts when talking about proxies and lazy loading.

Now we want to tell NHibernate how to save Player objects into the database. Add XML file named Player.hbm.xml to the project. Write the following lines in this file:

<?xml version="1.0" encoding="utf-8"?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2"
  assembly="firstSteps" namespace="firstSteps">
  <class name="Player">
    <id name="Id">
      <generator class="native"/>
    </id>
    <property name="Name"/>
    <property name="Rating"/>
  </class>
</hibernate-mapping>

On the top of this XML there is a hibernate-mapping element, stating the assembly and the namespace to search your domain classes in. Inside you can see a class mapping. That’s the simplest mapping possible; it maps the class to the table with the same name (by default as no table name is specified), then maps every listed property to the column with the same name, and uses identifier generation strategy supplied by the underlying database server (identity field on SQL Server).

Add the following line before running Configure method of NHibernate configuration object:

config.AddFile("Player.hbm.xml");

Now we’ve created the mapping between the Player class and the corresponding table, but the database does not have any tables yet. Of course, you can go and create Player table with all the required columns, but there is a better solution. For the most part of development time you’ll want NHibernate to automatically generate database metadata from mapping files. It’s quite handy because NHibernate can even gently update the existing database when you add or modify your mapping.

Add the following line after the Configure() call:

var sessionFactory = config.BuildSessionFactory();

(parameters mean “do not process generated script further” and “do update the database”).

You can run the program and see that the table has really been created.

Finally, we can actually write some code to add a new player to the database:

var player = new Player { Name = "Killer Bean", Rating = 2200 };

using (var session = sessionFactory.OpenSession())
{
    session.Save(player);
}

Console.WriteLine("Added player #{0}", player.Id);

Run the program and see how it’s inserting new records: we’ve done it! But it’s enough for this time, we’ll discuss the basic data manipulation in the next post in the series.

P.S. Experienced database developer can ask “What if I already have the database and need to set up the tables and column names, nullable flags, column length etc.?“ In fact NHibernate has rich mapping capabilities to satisfy even the most demanding requirements. You can explore the NHibernate documentation at nhforge and load mapping XSD from Required_Bins NHibernate folder into the Visual Studio to put Intellisense to operation.

First steps in NHibernate development. Setting up

NHibernate is a highly customizable and tried open source ORM framework for the .NET platform. While it is a very powerful tool, it’s often being criticized due to the very steep learning curve. Indeed, its Java legacy results in a lot of XML configuration, and feature richness brings a large API to comprehend, making diving in NHibernate a hard step for a regular .NET developer. That’s why I will make the series of posts describing NHibernate development in hope to help the beginners.

I will use NHibernate 2.1.2 with Microsoft SQL Server Express 2005 in a console application project.

Let’s go!

  1. Download NHibernate from its sourceforge site, unpack files to some folder.
  2. Create a console application project. Add reference to NHibernate.dll from Required_Bins subfolder of the folder you’ve created on the previous step. Add reference to the NHibernate.ByteCode.LinFu.dll from Required_For_LazyLoading\LinFu folder.
  3. Create the application configuration file (app.config) and make it look like this:
    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="hibernate-configuration"
         type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate"/>
      </configSections>  
      <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
        <session-factory>
          <property name="dialect">
            NHibernate.Dialect.MsSql2005Dialect
          </property>     
          <property name="connection.connection_string">
            Server=.\SQLEXPRESS;initial catalog=NHFirstSteps;
            Integrated Security=SSPI
          </property>
          <property name="proxyfactory.factory_class">
            NHibernate.ByteCode.LinFu.ProxyFactoryFactory,
            NHibernate.ByteCode.LinFu
          </property>
        </session-factory>
      </hibernate-configuration>
    </configuration>
    
  4. Create a database named NHFirstSteps in the SQL Express.
  5. Put NHibernate.Cfg namespace in the using section of the program. Add the following code to the Main method:
    var config = new Configuration();
    config.Configure();
    var sessionFactory = config.BuildSessionFactory();
    
    Console.WriteLine("Hello, NHibernate!");
    
  6. Now run the console app. If you are seeing the “Hello, NHibernate!” message, all the settings are correct and you are ready to go further.

But wait for a minute, what’s the meaning behind all these magical passes?

Of course, referencing NHibernate.dll is a natural way to use framework’s capabilities, but adding NHibernate.ByteCode.LinFu.dll is a little bit more interesting. That is required to support lazy loading feature, and in fact you can choose from the three implementations out there: Castle Dynamic Proxy, LinFu Dynamic Proxy or Spring AOP. Don’t be afraid – you don’t need to delve in these matters right now, just select one proxy library and set its name in the proxyfactory.factory_class property of the configuration file.

Another required setting in the configuration file is, of course, database server type (dialect) and actual database connection string. All the common database servers such as MS SQL, Oracle, DB2, MySQL, PostgreSQL are supported. Database connection string must be in the format specified by the ADO.NET driver being used (this example uses SQL Server connection string with local SQL Express server, NHFirstSteps database and Windows authentication).

In the code we initialize NHibernate (by default configuration is loaded from the application config file) and build session factory. Session factory is a tool to make sessions, the main objects in the NHibernate development. Sessions implement unit of work pattern and allow you to load, save and query the data.

Note that both configuration and session factory building are very time-consuming processes, and usually should be called once at the app domain start.

Where to go next? Wait for the next post in NHibernate first steps series!