Git Rename Branch : local & remote


If you have named a branch incorrectly and pushed this to the remote repository follow these steps to rename the branch name both locally and on server.

1. Rename your local git branch.
If you already have branch checked out which you want to rename

git branch -m newName</code>

If you are on a different branch

git branch -m oldName newName


2. Delete the old-name remote branch and push the new-name local branch


git push origin :oldName newName

3. Reset the upstream branch for the new-name local branch.
Switch to the branch and then:

git push origin -u newName

How to resolve “Circular dependency” in Project Plan


I was recently working on a low level plan  created in Microsoft Project (.mpp) which was designed for tracking activities, time & resources for a critical project activity. We need input from multiple teams for time & resource estimation and thus multiple people were updating the plan.

Every thing was fine till I open the plan to update in morning which was working till late evening. I was unable to open the document due to circular dependency error. The error says

  No Calculations are performed.

There is circular relationship in the task 947 <Task Description> of  “LLP”. The successors of this task refer back to this task or its predecessors, causing a circular reference.

To remove the link that is causing the circular reference, select the two tasks  that are causing the circular link,  and then click Unlink Tasks on the Standard toolbar.

Circular Dependency in Microsoft project project plan(.mpp)

I tried to find the two tasks but plan was having thousands tasks so finding manually was cumbersome & time consuming. Further I start by removing dependency of that task that is causing circular dependency. But this approach was not fruitful as same error was replicating for further task & on some research I found the task provided in error has no circular dependency at all. I was still to find a way that can same  my day from manually checking about three thousand task plan manually.

I google it on the internet & with some efforts I was able  to resolve the problem. The Solution  was:

  • Insert a new column in Microsof Project  plan.
  • Copy all predeccessor column value in the new custom text field(say Text1_Pred)
  • now bulk delete all values in predeccessor column
  • Now copy back all the value from Text1_Pred into Predeccessor Column again
  • it would start giving error with “Task ID No” as pasting error for circular reference. Note TaskId.
  • It give you option to ignore problem or continue without problem or cancel Choose NO “continue without problem “) option to remove.

Voila, this took only two minutes  and the error was gone. I was again able to open project plan again & this saved my day.

Hope it will someone else with the problem.

www.HyperSmash.com

Schema & Data Comparison of Two Databases with Visual Studio


Visual Studio has many hidden gems & most of us usually overlook it until we need in some work/project. One of less used but extremely useful feature is Schema & Data comparison of two databases. Moreover we can generate scripts for updating the schema/data from visual studio itself.

Note: Schema & Data comparison are possible only in Visual Studio Ultimate & Visual Studio Premium and not in most-popular professional edition or free express edition.

Let us see how it works. First I have two different databases – one is local copy before deployment & other one is copy of same database after new release.

1. First of start visual studio, in the main menu, select “SQL,” then “Schema Compare,” then “New Schema Comparison”.

SchemaDataComparision1

2. This will open a new schema comparison file  (.scmp)

SchemaDataComparision3

3. In the schema compare file we have two drop-down, one for source database & another for destination. Select the two database to be compared.

SchemaDataComparision2

4. After selecting database you can have various options like filtering based on Object types (Tables, stored procedures keys etc).

5. You can also check various useful options in “General” tab.

6. Now compare the database schema.

You can find objects added, removed or edited and what’s the difference.

 

In the similar way, you can use Data Comparison:

1. In visual studio, select SQL menu, then Data Compare, then new Data Comparison.

2. In New Data Comparison, 

  •  First select Source Database  & Target Database.
  • For data comparison, you have following database options for Records to compare:
    •  Different Records
    •  Only in Source
    •  Only in Target
    •  Identical Records

3. Based on your requirements, select any combination of aforementioned data comparison options.

 

One very important thing to notice here is to explore the various options available to tweak your comparison. You have different options like:

Most important features are:

  • Compare: compares the schema or data. Shortcut is Shift+Alt+C.
  • Update: can update changes(schema or data) from source database to destination database. Shortcut is Shift+Alt+U
  • Generate Script: can generate script for the difference in schema or data.
  • Filter options: can filter results based on object types like Tables, functions, stored procedures etc. This option comes very handy when you want to filter data for some tables in case of data compare and when you want to compare only few stored procedures/any other object type or all stored procedure/ any other object type.

Here is screen-shot of schema compared.

Note: I have deliberately blurred the picture so that actual schema mustn’t be visible.

 

Both Data Comparison & Schema Comparison is very easy & need no prior SQL experience.

These options comes very handy when you have application development environment on many servers like Development Servers, Staging Servers, QA/ Testing Database &  many distributed Production Servers and they need to be synchronized after some builds/releases.

www.HyperSmash.com

Deploying DotNetNuke on Windows Azure


In this blog post, we will go through step by step how to actualize DotNetNuke on Windows Azure Website from Gallery. For those who are not familiar with  DotNetNuke, we start by introducing what it is.

DotNetNuke is a web content management system based on Microsoft .NET. The Community Edition is open source, and source code and related information can be found on Codeplex.  The product is used to build professional looking and easy-to-use commercial websites, social intranets, community portals, or partner extranets.

In addition to robust content management, the free, open source DotNetNuke Community Edition includes the following built-in features:

  • A rich-text editor
  • File management
  • Cloud-ready with MS Azure compatibility
  • Mobile API and basic mobile device detection
  • Core written in C#
  • Single installation, multiple portals
  • Social API (in DNN 6.2 and above)
  • Modern client-side Web tools like CSS 3, HTML 5 and JQuery
  • Bulk email
  • Robust security
  • Administration features like: security roles, protected content and site log.

Windows Azure website from gallery makes available a wide range of popular web applications developed by Microsoft, third party companies, and open source software initiatives. Web applications created from the gallery do not require installation of any software other than the browser used to connect to the Windows Azure Management Portal.

So after a brief about DotNetnuke and Azure Websites, we are ready to go through step-by-step journey to set-up DotNetNuke on Azure.

NOTE:  For following steps you need a Windows Azure account that has the Windows Azure Web Sites feature enabled.  If you don’t have one, you can create trial for free at  following link:  Create a Windows Azure account and enable preview features.

1. Login to the Windows Azure Management Portal.

2. Click the New icon on the bottom left of the dashboard.

new

3. Click the Compute Icon, then click Web Site icon, and click From Gallery.

From Gallery

4. Locate and click the DotNetNuke Community Edition  icon in list, and then click  Next.

DNNCE

5. On the  Configure Your App  page, enter or select values for all fields:

DataBase

    • Enter a URL name of your choice
    •  Leave Create a new SQL database selected in the Database field
    • Select the region closest to you.

6. Then click Next.

7.  On the ADD WEB APP page, you can specify a name for your new SQL database or use the default name. Select the region closest to you as the hosting location.  Then enter Server Login Name and Server Login Password.  Then click the check to complete the site creation.

DBSetting

NOTE: Please note down the Server login name and password, as this will be later required in setting up DotnetNuke installation.

8. Windows Azure will take a little time to deploy DotNetNuke Community Edition CMS to your site.

Time

9. After successful setup, a new website with given name can be seen in Running status.

Successful

10. We are done at the part to be done at Windows Azure Management Portal, now open the deployed site by clicking website link.

11.  At the first time open of site will require some data from you.

admin

    • Fill up Administrative Information

a) Fill up Username and enter Password.

Note:  Note down this username and password as it will be your admin username and password.

    • Enter Website Information

a)  Fill up website name and change language, if necessary.

    • Enter Database Information

dbsetup

a) Select Database Setup type Custom

b) Select Database Type as SQL Server/SQL Server Express Database

c) Enter Server Name and Datbase Name (You can check your server name at Windows Azure Management Portal)

connUserServer

d) Select  Security type User Defined.

e) Enter Database Username (this is also can be found at Windows Azure Management Portal).

f) Enter Database Password (that we saved in step 7).

    • Finally click on continue.

12. Installation will take for a while for verifying database connection.

verifydb

13. Page is then redirected to installation page, which will take a little time to install.

dnninst

14. After installation is complete, message is shown as Installation complete, Click Visit Website.

dnninstcomp

15. DotNetNuke is installed on Windows Azure with SQL azure database and is ready to use.

ready

You can now enjoy the benefits of Azure Cloud Scalability and pay as you use model. You can monitor the traffic on website & database on Azure Dashboard.

dashbrd

www.HyperSmash.com

Introduction to Design Patterns


In once a while, each developer goes through the term design pattern, analyze these patterns & eventually use in various code.  So question first arises in mind is what’s the design pattern,  what did they do and how did they do. We start with answering first question here.

Definition :

Design Pattern is is a general reusable solution to a commonly occurring problem within a given context.

What exactly this means ??? Lets understand.

What did we do when we get a problem to solve which is new to us?  Google it and check if somebody already solved our problem. Exactly like this case,  each design pattern is already available solution to solve some particular problems that we encounter while designing logic or writing code for our applications.

Now let’s explore various types of Design Patterns. Design patterns are mainly categorized into three types:

1. Creational Patterns : Creational patterns are used to construct objects such that they can be decoupled from their implementing system.

Example of creational patterns are :

  • Abstract Factory: Create instances of classes belonging to different families.
  • Builder : Separate representation and object construction.
  • Factory:  Create instances of derived classes.
  • Prototype : Clone or copy initialized instances.
  • Singleton: Class with only one single possible instance.

2. Structural Patterns : Structural Patterns are used to form large object structures between many disparate objects.

Example of structural patterns are :

  • Adapter: Match interfaces of classes with different interfaces.
  • Bridge: Separate implementation and object interfaces.
  • Composite: Simple and composite objects tree.
  • Decorator: Dynamically add responsibilities to objects.
  • Facade: Class that represents subclasses and subsystems.
  • Flyweight: Minimize memory usage by sharing as much data as possible with similar objects.
  • Proxy: Object that represents another object.

3. Behavioral Patterns:  Behavioral Patterns are used to manage algorithms, relationships, and responsibilities between objects.

Example of behavioral patterns are:

  • Chain of Responsibility: Pass requests between command and processing objects within a chain of objects.
  • Command: Encapsulate a method call as an object containing all necessary information.
  • Interpreter: Include language elements and evaluate sentences in a given language.
  • Iterator: Give sequential access to elements in a collection.
  • Mediator: Encapsulates and simplifies communication between objects.
  • Memento:  Undo modifications and restore an object to its initial state.
  • Observer: Notify dependent objects of state changes.
  • State: Change object behavior depending on its state.
  • Strategy: Encapsulate algorithms within a class and make them interchangeable.
  • Template: Define an algorithm skeleton and delegate algorithm steps to subclasses so that they may be overridden.
  • Visitor: Add new operations to classes without modifying them.

In design pattern we often listen the term Gang of Four, GOF, or GO4. Gang of four is nothing to do with technical sense, it’s name of four authors(Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides) of book Design Patterns: Elements of Reusable Object-Oriented Software.

In next posts, I will pick each one of original 23 GOF design patterns, discuss pros, cons & need, UML diagrams for patterns and simple code illustration in C#.

www.HyperSmash.com

Performance Analysis: Disabling code-analysis warnings and Excluding Code Coverage for tested common methods


When the project in which I was working was going through performance analysis, we found our project has a lot of warning generated by code analysis and also code coverage is not up to mark. We analyze warning & methods that was not under test coverage. What we found was that we were mostly following best practices but still code analysis left us with a lot of warnings. Same goes with code-coverage, all new methods were having proper test cases for all scenarios. What’s wrong was happening???

Actual problem was :

1. Some code components (commonly used components and third-party code) developed earlier was considered tested and free from warnings, but that wasn’t the case.

2. Also we can’t change that code for warnings & test coverage (because nor time-constraint allows that neither we want to do so for ample many other reasons like copyright with change etc.)

So what can be solution.

Solution was nevertheless easier then we thought. Microsoft has provision for disabling code-analysis warnings & excluding code-coverage for such a scenarios only in System.Diagnostics.CodeAnalysis namespace.

NOTE: Although it’s not recommended to disable code-analysis warnings and also disabling code-coverage. Doing this can project wrong code-analysis data, but our scenario was just perfect for what Microsoft has provisioned disabling.

The System.Diagnostics.CodeAnalysis namespace contains classes for interaction with code analysis tools :

1. ExcludeFromCodeCoverageAttribute: Specifies that the attributed code should be excluded from code coverage information.

Actual working example

 [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
 public static OperationControl GetInstance()
 {
   //Your code goes here
 }

In above code, ExcludeFromCodeCoverage attribute will prevent the method from being covered in test coverage & thus increases code coverage percentage. Please note only third-party tested code, test methods and such cases are recommended for using the attribute & it must not be applied to all/most of methods that will defeat purpose of code-coverage check.

2. SuppressMessageAttribute: Suppresses reporting of a specific static analysis tool rule violation, allowing multiple suppressions on a single code artifact.

The SuppressMessage attribute has the following format:

[Scope:SuppressMessage("Rule Category", "Rule Id", Justification = "Justification", MessageId = "MessageId", Scope = "Scope", Target = "Target")]

Where:

  • Rule Category – The category in which the rule is defined. More information on categories can be found on msdn.
  • Rule Id – The identifier of the rule. Support includes both a short and long name for the rule identifier. The short name is CAXXXX; the long name is CAXXXX:FriendlyTypeName.
  • Justification – The text that is used to document the reason for suppressing the message.
  • Message Id – Unique identifier of a problem for each message.
  • Scope – The target on which the warning is being suppressed. If the target is not specified, it is set to the target of the attribute. Supported scopes include the following:
    • Module
    • Namespace
    • Resource
    • Type
    • Member
  • Target – An identifier that is used to specify the target on which the warning is being suppressed. It must contain a fully-qualified item name.

Actual working example

 [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design""CA1024:UsePropertiesWhereAppropriate")]
 public static OperationControl GetInstance()
 {
   //Your code goes here
 }

In above code SuppressMessage attribute will prevent Microsoft.Design warning”CA1024″.

For more detailed information you can refer following links on msdn:

http://msdn.microsoft.com/en-IN/library/ee1hzekz%28v=vs.100%29.aspx

http://msdn.microsoft.com/en-IN/library/ms244717%28v=vs.100%29.aspx


www.HyperSmash.com

Stored Procedure having Sorting, Paging and Filtering


In day to day work we often need data to displayed in Grid that needs sorting, paging and filtering on User Interface whether web or windows. I often struggle to find a unified solution. I found that best way is to have fetch data  in required  format from stored procedure and just have presentation logic on UI  rather than mixing a lot of logic for Sorting, Paging and Filtering.  Here I am presenting a simple approach to have data from Stored procedure in required format based on given parameters.

CREATE PROCEDURE USP_SEL_Contacts
(
        /* Optional Filters for Dynamic Search*/
       @ContactID INT = NULL,
       @FirstName NVARCHAR(50) = NULL,
       @LastName NVARCHAR(50) = NULL,
       @EmailAddress NVARCHAR(50) = NULL,
       @EmailPromotion INT = NULL,
       @Phone NVARCHAR(25) = NULL,
       /*– Pagination Parameters */
       @PageNo INT = 1,
       @PageSize INT = 10,
      /*– Sorting Parameters */
     @SortColumn NVARCHAR(20) = ‘Title’,
    @SortOrder NVARCHAR(4)=‘ASC’
)
AS
BEGIN
         /*–Declaring Local Variables corresponding to parameters for modification */
         DECLARE 
        @lContactID INT,
        @lFirstName NVARCHAR(50),
        @lLastName NVARCHAR(50),
        @lEmailAddress NVARCHAR(50),
        @lEmailPromotion INT,
        @lPhone NVARCHAR(25),
         @lPageNbr INT,
         @lPageSize INT,
         @lSortCol NVARCHAR(20),
         @lFirstRec INT,
         @lLastRec INT,
         @lTotalRows INT
        /*Setting Local Variables*/
        SET @lContactID = @ContactID
        SET @lFirstName = LTRIM(RTRIM(@FirstName))
        SET @lLastName = LTRIM(RTRIM(@LastName))
        SET @lEmailAddress = LTRIM(RTRIM(@EmailAddress))
        SET @lEmailPromotion = @EmailPromotion
        SET @lPhone = LTRIM(RTRIM(@Phone))
        SET @lPageNbr = @PageNo
        SET @lPageSize = @PageSize
        SET @lSortCol = LTRIM(RTRIM(@SortColumn))
         SET @lFirstRec = ( @lPageNbr – 1 ) * @lPageSize
         SET @lLastRec = ( @lPageNbr * @lPageSize + 1 )
         SET @lTotalRows = @lFirstRec – @lLastRec + 1
         ; WITH CTE_Results
         AS (
         SELECT ROW_NUMBER() OVER (ORDER BY
                   CASE WHEN (@lSortCol = ‘ContactID’ AND @SortOrder=‘ASC’)
                            THEN ContactID
                  END ASC,
                  CASE WHEN (@lSortCol = ‘ContactID’ AND @SortOrder=‘DESC’)
                           THEN ContactID
                  END DESC,
                 CASE WHEN (@lSortCol = ‘Title’ AND @SortOrder=‘ASC’)
                          THEN Title
                 END ASC,
                 CASE WHEN @lSortCol = ‘Title’ AND @SortOrder=‘DESC’
                         THEN Title
                 END DESC,
                CASE WHEN @lSortCol = ‘FirstName’ AND @SortOrder=‘ASC’
                        THEN FirstName
                END ASC,
                CASE WHEN @lSortCol = ‘FirstName’ AND @SortOrder=‘DESC’
                        THEN FirstName
                END DESC,
                CASE WHEN @lSortCol = ‘MiddleName’ AND @SortOrder=‘ASC’
                        THEN MiddleName
                END ASC,
                CASE WHEN @lSortCol = ‘MiddleName’ AND @SortOrder=‘DESC’
                       THEN MiddleName
                END DESC,
                CASE WHEN @lSortCol = ‘LastName’ AND @SortOrder=‘ASC’
                      THEN LastName
                END ASC,
                CASE WHEN @lSortCol = ‘LastName’ AND @SortOrder=‘DESC’
                      THEN LastName
                END DESC,
               CASE WHEN @lSortCol = ‘Suffix’ AND @SortOrder=‘ASC’
                     THEN Suffix
               END ASC,
               CASE WHEN @lSortCol = ‘Suffix’ AND @SortOrder=‘DESC’
                     THEN Suffix
               END DESC,
                CASE WHEN @lSortCol = ‘EmailAddress’ AND @SortOrder=‘ASC’
                      THEN EmailAddress
                END ASC,
                CASE WHEN @lSortCol = ‘EmailAddress’ AND @SortOrder=‘DESC’
                      THEN EmailAddress
                END DESC,
                 CASE WHEN @lSortCol = ‘EmailPromotion’ AND @SortOrder=‘ASC’
                      THEN EmailPromotion
                END ASC,
                CASE WHEN @lSortCol = ‘EmailPromotion‘ AND @SortOrder=‘DESC’
                     THEN EmailPromotion
                END DESC,
                 CASE WHEN @lSortCol = ‘Phone’ AND @SortOrder=’ASC’
                    THEN Phone
                 END ASC,
                 CASE WHEN @lSortCol = ‘Phone’ AND @SortOrder=’DESC’
                     THEN Phone
                 END DESC
       ) AS ROWNUM,
       Count(*) over () AS TotalCount,
       ContactID,
       Title,
       FirstName,
       MiddleName,
       LastName,
       Suffix,
       EmailAddress,
       EmailPromotion,
       Phone
   FROM Contact
   WHERE
         (@lContactID IS NULL OR ContactID = @lContactID)
         AND(@lFirstName IS NULL OR FirstName LIKE ‘%’ + @lFirstName + ‘%’)
         AND(@lLastName IS NULL OR LastName LIKE ‘%’ + @lLastName + ‘%’)
        AND (@lEmailAddress IS NULL OR EmailAddress LIKE ‘%’ + @lEmailAddress + ‘%’)
        AND (@lEmailPromotion IS NULL OR EmailPromotion = @lEmailPromotion)
        AND (@lPhone IS NULL OR Phone  LIKE ‘%’ +@lPhone+ ‘%’)
)
SELECT
    TotalCount,
    ROWNUM,
    ContactID,
    Title,
    FirstName,
    MiddleName,
    LastName,
    Suffix,
    EmailAddress,
    EmailPromotion,
    Phone
FROM CTE_Results AS CPC
WHERE
         ROWNUM > @lFirstRec
               AND ROWNUM < @lLastRec
 ORDER BY ROWNUM ASC
END
GO

 

SP can be used to filter data as per given parameters as:

No parameters provided, fetch first 10 default records with title in ascending Order :
EXEC USP_SEL_Contacts

 On providing @SortCol = ‘FirstName’ and @SortOrder=’Asc’, will fetch 10 records sorted by First Name in ascending order:
EXEC USP_SEL_Contacts @SortColumn = ‘FirstName’, @SortOrder=‘Asc’

 On providing @SortCol = ‘LastName’, will fetch 10 records sorted by Last Name in descending order:
EXEC USP_SEL_Contacts @SortColumn = ‘FirstName’, @SortOrder=‘Desc’

 Following query will pull out 20 records in a page having Email Address ‘b@b.cc’ sorted by Last Name in Descending order:
EXEC USP_SEL_Contacts @EmailAddress = ‘b@b.cc’, @PageSize = 20, @PageNo=1, @SortColumn = ‘LastName’ , @SortOrder=‘Desc’

NOTE: Please note that while publishing blog single quotes ‘ & minus sign – are converted to some unrecognizable characters, if you have error like

Msg 102, Level 15, State 1, Procedure USP_SEL_Contacts, Line 14
Incorrect syntax near ‘‘’.
Msg 137, Level 15, State 2, Procedure USP_SEL_Contacts, Line 42
Must declare the scalar variable “@SortColumn”.
Msg 102, Level 15, State 1, Procedure USP_SEL_Contacts, Line 43
Incorrect syntax near ‘–’.
Msg 102, Level 15, State 1, Procedure USP_SEL_Contacts, Line 45
Incorrect syntax near ‘–’.
Msg 102, Level 15, State 1, Procedure USP_SEL_Contacts, Line 49
Incorrect syntax near ‘‘’.

please replace those characters by single quotes & minus sign respectively.

www.HyperSmash.com