Tuesday, July 12, 2011

Deployment of a Website on IIS

Deployment of a Website on IIS

During last few days, I was deploying my application and I faced a lot of issues. I found deploying an application properly is as much as important as developing application. If application is not deployed properly, it can be very harmful to you application Here I want to share my learning to you all.
For deployment, first we need to understand IIS, it's request processing and then we'll go for deployment of the website and various configuration available in IIS, their key features, advantages and disadvantages etc..

IIS

IIS at root level, a Windows Service that is responsible for processing requests received on specific ports. For it, a service called the World Wide Web Publishing Service runs on the system. For deploying an application, we cerate a Virtual directory and the convert it into an application. Actually Virtual Directory is nothing more than a configuration entry in IIS for sharing a physical path for access through Web Server.
Final2.JPG
The complete configuration (with all its settings) is stored in a file, called a metabase, on local system. IIS metabase is a XML -based data store in IIS6.x and it can be configured through IIS management console.

IIS and URL Processing:

Normally ,Web application are accessed and processed through browser. Browser sends the request to the Server (Here it is IIS) which actually process the request. The following are the steps that are done by IIS
  • First, IIS examine the requested URL. It also check the port if it is not configured on default port 80,then url also requires port no.
  • If we have a URL "http://webserver/store/books.aspx" then here web server shows the name of Virtual directory and books.aspx is the requested file.
  • Every file extension is registered in IIS and connected with ISAPI extension and every file is connected to a DLL file.
  • Every file extension is connected to ASP.NET runtime are connected with appropriate aspnet_isapi.dll ISAPI extension. these are automatically added at the time of installation. Using this different version of framework are managed (as, ASP.NET 1.0 1.1 and 2.0) and can be configured for every website.
  • IIS 6 is split in several componants:In it a Kernel driver as the picture below is responsible for receiving HTTP requests from the clients then it forwards requests to any process that registers itself for specific URLs. i e any application that registers with the kernel mode driver can receive HTTP requests without running the whole server.
  • IIS launches worker processes which provide mechanism of Isolation and each worker process runs one or more applications, either ASP.NET based or any other type

IIS 6.0 Process Model:

The web server is now split into several components.IIS 6.0 includes a kernel mode driver called HTTP.SYS,which is responsible for receiving HTTP requests from clients. And the kernel forword the requests to any process that registers itself to specific URLs.
All the reliability and security options are configured at the applications pool level.Therefore,when running ASP.NET on IIS6.0,the classic ASP.NET process model with the configuration of the <processModel> element in the machine.config is desabled ,cause all the options introduced for the <processModel> are configured for IIS6.0 worker process.
Final1.JPG
WAS monitors each workers process and if one fails it restarts it so that it application doesn't go down abruptly.
Deploy7.jpg
  • We can define separate identity for each worker process ie it allows to configure additional isolation through permissions of the account that's configured for the worker process and these are configured through application pools in IIS management console i e every application pool has itself own worker process and every Virtual Directory can be be assigned to these application pools as I discuss in the last section.Each application pool can run as many application as needed.
  • Application pools allows us to easily configure different web applications to run under different account with different resource usage limits and provide more web application isolation

Managing a Virtual Directory :

Managing a virtual directory includes creating a virtual directory and its all settings. When IIS is installed a directory named "c:/Inetpub/wwwroot" is created automatically.Any files in this directory will appear as they're in the root of the web server.using the wwwroot directory fro creating a virtual directory makes a very poor organisation so try to avoid it.That's why I coosen the second option as below

Making a Virtual directory:

  1. Go to run and type inetmgr and press enter. You will get IIS management console as below and do as the screen shot.
Deploy8.jpg
2. Click next.Set alias of your website as you want
Deploy9.jpg
3. Click Next and browse the physical path of your application.
Deploy10.jpg
4. Set Permissions as we have five options as
Deploy11.jpg
  • Read: It is most basic and is mandatory to access the webpage of your application.
  • Run Scripts: It is required for the aspx pages not for the static HTML pages because aspx pages need more permissions sp that they could conceivably perform operations.
  • Execute: This allows the user to run an ordinary executable file or CGI application. This can be a security risk so allow when it is really needed.
  • Write: It allows to add, modify or remove files from the web server. This should never be allowed.
  • Browse: This allows one to retrieve a full list of files in the virtual directory even if the contents of the file are restricted.It is generally disabled.
5. Right Click on the Virtual Directory and go to properties and clock on create to set it as application
Deploy12.jpg

Virtual Directories settings:

IIS made very easy to configure Virtual directory settings after creation of it. Just Right click on virtual directory and choose properties. And the property window will appear. Below I am trying to explore some most important settings.
File Mappings: As earlier, IIS forwards requests for aspx pages to the ASP ISAPI extension and sends requests for ASP.NET pages to the ASP.NET ISAPI extensions. And IIS decides the ISAPI extension based on the filename extension of the requested URL and these mappings can be done per virtual directory basis. To view it, click Configuration button on the Virtual Directory tab in the properties of a Virtual Directory.
Deploy13.JPG
S No File Extensions Description
1 .aspx These are ASP.NET WebPages
2 .ascx These are ASP.NET user controls. It can't be accessed directly, to access it it must be hosted on ASP.net pages.
3 .asmx These are ASP.NET web services, which is used for exposing functionality to other applications over HTTP.
4 .asax These are for Glo9bal application file which is used for global events like when user starts the application.
5 .ashx These are HTTPHandlers,which allow to process requests without using the full-fledged ASP.NET web-page model.
6 .axd These are used for the trace.axd application extension, which allows to trace messages while debugging
7 .rem and .soap These extn identify that IIS is hosting an object that can be called by .NET Remoting
8 .cs,.csproj,.licx,.config,.resx,.webinfo These files are used by ASP.NET, but that can't be directly called by clientsAlthow,ASP.NET registers them so that it can explicitly prevent users from accessing these files, regardless of the IIS security settings.
Normally, if we have multiple versions of ASP.NET installed at one point of time, one may want to configure the mappings deffrently in different directories.
Documents: This tab allows one to specify the default documents for a Virtual Directory. Like if user just type "http://MyServer/MyApplication" then IIS simply redirect to the user to that default page. If none page is found, IIS will return the HTTP 404 (page not found error). To see and set the default page, in the properties of the Virtual Directories, Click on the documents tab
Deploy14.jpg
Custom Errors: This tab allows us to specify an error page that'll be displayed for specific type of HTTP errors (see below picture) .One can use ASP.NET configuration to replace HTTP errors or application errors with custom messages. This only work if the web request makes it to ASP.NET service.
Deploy15.jpg

Managing a Application Pool ( worker processes):

As a default installation, one application pool called DefaultAppPool is created. This runs as a Network Service, every web application runs on default website uses this default pool.

Creating Application Pools:

First let us try to know, when we need different application pool as we have already an application pool as DefaultAppPool .Mainly there are three reasons
  • Stability problems: If on a server there are multiple application are running, If all are on same pool then if this pool have any problem the all the application using this pool are going to affected.
  • Memory Leaks: If there is resource intensive application an old application running on a application pool with a memory leak is perfect candidate for regular recycling. In this case, applications running on different application pool, will not get affected.
  • Security: Security configuration is another main reason for having multiple application pool. Let us ,we want an application that will be able to write some logs on the client computer, then we should have an application pool which should run on LocalSystem's account other might be doesn't need the same so they can on different accounts.
  • Administration: This is also one of the reasons for having separate pools .Might be on a server, there are multiple sites hosted for saparate parties then it doesn't allow to access the resources of another pools.
Note: Recycling an application pool (worker process) means stoppinng the old worker proceses which have already take lots of resources and start new instance of it for the application pool.
To create the application pool follow the below steps ( Please keep in mind that IIS should be installed on the machine)
  1. Go to run -> type inetmgr then click ok. You will get the following window.
Deploy1.jpg
2.
Deploy18.jpg
3.
Deploy19.jpg
Here you have two options
  • First, if you want to use default settings (use it when you want to create it with new settings)
  • Second, If you want to have a new pool with just same settings as some another pool then you can can select this one and change the template pool from the dropdown (It'll save your time from doing the same settings again)
4. You can configure the application pool by right click on the pool created and select properties
Deploy20.jpg
5. You can configure the identity of every application pool by selecting Identity tab from the property window of application pool as above window
Deploy21.jpg
Here in the dropdown ,one has three options:
Network Service: This account is restricted account with least privileges in the three.This is mainly used for applications that require access to network and need to be accessed from other machines in the network.
Local Service: This account is having more restricted than Network service and mainly to be used for services that don,t require additional network access.
Local system: Generally this account is not recommended to use, because it is most powerful account of the system. It can perform any action on the local system. so the basic motto , one should provide that much of privilege that the application needed so it can't be hacked easily.
you can also configure it as selecting your own user account by specifying the the Windows user name and password for this account.

Application Pools Configuration:

Right Click on the application and go to Virtual directory tab Deploy22.jpg
change the application pool and click on apply button.

Deploying Application:

Deploying is nothing more than copying the published code of the application to target machine and configure the environment as needed. this is true for simple application but for application using database or access other resources, one need to perform additional steps.
  1. Copy required file to target machine: Check whether all assemblies are in place. If not use install it using gacutil.exe.
  2. Create and configure the Database
  3. Add IIS file mappings as per requirement
  4. Update web.config for any application settings or connection strings etc.
  5. Rest settings can be done as per requirement as we discussed above like application pool etc.
Hope you all like this article. Please do post your comments it'll help me a lot to improve this article as well as my upcoming articles.

PM Lite Methodology

A Quick Overview of the PM Lite MethodologyThe PM Lite Methodology is a set of methods and techniques to ensure successful delivery of quality projects in a cost-effective, schedule-compressed manner.
Target Projects
A project management methodology is used whenever a delivery organization puts together a team of people to understand a customer's requirements and to design and deliver a solution to those requirements within an agreed-upon budget and schedule.
The PM Lite Methodology is a condensed version of the Project Management Methodology. Use PM Lite for information technology projects that are managed by a single Project Manager.
Use the full version of the Project Management Methodology for projects that are managed by a Project Management Office. These are typically larger, more complex projects that involve (for example) a complex contract, many hardware and software products and other deliverables, and a distributed project team in which work is performed in multiple locations by multiple companies.
Use the full version of the Project Management Methodology for projects that are managed by a Project Management Office. These are typically larger, more complex projects that involve (for example) a complex contract, many hardware and software products and other deliverables, and a distributed project team in which work is performed in multiple locations by multiple companies.


Although the methodology uses the terminology of a customer and a delivery organization, it is equally valid whether the customer is an internal or external organization.


Relationship to Other Methodologies
The PM Lite Methodology is used in conjunction with the other methodologies that generate the specific component products that make up the delivered systems and services.


Relationship to Industry Standards
The PM Lite Methodology is consistent with the full version of the PMP or Prince2 Project Management Methodologies, which has been designed to reflect and support compliance with leading national and international standards including the ISO 9000-3 Quality Management and Quality Assurance Standards, the Software Engineering Institute's software engineering criteria for level 4 and level 5 methodologies, and the Project Management Institute's Body of Knowledge (PMBOK), which categorizes the body of knowledge about project management for purposes of advancing the state-of-the-art in the theory and practice of project management.

Monday, July 11, 2011

Dot Net Remoting

Introduction

Dot Net Remoting is a simple programming model/framework which allows objects from different machines/processes/app-domains to communicate each other. It allows the flexibility of using different types of communication protocols (tcp, http etc..) and message formatters (binary, SOAP etc..). Communication among different app-domains is facilitated by Remoting objects. Remoting objects can be hosted using Managed Executables/IIS/.Net Component Services. It is also possible for .Net applications running on different machines to share the same instance of a remoting object hosted on a server. 

This document demonstrates how to handle events from a remote object using a real time �Message and file transfer� application.

 

Technologies covered in this document


This document demonstrates the following pattern and technologies.

         Publisher listener design pattern
         Server activated singleton objects
         Marshal by reference remote object access
         Raising events from remote objects
         Use of binary format over TCP channel

 

Publisher-Listener Design pattern.

Design patterns are an efficient way of reusing and sharing solutions to repeating problems. �Publisher-Listener� is a behavioral design pattern. It is also known as �observer� pattern. By definition, a �Publisher-listener� pattern establishes a one-to-many dependency between objects so that when one object changes state , all it�s dependents are notified and updated automatically.

Sample screenshot 

As shown in the above diagram, in a �Publisher-Listener� design pattern, when a publisher post a message, all the listeners are automatically get updated with the message. A publisher and listener can be the same object. There can be so many publishers and listeners. All the listeners have to register to the server to make them enable to listen to the messages.

Dot Net Remoting terminologies


Server-Activated Objects

Server-activated objects are objects whose lifetimes are controlled by the server. They are created by the server only as needed when the client invokes the first method on the object. Server-activated objects only support default constructors. To use a remote object with parameterized constructors you can use client activation or dynamic publication (see below). Server-activated objects are also referred to as well-known object types, as their location (URL) is published and known in advance. There are two activation modes for server-activated objects, Singleton and SingleCall, both of which are described below.

 

Single Call

Single Call objects service one and only one request coming in. Single Call objects are useful in scenarios where the objects are required to do a finite amount of work. Single Call objects are usually not required to store state information, and they cannot hold state information between method calls. However, Single Call objects can be configured in a load-balanced fashion.

Singleton Objects

Singleton objects are those objects that service multiple clients and hence share data by storing state information between client invocations. They are useful in cases in which data needs to be shared explicitly between clients and also in which the overhead of creating and maintaining objects is substantial.
For example, the following code snippet depicts a server-activated (wellknown) type with activation mode set to SingleCall.

<service>
  <wellknown mode="SingleCall" type="Hello.HelloService, Hello" objectUri="HelloService.soap" />
</service>

Client-Activated Objects (CAO)

Client-activated objects (CAO) are server-side objects that are activated upon request from the client. When the client submits a request for a server object using "new" operator or Activator.CreateInstance(), an activation request message is sent to the remote application. The server then creates an instance of the requested class and returns an ObjRef back to the client application that invoked it. A proxy is then created on the client side using the ObjRef. The client's method calls will be executed on the proxy. Client-activated objects can store state information between method calls for its specific client and not across different client objects. Each invocation of "new" returns a proxy to an independent instance of the server type. For example, the following code snippet depicts a ClientActivated type. Note that we no longer need an URL, as for client-activated types the type alone is sufficient for activation. Also, the wellknown tag has been replaced by the activated tag.

<service>
  <activated type="Hello.HelloService, Hello" objectUri="HelloService.soap" />
</service>

Types of Marshalling

Objects are valid only in the application domain where they are created. Any attempt to pass the object as a parameter or return it as a result will fail unless any of the following types of marshalling is used.

Marshal By Value (MBV)

For objects that are Marshal By Value (MBV), a complete copy of the object is made when the object is passed from one application to another. If the object is marked as Serializable, the object will automatically be serialized, transported from the one application domain to the other, and then deserialized to produce an exact copy of the object in the second application domain.

Marshal By Reference (MBR)

For objects that are Marshal By Reference (MBR), a reference to the object is made when passed from one application to another. When the object reference (ObjRef) arrives in the remote application, it is turned into a "proxy" back to the original object. In order to marshal a remoting object by reference, inherit it from MarshalByRefObject class.

Proxy objects.

 When a client creates an instance of a remote object, it receives a proxy to the class instance on the server. All methods called on the proxy will automatically be forwarded to the remote class and any results will be returned to the client. From the client's perspective, this process is no different than making a local call.

Stateless and Stateful objects.

 The .Net Framework makes a provision for creating remote objects as stateless. When an object is configured as SingleCall, it will be created when a method is called on that object. The object processes the call, returns an optional result, and is then collected by the garbage collector. This way the client is always connected to a fresh object with each call.
Configuring an object as a Singleton ensures that all clients will be connected to the same object whenever a call is made to that object.

Lease based Lifetime.

The lifetime of remote objects is controlled by a leasing mechanism. When an object is first created, it is given a lease time. When the lease time of the object reaches zero, the object will be disconnected from the Remoting infrastructure and when all references to the object has been freed within the AppDomain, it will be collected by the garbage collector. A number of mechanisms are provided that allow the client to extend the lease on the object, thereby sustaining its life.

Raising events from remote objects

As with any normal .Net class, event handlers can be attached to remoting objects so that a client can hook methods to serve the declared events. Whenever the event gets fired in the remote object, the event handler method is executed in the client. However delegates require that the receiving object be able to obtain the type information for the class whose function is being wrapped by the delegate. In the case of the remoting, it means that he client assembly be available to the server. If the client assembly is not available to the server, that type information cannot be loaded.

To make remoted delegates work, an abstract class (MustInherit in Visual Basic .NET, abstract in C#) that contains the callback function must be defined in a common assembly that both client and server have access to. The client can then derive a custom class from this abstract class to implement the logic in the callback. The abstract class needs to have a specific structure. The function to be used for callbacks must be a public function that cannot be overriden. This function must forward all calls to a protected abstract function that is overridden in the derived client classes. The reason for this architecture is that the delegate needs to be able to bind to a concrete implementation of the callback function, and this implementation must not be overridable.

Remoted delegates are implemented in the �Message and File Transfer Application� (explained in section 6). You can refer the source code attached.

Message and File Transfer Application


Problem Definition

Basically, it is a chat application for intranet users of Windows network. The following screen shots explain the required functionality of this tool. When a user execute the client application, it the user gets automatically logged into the application. It then loads a Win-Form with a list of all the users who have already logged in. This list gets automatically updated in frequent intervals. In order to chat with a user, all that you have to do is to select the name of the user and type the message on the editable textbox. On entering the message, it get published to the remote object with the �from� and �to� addresses and all the listening clients get it. On receiving a message, each client checks the �to� address and decide whether to display that message or not.

Step1:
User �Joser� log in

Sample screenshot 

Step2:
User �Vijiths� log in and send a few messages and file to user �Joser�

Sample screenshot 

Sample screenshot

Step3:
User � �Joser� gets a down load-confirmation message.

Sample screenshot 
Sample screenshot

Sample screenshot

 

Solution architecture

The solution architecture is shown in the diagram below. There is class the object of which (the remote object) is hosted on a remote server by using a console application. Loading of this application can be configured using a windows service. As with any client-server application, it is must that the server application should be up running before the clients can access it. This object is a singleton object. The client application is a Winform which has reference to a local copy of the remote component. Using the local reference, the client application creates a proxy object. This proxy object then gets a reference of the remote object so that whenever the clients access the proxy object, it in turn accesses the remote object. Since the remote object is a singleton object, all the clients connecting to a single server is accessing the same instance of the remote class. This facilitates the communication among different clients.

The remote object exposes certain event handlers such as OnLogin, OnLogout, OnMessagePublish etc.. The client application can hook methods to these event handlers. So, whenever these events happen, all the clients get notified about it.

Whenever a user sends some message to another user, the �OnMessagePublish� event is raised. The sender acts as a publisher. All the clients, who have registered (added) a method to the �OnMessagePublish� event handler act as listeners. This is how �Publisher-Listener� design pattern is being implemented in this design.

Sample screenshot

Configuration Files


Server Configuration File

<configuration>
   <system.runtime.remoting>
      <application>
<lifetime leaseTime="20D" sponsorshipTimeout="1H" renewOnCallTime="1D" leaseManagerPollTime="1H" />
         <service>
            <wellknown
               mode="Singleton"
               type="MessageShare.SharedMessage,MessageShare"
               objectUri="SharedMessage"/>
                                                </service>
                                                <channels>
                                                                <channel ref = "tcp" port = "8080">

                                                                <serverProviders>
                                                                                <formatter ref="binary" typeFilterLevel="Full" />
                                                                </serverProviders> 
                                                                </channel>
                                                </channels>
                                </application>
                </system.runtime.remoting>
</configuration>

Client Configuration File

<configuration>
   <system.runtime.remoting>
      <application>
      <lifetime leaseTime="20D" sponsorshipTimeout="1H" renewOnCallTime="1D" leaseManagerPollTime="1H" />
        <client>
        <wellknown type="MessageShare.SharedMessage,MessageShare" url="tcp://10.201.33.229:8080/SharedMessage" />                                       
        </client>
         <channels>
            <channel ref="tcp" port="0" clientConnectionLimit="20" >
           </channel>
         </channels>       
       </application>
   </system.runtime.remoting>
<appSettings>
   <add key="RemotingUrl" value="tcp://10.201.33.229:8080/SharedMessage"></add>
</appSettings>
</configuration>

 

Please note to change the IP address and port number - tcp://10.201.33.229:8080 to that of the server machine where the server application is running. The port number should be same as that configured in the server configuration file.

Code snippets

Remoting class

 

  

Server Application

 

 

Client application (Win-Form)

Download sourcecode - ClientAppSource.Zip

Installation Files



Installation Notes:


         Please note to change the IP address and port number - tcp://10.201.33.229:8080 in the client configuration file to that of the server machine where the server application is running.
         The port number in the client configuration file should be same as that configured in the server configuration file.
         Manually start the server application (executable console application)
         Use the client application only after ensuring the following
o        The configuration files are updated properly
o        The server application is started.

Reference

         Remoting Events

Abbreviations

Abbreviation
Expansion
MBV
Marshal By Value
MBR
Marshal By Reference
CAO
Client Activated Objects
SOAP
Simple Object Access Protocol
IIS
Internet Information Services

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.
A list of licenses authors might use can be found here