Feb032009

if(int?)

Published by volkanuzun at 9:12 AM under

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



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

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

Jan272009

lock(string) deadlock, and interning

Published by volkanuzun at 2:26 PM under

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();


[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

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

Jan262009

Azure? Cloud Computing?

Published by volkanuzun at 12:02 AM under

    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 :)



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

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

Jan252009

Socal Codecamp

Published by volkanuzun at 10:57 AM under

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 :)



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

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

Dec282008

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

Published by volkanuzun at 3:31 PM under

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:

  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

    } 

 

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 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

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

Dec192008

2009 Resolutions (Programming & Career)

Published by volkanuzun at 9:24 AM under

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?

 

 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

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

Dec182008

LINQ Entity Properties

Published by volkanuzun at 10:18 PM under

Let's assume you create an entity class, that represents a structure in your database, for example:
public class Person 
{
public int PersonID{get;set;}
public string FirstName{get;set;}
public string LastName{get;set;}
...
}
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:
[Table(Name="PersonsTB")]//this tells linq that the table for this entity is PersonsTB
public class Person
{
...
}
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:
[Table(Name="PersonsTB")]
public class Person
{
[Column(IsPrimaryKey=true)] public int PersonID{get;set;}
....
}
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
[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;}
...
}
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:
[Table(Name="PersonsTB")]
public class Person 
{
[Column(IsPrimaryKey=true), IsDBGenerated=true] public int PersonID{get;set;}
...
}
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.
[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;}
...
}
Confused ? dont be...


[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

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

Dec042008

Best Programmer's Joke

Published by volkanuzun at 10:26 AM under

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



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

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

Nov182008

IComparable, IEquatable

Published by volkanuzun at 9:51 AM under

I am still reading the book about writing more effective c# code. One of the chapters is talking about using IComparable and IEquatable for comparions, and checking equality. The news interfaces are strongly typed, so the code is less, cleaner, and nicer; however, for a lot of purposes you may want to support old style override Equals(object obj) too, and as good practive whenever you overwrite Equals, you should overwrite GetHastCode, especially if you are using LINQ or update wont work.

here is a simple code from one my project that does it all 

 public class Restriction:IComparable<Restriction>,IEquatable<Restriction>
    {
        /// <summary>
        /// Restriction Unique ID, should be assigned by DB
        /// </summary>
        /// <remarks>if it is <1 then throws ArgumentOutOfRangeException</remarks>
        private int ID_;
        public int ID
        {
            get{ return this.ID_;}
            set
            {
                if (value<1)
                    throw new ArgumentOutOfRangeException("ID can not be less then 1");
                this.ID_ = value;
            }
        }
        /// <summary>
        /// Restriction rule
        /// </summary>
        /// <remarks>If it is empty or null, will throw ArgumentNullException
        ///          If len(Rule)>MAX_RESTRICTION_LEN throws ArgumentOutOfRangeException
        /// </remarks>
        /// <seealso cref="Constants"/>
        private string Rule_;
        public string Rule
        {
            get { return this.Rule_; }
            set
            {
                if(String.IsNullOrEmpty(value))
                    throw new ArgumentNullException("Rule can not be empty or null");
                if(value.Trim().Length==0)
                    throw new ArgumentNullException("Rule can not be empty or null");
                if(value.Trim().Length>Constants.MAX_RESTRICTION_LEN)
                    throw new ArgumentOutOfRangeException("Length of Rule can not be bigger than MAX_RESTRICTION_LEN");
                this.Rule_ = value;
            }
        }

        public Restriction(int ID, string Rule)
        {
            this.ID = ID;
            this.Rule = Rule;
        }

        public int CompareTo(Restriction other)
        {
            if (other == null)
                return 1; // any non null object > null
            int rVal = Comparer<string>.Default.Compare(this.Rule.ToLower().Trim(),
                                                        other.Rule_.ToLower().Trim());
            return rVal;
        }

        public bool Equals(Restriction other)
        {
            if (Object.ReferenceEquals(other, null))
                return false;
            return this.Rule.ToLower().Trim() == other.Rule.ToLower().Trim();
        }

        public override bool Equals(object obj)
        {
            if (obj.GetType() == typeof(Restriction))
                return this.Equals(obj as Restriction);
            return false;
        }

        public override int GetHashCode()
        {
            return this.Rule.ToLower().Trim().GetHashCode();
        }

        public override string ToString()
        {
            return this.Rule;
        }
    }



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags:

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

Nov102008

Refactor code, Design Practices

Published by volkanuzun at 9:31 PM under

I start reading "More Effective C# from Bill Wagner". It is a really nice book, unlike the other books i read, with this book i start reading random chapters. Actually not that random, the chapters that i like more :) I will highly recommend this book btw.

So lets take a look at the Item 17: Create Composable APIs for Sequences

here is a simple code from the book:

public static void Unique(IEnumerable<int>num)
{
   Dictionary<int,int>uniqueVals = new Dictionary<int,int>();
   foreach(int num in nums)
   {
      if(!uniqueVals.ContainsKey(num))
         {
    uniqueVals.Add(num,num);
    Console.WriteLine(num);
         }
   }

 

 So what's wrong with the code above? First of all, the code is writing the unique numbers to the console on a passed IEnumerable<int>. However, the function is doing more than 1 principal job, it does 2 different things. First it loops through the numbers, collects the unique numbers in a dictionary, and second, it writes the numbers to the console. Because of 2 unrelated jobs being assigned to this function, it is not easy to reuse the code, and also not easy to  unit test the code. If you could seperate this 2 jobs into 2 different functions, it will be easier to unit test this code and also reuse this code. Let's try to do refactor code as step 1 progress:


public static Dictionary<int,int> Unique(IEnumerable<int>num)
{
   Dictionary<int,int>uniqueVals = new Dictionary<int,int>();
   foreach(int num in nums)
   {
      if(!uniqueVals.ContainsKey(num))
         {
    uniqueVals.Add(num,num);
 }
   }
   return uniqueVals;


private static void PrintUniques(IEnumerable<int>numbers)
{
      Dictionary<int,int>uniqueVals = Unique(numbers);
      foreach(int num in uniqueVals )
      {
         Console.WriteLine(num);
      }

 

Now we divided the function into 2  functions, and they can be easily reused as they only do 1 task, also it is easier to unit test it (to unit test PrintUniques function, you can use StreamWriter instead of console). However we can easily refactor this code more :), using "yield". Yield is an interesting function, it returns the value while you are iterating one at a time. One big advantage is you dont have to load the whole array into the memory, so if in any part of your loop, you have an exit from the iteration, you wont end up having everything loaded in the memory and not using it :) So you will get the value, and the index pointer will move to the next element, for the next step in the iteration. This is kinda like lazy loading in LINQ. Here is the code again:

 

public static IEnumerable<int> Unique(IEnumerable<int>num)
{
   Dictionary<int,int>uniqueVals = new Dictionary<int,int>();
   foreach(int num in nums)
   {
      if(!uniqueVals.ContainsKey(num))
         {
    uniqueVals.Add(num,num);
            yield return num;
 }
   }


private static void PrintUniques(IEnumerable<int>numbers)
{
      foreach(int num in Unique(numbers))
      {
         Console.WriteLine(num);
      }

 

 Hope it is clear and easy to understand. Let me know if you have any questions. 



[KickIt] [Dzone] [Digg] [Reddit] [del.icio.us] [Facebook] [Technorati] [Google] [StumbleUpon]

Tags: ,

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