TechBubbles

WebForms Routing in ASP.NET 4

This post explains about WebForms routing features available in ASP.NET 4. Routing feature originally designed for ASP.NET MVC and now available for Webforms as well. You need to install Visual Studio 2010 ultimate beta2 to try the routing features in ASP.NET 4.

 

1. Create a ASP.NET Web Application in Visual Studio 2010 as follows

image  

2. Add the route definitions to the Global.asax.cs file as follows


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Routing;

namespace RoutingWebApp
{
    public class Global : System.Web.HttpApplication
    {

        void RegisterRoutes(RouteCollection routes)
        {
           routes.MapPageRoute(
                 "List-Show",     // Name of the method
                 "List/{state}",  // URL Semantics
                 "~/List.ASPX"  // Physical page which displays the 

                                   results for different URL semantics
    );
        }
        protected void Application_Start(object sender, EventArgs e)
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

 

RegisterRoutes method will be called in application start and routing definitions are registered using routes collection.

3. Now go to the Default.aspx page to add some links which displays the list of results based on city link.


<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
          WebForms Routing in ASP.NET 4......
    </h2>
    <p>
        <asp:LinkButton ID="lbCity1" runat="server" PostBackUrl="~/List/CA"> 

          List / CA 

        </asp:LinkButton>
    </p>
    <p>
        <asp:LinkButton ID="LinkButton1" runat="server" PostBackUrl="~/List/CO"> 

         List / CO 

        </asp:LinkButton>
    </p>
</asp:Content>

 

4. Add a new webform named List.aspx to the application and add Gridview control to the page and configure the data source as follows

Here we are using Person.StateProvince table to bind the data to Gridview control

image

In where clause select the RouteData as parameter source and mention the RouteKey with the name that we mentioned in the Global.asax.cs file.

5. Run the application by setting the Default.aspx as start-up page then click on the CA hyper link you will see the following results

image

6. Notice the URL after clicking on List/CA

image 

7. Results can also be populated based on the user input. To demonstrate this feature drag a text box and command button to the default.aspx. Write the following code in button click event handler.

string strUrl = Page.GetRouteUrl("List-show", new { state = TextBox1.Text });
Response.Redirect(strUrl);

So based on user-input also we were able to generate URL-Semantics using this routing feature.

Conclusion

We have seen the power of routing in ASP.NET 4 and declarative routing mechanism in ASP.NET WebForms application.

Share this post :

No comments

Dynamic Metadata using ASP.NET 4.0

This post explains about Dynamically assigning Metadata to a page using code behind in ASP.NET 4.0. Metadata is so important as Search engine optimization considers Metadata keywords and description to index  the page. If you can dynamically assign the metadata to your page then search engine can easily analyze and puts the page in results list.

1. Create a ASP.NET web application in VS 2010 and add a grid view to the page

image 

2. Configure the SqlDataSource to grid view with Address table as shown below

image

3. Run the application then you will see the following page

image

4. Right click the above and you will notice that there won’t be any meta tags in the page source.

image

This could be problematic for SEO search engine. One solution is you can go to the page and statically can give the meta data description and keywords. This won’t help for the website where data is dynamically updated and want to update their page meta tags according to their generated data.

5. Now We will display the list of sales persons from particular city and update the meta tags accordingly.

6. In code behind for the above page write the following code

string strCity = Page.RouteData.Values["State"] as string;
Page.MetaDescription = "A List of sales persons from " + strCity;
Page.MetaKeywords = "Lists, Sales person" + strCity;

The above code gets the city value from the routing URL and then appends the value dynamically to the page meta description and keywords.

Now run the application and you will see the following output in the page view source.

image 

You can notice that meta tags are update based on the visited cities and this description updated dynamically whenever the city value changed in the URL.

Share this post :

No comments

WCF Discovery with UDP

Inorder to call the WindowsCommunicationFoundation service, a port or pipe which assigned to the service must be available and the client must know the address endpoints before calling the services.

If the service could use any available address then client can discover that address at runtime. There is a industry standard-based solution which helps in discovering the service addresses.

Address Discovery

Discovery relies on the User Datagram Protocol(UDP). Client uses UDP to broadcast discovery requests for any end-point which supports the contract type. These requests are received by dedicated end-points. The end-points responds back to the client with service-address that support specified contract.

WCF offers a standard discovery endpoint with the type UdpDiscoveryEndpoint

public class DiscoveryEndpoint : ServiceEndpoint
{.......}

public class UdpDiscoveryEndpoint : DiscoveryEndpoint
{.......}

Adding ServiceDiscoveryBehavior the service

ServiceHost host = new ServiceHost(....);
host.AddServiceEndpoint(new UdpDiscoveryEndpoint());
host.Description.Behaviors.Add(discovery);
host.open();

Adding ServiceDiscoveryBehavior to service using config file

<services>
  <service name="MyService">
    <endpoint kind= "udpDiscoveryEndpoint" />
    .......
 </service>
</services>
<behaviors>
   <serviceBehaviors>
     <behavior>
        <serviceDiscovery/>
      </behavior>
   </serviceBehaviors>
</behaviors>

If you want dynamic base address for your service, the above code is still not perfect as it is requires to add discovery in config file or through code.

Auto Enabling the Discovery through code

public static class DiscoveryHelper
{
  public static Uri AvailableIpcBaseAddress
  {get; }

  public static Uri AvailableTcpBaseAddress
  {get; }
}
Uri baseAddress = DiscoveryHelper.AvailableTcpBaseAddress;

ServiceHost host = new ServiceHost(typepf(MyService),baseAddress);
host.EnableDiscovery();
host.Open();

If the host has not already defined the endpoints for the service, EnableDiscovery will add the default endpoints.

Client-Side Code for Discovering end-points

The client uses the DiscoveryClient class to discover all endpoint addresses of all services that support specified contract:

public sealed class DiscoveryClient : ICommunicationObject
{
   public DiscoveryClient();
   public DiscoveryClient(string endpointName);
   public DiscoveryClient(DiscoveryEndpoint discoveryEndpoint);
   public FindResponse Find(FindCriteria criteria);

}

Discovering and Invoking an Endpoint

DiscoveryClient discoveryClient = new
DiscoveryClient(new UdpDiscoveryEndpoint() );
FindCriteria criteria = new FindCriteria(typepf(IMyContract));
FindResponse discovered = discoveryClient.Find(criteria);
discoveryClient.Close();
//Just grab the first found
EndpointAddress address = discovered.Endpoints[0].Address;
Binding binding = new NetTcpBinding();
IMycontract proxy = ChannelFactory<IMycontract>.CreateChannel(binding.address);
proxy.MyMethod();

Client may discover multiple endpoints supporting the desired contract, it simply invokes the first one in the returned collection.

No comments

Remote Desktop Sessions from Commandline

You will commonly see the following error message when you try to connect windows 2003 server using RemoteDesktopConnection.

“The terminal server has exceeded the maximum of allowed connections ”

logon-exceeded

 

You can disconnect the other remotely logged in users if you are a domain Admin user. Most of the users some time not even be using the sessions.

To see the list of remote sessions in the command window, type the following command.

qwinsta /server:<ServerIP>

Example:

qwinsta /server: 192.168.219.2

Remote sessions list

 

Use the following command line to disconnect the remote session

rwinsta /server: <ServerIP> <SessionID>

Example:

rwinsta /server:192.168.219.2 2

The user who disconnected from the session will see the following message

Disconnected-Server-Session

 

The remote session was disconnected because your session was logged off at the remote computer. Your administrator or another user might have ended your connection.


Share this post :

No comments

WCF Service using ASP.NET AJAX Library

More often, the data to shown in an AJAX page is retrieved from the Web server using a Web service, a Windows Communication Foundation (WCF) service. The services that can also return JavaScriptObjectNotation(JSON) are potential candidates for AJAX pages.

This post explains about calling a WCF service using ASP.NET AJAX Library Data View control. The following are the steps to create and call the service using ASP.NET AJAX Library.

1. Creating a AJAX enabled WCF service

2. Loading the required scripts

3. Calling a service using ASP.NET AJAX Data View Control

Creating a AJAX enabled WCF service

1. To Create a WCF service, Right click the website project and say Add new item and Select the AJAX-enabled WCF Service template as shown below.

image

2. After creating the service, add a custom operation that returns the data to the AJAX application. The following code displays the list of employee object which can be returned from service code.


[ServiceContract(Namespace = "www.techbubbles.com/AJAXServices")]
[AspNetCompatibilityRequirements(RequirementsMode =

 AspNetCompatibilityRequirementsMode.Allowed)]
public class Service
{

    [OperationContract]
    public List<Employee> GetEmployee()
    {
        // Add your operation implementation here
        using (AdventureWorksModel.AdventureWorksEntities1 advContext = 

            new AdventureWorksEntities1())
        {
            return advContext.Employees.Take(10).ToList();

        }

    }

}

 Loading the required scripts

1. The JavaScripts in the ASP.NET AJAX library can be loaded using the following     code

<script type="text/javascript" src="Scripts/Start.js"></script>

     <script type="text/javascript">
         Sys.require([Sys.components.dataView, Sys.scripts.WebServices]);  
    

</script>

Calling WCF service using DataView Component

Data View component use Sys.create.dataView and pass the template to bind the data.

<script type="text/javascript">
   1:  
   2:        Sys.require([Sys.components.dataView, Sys.scripts.WebServices], function() {
   3:            Sys.create.dataView("#EmployeeView",
   4:    {
   5:        dataProvider: "Service.svc",
   6:        fetchOperation: "GetEmployee",
   7:        autoFetch: true,
   8:        itemRendered: EmployeeRendered
   9:    });
  10:  
  11:            function EmployeeRendered(dataView, ctx) {
  12:                Sys.bind(Sys.get("li", ctx), "innerHTML", ctx.dataItem, "NationalIDNumber");
  13:            }
  14:        });     
  15:    

</script>

The above code calls GetEmployee operation on WCF service. By setting the autofetch property to true the service will be called automatically as the page loads. After returning the data from WCF service EmployeeRenderd function will be called and data is bound to the template named EmployeeView.

The following HTML markup  can be used to attach the Data View component.

<<body xmlns:sys="javascript:Sys"
      xmlns:dataview="javascript:Sys.UI.DataView">
    <form runat="server" id="form1">
    <div id="EmployeeView"   

        sys:attach="dataview"
        dataview:autofetch="true"
        dataview:dataprovider="Service.svc"  

        dataview:fetchoperation="GetCustomers">
        <ul>
            <li>{{NationalIDNumber}}</li>
        </ul>
    </div>
    </form>
</body>  

The above mark up defines the name space for Dataview component in body element with the value javascript:Sys.UI.DataView.

1 comment

Master-Detail Views using ASP.NET AJAX

Master-Detail Views are very common in data-driven Web pages. These views are used for rendering one-to-many relationships. ASP.NET Web forms provided the strong server controls like grids,lists and drop-down lists which supports the multiple levels of data.

In Master-Detail View we normally navigate among master records and drill down into the details of the records that are of interest. In classic Web forms we need trigger many post-backs which most of the users are not happy these days.

This post explains about building a Master-Detail View using ASP.NER AJAX Library.

The DataView Client control is the fundamental tool for building master-derail views in ASP.NET AJAX and it can be used to generate both Master and Detail views.

Basic steps to build the Master-Detail application using ASP.NET AJAX

1. Create markup for the master and detail views.

2. Attach the DataView control to each view.

3. Use data-binding expressions to populate the data to the controls.

 

Building a Master View

1. In order to use the dataview component we need to load the scripts in the ASP.AJAX library as shown below

<head runat="server">
    <title>Master-Detail View</title>
    <script type="text/javascript" src="Scripts/Start.js"></script>
   1:  
   2:     <script type="text/javascript">
   3:         Sys.require([Sys.components.dataView, Sys.scripts.WebServices]);  
   4:     

</script>
</head>

2. Once the required scripts are available two namespace prefixes must be defined within the HTML document.

<body xmlns:sys="javascript:Sys" xmlns:dataview="javascript:Sys.UI.DataView">
</body>

3. The Master view markup

<div id="masterview">
       <ul id="master-view" sys:attach="dataview"
           dataview:autofecth="true"
           dataview:dataprovider="/service.asmx"
           dataview:fetchoperation="GetCustomers"
           dataview:fetchparameters="{{ {query: 'A'} }}">

        <li>
           <span sys:command="Select">
             <span> {binding CompanyName} </span>
              ,&nbsp;&nbsp;
              <span>{binding Country} </span>
           </span>
        </li>   

       </ul>
   </div>

The body of the UL tag binds the fetched data using web service. We have used the ASP.NET Ajax Library live-binding syntax.

4.  The Detail view markup

<div id="DetailView" sys:attach="dataview"
  dataview:data="{binding selectedData, source=$masterView}" >
    <table>
        <tr>
            <td>
             <b>Contact</b>
            </td>
            <td>
              <input id="contact" type="text" sys:value="{{contactname}}" />
            </td>
        </tr>
        <tr>
        <td> <b>Address</b> </td>
        <td><input id="address" type="text" sys:value="{binding  street}" /></td>
        </tr>
    </table>
</div>

The data property of dataview used an expression where the values come from the object named master View.

This post explained,  how to configure dataview control to support auto fetching. Dataview object is responsible for triggering the specified fetch operation after initialization.

Share this post :

No comments

ASP.NET AJAX Library Beta in Visual Studio

Overview

The ASP.NET AJAX Library is a JavaScript library which enables the developer to build highly interactive Ajax applications. Using ASP.NET Ajax client controls we can take the advantage of building database-driven web applications. This post explains how to add these controls to Visual Studio toolbox and explore the beta features.

The ASP.NET AJAX Library is compatible with Visual Studio 2008 and Visual Studio 2010 beta when targeting ASP.NET 3.5.

Using the ASP.NET AJAX Library Beta Scripts

There are two ways that we can use AJAX Library scripts in a  web applications.

  1. Adding controls from AJAX library to Visual Studio Toolbox.
  2. We can instantiate ASP.NET AJAX Controls  in JavaScript Code.

Adding ASP.NET AJAX Library Controls to Visual Studio Toolbox

To add the controls to visual studio toolbox, follow these steps

1. Create a ASP.NET Web Site project or Web application project

2. Open the default page in visual studio designer.

3. Right click the Toolbox and then click Add Tab. Name the new tab ASP.NET Ajax Library.

image  

4. Right click beneath the ASP.NET AJAX Library Tab and then click on chooseitems option.

5. Browse the downloaded path and then go to Webforms folder in it, choose AjaxControlToolkit.dll assembly and then say OK.

you can download ASP.NET AJAX library beta here

image

6. After adding the above dll you can see the controls as shown below

image

Adding AJAX library controls using Java Script

1. Copy the script folder from downloaded location to your web application.

2. Add the following script element to your .aspx page

<script src="../Scripts/Start.js"

type="text/javascript"></script>

3. After adding a reference to the start.js script, we can create and attach an ASP.NET AJAX control to a DOM element by using System.create method.

4. Following is the example to add a control using Java Script


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Simple Calendar</title>
    <link href="../Scripts/Extended/Calendar/Calendar.css" 

     rel="stylesheet" type="text/css" />

    <script src="../Scripts/Start.debug.js" type="text/javascript"></script>
   1:  

   2:     <script src="../Scripts/Extended/ExtendedControls.debug.js" 

           type="text/javascript">
   1: </script>
   2:     <script type="text/javascript">
   3:  
   4:         Sys.require(Sys.components.calendar, function() {
   5:             Sys.create.calendar("#travelDate");
   6:         });
   7:     
   8:     

</script>
</head>
<body>

<input id="travelDate" />

</body>
</html>

Share this post :

2 comments

Runtime Settings with SSIS Package

Introduction

Clients may require to integrate the SSIS packages in their environment(Production). SSIS package settings needs to be changed at run time and all settings needs to be pulled from the database using set of stored procedures.

1. Create a SSIS package and drag the Execute SQL task to control flow in the package as follows

image

Read more

No comments

Domain Model Using UML

Introduction

Unified Modeling Language is a graphical language used to describe objects in a system. This post describes the UML class diagrams and relationships among business entities in the system.

Domain Model represents the relation ship between logical entities in the system. It also illustrates how different entities in application domain would interact with each other.

Class

                         clip_image001

Relationships

                clip_image002

Read more

No comments

ASP.NET Application Architecture Steps

Introduction

If you have good logical skills and aptitude then it can be easier for learning programming languages. Unlike programming Software Architecture requires years of experience to master. Software Architecture is a guide to shape your project and Architecture of a system is nowhere related to the code that you write for this system. This post explains the architectural steps involved in application development.

Software Architecture is simply blueprint of your application. Software Architecture is closely related to the business needs of the project and it is not concerned about technology on which the project built upon.

Software Design deals with the implementation of the architecture which includes what design patterns to use to make the application scalable, what development methodology that we use in development phase. Basics about software architecture can be found here.

Business Requirements

Assume the following are the high-level specifications of the requirements

· System should be accessible from any location.

· System should be able to process multiple tasks.

· System should be able to process information from different databases.

· System should interact with other software packages.

Software Architecture Specification

Architecture specification for the above requirement

  • The system should be web based
  • The system should have built-in multithreading capabilities.
  • The system should be database-independent.
  • The system should expose APIs to import and export data from other sources.

Software Design Specification

Choosing a design pattern- Design patterns are proven solutions to the business problems. It tells us how we can achieve a solution in-terms of implementation.

We will need to customize the design-patterns to meet your unique needs.

Use Case Design: Creating use-case document which explains the interaction between the application and the end user. It lists the interaction steps sequentially. Each use-case should capture a specific scenario from end-to-end.

Prototyping

For Web projects, designing a working prototype in HTML before starting to work on developing is really helpful. Properly-Linked HTML pages with some dummy data shows the important business process flows and answers the business-related questions. It is highly recommended to develop a prototype before the actual coding for a project.

Class Model

The Architect and Technical lead will create an object model of the system which specifies important entities in the system and how they will interact.

Database Model

A database model would be created based on the class model described above. The use-cases, class model and database model will help the development team with clear instructions. Based on this project manager will highlight the milestones of the development phase.

Development-Phase

Identify and Separate the different components in the application. This separation can be at two levels

  • Physical Separation: We separate code physically into different assemblies. Each assembly or component can be deployed to servers across the geographical locations. We also call this as n-tier architecture.
  • Logical Separation: Separating the code logically into different layers, but the entire application will be part of a single assembly and can be deployed to single server. Unlike physical or tier architecture it is not possible to deploy parts of the application in a distributed manner.

Programming the layers

  • Web forms as the presentation layer

-Usually contains the graphical display components like ASPX pages,

Master pages and style sheets.

  • C# or VB code for handling the business logic as the Business Logic Layer (BLL).

-Usually contains business rules and presents the data to presentation layer. This layer may also include code for error handling and logging.

  • Data Access code as the Data Access Layer (DAL).

- This layer is a set of classes used to encapsulate data access methods. DAL’s primary job is to communicate with the database and pass it to the business logic layer.

Conclusion

This post examined the difference between tiers and layers and the different  ways we can structure our project using tiers and/or layers in ASP.NET application.

No comments

Next Page »