Maverick

Friday, June 6, 2008

.NET Custom Settings

We normally tend to lazy and use the .NET Configuration AppSettings element for defining our own custom configuration keys. Though this does solve the purpose but sometime we need MORE. We may need our own tags like <myTag> to be used in the configuration file. .NET provides a standard mechansim to achieve this. Lets assume we want the following in our .config file

<MySettings>

    <Setting Name=”" Value=”" IsValid=”" />

</MySettings>

There are 5 things to be done

  1. Define a class that inherits from ConfigurationElement, this represent the element node i.e. <MySetting> for the above mentioned XML.
  2. Define a class that inherits from ConfigurationElementCollection, this represents the collection node that contain the element node i.e. <MySettings> for the above mentioned XML.
  3. Define a class that inherits from ConfigurationSection, this represent the master class through which the section is accessed.
  4. Add entry in the <configSections> of the config file.
  5. Use System.Configuration.ConfigurationManager.GetSection method to access the section defined in the code.

Now let’s drill with the code

Inherit from ConfigurationElement

public class MySetting : ConfigurationElement
    {
                
        [ConfigurationProperty("Name", IsRequired = true)]
        public String Name
        {
            get
            {
                return (string)this["Name"];
            }
            set
            {
                this["Name"] = value;
            }
        }

      
        [ConfigurationProperty("Value")]
        public String Value
        {
            get
            {
                return (string)this["Value"];
            }
            set
            {
                this["Value"] = value;
            }
        }

        [ConfigurationProperty("IsValid")]
        public bool IsValid
        {
            get
            {
                return (bool)this["IsValid"];
            }
            set
            {
                this["IsValid"] = value;
            }
        }
    }

Inherit from ConfigurationElementCollection

public class MySettings : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new MySetting();
        }
        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((MySetting)element).Name;
        }
        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.BasicMap; }
        }
        protected override string ElementName
        {
            get { return “MySetting”; }
        }
        public MySetting this[int index]
        {
            get{ return (MySetting)BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                    BaseRemoveAt(index);
                BaseAdd(index, value);
            }
        }
        new public MySetting this[string Name]
        {
            get { return (MySetting)BaseGet(Name); }
        }
        public bool ContainsKey(string key)
        {
            bool result = false;
            object[] keys = BaseGetAllKeys();
            foreach (object obj in keys)
            {
                if ((string)obj == key)
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
    }

Inherit from ConfigurationSection

public class MySection:ConfigurationSection
    {
       [ConfigurationProperty("MySettings",IsDefaultCollection=true)]
        public MySettings MySetting
        {
            get
            {
                return (MySettings)base["MySettings"];
            }
        }
    }

 

Entry in App.Config/Web.Config

<configuration>
  <configSections>
    <section name=”MySettings” type=”DebasishPramanik.Configuration.MySection,
      CustomSettings”/>
  </configSections>
  <MySettings>
    <MySetting Name=”BlogID” Value=”12345″ IsValid=”true”/>
  </MySettings>
</configuration>

 

Use in Application

 

DebasishPramanik.Configuration.MySection section = (DebasishPramanik.Configuration.MySection)System.Configuration.ConfigurationManager.GetSection(”MySettings”);
            
foreach (DebasishPramanik.Configuration.Setting setting in section.MySettings)
 {
     Console.WriteLine(setting.Name);
}

 

 

    Thursday, June 5, 2008

    Remove Cookie in ASP.NET

    Filed under: .NET Framework, ASP.NET, C# — Tags: , , , — debasishpramanik @ 10:29 am

    I was working on the Cookies using the HTTPCookie class in ASP.NET. Though it is simple to add cookie and use them in the program but I really struggle to remove the cookies. I tried initially

    1. Get the reference to the cookie.
    2. Use the Response.Cookies.Remove method to remove the cookie.

    I expected the API to behave as per the name i.e. delete the cookie but to my utter shock it didn’t work. After long search I found the solution. The key was to make the cookie expire instead of removing it from the collection

    Response.Cookies["MY_COOKIE"].Expires = DateTime.Now;

    This works perfectly for me.

     

    Monday, May 12, 2008

    The Innovative Product of the Decade

    Filed under: Latest Trends, Others — Tags: , , , , — debasishpramanik @ 11:57 pm

    Dubflick announces the world first online video sound editing tool. This is completely a web based tool and is accessible through http://www.dubflick.com/tomcat.php. The innovator is little bit apprehensive about the success of the product which is visible from the fact that home page is still not developed.

    The following are the features

    1. Create an account or get Register with the site.
    2. Open a video from YouTube by copying the link of YouTube video.
    3. Then start editing the video like putting lot of expressions.
    4. Inserting your own voice.

    This is a great tool for people who loveto make video spoofs but have to depend upon desktop based tool. This is now on web and completely FREE. NO download of heavy software, NO need to buy software and learn the art. It as simple cutting the cake on your birthday.

    Try yourself the most innovative product of the decade.

     Website: http://www.dubflick.com/tomcat.php

    Wednesday, May 7, 2008

    Good Link on HTTP Performance

    Filed under: Latest Trends, Others — Tags: , , — debasishpramanik @ 4:24 pm

    A very good link on HTTP performance

    http://www.stevesouders.com/blog/2008/03/20/roundup-on-parallel-connections/

    Good HTTP Sniffer Tool

    Filed under: Latest Trends, Others — Tags: — debasishpramanik @ 3:31 pm

    In recent past I have been looking on the performance of our web application. To understand what takes more time I was looking for a tool that provide me detailed report what part of the web page takes more time.

    My hunt started with Fiddler, an excellent tool and provides great information but when I looked at the tool named HTTPWatch, I was IMPRESSED. An awesome tool and provide great detail information similar to Fiddler. But the most impressive was it get integrated with your IE browser including IE 8.0 beta. So while you traverse a page and wait for the page getting rendered the tool will display all the HTTP request from browser to web page server. This includes the AJAX request.

    Great tool!!!!! try it out Download

    ASP.NET Config files: Un-necessary Strings

    Filed under: .NET Framework, ASP.NET, C#, Web Services — Tags: , , , — debasishpramanik @ 3:24 pm

    We have been using ANTS Profiler lately to understand the memory behaviour of our ASP.NET application. What we observed is

    1. Too much memory have been allocated by Strings Objects.
    2. These string objects survives across many GC collection.

    When we drill those strings more, we discovered

    1. That these are not our strings.
    2. Actually ASP.NET loads the settings of machine.config and web.config into the memory.
    3. I can now make out why it need to unload the AppDomain when we change these config files as the environment have to reload the settings again.
    4. There are many settings in these config files which have no relevance to our application.
    5. So we started commenting or removing from the machine.config file. (We took the backup of the ORIGINAL file).
    6. For e.g. webPart settings. We removed the entire block.
    7. We tested our web application and found everything to work fine.
    8. We then started removing those un-necessary entries.
    9. We then used the ANTS profiler to profile the memory and found that we save some 58 MB of memory by doing so.
    10. There was direct impact on the Gen 0 collection.

    We haven’t decided whether we will do these on our production server but these can be done provided our application is the only app being used on that server.

    Please take appropriate backup before trying this out.

    Wednesday, April 23, 2008

    String V/s StringBuilder

    Filed under: .NET Framework, ASP.NET, C# — Tags: , , , , — debasishpramanik @ 8:30 pm

    With the help of my friend we did a small test to understand the behavior of StringBuilder and String in terms

     

    1. Execution Time
    2. Memory

    We executed the following piece of code

     

     

    class Program
        {
            ulong SessionID = 1000;
            ulong UserID = 292902;
            String GLOBESNAME = “XXX”;
            static void Main(string[] args)
            {
               
                Stopwatch sw = new Stopwatch();
                sw.Start();
                for (int i=0; i < 1000000; i++)
                {
                    Program p = new Program();
                    p.getXML();
                    
                }
                sw.Stop();
                Console.WriteLine(sw.ElapsedMilliseconds.ToString());
                Console.Read();
            }
            private void getXML()
            {
                String xml = @”<INPUTXML>
                        <SESSIONID>” + SessionID.ToString() + @”</SESSIONID>
                        <USERID>” + UserID.ToString() + @”</USERID>
                        <GLOBESNAME>” + GLOBESNAME + @”</GLOBESNAME>
                        <LANGUAGE>ENGLISH</LANGUAGE>
                        <SEARCH>
                            <LOOKINGFORME>VAULT</LOOKINGFORME>
                            <LOOKINGFORMETYPE>ENTITY</LOOKINGFORMETYPE>
                            <LOOKINGFORMEREQUIRED>FALSE</LOOKINGFORMEREQUIRED>
                            <LOOKINGFOR>
                                <ACCESSTONAME>READ</ACCESSTONAME>
                            </LOOKINGFOR>
                        </SEARCH>
                    </INPUTXML>”;
            }
        }
    The getXML method was changed for StringBuilder.Append and StringBuilderAppenFormat.
    StringBuilder.Append
    ===========================================================
              StringBuilder sb = new StringBuilder(500);
               sb.Append(@”<INPUTXML>
                        <SESSIONID>” + SessionID.ToString() + @”</SESSIONID>
                        <USERID>” + UserID.ToString() + @”</USERID>
                        <GLOBESNAME>” + GLOBESNAME + @”</GLOBESNAME>
                        <LANGUAGE>ENGLISH</LANGUAGE>
                        <SEARCH>
                            <LOOKINGFORME>VAULT</LOOKINGFORME>
                            <LOOKINGFORMETYPE>ENTITY</LOOKINGFORMETYPE>
                            <LOOKINGFORMEREQUIRED>FALSE</LOOKINGFORMEREQUIRED>
                            <LOOKINGFOR>
                                <ACCESSTONAME>READ</ACCESSTONAME>
                            </LOOKINGFOR>
                        </SEARCH>
                    </INPUTXML>”);
    For StringBuilder.AppendFormat
    ===========================================================
    StringBuilder sb = new StringBuilder(500);
               sb.AppendFormat(@”<INPUTXML>
                        <SESSIONID>{0}</SESSIONID>
                        <USERID>{1}</USERID>
                        <GLOBESNAME>{2}</GLOBESNAME>
                        <LANGUAGE>ENGLISH</LANGUAGE>
                        <SEARCH>
                            <LOOKINGFORME>VAULT</LOOKINGFORME>
                            <LOOKINGFORMETYPE>ENTITY</LOOKINGFORMETYPE>
                            <LOOKINGFORMEREQUIRED>FALSE</LOOKINGFORMEREQUIRED>
                            <LOOKINGFOR>
                                <ACCESSTONAME>READ</ACCESSTONAME>
                            </LOOKINGFOR>
                        </SEARCH>
                    </INPUTXML>”,SessionID,UserID,GLOBESNAME);
    The reading for execution time was done through Stopwatch class and the reading for memory was taken using ANTS Profiler.
    The idea was execute the getXML method 10,000,000 times and determine which out of three  methodology is best for string concatenation. The three method considered was
    a. String
    b. StringBuilder.Append
    c. StringBuilder.AppendFormat
    For StringBuilder we considered two cases
    a. With inital capacity
    b. With Capacity
     
    the above was done only for execution time, we ignore this for Memory  load.
    The results were SHOCKING compare to our belief. We are still not sure that we are right and would like comment from Microsoft CLR team about the behaviour.
    The results for execution time is
    The 500 in the above stats means that StringBuilder initial capacity was set to 500.
    The readings for memory load taken using ANTS profiler is as follows
    The columns are
    a. Number of Objects Created.
    b. Total Size for entire allocation.
    c. Number of time the Garbage Collector was called.
    The results are really SHOCKING. It seems concatination using String object is THE MOST EFFICIENT methodology. This is contradictary to what the internet have been saying since the inception of .NET.

    ITS A REQUEST TO ALL, TO RUN THE ABOVE CODE AND SHARE YOUR RESULTS. WE ALSO REQUEST THE .NET CLR TEAM TO COMMENT ON THIS.

     

    Thursday, April 17, 2008

    StringBuilder Performance

    Filed under: .NET Framework, ASP.NET, C# — Tags: — debasishpramanik @ 2:00 pm

    C# programmers typically uses StringBuilder avoid creation too many string while concatenation operation. This is good practice and should be adopted everywhere. But normally we tend to do the following

    StringBuilder sb = new StringBuilder();

    and creates a program where there is too much load on .NET Memory manager. Let me explain it.

     

          1.  Creating an instance of StringBuilder using the deafult constructor causes  
                            StringBuilder sb = new StringBuilder();  

    an instance of StringBuilder to be created with a size of 16 bytes.

              

        2.  Now when AppendFormat or Append is called on the StringBuilder instance
            sb.Append(”WordPress”);

       3.  It internally checks whether the string can fit within the existing StringBuilder instance.

        

        4. If there is enough then it appends to the existing.

        5. If there is not enough space it allocate the new String object and copies the entire string into it.

        6. This is where it hit the most as the allocation of new object is expensive and copying adds to the overhead.

        7. To overcome this issue always provide a size that is nearest to the length of the string.

             StringBuilder sb = new StringBuilder(400);

         8. This will really help to avoid calling .NET memory manager for each Append String call and thus taking away the benefit that is provided by the StringBuilder class.

    Please write back if you feel something needs to add.

     


     

     

     

     

    Wednesday, April 9, 2008

    One Year of Blogging

    Filed under: Others — Tags: — debasishpramanik @ 9:59 am

    Its’s been a year that I have start writting which co-incidently co-incides with birth date of my late mother 9th April. I always wanted to be in this great world of blog but didn’t know how to go about it. Then come the great guy Rajgo my ex-boss motivational speech in weekly team meeting. Thanks to him I could start and now I’m proud of the fact I have a space of my own in this big world of Blogging. 

    One year I posted some 37 posts many of them were just links. I started with some stupid stuff and then added I believe some good stuff on Adobe AIR and WCF. These post are getting the maximum hit so thought so they are good. Overall there 4033 hits on my blog in the first year. To me this figure means a lot. Now on a daily basis I get a hit count of 20-25 which is great for a beginner like me.

    The only problem with my post I’m unable to write more about a particular topic due to the fact my work keeps on changing from topic to topic so unable to provide much insight into a topic like AIR and WCF. Will try aim those stuff for this year. Hopefully at this time by next year I have a better story to write.

    Wednesday, March 19, 2008

    Good Article on Management V/s Expert

    Filed under: Others — debasishpramanik @ 5:34 pm

    A very good post on why you should never ignore an expert

    http://thedailywtf.com/Articles/No,_We_Need_a_Neural_Network.aspx

    Older Posts »

    Blog at WordPress.com.