Tuesday, 30 July 2013

Regular Expression Basic Syntax Reference

Characters
CharacterDescriptionExample
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+-*/
\xFF where FF are 2 hexadecimal digitsMatches the character with the specified ASCII/ANSI value, which depends on the code page used. Can be used in character classes.\xA9 matches © when using the Latin-1 code page.
\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.
\a, \e, \f and\vMatch a bell character (\x07), escape character (\x1B), form feed (\x0C) and vertical tab (\x0B) respectively. Can be used in character classes. 
\cA through \cZMatch an ASCII character Control+A through Control+Z, equivalent to\x01 through \x1A. Can be used in character classes.\cM\cJ matches a DOS/Windows CRLF line break.
Character Classes or Character Sets [abc]
CharacterDescriptionExample
[ (opening square bracket)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. The rules outside this section are not valid in character classes, except for a few character escapes that are indicated with "can be used inside character classes". 
Any character except ^-]\ add that character to the possible matches for the character class.All characters except the listed special characters.[abc] matches a, b orc
\ (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 characternot 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, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). 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
[\b]Inside a character class, \b is a backspace character.[\b\t] matches a backspace or tab character
Dot
CharacterDescriptionExample
. (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
Anchors
CharacterDescriptionExample
^ (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 inabc\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 inabc\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
\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 inabc\ndef
\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..\z matches f inabc\ndef
Word Boundaries
CharacterDescriptionExample
\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
Alternation
CharacterDescriptionExample
| (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.abc|def|xyz matchesabc, def or xyz
| (pipe)The pipe has the lowest precedence of all operators. Use grouping to alternate only part of the regular expression.abc(def|xyz)matches abcdef orabcxyz
Quantifiers
CharacterDescriptionExample
? (question mark)Makes the preceding item optional. Greedy, so the optional item is included in the match if possible.abc? matches ab orabc
??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 orabc
* (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" inabc "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"inabc "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" inabc "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"inabc "def" "ghi" jkl
{n} where n is an integer >= 1Repeats the previous item exactly n times.a{3} matches aaa
{n,m} where n >= 0 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 aaaa,aaa or aa
{n,m}? where n >= 0 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 aa,aaa or aaaa
{n,} where n >= 0Repeats 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 aaaaain aaaaa
{n,}? where n >= 0Repeats the previous item n or more 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 inaaaaa

Monday, 29 October 2012

JS Code for Pagination and Sorting


  //Script for displaying specific number of pages
    $(".TableSize").change(function () {
        var numberOfApps = $(".TableSize").val();
            $.ajax({
                type: "POST",
                url: "/Home/JsonAppManager",
                success: function (imageList) {
                                var imageCount = imageList.length;
                                var pages = parseInt((imageCount / numberOfApps), 10);
                                var totalPages, currentPage, startRow, endRow,tempList=[];
                                    if ((imageCount % numberOfApps) > 0) {
                                        totalPages = pages + 1;
                                    }
                                    else {
                                        totalPages = pages;
                                    }
                                    if (imageCount <= numberOfApps) {
                                        totalPages = 1;
                                    }
                                $('#FeaturedAppsTable').remove();
                                $('.AppsTableDiv').html('');
                                $('<table id="FeaturedAppsTable"></table>').appendTo('.AppsTableDiv');
                                    for (rowNum = 0; rowNum < numberOfApps; rowNum++) {
                                        currentPage = 1;
                                        if (imageList[rowNum] == null) {
                                            break;
                                        }
                                        tempList[rowNum] = imageList[rowNum];
                                    }
                                createTable.call(this,tempList);
                                $('<div class="PaginationDiv"></div>').appendTo('.AppsTableDiv');
                                $('<div class="PageNumberDiv"></div>').appendTo('.PaginationDiv');
                                $('<label id="CurrentPage">' + currentPage + '  of  ' + totalPages + '</label>').appendTo('.PaginationDiv');
                                    for (pages = 1; pages <= totalPages; pages++) {
                                        $('<a href="#" class="PageNumberAnchor"><span class="PageNumber">' + pages + '</span></a>').appendTo('.PageNumberDiv');
                                        if (pages != totalPages) {
                                            $('<span> |   </span>').appendTo('.PageNumberDiv');
                                        }
                                    }

                                     //Script for Pagination for Featured Apps Table
                                    $('.PageNumber').click(function () {
                                        $('#FeaturedAppsTable').html('');
                                        var page = $(this).html();
                                        currentPage = parseInt(page, 10);
                                        startRow = (currentPage - 1) * numberOfApps;
                                        endRow = parseInt(startRow, 10) + parseInt(numberOfApps, 10);
                                        tempList = [];
                                            for (rowNum = startRow,page=0; rowNum < endRow; rowNum++) {
                                                if (imageList[rowNum] == null) {
                                                    break;
                                                }
                                                tempList[page++] = imageList[rowNum];
                                            }
                                        createTable.call(this, tempList);
                                        $('#CurrentPage').text(currentPage + '  of  ' + totalPages);

                                        //Script to sort list in Ascending order
                                        $('#SortAsec').click(function () {
                                            imageList = sortListInAscending.call(this, imageList);
                                            tempList = [];
                                            for (rowNum = startRow, page = 0; rowNum < endRow; rowNum++) {
                                                if (imageList[rowNum] == null) {
                                                    break;
                                                }
                                                tempList[page++] = imageList[rowNum];
                                            }
                                            reCreateTableBody.call(this, tempList);
                                        });
                                        //Script to sort list in Descecinding Order
                                        $('#SortDesc').click(function () {
                                            imageList = sortListInDescending.call(this, imageList);
                                            tempList = [];
                                            for (rowNum = startRow, page = 0; rowNum < endRow; rowNum++) {
                                                if (imageList[rowNum] == null) {
                                                    break;
                                                }
                                                tempList[page++] = imageList[rowNum];
                                            }
                                            reCreateTableBody.call(this, tempList);
                                        });
                                    });

                                    //Script to sort list in Ascending order
                                                $('#SortAsec').click(function () {
                                                    imageList = sortListInAscending.call(this, imageList);
                                                    tempList = [];
                                                    for (rowNum = 0; rowNum < numberOfApps; rowNum++) {
                                                        if (imageList[rowNum] == null) {
                                                            break;
                                                        }
                                                        tempList[rowNum] = imageList[rowNum];
                                                    }
                                                    reCreateTableBody.call(this, tempList);
                                                });
                                    //Script to sort list in Descecinding Order
                                                $('#SortDesc').click(function () {
                                                    imageList = sortListInDescending.call(this, imageList);
                                                    tempList = [];
                                                    for (rowNum = 0; rowNum < numberOfApps; rowNum++) {
                                                        if (imageList[rowNum] == null) {
                                                            break;
                                                        }
                                                        tempList[rowNum] = imageList[rowNum];
                                                    }
                                                    reCreateTableBody.call(this, tempList);
                                                });

                }
            });
    });

    //User Defined function for Creating a Table using given Image List
    function createTable(imageList) {
        $('<thead id="TableHead"><tr><th>Image</th><th>Title <a href="#" class="SortAnchor"><span id="SortAsec" title="Sort Asecinding">&Delta;</span></a><a href="#" class="SortAnchor"><span id="SortDesc" title="Sort Descinding">&nabla;</span></a></th><th>Description</th><th></th><th></th></tr></thead>').appendTo('#FeaturedAppsTable');
        $('<tbody id="TableBody"></tbody>').appendTo('#FeaturedAppsTable');
        $(imageList).each(function (imageList, value) {
            $('<tr><td><img src="' + value.ImagePath + '" alt="'+value.Title+'" height="50" width="50"/></td><td class="AppTitleColumn">' + value.Title + '</td><td class="AppDescriptionColumn">' + value.Description + '</td><td><a href="/Home/editApp/' + value.ID + '" title="Edit This App Details"><img src="../../Content/themes/base/images/edit.png" height="20" width="20" class="EditAppImg"/></a></td><td><a href="/Home/deleteApp/' + value.ID + '" title="Delete This App"><img src="../../Content/themes/base/images/delete.png" class="DeleteAppImg" height="20" width="20"/></a></td></tr>').appendTo('#TableBody');
        });
        $('<tfoot id="TableFooter"><tr><th>Image</th><th>Title</th><th>Description</th><th></th><th></th></tr></tfoot>').appendTo('#FeaturedAppsTable');
        return 1;
    }

    //User Defined function for Changing the body of a table using given image List
    function reCreateTableBody(imageList) {
        $('#TableBody').html('');
        $(imageList).each(function (imageList, value) {
            $('<tr><td><img src="' + value.ImagePath + '" alt="' + value.Title + '" height="50" width="50"/></td><td class="AppTitleColumn">' + value.Title + '</td><td class="AppDescriptionColumn">' + value.Description + '</td><td><a href="/Home/editApp/' + value.ID + '" title="Edit This App Details"><img src="../../Content/themes/base/images/edit.png" height="20" width="20" class="EditAppImg"/></a></td><td><a href="/Home/deleteApp/' + value.ID + '" title="Delete This App"><img src="../../Content/themes/base/images/delete.png" class="DeleteAppImg" height="20" width="20"/></a></td></tr>').appendTo('#TableBody');
        });
    }

    //user Defined funtion for Sorting a List in Ascending Order
    function sortListInAscending(tempList) {
        tempList.sort(function (a, b) {
            var titleA = a.Title.toLowerCase(), titleB = b.Title.toLowerCase();

            if (titleA < titleB)
                return -1;
            else if (titleA > titleB)
                return 1;
            else

                return 0;

        });
        return tempList;
    }
    //User Defined function for Sorting List in decending Order
    function sortListInDescending(tempList) {
        tempList.sort(function (a, b) {
            var titleA = a.Title.toLowerCase(), titleB = b.Title.toLowerCase();

            if (titleA > titleB)
                return -1;
            else if (titleA < titleB)
                return 1;
            else

                return 0;

        });
        return tempList;
    }
});

Thursday, 4 October 2012

C# Snippets: Visual Studio


Snippets are a useful feature in the Visual Studio IDE. These allow you to type a few letters and then press tab twice to insert a common fragment of code. They can be useful to reduce repetitive statements and reduce overuse injuries with your hands.

Ctor

First, the ctor snippet is available in Visual Studio 2010. To use ctor, place the cursor inside a class body. Then, type the four letters 'ctor' and press tab twice. This article shows what happens after you press TAB TAB.
Where to use ctor snippet [press tab tab]

class Example
{
    ctor
}

class Program
{
    static void Main()
    {
    }
}

Result

class Example
{
    public Example()
    {

    }
}

class Program
{
    static void Main()
    {
    }
}
Programming tip
Adding parameters. The snippet inserts a parameterless public constructor, which is probably the most common type. However, if you want to add parameters, simply add them inside the parentheses manually. If you want multiple constructors, just add more in the same way.
Constructor Tips

Class

Visual Studio logo; copyright Microsoft
With the class snippet you insert a new class. You must type the keyword "class" and press tab and then tab again to insert the class definition. The default name will be MyClass; you can then rename this to a more appropriate type identifier. You can use the class snippet anywhere in a file, but you should only use it in a place where a class can be declared.
Where to use class snippet [press tab tab]

class Program
{
    static void Main()
    {
    }
}

class

Result

class Program
{
    static void Main()
    {
    }
}

class MyClass
{

}
The class snippet allows you to instantly insert the class definition with correct syntax in your C# program. This can be useful if you create many classes in your projects. You can find more information on classes on this website.
Class Examples

Cw

Console screenshot
The cw snippet is available in Visual Studio 2010 and also earlier versions. In a place where you want to insert a call to Console.WriteLine(), type cw and press TAB twice. The letters 'cw' will be expanded to "Console.WriteLine()". If the System namespace is required, it will be added to the start of the method call.
Where to use cw snippet [press tab tab]

class Program
{
    static void Main()
    {
 cw
    }
}

Result

class Program
{
    static void Main()
    {
 System.Console.WriteLine();
    }
}
After typing cw and then TAB TAB, the caret will be positioned inside the parentheses, so you can immediately start specifying the arguments. For developers working on large console programs, this is useful for saving a few keystrokes.

Do

Do keyword
You want to insert a do-while loop quickly. To use the do snippet, type the word "do" and then press tab twice. This will insert the do-while code into your program at that position. The "true" will be highlighted so you can change it easily, without repositioning yourself.
Where to use do snippet [press tab tab]

class Program
{
    static void Main()
    {
 do
    }
}

Result

class Program
{
    static void Main()
    {
 do
 {

 } while (true);
    }
}
Note
Of all the loop constructs in the C# language, the do-loop has the shortest initial keyword. However, if the entire loop structure is too verbose for you, the do snippet can come in handy. As an aside, I wonder if anyone has ever actually used it to his or her advantage.

Lock

Lock keyword
The lock snippet can be useful. This program has a static object added to it that we can use in the lock statement. Type the string "lock" and press the tab key twice. The resulting program will contain the lock(){} statement; you must replace the object to be locked upon with the best object. Here, we use the _locker object.
Where to type the lock snippet [C#]

class Program
{
    static object _locker = new object(); // Lock on this object!

    static void Main()
    {
 lock
    }
}

Resulting program [C#]

class Program
{
    static object _locker = new object(); // Lock on this object!

    static void Main()
    {
 lock (_locker)
 {

 }
    }
}
Question and answer
When to lock? This is not a good real-world example of using the lock statement. For more information on the lock statement, including a broader conceptual view, visit the specific article on this site.
Lock Statement
Tip:Don't forget to use the lock statement when the possibility of data corruption is present because of multiple concurrent threads. Having a lock statement can mean the difference between a program that works correctly and one that fails at unexpected times.

Mbox

With the mbox snippet you can insert a simple method call with only a few keystrokes in Visual Studio. Type the letters "mbox" into your program. Typically, you will be doing this in a Windows Forms program, but you can use MessageBox.Show in any .NET program. After typing "mbox", press tab twice. You can see in the second part of the example that a call to MessageBox.Show was generated.
Where to use mbox snippet [C#]

class Program
{
    static void Main()
    {
 mbox
    }
}

Result of the snippet

class Program
{
    static void Main()
    {
 System.Windows.Forms.MessageBox.Show("Test");
    }
}
Tip:If you try to compile the output program in a console program, you will get a compile-time error. This is because the project lacks the System.Windows.Forms assembly. Right click on References and go to Add Reference; click on .NET and then click OK on System.Windows.Forms in the dialog.
The mbox snippet allows you to insert a call to the MessageBox.Show method. You can use this snippet in any C# program inside Visual Studio, but it is most useful in Windows Forms programs.
System.Windows.Forms

Prop

Next we use the prop snippet in Visual Studio. To begin, place the cursor somewhere in the scope of a class, where you want to put your property. Type prop and then press tab twice. Next, Visual Studio will select the 'int' keyword; you can change this to 'string' or 'bool' or any type you want. It is a good idea also to change the name from MyProperty to something more descriptive.
Property
Where to use prop snippet [press tab tab]

class Program
{
    prop

    static void Main()
    {
    }
}

Result

class Program
{
    public int MyProperty { get; set; }

    static void Main()
    {
    }
}
The 'prop' snippet in Visual Studio 2010 (and earlier versions) is useful for creating automatically implemented properties. Because the just-in-time compiler optimizes properties, they are typically as fast as field accesses but slower than local variables.
JIT Method Test

Propfull

Property; icon copyright Microsoft
This C# example shows how to use the propfull snippet in Visual Studio. To begin, put your cursor on a line in the scope of a class. Type propfull and press tab twice. The keyword 'int' will be highlighted; you can change this another type of your choosing. When you press tab after making the change, the type will be matched in the property itself. Finally, change the MyProperty to a more descriptive identifier.
Where to type propfull [press tab tab]

class Program
{
    propfull

    static void Main()
    {
    }
}

Result of the snippet

class Program
{
    private int myVar;

    public int MyProperty
    {
 get { return myVar; }
 set { myVar = value; }
    }

    static void Main()
    {
    }
}
While the 'prop' snippet provides an automatically generated property member, the 'propfull' snippet inserts the code for the more verbose syntax form. In many programs, you may need to use a full property because of a requirement for special code such as logging statements or statements that have side effects when a property is accessed.

Sim

Method call
The sim snippet refers to static int Main. To get started, find a place where you want to insert the Main method. Type sim and then press tab twice. The result is that the static int Main method with a string[] formal parameter will be inserted.
Where to type sim snippet [press tab tab]

class Program
{
    sim
}

Result

class Program
{
    static int Main(string[] args)
    {

 return 0;
    }
}
As with several other snippets, the sim snippet is not likely to be useful often. However, it is an interesting example of providing textual shortcuts (aliases) for software development. The term 'sim' abbreviates "static int Main".

Svm

Void keyword
Next, we use the svm snippet. First position your cursor in a class and then type svm and press tab twice. The static void Main method then appears. You can now type statements inside the Main entry point.
Main Args ExamplesVoid Type
Where to type svm [press tab tab]

class Program
{
    svm
}

Result

class Program
{
    static void Main(string[] args)
    {

    }
}
The svm snippet is the same as the sim snippet except it returns no value; sim returns an integer value. Neither of these snippets have been useful to me, but they are part of Visual Studio and thus necessary for complete coverage.

Switch

This C# example shows how to use the switch snippet in Visual Studio. To start, type switch and then press tab twice. Next, the "switch_on" identifier is selected; you need to change this to a valid variable to switch on. After you finish with this, you can add cases to the switch statement.
Case Example
Where to use switch snippet [press tab tab]

class Program
{
    static void Main(string[] args)
    {
 switch
    }
}

Result

class Program
{
    static void Main(string[] args)
    {
 switch (switch_on)
 {
     default:
  break;
 }
    }
}

Result with new switch selection statement

class Program
{
    static void Main(string[] args)
    {
 switch (args.Length)
 {
     default:
  break;
 }
    }
}
The switch statement is not very popular with many developers. More complex problems can often be expressed better with inheritance and virtual methods (object-orientation). And rarely does a programmer use the switch statement so often that a snippet is necessary.
Object-Oriented Programming BenefitsVirtual Method
The switch snippet is not highly useful for many developers, and was probably included in Visual Studio for completeness not actual utility. However, it is nice to know it exists.

Using

Using keyword
This example shows how and where you can use the using snippet. Simply type 'using' and then press tab twice. The term 'using' will be expanded into the using-statement. You will want to specify the resource; typically, a using statement has a constructor for an object in the resource acquisition part.
Where to put using snippet [press tab tab]

class Program
{
    static void Main()
    {
 using
    }
}

Result

class Program
{
    static void Main()
    {
 using (resource)
 {

 }
    }
}
Note
Using statements. Some of the most popular types that are instantiated in using statements include StreamReader and StreamWriter. Also, you can create your own types that can be used in a using-statement; you must implement the IDisposable interface.
Using StreamReaderUsing StreamWriter
For quickly inserting a using statement in your C# program, the using snippet is unparalleled. You must change the 'resource' part of the inserted code. Often you will use a Stream-derived type in this context.

Summary

The C# programming language
Snippets are useful if you have to type a huge amount of code. Once you memorize them you no longer will have to type certain constructs. Many developers do not type enough code to really need snippets.
And:Most of the time, a clear understanding of code is more important. Bad code is often worse than useless.