Friday, April 10, 2015

Do not declare function and variable with the same name in same scope

In Javascript functions and variables share same namespace  and that is why this code will break

 

<script>

        function ThisIsAFunction(n) {

            alert(n);

        };

 

        var ThisIsAFunction = 'India';

 

        alert('abount to execute');

 

        ThisIsAFunction('Hello');

    </script>

 

Basically 1st statement in code is similar to

var ThisIsAFunction  = function ThisIsAFunction(n) { alert(n); };

 

Or

 

var ThisIsAFunction = = function (n) { alert(n); };

 

and this will collide even inside a closure as closure will be scope rather than global.

Sunday, April 05, 2015

Close with function notation

See how private and public methods are accessible from outside. Last statement will not work,  tell me why ?

 

var Inventory = function InventoryConstructor(n)

{

     var that = function(n)

     {

        title = n;

        GetTitle = function()

        {

             return title;

        };     

     };

 

     var names = ['Honda', 'BMW', 'Kia', 'Toyota'];

     that.FindIfCarMakeIsInList = function(m)

     {

         return names.indexOf(m) > -1 ;

     };

 

     that.TotalMakesWeHave = names.length;

    

     that.AddMake = function(m)

     {

       if(names.indexOf(m) === -1)

       {

          names[names.length] = m;

       }

       return true;

     }

 

     return that;

}('India inv');

 

alert('Is Acura in list ->' + Inventory.FindIfCarMakeIsInList('Acura'));

alert('How many car make we have ? ' + Inventory.TotalMakesWeHave);

alert('add Acura in list ->' + Inventory.AddMake('Acura'));

alert('Is Acura in list ->' + Inventory.FindIfCarMakeIsInList('Acura'));

alert('How many car make we have ? ' + Inventory.TotalMakesWeHave);

alert(Get Title ' + Inventory.GetTitle()); // This will fail, tell me why ?

 

 

Thanks

Pradeep

Clouse that return Object literal and how to use returned Object literal Methods

Returning Object literal from Closure and using methods and Properties returned in the object literal.

 

 

var Inventory= function()

{

var names = ['Honda', 'BMW', 'Kia', 'Toyota']; // it will be initialized only once.

 

 // return an object literal so that we can access more than one operation

return {

     FindIfCarMakeIsInList : function(make)

     {

         return names.indexOf(make) > -1 ;

     },

 

     TotalMakesWeHave : names.length,

     AddMake : function(m)

     {

        if(names.indexOf(m) === -1)

        {

           names[names.length] = m;

        }

        return 1;

     }

   }

}();

 

alert('Is Acura in list ->' + Inventory.FindIfCarMakeIsInList('Acura'));

alert('How many car make we have ? ' + Inventory.TotalMakesWeHave);

alert('add Acura in list ->' + Inventory.AddMake('Acura'));

alert('Is Acura in list ->' + Inventory.FindIfCarMakeIsInList('Acura'));

alert('How many car make we have ? ' + Inventory.TotalMakesWeHave);

 

 

Thanks

Pradeep

When to use Closure in JavaScript

Here is when and how..

Problem to solve – find if an element exists in an array.

Bad code 1 – clutter global namespace


var names = ['Honda', 'BMW', 'Kia', 'Toyota'];

var findIfCarMakeIsInList = function(make)
{
  return names.indexOf(make) > -1 ;
}
alert('Is Honda in list ->' + findIfCarMakeIsInList('Honda'));
alert('Is Acura in list ->' + findIfCarMakeIsInList('Acura'));



Bad code 2  - slow because of initialization of local list every time method is call


var findIfCarMakeIsInList = function(make)
{
  var names = ['Honda', 'BMW', 'Kia', 'Toyota'];
  return names.indexOf(make) > -1 ;
}
alert('Is Honda in list ->' + findIfCarMakeIsInList('Honda'));
alert('Is Acura in list ->' + findIfCarMakeIsInList('Acura'));


Closure helps us to
1.       Avoid polluting global namespace
2.       And get the benefit of global objects.


var  FindIfCarMakeIsInList = function()
{
var names = ['Honda', 'BMW', 'Kia', 'Toyota']; // it will be initialized only once.

// return function reference so that if can be called.
return function(make)
{
      return names.indexOf(make) > -1 ;
};
}();

alert('Is Honda in list ->' + FindIfCarMakeIsInList('Honda'));
alert('Is Acura in list ->' + FindIfCarMakeIsInList('Acura'));



Thanks
Pradeep
Keep learning “JavaScript good part..”

Tuesday, June 25, 2013

Visual Studio 2012, shortcut key combinations

I found it very helpful and putting in my blog to help others, If you find any other combination that is missing in this list, Do update in comment section and I`ll include them into the list

All shortcuts beginning with CTRL+W are for opening or navigating to Windows:

  •   CTRL+W, S: Solution Explorer
  •   CTRL+W, E: Error list
  •   CTRL+W, R: Resourceview
  •   CTRL+W, A: Command window
  •   CTRL+W, T: Taskview
  •   CTRL+W, Q: Find Symbol Results
  •   CTRL+W, X: ToolboX
  •   CTRL+W, C: Classview

Thanks
Pradeep

Monday, June 03, 2013

Serialize object or list of objects using xDocument

This works for any serializable type or list of serializable type and deserialize back.

 

XDocument doc = new XDocument();

using (var writer = doc.CreateWriter())

{

    var serializer = new DataContractSerializer(objToSerialize.GetType());

    serializer.WriteObject(writer, objectToSerialize);

}

Var objectXml = doc.ToString();

 

To Deseralize xml back to type T.

 

DataContractSerializer ser = new DataContractSerializer(typeof(T));

return  (T)ser.ReadObject(xmlDocument.CreateReader(), true);

 

 

you need to refer using System.Xml.Serialization; in your class type.

 

Thanks

Pradeep

(425)463-7804

 

Wednesday, April 24, 2013

Windows service and relative file path problem

I created a console application which was dependent of an xml file, I set the property of file to always copy and I always for new version of xml file inside execution directory and my console application worked until one day I wrapped that console application into windows service to run it periodically. And then this problem started.

 

When I run it in debug mode or console app mode it worked. I can to know about this error when I put a logging statement to log the error in eventviewer and then I found that Windows service code was looking for this file under system folder, here is error message I got in log “Could not find file 'C:\Windows\system32\ticks.xml'.”  

 

Actually windows service runs from within system folder and their current directory (Environment.CurrentDirectory) is set to system directory and hence any relative lookup is based on this path.

 

To fix this problem, build your file path using AppDomain.CurrentDomain.BaseDirectory and relative path.

 

 

Thanks

Pradeep

Monday, April 01, 2013

XmlReader, XmlWriter and IsEmptyElement

Today I`ll explain the problem I faced with simple xml read/write. We all know,

xmlreader is used to read xml, actually it “Represents a reader that provides fast, noncached, forward-only access to XML data.” And
xmlwriter is used to write xml, in other words it “Represents a writer that provides a fast, non-cached, forward-only means of generating streams or files containing XML data.”

I had to create a xml config file with same nodes but with localized string of multiple markets. To solve this problem here is what I decided
1.      Read Xml from beginning to end using xmlreader as I do not wanted to use Xpath to make is dependent on XML, a simple start to end scan of nodes, was my plan.
2. When reader read a attribute or node value , localize it and pass it to writer
3. Write everything else unchanged.

Sample Xml
 <events text="EVENTS">
      <event key="Dividends" value="dividend"/>
      <event key="Splits" value="splits"/>
      <event key="Earnings" value="earnings"/>
    </events>

Sample code
while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                        case XmlNodeType.Attribute:
                            writer.WriteStartAttribute(reader.Name);
                            writer.WriteValue(LocalizeIt(reader, country));
                            break;
                        case XmlNodeType.Element:
                            bool isEmptyNode = reader.IsEmptyElement;
                            writer.WriteStartElement(reader.Name);

                            if (reader.HasAttributes)
                            {
                                WriteAttributes(writer, reader, country, culture);
                            }

                            if (isEmptyNode)
                            {
                                writer.WriteEndElement();
                            }
                            break;
                        case XmlNodeType.EndElement:
                            writer.WriteEndElement();
                            break;
                        case XmlNodeType.Text:
                             writer.WriteValue(LocalizeIt(reader, country));
                            break;
                        case XmlNodeType.Whitespace:
                            writer.WriteWhitespace(reader.Value);
                            break;
                    }


I thought this switch clause will read each and every node and write it using writer but it failed for EMPTY NODES (e.g. event in sample xml) and resulted into currupted xml, none of the event tags were closed. After some research I found reader has a property and that saved me. I had to update the code and included clause to check if reader has IsEmptyElement flag set ? and if its true I had to close the node explicitely and before closing write each attributes, actually with this change there is no need of 1st case (XmlNodeType.Attribute) but I kept it in demo code.

Make sure that you read this property on Xml Node not of node attributes, to ensure this
1. Either read it in the beginning as I did or
2. Revert to Node using MoveToElement() on reader.

I am writing this post so that you do not need to re-invent it and save your time.

Thanks
Pradeep

Wednesday, March 27, 2013

How to learning c#

This is one of the common question see if various places. How to learn c# FAST ?

Well I do not know why to make this process faster apart from practicing it initially as much as possible. and if you have other suggestion please include in comment and I`ll update this post with credits to you :)

I am going to answer, How to learn c#, to Learn c# here are some of the posts, sites that I found useful

1. MSDN  (http://msdn.microsoft.com/en-us/library/Vstudio/67ef8sbd.aspx)

MSDN is really a good source of knowledge and actually this is the preferred place to get any new feature detail, but this contains basic information and you have to try hands-on to know many hidden things or boundary conditions.

More detailed list http://msdn.microsoft.com/en-us/library/Vstudio/kx37x362.aspx


2. Channel9.msdn (http://channel9.msdn.com/Series/C-Sharp-Fundamentals-Development-for-Absolute-Beginners)


This is second in my priority list as its really a good site with lot many videos, to learn c# they have created a list of videos and they are sequentially arranged at the given URL.

3.  Pluralsight Videos : http://www.pluralsight.com/training/Courses/TableOfContents/dotnet-csharp-tutorial

These courses are created by industry experts and they surely has great in depth knowledge about subject. These videos are structured and time bound. These are really good source of knowledge but these are not free, you need to have subscription to access these videos. C# videos were published in 2009,  not sure if they have  updated them for new version of C# or not, If you know, please provide those details in comment section.

4. http://www.csharp-station.com/tutorial.aspx 

This site is also well structured and they have webpages with details and also c# sample code. Good source to get practice code. They are very descriptive.



5. About.com (http://cplus.about.com/od/learning1/Learn_about_C_and_how_to_write_Programs_in_It.htm)


This site is very good source of information and they have plenty of them, but only problem that I find with about.com is its not well structured and any new member get lost in their vast information.

If you know any other good source that you want me to put into this list. Please share that in comment section and I`ll include in the list.

thanks
Pradeep