Feb112009

First NHibernate Experience

I was reading about NHibernate in the last 3-4 days.  When i heard that LINQ2SQL will not be supported anymore, i was looking for a good ORM tool, and i decided to give a try to NHibernate. I just went to its website and downloaded version 2.0.1. I decided to write a very simple insert operation using NHibernate so i opened up many websites talking about NHibernate tutorials and tried to copy the code. I got so many errors :) that one time i decided to give up. One major problem i had was the configuration settings, unfortunately NHibernate wasn't throwing good error message so it took me sometime to figure out that configuration settings for NHibernate 2.0.0.1 is different than older versions, so here is a sample configuration file i have in my app.config that works :)

<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="dialect">
                NHibernate.Dialect.MsSql2005Dialect
            </property>
            <property name="connection.driver_class">
                NHibernate.Driver.SqlClientDriver
            </property>
            <property name="connection.connection_string">
                Data Source=acm48_89\SQL;Integrated Security=True; initial catalog=StudentsDB
            </property>
        </session-factory>
    </hibernate-configuration>
</configuration>

After i set this up, i got my second error :), which was basically telling me that NHibernate can’t find the property in my class. My class was partially like this:

public class Student
   {
       public int SID { get; set; }
       public string FirstName{ get; set; }
       public string LastName { get; set; }

and my mapping xml was:

<class name="Student" table="Students">
       <id name="SID" access="field" column="SID">
           <generator class="native"/>
       </id>
       <property name="FirstName" access="field" column="FName"/>
       <property name=”LastName access=”field” column=”LName”/>
  </class>

NHibernate was telling me that it can’t find any of these properties :), so i tried to read the documentation and it was really boring, and for some reason i don't remember, i decided to remove access=”field” section from the mapping and xml, and boom, this error message disappeared and i got my third error message :) which  this time was more self explanatory: The properties has to be virtual.. This was easy fix for me as i read that, to support lazy loading, you have to mark you fields as virtual. I didn't want to have lazy loading for this simple project, so i added the key to mapping xml to turn off the lazy loading which is simply :lazy="false"

i think i am kind of having fun for now while i am learning NHibernate but i will use code smith to derive my classes and configuration settings once i get familiar doing them manually.



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 1 Responses

Feb102009

Attending MIX’09, Silverlight Finally

mix09_blogbling_interfaceinspiration_cr4

I am attending this year’s Mix event at Las Vegas. I took so many training classes for Microsoft products, been an active .net developer from some years, and first time attending this type of event :) Before i attended TechEd, or Google Developer’s Conference, and first time MIX thanks to Lynn Langit. I am checking some of the sessions and i am glad to see lots of Silverlight sessions. I don't know why i couldn't see many Silverlight sessions at code camps and i started to think that Microsoft was pushing enough. Now that seeing lots of Silverlight sessions changed my idea.

At work, i might use Silverlight in the future, for now,we use flash to stream the videos, and as long as there is no converter from a flash streaming video to Silverlight streaming video, we wont be jumping to Silverleright directly. So many hours and millions of dollars are already spent to record those videos, nobody can trash them :).

As a developer and most of the time as a person deciding the technology to use for the future projects, i will definitely use Silverlight, as i speak C# but not actionscript :). I already start talking about Silverlight at work to influence people ;).

See you at MIX



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Feb032009

if(int?)

One of my friend had an interview with a company, and he told me it didn't go well as they asked some detail questions in C#. I asked him to tell me a few of the questions. One question was interesting i guess, cause i think it is so simple that nobody will ask in the interviews. Of course guess what? my friend didn't give the right answer :).

It is a small sample code, asking what is wrong this with code. here is the code:

string name=”john Doe”;
if(name.Length)
{
Console.WriteLine("name is greater than 0 characters");
}

Maybe my friend was very anxious during the interview, as it is very difficult to get a job nowadays (economic crisis really hurt a lot), but i think any decent c# programmer should see the problem right away because it is a compiler time error. It is difficult to catch the runtime errors, but compile time errors? You just need to compile your code a good number of times i guess :) Anyways let’s go back our question. If you read the C# reference for if keyword, you will see that inside the parentheses right after if; you have to write an expression that can be implicitly converted to a bool.  Integer types can’t be converted to bool implicitly, and you have to write an expression that will evaluate a boolean value .

In the code if(name.Length) , the expression name.Length returns an integer not a bool, so if want to fix this code :

string name=”john Doe”;
if(name.Length>0)
{
Console.WriteLine("name is greater than 0 characters");
}

Also checkout String.IsEmptyOrNull()

let the force help you



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Jan272009

lock(string) deadlock, and interning

In one of my applications, one of the database (Oracle Server), started responding very slowly which was causing timeout errors on the browser. I decided to cache the data, so i wrote this:

   1: HttpContext.Current.Cache.Add("dtUsers", dtUsers, null, DateTime.Now.AddDays(2), 
   2: TimeSpan.Zero,System.Web.Caching.CacheItemPriority.Normal, null);


The above code is simply putting the database into the cache.I read in so many different places that System.Web.Cache is thread safe; however still i decided to put a lock mechanism to make sure, only 1 instance can access to cache, as there is only 1 item in the cache (which is the datatable), and all other threads will be reading/writing to this. So i read about lock in ASP.NET, and i wrote the below code:

   1: DataTable dtUsers = null;
   2: if (HttpContext.Current.Cache["dtUsers"] != null)
   3:     {
   4:         return (HttpContext.Current.Cache["dtUsers"] as DataTable).Copy().DefaultView;
   5:     }
   6:     lock (CacheSyncObject)
   7:     {          
   8:         if (HttpContext.Current.Cache["dtUsers"] != null)
   9:         {           
  10:             return (HttpContext.Current.Cache["dtUsers"] as DataTable).
  11:                 Copy().DefaultView;
  12:             }
  13:             dtUsers = OnlineDirectoryAccess.GetUsers();
  14:             HttpContext.Current.Cache.Add("dtUsers", dtUsers, null, 
  15:                 DateTime.Now.AddDays(2), TimeSpan.Zero,
  16:                 System.Web.Caching.CacheItemPriority.Normal, null);
  17:             return (HttpContext.Current.Cache["dtUsers"] as DataTable).Copy().DefaultView;
  18:         }

The lock object CacheSyncObject was a string object i created as a static variable, so that simple code was:

   1: public static string CacheSyncObject = "CacheSync";

Everything was working in my local, however when i deployed the project, the web application stopped working, and got timeout errors. I put some logs to see when it hang, and apparently at the lock() statement, the system was frozen. There was a deadlock in the system, after so many reading, and asking questions in the forums, i got my answer :) and i want to share it now :)

.NET Framework uses string interning to store strings. You can see the definition of this at wikipedia. Basically for performance issues, framework is storing only 1 copy of each distinct string value in the memory. By this way, same copy of string is shared between threads and different AppDomains. This also brings the issue of not being able have too much control over the strings. For this reason we should not put locks on string objects as other threads have still access to the same memory address.

The solution was very simple:

   1: public static object CacheSyncObject = new object();


Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Jan262009

Azure? Cloud Computing?

    So what is this Azure platform? What is cloud computing? I went to Southern California Code Camp. and attended the Azure presentations, as well as i attended the user group meetings. What is the cloud? Let’s say you are web developer, and you create a website; What do you do next? Publish it to a host so that everyone in the world can access to your site right? You can think Cloud environment as a hosting environment for you but there are some differences :). Microsoft Azure is a cloud environment from Microsoft.

    One of the biggest difference is, your website will be in a datacenter that Microsoft (i am talking about Microsoft Azure when i mention Cloud in this post) owns. These datacenters (yes there is more than one geographically located around the world) are huge, and 7/24 up. These datacenters will synchronize your web application by checking the your visitors’ locations, For example if your application is in a datacenter at Southern California, and you are getting so many hits from Europe, your application will be copied to datacenter in Europe automatically to serve your visitors faster. This geo relocation will be done completely by Microsoft.
These servers will be patched by Microsoft, the security will be handled by Microsoft, uptime will be handled by Microsoft, power issues will be handled by Microsoft, ram, disk, cpu resources will be handled by Microsoft… You only have to worry about your application and your visitors. Some of you may be worried about data confidentiality; but think this, if Microsoft uses your data for their own business, and they are caught doing this; all their customers will leave them, and they will be left alone with their multi million dollar investments :).

    This cloud computing in Microsoft world is called Windows Azure platform. You can think of Microsoft Azure, as the operating system of this cloud that supports some services such as: Microsoft .NET Services (of course :)), Live services, Sql Data Services.. Here is simple picture that shows Azure and its layers:

azurePlatform_web

   It is a simple topology i guess, just a virtual kinda operating system called Windows Azure, supporting some programming platforms, and you host your application here, that could be synced to multiple datacenters depending on the requests. So is this all? just a bunch of datacenters that syncs your app :) no not at all. There are more stuff in this system than just a distributed environment.

   Now lets talk about  some other advantages, If you host your web application in a host environment, after some time, if your web application gets good hits, you may want to buy a dedicated server to have more resources, and maybe later on if your business is really doing good, more servers or a web farm. However what if your application will be getting hits on some specific days such as a super bowl night, Christmas weekend or valentines day as more people will be shopping, will be buying more servers just for 10 days of the year? In the cloud environment, what you can do is ask for more ram, more machines instantly, use it, and then give it back, so you only get the resources you need, when you need it. For the ctp version, you request the resources through a configuration file, however in the release version it is said that, the system will scale the resources automatically, which means will add more cpu or ram when your application requires it (of course you will put a maximum resource limit in the configuration file).

   Now that we have this super efficient, reliable, scalable computer network out there for us, how much will Microsoft charge us? Don't know, as they haven't announced it. All i know is the price will be comparable and affordable to other Cloud network suppliers (such as Google or Amazon).

   I will download the tools to start doing some experiments, and will be posting my experiences too. Stay tuned :)



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 1 Responses

Jan252009

Socal Codecamp

azurelogo The star of this year’s codecamp was Windows Azure. So many good talks about Windows Azure was on the first day. I got the basics of it, even though i still have some doubts such as how about the sessions, sync of sessions, file backup/restore, using third party tools in the cloud such as emailer etc. I do have a small poject in my mind that my wife was the starter for this project :). I will be using Azure, Sql Data Services and Silverlight. I dont know how this will work out but we will see what i could do with these :)



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Dec282008

Castle.Windsor case sensitive urls with asp.net MVC?

I am completely a newbie when it comes to using ioc frameworks. For one my hobby projects i was working on using asp.net mvc, i decided to use castle.windsor for the dependency injection. I created a class deriving from IControllerFactory as below:

[code:c#]

  internal class WindsorControllerFactory:IControllerFactory

    {

        WindsorContainer container;

 

        public WindsorControllerFactory()

        {

            container = new WindsorContainer(new XmlInterpreter(new ConfigResource(("castle"))));

            // Also register all the controller types as transient

            foreach (Type t in Assembly.GetExecutingAssembly().GetTypes())

                if (typeof(IController).IsAssignableFrom(t)) // Is it a controller?

                    container.AddComponentWithLifestyle(t.Name, t,

                    LifestyleType.Transient);

        }

 

        #region IControllerFactory Members

 

        public IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)

        {

            string name = controllerName + "Controller";

            return container.Resolve<IController>(name);

        }

 

        public void ReleaseController(IController controller)

        {

            IDisposable disp = controller as IDisposable;

            if (disp != null)

                disp.Dispose();

        }

 

        #endregion

    } 

[/code] 

The interesting thing is my urls become case sensitive suddenly :) so /home/list is not matching whereas /Home/List is matching route. Fix? dont know yet hehe 



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Dec192008

2009 Resolutions (Programming & Career)

Here is a list of things i would like to accomplish next year (not in any particular order)

 

  1. Get MCT, MCDBA, and MCSD certificates
  2. Do more unit testing in every project (visual studio test framework, moq)
  3. When MVC is released, use it for the new projects
  4. Become more familiar with a dependency injection framework (windsor maybe?)
  5. Spend more time on YABE (lack of time i stop doing updates)
  6. Spend more time on silverlight
  7. spend more time on open source contributions
what is urs?

 

 



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 3 Responses

Dec182008

LINQ Entity Properties

Let's assume you create an entity class, that represents a structure in your database, for example:
[code:c#]
public class Person 
{
public int PersonID{get;set;}
public string FirstName{get;set;}
public string LastName{get;set;}
...
}
[/code]
Now after you create this class, you have to tell the compiler that this class represents a table in your database.
Let our table name be PersonsTB. Below is the attribute you have to use:
[code:c#]
[Table(Name="PersonsTB")]//this tells linq that the table for this entity is PersonsTB
public class Person
{
...
}
[/code]
If my class name was exactly the same with the actual table name, then i didnt have to specity the name, i could simply write [Table].
However i used a different class name, so i have to specify the table name as an attribute of the class. What else? All the entity objects
must have a primary key (know why? if you dont have a unique primary key in your entity class, they are readonly, 
you cant modify them, cause datacontext cant keep track of them), lets define our primary key name:
[code:c#]
[Table(Name="PersonsTB")]
public class Person
{
[Column(IsPrimaryKey=true)] public int PersonID{get;set;}
....
}
[/code]
Now our entity class has a table name and a primary key, let's define the other 2 columns. FirstName has the same column name in our table so 
i didnt specify Column Name attribute, but, LastName represents the column SurName in the table, and i did specify a name attribute
[code:c#]
[Table(Name="PersonsTB")]
public class Person 
{
[Column(IsPrimaryKey=true)] public int PersonID{get;set;}
[Column] public string FirstName{get;set;}
[Column Name="SurName"] public string LastName{get;set;}
...
}
[/code]
Next step is, opps stop, we have a primary key, and usually the primary keys are auto incremented, database generated columns, which means
whenever i insert a value into the table, this primary key will be assigned a value. I want that value to be copied to my primary variable
in the class automatically after the insertion. How? simple just add this attribue:
[code:c#]
[Table(Name="PersonsTB")]
public class Person 
{
[Column(IsPrimaryKey=true), IsDBGenerated=true] public int PersonID{get;set;}
...
}
[/code]
How about if i assign a value to my entity class's properties and submit the change to the database, however the database has a trigger
or some other way of changing this value before it is submitted!! I also want my entity class properties be synced. Let's assume there is trigger on 
the firstname column, and i want this column to be updated in my entity class after my insertion.
[code:c#]
[Table(Name="PersonsTB")]
public class Person 
{
[Column(IsPrimaryKey=true), IsDBGenerated=true] public int PersonID{get;set;}
[Column(AutoSync=AutoSync.Insert)] public string FirstName{get;set;}
...
}
[/code]
Confused ? dont be...


Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Dec042008

Best Programmer's Joke

One of the best programmer's joke i've seen:



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses