Jean Paul's Blog

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

    Advertisements
  • 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
  • Advertisements

Archive for the ‘ASP.NET’ Category

Advantage of [ServiceDependency] in WCSF – Instance Reuse

Posted by Paul on April 6, 2011

Web Client Software Factory provides with a good feature through [ServiceDependency] attribute.

This attribute allows us to make use of the Dependency Injection and Instance Reuse advantages.

Example

Let us have an example to learn the [ServiceDependency] attribute.

Step 1: Create a new WCSF project

You can open the Visual Studio 2010, and use File>New Project and enter the project name as shown in the image below:

clip_image002

In the appearing wizard after screen above click Finish.

Step 2: Create a Utility class in Shell module

You can view from the solution explorer that there is a Shell module.

Right click on it and add new class named Utility which is having a single method named Greetings();

clip_image004

After the actions the solution explorer looks like above image.

The content of Utility class will be:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ServiceDependencyTest.Shell

{

public class Utility

{

public Utility()

{

}

public string Greetings()

{

return “Hello There!”;

}

}

}

Step 4: Specify the class Utility in global services

The Web Client Software Factory framework uses the term services for instances of classes that implement a particular interface. The services would be accessible through a service locator.

For specifying our class instance as a service we have to modify the ShellModuleInitializer.cs

Note: There are global and module services. The services specified as global would be accessible to all modules in the application and the services specified as module is visible only to the module in which it is declared.

In our case we are going to declare the Utility class in the global services. For this add the line

globalServices.AddNew<Utility, Utility>(); in the method AddGlobalServices(IServiceCollection globalServices)

clip_image006

Step 5: Declare the property with [ServiceDependency]

Now we proceed with declaring a new property named Utility in the DefaultViewPresenter class.

[ServiceDependency]

public Utility Utility

{

get;

set;

}

Please note that we marked the property with [ServiceDependency] – this will automatically take care of the instance injection.

The other way of instance creation is using the [CreateNew] attribute.

Step 6: Testing the application

Back to the web application we can place a label and button on the form. On click of the button use the following code.

protected void Button1_Click1(object sender, EventArgs e)

{

Label1.Text = this._presenter.Utility.Greetings();

}

Now you can run the application and clicking the button you will be able to see the greetings text.

clip_image008

Note: The Model View Presenter (MVP) constraints are violated in the above example by placing button handler code inside the view inorder to make the example more simple.

Instance Reuse

The WCSF provides the flexibility of instance reuse in the above scenario. You can verify it by placing a breakpoint in the constructor of Utility class and pressing button multiple times. There will be only one hit of the breakpoint. For getting the complete feel through running application, just replace the content of Utility class with the following.

public class Utility

{

public Utility()

{

_InstanceCount++;

}

private static int _InstanceCount;

public string Greetings()

{

string msg = string.Format(“(From instance: {0})”, _InstanceCount);

return “Hello There!” + msg;

}

}

Using Code

The WCSF 2010 framework is needed to run the application.  For installing WCSF please refer to http://www.c-sharpcorner.com/UploadFile/40e97e/4402/

Advertisements

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

Advantage of [ServiceDependency] in WCSF – Instance Reuse

Posted by Paul on April 6, 2011

Web Client Software Factory provides with a good feature through [ServiceDependency] attribute.

This attribute allows us to make use of the Dependency Injection and Instance Reuse advantages.

Example

Let us have an example to learn the [ServiceDependency] attribute.

Step 1: Create a new WCSF project

You can open the Visual Studio 2010, and use File>New Project and enter the project name as shown in the image below:

clip_image002

In the appearing wizard after screen above click Finish.

Step 2: Create a Utility class in Shell module

You can view from the solution explorer that there is a Shell module.

Right click on it and add new class named Utility which is having a single method named Greetings();

clip_image004

After the actions the solution explorer looks like above image.

The content of Utility class will be:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ServiceDependencyTest.Shell

{

public class Utility

{

public Utility()

{

}

public string Greetings()

{

return “Hello There!”;

}

}

}

Step 4: Specify the class Utility in global services

The Web Client Software Factory framework uses the term services for instances of classes that implement a particular interface. The services would be accessible through a service locator.

For specifying our class instance as a service we have to modify the ShellModuleInitializer.cs

Note: There are global and module services. The services specified as global would be accessible to all modules in the application and the services specified as module is visible only to the module in which it is declared.

In our case we are going to declare the Utility class in the global services. For this add the line

globalServices.AddNew<Utility, Utility>(); in the method AddGlobalServices(IServiceCollection globalServices)

clip_image006

Step 5: Declare the property with [ServiceDependency]

Now we proceed with declaring a new property named Utility in the DefaultViewPresenter class.

[ServiceDependency]

public Utility Utility

{

get;

set;

}

Please note that we marked the property with [ServiceDependency] – this will automatically take care of the instance injection.

The other way of instance creation is using the [CreateNew] attribute.

Step 6: Testing the application

Back to the web application we can place a label and button on the form. On click of the button use the following code.

protected void Button1_Click1(object sender, EventArgs e)

{

Label1.Text = this._presenter.Utility.Greetings();

}

Now you can run the application and clicking the button you will be able to see the greetings text.

clip_image008

Note: The Model View Presenter (MVP) constraints are violated in the above example by placing button handler code inside the view inorder to make the example more simple.

Instance Reuse

The WCSF provides the flexibility of instance reuse in the above scenario. You can verify it by placing a breakpoint in the constructor of Utility class and pressing button multiple times. There will be only one hit of the breakpoint. For getting the complete feel through running application, just replace the content of Utility class with the following.

public class Utility

{

public Utility()

{

_InstanceCount++;

}

private static int _InstanceCount;

public string Greetings()

{

string msg = string.Format(“(From instance: {0})”, _InstanceCount);

return “Hello There!” + msg;

}

}

Using Code

The WCSF 2010 framework is needed to run the application.  For installing WCSF please refer to http://www.c-sharpcorner.com/UploadFile/40e97e/4402/

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

Website Recursive Url Parser

Posted by Paul on March 26, 2011

In this article I am trying to share a piece of code that might be useful to some of the developers.

We can find a lot of code in C# that will parse the http urls in given string. But it is difficult to find a code that will:

  • Accept a url as argument, parse the site content
  • Fetch all urls in the site content, parse the site content of each urls
  • Repeat the above process until all urls are fetched.

Scenario

Taking the website http://valuestocks.in (A Stock Market Site) as example I would like to get all the urls inside the website recursively.

Design

The main class is SpiderLogic which contains all necessary methods and properties.

clip_image002

The GetUrls() method is used to parse the website and return the urls. There are two overloads for this method.

The first one takes 2 arguments. The url and and a Boolean indicating if recursive parsing is needed or not.

Eg: GetUrls(http://www.google.com”, true);

The second one is 3 arguments, url, base url and recursive Boolean.

This method is intended for usage like the url is a sub level of the base url. And the web page contains relative paths. So in order to construct the valid absolute urls, the second argument is necessary.

Eg: GetUrls(“http://www.whereincity.com/india-kids/baby-names/”, http://www.whereincity.com/, true);

Method Body of GetUrls()

public IList<string> GetUrls(string url, string baseUrl,

bool recursive)

{

if (recursive)

{

_urls.Clear();

RecursivelyGenerateUrls(url, baseUrl);

return _urls;

}

else

return InternalGetUrls(url, baseUrl);

}

InternalGetUrls()

Another method of interest would be InternalGetUrls() which fetches the content of url, parses the urls inside it and constructs the absolute urls.

private IList<string> InternalGetUrls(string baseUrl, string absoluteBaseUrl)

{

IList<string> list = new List<string>();

Uri uri = null;

if (!Uri.TryCreate(baseUrl, UriKind.RelativeOrAbsolute, out uri))

return list;

// Get the http content

string siteContent = GetHttpResponse(baseUrl);

var allUrls = GetAllUrls(siteContent);

foreach (string uriString in allUrls)

{

uri = null;

if (Uri.TryCreate(uriString, UriKind.RelativeOrAbsolute, out uri))

{

if (uri.IsAbsoluteUri)

{

if (uri.OriginalString.StartsWith(absoluteBaseUrl)) // If different domain / javascript: urls needed exclude this check

{

list.Add(uriString);

}

}

else

{

string newUri = GetAbsoluteUri(uri, absoluteBaseUrl, uriString);

if (!string.IsNullOrEmpty(newUri))

list.Add(newUri);

}

}

else

{

if (!uriString.StartsWith(absoluteBaseUrl))

{

string newUri = GetAbsoluteUri(uri, absoluteBaseUrl, uriString);

if (!string.IsNullOrEmpty(newUri))

list.Add(newUri);

}

}

}

return list;

}

Handling Exceptions

There is an OnException delegate that can be used to get the exceptions occurring while parsing.

Tester Application

A tester windows application is included with the source code of the article.

You can try executing it.

The form accepts a base url as the input and clicking the Go button it parses the content of url and extracts all urls in it. If you need a recursive parsing please check the Is Recursive check box.

clip_image004

Next Part

In the next part of the article, I would like to create a url verifier website that verifies all the urls in a website. I agree after doing a search we can find free providers like that. My aim is to learn & develop a custom code that could be extensible and reusable across multiple projects by community.

Source Code

The associated source code can be found in c-sharpcorner.  Please search using the same title there.

Posted in ASP.NET | Tagged: , , | 2 Comments »

How to avoid security error in ASP.NET textbox while inputting html content?

Posted by Paul on February 9, 2011

The ASP.NET handler checks for security threats on page submissions.  This is part of the security checks, otherwise malicious scripts could be injected to the server.

But, in some alternative cases we need to bypass this – say we need to save a webpage into the database.  But the page validation throws the error.

You can try the following:

1. Create a web application and place a textbox and button on it.

2. Run the application and try entering the following data into the textbox

<html>Test Content</html>

3. Click the button to submit the page

4. You will be receiving the following error:

Server Error in ‘/’ Application.


A potentially dangerous Request.Form value was detected from the client (TextBox1=”<html>test</html>”).

Description: Request Validation has detected a potentially dangerous client input value, and processing of the request has been aborted. This value may indicate an attempt to compromise the security of your application, such as a cross-site scripting attack. You can disable request validation by setting validateRequest=false in the Page directive or in the configuration section. However, it is strongly recommended that your application explicitly check all inputs in this case.
Exception Details: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client (TextBox1=”<html>Test Content</html>”).

 

Solution

Set the ValidateRequest property to false in the page level

<%@ Page Language=”C#” AutoEventWireup=”true” CodeBehind=”Default.aspx.cs” Inherits=”WebApplication2._Default” ValidateRequest=”false” %>

Now try rerunning the application and click the button.  The error is disappeared now.

Posted in ASP.NET | Tagged: , , | 2 Comments »

Manually install .Net 4.0 application pools

Posted by Paul on January 17, 2011

If you are working in old version of IIS, you may not find the latest application pools for .Net 4.0.  This small article provides to install the missing .Net 4.0 application pools.

Manually install the .Net 4.0 Application Pools

Step 1: Open command prompt and locate the 4.0 folder

image

Step 2: Use the command “aspnet_regiis.exe –i”

image

Wait for the installation to complete.

image

Step 3: Open IIS Manager to view the pools

You can click on the Application Pools link on the left to view the installed .Net 4.0 pools

image

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

What is Host Header and how to configure it?

Posted by Paul on January 11, 2011

 

Host Header is a third piece of information to identify a web site.

Thus the web site can be identified by using the following:

    • IP Address
    • Port
    • Host Header

Host Headers was introduced in HTTP 1.1

Eg: http://www.google.com

www.google.com is the host header

Configuration in IIS

We can configure host header in IIS using inetmgr application.

After configuration we need to publish the host header in the WINS (Windows Name Service) or DNS (Domain Name Service) depending on the site is an intranet or internet site.

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

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

Posted by Paul 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.

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

Deploying ASP.NET application to Production Server using FTP

Posted by Paul 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 »

Installation of WCSF for Visual Studio 2010

Posted by Paul 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 »

Part 5: WCSF : Power of [ServiceDependency] attribute

Posted by Paul 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 »