Thursday, February 28, 2008

XSL Rocks!!


I was reading a little about XSL (extensible style sheet language) on http://www.w3schools.com/xsl/ and I found that it is absolutely awesome! I completely got the whole thing and I realized that XSL will be one of my favorites soon; apparently XSL is XML-Based style sheet language! XSLT however –which stands for XSL Transformation- is the most important part of XSL and is used to transform an XML document into another XML document that is recognized by a browser by transforming each XML element into an (X)HTML element and it uses X-Path is to navigate through elements and attributes of the XML document.
Pretty cool huh! If you still don’t know much about XSL you should definitely start looking it up.

Memories..(1)


What are the three most important features of OOP?

Encapsulation:
Encapsulation conceals the functional details of a class from objects that send messages to it.

Inheritance:
‘Subclasses’ are more specialized versions of a class, which inherit attributes and behaviors from their parent classes, and can introduce their own.

Polymorphism (Overloading, Overriding):
Polymorphism allows you to treat derived class members just like their parent class' members


What is a garbage collector and how does it work?
garbage collection (GC) is a form of automatic memory management.
Garbage collection is often portrayed as the opposite of manual memory management, which requires the programmer to specify which objects to deallocate and return to the memory system.it frees the programmer from having to worry about releasing objects that are no longer needed.
The basic principle of how a garbage collector works is:
Determine what data objects in a program will not be accessed in the future
Reclaim the resources used by those objects



Reference: http://en.wikipedia.org

Starting Over..

I am bored to tears, yes I am. I have been working for more than a year now and am wondering where did all the fun go? Its not as fun as it used to be, I have weird cravings for C and C++, I want to write something special, an awesome piece of a code, something that sweeps my brains away, and until am able to feed that urge,, until I do that I have decided to look back at the good times, remember all the theories, all the SCIENCE and stuff I used to love.

The majority of developers working today are working on fairly straight forward systems doing fairly simplistic things like tying up a gui to a database. For the most parts that means you don’t need to be a good software developer, broadly speaking it doesn’t matter if you don’t have an in-depth understanding of your programming language or lack a formal comp sci education.

However there is another world, a much more fun world in my opinion although others may disagree. A world in which you need to have expertise in your language, where you really need to understand what exactly your code is doing and often how it’s achieving it. A world in which you need to be a good software developer to survive and get the job done.

You may find this series pretty useful for any technical interview but I am writing it for the sake of pure enjoyment and for the sake of my poor soul before I become a total “tool expert” and not a programmer anymore:(.

I will start with bits n pieces of the old days’ memories...

Nothing is Regular About Expressions..

And I say that because I just love regular expressions, they are dazzling, challenging, and there isn’t a text you can’t search and manipulate based on a regular expression pattern.
I thought that I might share some of the useful things I have leant while working with patterns to validate user’s input.
Now here are some of the basic concepts that you need to learn about patterns:
Alternation:
A vertical bar separates alternatives. For example, apple apple can match "apple” or “apple".
Grouping:
Parentheses are used to define the scope and precedence of the operators (among other uses). For example, apple apple and ap (pl) e are equivalent patterns which both describe the set of “apple" and " apple".
Quantification:
A quantifier after a token (such as a character) or group specifies how often that preceding element is allowed to occur. The most common quantifiers are ?, *, and +.
  • ? The question mark indicates there is zero or one of the preceding element. For example, colou?r matches both "color" and "colour".

  • * The asterisk indicates there are zero or more of the preceding element. For example, ab*c matches "ac", "abc", "abbc", "abbbc", and so on.

  • + The plus sign indicates that there is one or more of the preceding element. For example, ab+c matches "abc", "abbc", "abbbc", and so on, but not "ac".

  • I am also refering to this Basic Syntax Reference that will help you a lot in understanding patterns.


    CharacterDescription Example
    Any character except [\^$.?*+()All characters except the listed special characters match a single instance of themselves. { and } are literal characters, unless they're part of a valid regular expression token (e.g. the {n} quantifier).a matches a
    \ (backslash) followed by any of [\^$.?*+(){}A backslash escapes special characters to suppress their special meaning.\+ matches+
    \Q...\EMatches the characters between \Q and \E literally, suppressing the meaning of special characters.\Q+-*/\E matches +-*/
    [ (square brackets)]Starts a character class. A character class matches a single character out of all the possibilities offered by the character class. Inside a character class, different rules apply. The rules in this section are only valid inside character classes. [abc] matches a, b or c
    \ (backslash) followed by any of ^-]\A backslash escapes special characters to suppress their special meaning.\^\] matches ^ or ]
    - (hyphen) except immediately after the opening [Specifies a range of characters. (Specifies a hyphen if placed immediately after the opening [)[a-zA-Z0-9] matches any letter or digit
    ^ (caret) immediately after the opening [Negates the character class, causing it to match a single character not listed in the character class. (Specifies a caret if placed anywhere except after the opening [)[^a-d] matches x (any character except a, b, c or d)
    \d, \w and \sShorthand character classes matching digits 0-9, word characters (letters and digits) and whitespace respectively. Can be used inside and outside character classes.[\d\s] matches a character that is a digit or whitespace
    \D, \W and \SNegated versions of the above. Should be used only outside character classes. (Can be used inside, but that is confusing.)\D matches a character that is not a digit
    . (dot)Matches any single character except line break characters \r and \n. Most regex flavors have an option to make the dot match line break characters too.. matches x or (almost) any other character
    \n, \r and \tMatch an LF character, CR character and a tab character respectively. Can be used in character classes.\r\n matches a DOS/Windows CRLF line break.
    ^ (caret)Matches at the start of the string the regex pattern is applied to. Matches a position rather than a character. Most regex flavors have an option to make the caret match after line breaks (i.e. at the start of a line in a file) as well.^. matches a in abc\ndef. Also matches d in "multi-line" mode.
    $ (dollar)Matches at the end of the string the regex pattern is applied to. Matches a position rather than a character. Most regex flavors have an option to make the dollar match before line breaks (i.e. at the end of a line in a file) as well. Also matches before the very last line break if the string ends with a line break..$ matches f in abc\ndef. Also matches c in "multi-line" mode.
    \AMatches at the start of the string the regex pattern is applied to. Matches a position rather than a character. Never matches after line breaks.\A. matches a in abc
    \Z, \zMatches at the end of the string the regex pattern is applied to. Matches a position rather than a character. Never matches before line breaks, except for the very last line break if the string ends with a line break..\Z matches f in abc\ndef
    \bMatches at the position between a word character (anything matched by \w) and a non-word character (anything matched by [^\w] or \W) as well as at the start and/or end of the string if the first and/or last characters in the string are word characters..\b matches c in abc
    \BMatches at the position between two word characters (i.e the position between \w\w) as well as at the position between two non-word characters (i.e. \W\W).\B.\B matches b in abc
    (pipe)Causes the regex engine to match either the part on the left side, or the part on the right side. Can be strung together into a series of options.abcdefxyz matches abc, def or xyz
    (pipe)The pipe has the lowest precedence of all operators. Use grouping to alternate only part of the regular expression.abc(defxyz) matches abcdef or abcxyz
    ? (question mark)Makes the preceding item optional. Greedy, so the optional item is included in the match if possible.abc? matches ab or abc
    ??Makes the preceding item optional. Lazy, so the optional item is excluded in the match if possible. This construct is often excluded from documentation because of its limited use.abc?? matches ab or abc
    * (star)Repeats the previous item zero or more times. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is not matched at all.".*" matches "def" "ghi" in abc "def" "ghi" jkl
    *? (lazy star)Repeats the previous item zero or more times. Lazy, so the engine first attempts to skip the previous item, before trying permutations with ever increasing matches of the preceding item.".*?" matches "def" in abc "def" "ghi" jkl
    + (plus)Repeats the previous item once or more. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is matched only once.".+" matches "def" "ghi" in abc "def" "ghi" jkl
    +? (lazy plus)Repeats the previous item once or more. Lazy, so the engine first matches the previous item only once, before trying permutations with ever increasing matches of the preceding item.".+?" matches "def" in abc "def" "ghi" jkl
    {n} where n is an integer >= 1Repeats the previous item exactly n times.a{3} matches aaa
    {n,m} where n >= 1 and m >= nRepeats the previous item between n and m times. Greedy, so repeating m times is tried before reducing the repetition to n times.a{2,4} matches aa, aaa or aaaa
    {n,m}? where n >= 1 and m >= nRepeats the previous item between n and m times. Lazy, so repeating n times is tried before increasing the repetition to m times.a{2,4}? matches aaaa, aaa or aa
    {n,} where n >= 1Repeats the previous item at least n times. Greedy, so as many items as possible will be matched before trying permutations with less matches of the preceding item, up to the point where the preceding item is matched only n times.a{2,} matches aaaaa in aaaaa
    {n,}? where n >= 1Repeats the previous item between n and m times. Lazy, so the engine first matches the previous item n times, before trying permutations with ever increasing matches of the preceding item.a{2,}? matches aa in aaaaa
    Here are some of the expressions which I came across or implemented and would like to share:

    ExpressionDescriptionUsage
    ^[a-zA-Z]+(([\'\,\.\-][a-zA-Z])?[a-zA-Z]*)*$Any single word that contains alphabets only.First Name or Family Name
    [^\<>~/^\"\'!@#$%\^&*()=+]+It allows any series of words that may contain alphabets, digits, hyphens, and commasAddress
    ^[\.\w\s\\\:?]+\.(JPGjpgDOCdocDOCXdocx)$It allows any text that ends with .doc or .jpgAttachments
    \d{4,5}It allows to enter no less than 4 digits or more than 5Postal Code
    \b(?:\d{1,3}\.){3}\d{1,3}\bWill match any IP address.IP address
    (0[1-9][12][0-9]3[01])[- /.](0[1-9]1[012])[- /.](1920)\d\dMatches a date in the dd-mm-yyyy formatDates
    [\d]*[\w]*Matches any numbers any digitsSection1

    Scheduling Daily Builds using Team Build(Tips and Tricks)

    A couple of weeks ago I have had so much fun configuring a daily build to the project I am working on. Yes it took a long time, but once I saw that green light ticking it was totally worth it. Anyway here are some of the things I learnt about Team Build that I think are the most important:
    It Requires a Permission:
    Okay first of all if you are trying to right click the “Builds” folder from the “Team Explorer” and the “New Build Definition” option is inactive then you probably don’t have the right permissions. You must have the Team Foundation Server “administer a build” permission and the Team Foundation Server start/resume a build permission.
    Multiple Solutions and their dependencies:
    Be aware of one solution having dependencies on another when determining the order in which they are built. For example, set Solution1 to be built before Solution2 in the case where Solution2 has a dependency on Solution1.
    Yes! insufficient space = failed builds
    When selecting the build directory, ensure that there is enough space to build; insufficient space will lead to failed builds. The same goes for the drop.
    Dropping Locations
    By default, the drop directory is not automatically created as a share and therefore is not accessible for publishing builds and tests results. You must manually establish a share, add write permissions to the Windows directory, and add share permissions for both the account used to run Team Foundation Build service for dropping builds and for the tester's account for publishing test results.

    Each generated build will be dropped into a separate directory. You will need to ensure that the account with which build machine is configured has write access to this UNC location.
    Not only builds but it deploys as well:
    Yes you can configure an “AfterDropBuild” target that will copy all the output files and BLLs to any directory you want, first you have to specify a PropertyGroup that points to the directory where the files are dropped after building:
    And then create an AfterDropBuild target like that:
    Different Deployments X Different Environments:
    Say you have different Environments, and each environment has its own configuration file have two solutions or simply the location you are deploying to needs a specific configuration you can implement this using one these two solutions:
    1. Use the MSBuild Community Tasks Project for VS
    MSBuild Community Tasks Project is a community project where you can find a long list of cool MSBuild Custom Tasks that you can use within your VSTS build environments. All you have to do is install the MSBuild Tasks on your local machine and the destination drop machine, you can download if from:http://msbuildtasks.tigris.org/svn/msbuildtasks/trunk msbuildtasks --username guest.In order to use the tasks in this project, you need to import the MSBuild.Community.Tasks.Targets files:



    At the beginning of your code right under the opening tag of the item.Using the msbuild community tasks project it becomes easy to change App.config and Web.config files as part of the build process. Install the Ms Build Community tasks on your server and you can use this code to update your App.config and Web.config keys during build. Create a new target:


    2. Simply Replace files after deployment:
    Create a separate configuration file for each environment and add it to the source control, then copy them in the destination directories after dropping:Add in the two items, one for the source of the configuration file and the other one for the destination location:
    Create an after drop target and then write the copy script:
    If your project is a web application and you need to reset the IIS you might want to consider this:
    You can use this script to reset a specific web site instead of resetting the IIS.
    The command line tool TfsBuild.exe
    See 1. Actually, I must say, the command line tool is really useful. You can find it at: \Common7\IDE\TFSBuild.exe and is surprisingly good. It can be called using: TfsBuild.exe start as you might have guessed, it'll go to your TFS Server, find the build type you've specified, download the configuration from source control (the current checked in version) and build based on that. Which I think is really neat.Fix your DLL referencesYes, I know, this is pretty much the whole point of an automated build. But still. I suffered a couple of times with DLL references.We have a bunch of 3rd party and legacy DLL 's that we reference from our current project, which is fine. We added them to a source controlled folder, everything's happy.
    What about the Data Dude?
    If you have a database project that you want to deploy every time your build runs, add this line in your “AfterDropBuild” target:

    However if you have more than a Database; for example you have a different database for each environment, you will need to create more than one configuration:
    · Click Configuration Manager on the Build menu.
    · In the row corresponding to you Database project click the arrow under the Configuration and click “new”.
    · Name your new configuration and save it.
    · In Solution Explorer, click your database project.
    · On the View menu, click Property Pages. You can also click ProjectName Properties on the Project menu.
    · Click the Build tab. And start customizing your configuration.Use the following script to deploy your database project according to the customized configuration you have created
    No built-in scheduler
    It’s not a big deal really, but before spending half the morning looking for it, know that it's not there to be found. You'll just have to schedule it to run via Windows' task scheduler.
    How about a little notification?
    After a little reading I discovered the Alerts system built into team foundation server (I've never really noticed it before). All I needed to do was go Team->Project Alerts... check on the "A build completes" alert and type in my email address. Every time the team build completes, I get an email with a link to a build results webpage \m/.
    Dont Forget to check-in
    After creating the buil and customizing it to your preferences dont forget to check it in so that changes will take affect.

    Design Patterns


    I was asked to do a presentation about design patterns and after the presentation people had asked me to post it, so here is a copy of my PPT :

    What are Design Patterns?



    • In software engineering, a design pattern is a general repeatable solution to a commonly occurring problem in software design.

    • Not a finished design that can be transformed directly into code

    • A description of how to solve a problem

    • Algorithms are not thought of as design patterns, since they solve computational problems rather than design problems.

    • Show relationships and interactions between classes or objects, without specifying the final application classes or objects that are involved.


    Why Design Patterns?



    • Can speed up the development process.

    • Prevent issues that can cause major problems.

    • Improves code readability.

    • Provide general solutions.

    • Design reuse, which is more powerful than code reuse.

    Classifications of Design Patterns:



    • Creational Patterns:
      Abstract Factory Creates an instance of several families of classes
      Builder Separates object construction from its representation
      Factory Method Creates an instance of several derived classes
      Prototype A fully initialized instance to be copied or cloned
      Singleton A class of which only a single instance can exist


    • Structural Patterns
      Adapter Match interfaces of different classes
      Bridge Separates an object’s interface from its implementation
      Composite A tree structure of simple and composite objects
      Decorator Add responsibilities to objects dynamically
      Facade A single class that represents an entire subsystem
      Flyweight A fine-grained instance used for efficient sharing
      Proxy An object representing another object


    • Behavioral Patterns
      Chain of Resp. A way of passing a request between a chain of objects
      Command Encapsulate a command request as an object
      Interpreter A way to include language elements in a program
      Iterator Sequentially access the elements of a collection
      Mediator Defines simplified communication between classes
      Memento Capture and restore an object's internal state
      Observer A way of notifying change to a number of classes
      State Alter an object's behavior when its state changes
      Strategy Encapsulates an algorithm inside a class
      Template Method Defer the exact steps of an algorithm to a subclass Visitor Defines a new operation to a class without change
    A Sample of a Design Pattern Document:



    • Pattern Name and Classification:

    • Intent: goal

    • Also Known As: Other names for the pattern.

    • Motivation (Forces): A scenario in which this pattern can be used.

    • Applicability: Situations in which this pattern is usable; the context for the pattern.

    • Structure: A graphical representation of the pattern. (Class diagrams, Interaction diagrams)

    • Participants: A listing of the classes and objects used in the pattern.

    • Collaboration: A description of how classes and objects used in the pattern interact

    • Consequences: A description of the results, side effects, and trade offs.

    • Implementation: A description of an implementation

    • Sample Code:

    • Known Uses: Examples of real usages of the pattern. Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns.
    Example?



    • Pattern Name and Classification: Singleton, creational pattern

    • Intent: Ensure a class has only one instance and provide a global point of access to it.

    • Also Known As: Single Instance .

    • Motivation (Forces): Sometimes it's appropriate to have exactly one instance of a class: window managers.

    • Applicability: Singleton can be used in a data repository or data collection where creation of more than one object can be resource wastage. Hence each client is given a reference to a single shared object to operate on. While the second case Singleton can be used in locking mechanisms. Once a client has got the object, no other client can have an object..

    • Structure:

  • Participants: The classes and/or objects participating in this pattern are:

  • –Singleton:defines an Instance operation that lets clients access its unique instance. Instance is a class operation.

  • responsible for creating and maintaining its own unique instance.

  • Collaboration: A description of how classes and objects used in the pattern interact

  • Consequences: A description of the results, side effects, and trade offs.

  • Implementation: A description of an implementation

  • Sample Code:
    – class Singleton { private static Singleton instance; // Note: Constructor is 'protected' protected Singleton() { } public static Singleton Instance() { // Use 'Lazy initialization' if (instance == null) { instance = new Singleton(); } return instance; } }
    –// .NET Singleton
    –sealed class Singleton
    –{
    – private Singleton() {}
    – public static readonly Singleton Instance = new Singleton();
    –}



  • Known Uses: Connection Pooling

  • Related Patterns: Other patterns that have some relationship with the pattern; discussion of the differences between the pattern and similar patterns

  • References:


    Here comes the Wizard! (1)

    In this article I will be explaining in brief how to collect related data across steps through an easy navigation wizard how cool is this? Okay suppose you have this scenario:

    Now to implement this I dragged the System.Web.UI.WebControles.Wizard control from my ToolBox, and then I added the following steps:

    • Select Product
    • Login
    • Register
    • Purchase
    • Confirmation
    • Forgot Password

    Now because I wanted to customize navigation, I defined each step as a “Complete” step. To navigate from one step to the other you might want to write this:
    protected void btnGo_Click(object sender, EventArgs e)
    {
    Wizard1.ActiveStepIndex = Wizard1.WizardSteps.IndexOf(this.Step1);
    }
    Where “Step1” is the ID I gave to the certain step I want to navigate to. Suppose you want to do some conditional navigation, you can use the OnActiveStepChanged event which fires
    protected void OnActiveStepChanged(object sender, EventArgs e)
    {
    // If the ActiveStep is changing to Step3, check to see whether the
    // SeparateShippingCheckBox is selected. If it is not, skip to the
    // Finish step.
    if (Wizard1.ActiveStepIndex == Wizard1.WizardSteps.IndexOf(this.Step3))
    {
    if (this.SeparateShippingCheckBox.Checked)
    {
    Wizard1.MoveTo(this.Step3);
    }
    else
    {
    Wizard1.MoveTo(this.Finish);
    }
    }
    }