Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Archive for November, 2010

Web Client Software Factory (WCSF) and Model View Presenter (MVP)

Posted by JP on November 30, 2010

MVP

One of the remarkable point of WCSF framework is the support for Model View Presenter (MVP).  MVP was quite popular and it is really flexible provided with a little learning curve involved.

Model constitutes the application specific Logic.

View would be basically the web page we are dealing with.

Presenter is the code that wires the view and model

Advantages

Decoupling: MVP and MVC provides the decoupling of user interface from the application logic. This makes the code more manageable and flexible for unit testing.

Multiple Views: Another advantage would be support for multiple views. Suppose you have a model of account transactions. Depending on the user type, you can show it in a chart page view or a table view.

Easier Replace: We can easily replace one portion of code without affecting the other. Suppose there is a change in the html page, we can do the massive change with less impact on the model and presenter code. Similarly if there is a change in data fetch service we can do that in the presenter, without even touching the view/model.

Implementation

In reality, the View would be an interface that is implemented by a web page. Model and Presenter should be actual classes which are tied to the View interface.clip_image002

Example

After setting up the IDE correctly using previous article, we can try to create a web page having one textbox and button. Here the textbox provides the Name of model.

On clicking the button the data will be saved to session.  Let us see what is the infrastructure needed for that.

Step 1: Create new Page

Right click on our previous WCSF project and use the context menu “Web Client Factory”> Add Page with Presenter

clip_image004

The following wizard will appear:

clip_image006

Enter the view name as “MyData” and click Finish.

Right click on the MyData.aspx and make it Default page.

Step 2: Add Data property to IDefaultView

Open the IMyDataView.cs from Shell project and add the following property inside it.

clip_image008

As the MVP provides decoupling of user controls from code, we need to create properties for each user interface element. Depending on the Property Type we will be having different UI controls.

Property Type

UI Control

String

TextBox

Bool

CheckBox

List

ListBox

List<Entity>

GridView

Step 3: Implement the Data property

Now we need to implement the new Data property inside our aspx page.

First we have to create a textbox in the webpage and connect it to the Data property.

For this place a new textbox and name it txtData.  Place a button too aside.

clip_image010

Create the property named Data inside the MyData.aspx page like following.

clip_image012

Step 4: Build the solution

If the build succeeds we are in good position. You can try executing the solution. From the presenter we can access the current value of Data using View.Data property.

Advertisements

Posted in ASP.NET, Web Client Software Factory | Tagged: , | Leave a Comment »

Deploying ASP.NET application to Production Server using FTP

Posted by JP on November 30, 2010

Visual Studio really makes it simple for deploying web applications.

In this article we are going to use FTP for deployment.

Scenario

Hope you have a web application with multiple folders and dozens of file.  Selecting each item and uploading to the site is really tedious job.  We can simplify it by the following.

Pre-requisites

You should have the following:

  • FTP Server Name
  • Username and Password
  • Folder on server

Deployment

Open the solution and right click on the web project and choose the option Publish.

image

You should see the following dialog window.

image

Click on the “…” button highlighted against the Target location item.

You will be prompted with the dialog box below.

image

Enter your Server name, Directory, Username and Password.

Uncheck the Anonymous Login checkbox.

After entering, cilck the Open button.  This will close the dialog box.

Now you can click Publish to do the deployment.

Posted in ASP.NET, IIS | Tagged: , , , | Leave a Comment »

New Features in .Net 4.0

Posted by JP on November 26, 2010

Feature Description
Background Garbage Collection
Dynamic Language Runtime
Covariance and Contravariance
Tuples
Memory-Mapped Files
Library Enhancements String.Concat, String.IsNullOrWhiteSpace, Enum.HasFlag, Environment.SpecialFolder

More Info: http://msdn.microsoft.com/en-us/library/ms171868.aspx

Posted in C# | Tagged: , , , , | Leave a Comment »

My Favorite Design Patterns

Posted by JP on November 26, 2010

Pattern Definition Type
Singleton

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

 
Command

Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.

 
Template Method

Define the skeleton of an algorithm in an operation, deferring some
steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.

 
Factory Method

Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.

 
Builder

Separate the construction of a complex object from its representation so that the same construction processes can create different representations.

 
Decorator

Attach additional responsibilities to an object dynamically. Decorators
provide a flexible alternative to sub classing for extending functionality.

 

Posted in C# | Tagged: | Leave a Comment »

How to map a command to method without using if/switch?

Posted by JP on November 26, 2010

Here I am trying to show the advantage of using Lambda expressions along with some built in delegates.

Scenario

The user will input a command like “MoveUp”, “MoveDown”, “TurnLeft”, “TurnDown”.  Based on the commands, you have to call the the methods MoveUp(), MoveDown(), TurnLeft(), TurnDown() respectively.

The old code will look like:

string command = "Move";

 

if (command == "MoveUp")

    MoveUp();

else if (command == "MoveDown")

    MoveDown();

else if (command == "TurnLeft")

    TurnLeft();

else if (command == "TurnRight")

    TurnRight();

We can replace the same code with Lambda and built-in delegate Action as:

string command = "Move";

 

IDictionary<string, Action> actions = new Dictionary<string, Action>();

actions.Add("MoveUp", MoveUp);

actions.Add("MoveDown", MoveDown);

actions.Add("TurnLeft", TurnLeft);

actions.Add("TurnRight", TurnRight);

 

actions.Where(a => a.Key == command).FirstOrDefault().Value();

Note: The Action is a built-in delegate with void as return and no arguments input.  There are total of 4 versions of Action.

Posted in Lambda Expressions | Tagged: , , , | Leave a Comment »

Installation of WCSF for Visual Studio 2010

Posted by JP on November 25, 2010

Step 1: First we have to install Guidance Automation Extensions for 2010. Guidance Automation provides the infrastructure for automated project creation actions inside Visual Studio IDE.

http://visualstudiogallery.msdn.microsoft.com/en-us/25e4b5e9-65e4-4950-967d-5f1e6a9dcbeb

clip_image002

Click on the Install button to proced.

Step 2: After installing the GAX 2010, you can proceed with downloading the actual WCSF 2010.

http://visualstudiogallery.msdn.microsoft.com/en-us/8fc2c9d6-5282-404b-9c58-e72b326b1e26

clip_image004

Click the Install button to proceed with and you could see the status below.

clip_image006

Validating the Installation

You can validate the installation by running VS 2010 and creating a new WCSF solution.

Execute VS 2010 and choose File > New Project

You should be able to select the project option below:

clip_image008

Select “Web Client Solution” from the dialog and enter the project name and click Ok button.

Now you will be prompted with further WCSF project options

clip_image010

Click Finish to complete the wizard. This will create 1 Shell Module and 1 website with all the necessary library file references added.

Back in the IDE you can try executing the project. You should be able to see the application below.

clip_image012

Posted in ASP.NET, Web Client Software Factory | Tagged: , , | Leave a Comment »

Compressing and Decompressing files in C#.Net

Posted by JP on November 16, 2010

In this tutorial I am trying to show the usage of .Net library to compress and decompress files.

GZipStream

We are using the class from namespace System.IO.Compression.

Basically the example, loads a text file compresses it into a file.

Compressing

private void Compress(string originalFile, string destinationFile)

{

    FileStream inStream = new FileInfo(originalFile).OpenRead();

    FileStream fileStream = File.Create(destinationFile);

    GZipStream gzipStream = new GZipStream(fileStream, CompressionMode.Compress);

 

    byte[] buffer = new byte[4096];

    int numRead;

    while ((numRead = inStream.Read(buffer, 0, buffer.Length)) != 0)

    {

        gzipStream.Write(buffer, 0, numRead);

    }

 

    gzipStream.Dispose();

    fileStream.Dispose();

    inStream.Dispose();

}

Decompressing

private void Decompress(string compressedFile, string destinationFile)

{

    FileStream compressedStream = new FileInfo(compressedFile).OpenRead();

    FileStream destinationStream = File.Create(destinationFile);

    GZipStream gzipStream = new GZipStream(compressedStream, CompressionMode.Decompress);

    byte[] buffer = new byte[4096];

 

    int numRead;

 

    while ((numRead = gzipStream.Read(buffer, 0, buffer.Length)) != 0)

    { 

        destinationStream.Write(buffer, 0, numRead); 

    }

 

    gzipStream.Dispose();

    destinationStream.Dispose();

    compressedStream.Dispose();

}

Posted in C# | Tagged: , , | Leave a Comment »

How to create Linked Server in Sql Server?

Posted by JP on November 11, 2010

Open the Management Studio and in the Server Objects > Linked Servers, right click select New Linked Server menu.

image

In the appearing screen enter the actual remoteserver alias name as “RS”

image

Enter Product Name=’’, Data source=[YourRemoteServerInstanceName], Catalog=[DbName]

and press Ok button.

In the security tab enter map the sa user like following screen.

Note: If you are using another user to connect to the current server, use that user name for mapping.

 

image

Press Ok to complete the form.

Testing the Server

You can type any query with the prefix REMOTESERVER to access the tables.

SELECT * FROM RS.Database.dbo.Table

If you can see the results,  Congratulations!  You have done with linked servers

In case of error try the following

1. Change the Security Property (previous screen) “Be made using the security context:”

2. Set the Remote login and password in the textboxes.

3. Retry the query

Creating backup of table in remote server to local

SELECT * INTO new_table_name FROM RS.Database.dbo.Table

Posted in C# | Tagged: , | Leave a Comment »

Sql Server :: Cool Sqls

Posted by JP on November 11, 2010

Some useful sqls I am sharing here.

Description Sql
Get Row Number of any table
SELECT ROW_NUMBER() OVER (ORDER BY Name ASC) AS ROWID, * FROM  TableX
Delete Duplicate Records

WITH CTE (Col1,Col2, DuplicateCount)

AS

(

SELECT Col1,Col2,

ROW_NUMBER() OVER(PARTITION BY Col1,Col2 ORDER BY Col1,Col2) AS DuplicateCount

FROM Table1

)

DELETE

FROM CTE

WHERE DuplicateCount > 1

Create Copy of a table

SELECT *

INTO new_table_name [IN externaldatabase]

FROM old_tablename

Create Linked Server

exec sp_addlinkedserver @server = ‘servername‘, @srvproduct = ”, @provider = ‘sqloledb’,

@datasrc = ‘serverhostname‘, @catalog = ‘dbname

Copy table from linked server to local server SELECT * INTO NewTable FROM RS.Db.dbo.RemoteTable
Transactions

BEGIN TRAN;

    SELECT * FROM Address

    IF (@@ERROR <> 0) GOTO ERR_HANDLER

    COMMIT TRAN;

    RETURN;

ERR_HANDLER:

PRINT ‘Unexpected error occurred!’

ROLLBACK TRAN

Identity Insert Enable SET IDENTITY_INSERT YourTable ON

Some Cool Sql Server Links

Insert Query Generator

http://www.codeproject.com/KB/database/InsertGeneratorPack.aspx

Posted in C# | Tagged: , , | Leave a Comment »

Part 5: WCSF : Power of [ServiceDependency] attribute

Posted by JP on November 11, 2010

In this part I would like to demonstrate the power and advantage of [ServiceDependecy] attribute in WCSF framework.

Advantage

We can restrict the instance creation of classes and make reuse a single instance across page requests.  This would drastically decreases memory utilization and simultaneously reduces the instance management code and makes the easier.

You can use the following class types to be shared using [ServiceDependency]

  • Data Access Classes
  • Web Service Classes
  • Utility Libraries
  • using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

     

    namespace GeneralLibrary

    {

        public class Utility

        {

            private static int _instanceCount;

     

            public Utility()

            {

                _instanceCount++;

            }

     

            public string GetMessage()

            {

                return string.Format("Instance Number: " + _instanceCount.ToString());

            }

        }

    }

    We can open the previous project and work upon it.

    After opening the WebClientApplication1, create a new Class Library project into it.  Let us call it GeneralLibrary.  After creating the project, add a class named Utility.cs into it.  The code should be:

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

     

    namespace GeneralLibrary

    {

        public class Utility

        {

            private static int _instanceCount;

     

            public Utility()

            {

                _instanceCount++;

            }

     

            public string GetMessage()

            {

                return string.Format("Instance Number: " + _instanceCount.ToString());

            }

        }

    }

    Basically, the above class will be counting the instances of itself using a static counter and it is exposing a method named GetMessage() that will give us information on number of instances created.

    Creating the test infrastructure

    For calling the above method we need to place a button and label on the MyData.aspx.  Rename the label to InfoLabel.

    image

    On the button click event place the following code:

    protected void ServiceDependencyCheck_Click(object sender, EventArgs e)

    {

    this.Presenter.ServiceDependencyCheck();

    }

    Place the following code in MyDataPresenter.cs

    public void ServiceDependencyCheck()

    {

          this.View.InfoMessage = Utility.GetMessage();

    }

    Create a new string property in IMyDataView interface

    public interface IMyDataView

    {

               string InfoMessage { get; set; }

    }

    Implement the property back in our MyData.aspx

    public string InfoMessage

    {

        get

        {

            return this.InfoLabel.Text;

        }

        set

        {

            this.InfoLabel.Text = value;

        }

    }

    Now we have to set the instance creation of Utility class inside the module

    Place the following code in ShellModuleInitializer.cs

    globalServices.AddNew<Utility, Utility>();

    inside method AddGlobalServices()

    Testing the Application

    Now you are ready to test the application.  Press F5 and execute the application.  In the appearing screen, press the “Service Dependency Test” button.  You can see the following output.

    image

    Even if you click the button multiple times, only one instance of the Utility class is created.

    Posted in ASP.NET | Tagged: , , | Leave a Comment »