Friday, December 7, 2007

Create Windows Service with C#.Net - Part 1

While surfing on Internet I found many people for How to create Windows Service?, Installing Windows Service, Schedule Windows Service. I had created one Schedule Windows Service with C#.Net. Here I will give you one example for how to create schedule windows service with less effort, how to add windows service to event log viewer. Why we need Windows Service? Many times we want to run a block of code at perticualr time. For example backup data from one server to other server ever 7 days. For this either we have to create backup data and upload to other server. Sometimes it needed every day, so we have to spend much time for backing up data and upload it to other server.
So why not use a code which create a backup and upload to other server at schedule time we set. This block of code is nothing but a Windows Service.
Creating Windows Service
Open "Create Project" dialog in Visual Studio IDE. Now choose Project Type Visual C# -> Windows. Then select Template Windows Service.
This will give you a blank service template. Right click on the template then choose "View Code" This will give you three code block.
Default constructor for Your service.
public Service1() { InitializeComponent(); }
InitializeComponent() will initialize your service components which are inserted at design time to a windows servie (This will be discussed later).
The second block is for Service Start code.
protected override void OnStart(string[] args) {
//TODO: Add code here to start your service.
This is override event for default start event of a service. Window will execute the code written in this block when a service is started.
The third part is for code to execute when the service is stopped.
protected override void OnStop() { // TODO: Add code here to perform any tear-down necessary to stop your service.
Add the required code to run your service. In next part we will see how to install the created service.

Friday, October 26, 2007

Invalid postback or callback argument solution. Event validation is enabled using in configuration or <%@ Page EnableEventValidation="true" %> in a page.

First of all I will give a brief overview of Postback and Callback. When ever you register a control's server side event, ASP.Net register a JavaScript which will submit the form's details and on the server it fires the event which is registered for the control. register __doPostBack javascript function. Syntax for the script is __doPostBack('Event Target','Event Argument'); Here Event Target can be a control or it can be a function created by developer. You can also generate a postback script reference for a control by using GetPostBackScript function. Now ASP.Net page always handle the PostBack event by it self.

For Callback you have to impliment a ICallBackEventHandler interface. After implimenting ICallBackEventHandler a page must contain two events, RaiseCallBackEvent with return type void and GetCallBackResult with return type string. Your code logic will be contained in the RaiseCallBackEvent function code block and the result of the Callback will be contained returned by GetCallBackResult. Function GetCallBackResult will call the client side callback result function. I will explain CallBack in detail in my future post.
Many of ASP.Net users are facing a problem with invalid Postback or Callback argument error. Invalid PostBack or CallBack argument error is basically raise because of Event Validation feature. The EventValidation feature is a new feature in ASP.NET 2.0, and provides an additional level of checks to verify that a postback from a control on the client is really from that control and not from someone malicious using something like a cross-site script injection to try and manipulate things. It is part of our overall strategy of increasingly adding security in depth levels to the programming model -- so that developers can be secure by default even if they forget to add security checks of their own.

Now, Invalid PostBack or CallBack argument error may occur when you are firing click event and the object is rebinding or its properties are changed in Page_Load event or someone is trying to hack into your system with cross site scripting. Each time .Net Framework render a page then it associate a unique Guid for all the controls. When binding a gridview or repeater, on each databind framework will associate a new guid for the contorl. So every time when you are firing event make sure Page_Load event does not change the control, because if the control changed the it will have a different Guid which have acutally fired the event for postback. Here are some scenario with this error.

1) Invalid Postback or Callback argument in GridView Problem may be: You are binding data in Page_Load event with either Object Data Source or Manual Binding with function call. This will make your GridView bind data on every event fire of any control. When you are firing any GridView command with OnRowCommand, before RowCommand fire your GridView will rebind and all control within it will be assigned to new id. So RowCommand could not get the item which have fired the event. Solution for Invalid Postback or Callback argument in GridView: You can bind your data within this if condition
1:  if (!IsPostBack)
2:  {
3:       //Your code for Bind data 
4:  }
This code will definitely give you solution if this not work then check whether any other control is not giving error.

2) Invalid Postback or Callback argument while submitting form. Problem may be: You have many textboxes and textareas and when user is entering "<" or ">" char then it is giving error. This is because of .Net framework is giving facility to validate request. This function will allow user not to submit script or html code directly so it is blocked. Solution for Invalid Postback or Callback argument while submitting form: You can replace this char with javascript before submitting the form replace "<" with "&lt;" and ">" with "&gt;" the javascript code is here
1:  function ReplaceChar(obj) //Here obj is your textbox object 
2:  {
3:      var Textvalue = obj.value;
4:      Textvalue = Textvalue.replace("<","&lt;");
5:      Textvalue = Textvalue.replace(">","&gt;");
6:      obj.value = Textvalue;
7:   } 

The other solution for both of this issue is to set enableEventValidation=false You can set this option declaration <@ Page > or even you can put this code in your web. config file in <system.web> block <pages enableeventvalidation="false">//set it true if you want to validate your each request. If you do not validate the request then your security of data will be decrease so this is not the perfect solution If both of this solution not work then you can contact me on my email and if you find any new solution please post it comment.

Thursday, October 25, 2007

Detect browser in C#

Detect browser in

This article will give a little information on detecting the browser in We can use HttpBrowserCapabilities class with C# language. HttpBrowserCapabilities class gives information on the capabilities of the browser that is running on the client. It needs the System.Web namespace. HttpBrowserCapabilities properties are accessible through the Browser property of ASP.NET's intrinsic Request object.

I have mention here the HttpBrowserCapabilities members:

An example in C# to get browser detection

<script language="C#" runat="server">
  Protected void Page_Load(sender as Object, e as EventArgs)
    ltlBrowserName.Text = Request.Browser.Type + ", " + Request.Browser.Platform
    ltlAllData.Text = "Type = " + Request.Browser.Type + "<br>"
    ltlAllData.Text += "Name = " + Request.Browser.Browser + "<br>"
    ltlAllData.Text += "Version = " + Request.Browser.Version + "<br>"
    ltlAllData.Text += "Major Version = " + Request.Browser.MajorVersion + "<br>"
    ltlAllData.Text += "Minor Version = " + Request.Browser.MinorVersion + "<br>"
    ltlAllData.Text += "Platform = " + Request.Browser.Platform + "<br>"
    ltlAllData.Text += "Is Beta = " + Request.Browser.Beta + "<br>"
    ltlAllData.Text += "Is Crawler = " + Request.Browser.Crawler + "<br>"
    ltlAllData.Text += "Is AOL = " + Request.Browser.AOL + "<br>"
    ltlAllData.Text += "Is Win16 = " + Request.Browser.Win16 + "<br>"
    ltlAllData.Text += "Is Win32 = " + Request.Browser.Win32 + "<br>"
    ltlAllData.Text += "Supports Frames = " + Request.Browser.Frames + "<br>"
    ltlAllData.Text += "Supports Tables = " + Request.Browser.Tables + "<br>"
    ltlAllData.Text += "Supports Cookies = " + Request.Browser.Cookies & "<br>"
    ltlAllData.Text += "Supports VB Script = " + Request.Browser.VBScript + "<br>"
    ltlAllData.Text += "Supports JavaScript = " + Request.Browser.JavaScript + "<br>"
    ltlAllData.Text += "Supports Java Applets = " + Request.Browser.JavaApplets + "<br>"
    ltlAllData.Text += "CDF = " + Request.Browser.CDF + "<br>"      
Your browser is: <asp:literal id="ltlBrowserName" runat="server" />
<b><u>Here is your browser's information:</u></b><br />
<asp:literal runat="server" id="ltlAllData" />


Saturday, October 20, 2007

Mac Viewstate and Server Clusters / Web Gardens

The terms 'server farm' and 'web garden' may be foreign to many of us but they provide the mechanisms that allow us to cluster instances (web garden) or cluster servers (server farm). Server clusters specifically give us the following abilities:
 1. Have seperate Internet connections so that our sites can be load balanced. (For instance round-robin dns).
 2. Cluster of servers to either load balance client requests while providing the ability to pull one server out of the cluster for maintence or repair.
 3. Fault tolerance - if a server does go down then there are other servers that can handle the requests (if properly configured).

Web Gardens allow basically the same clustering on a single machine. You can set web gardens in the IIS MMC under Application Pools. See my notes at end of this article. In most cases, if you are not behind a proxy - this set-up works quite well as sticky-ip (sticky IP means that once your browser gets the first DNS record and can resolve the address and grab a page - it will always use that ip for consequent connections) seems to persist.

However, from a proxied connection - such as AOL, each request would randomly hit either the DSL hosted site or the cable hosted site. This causes problems because authentification can not occur. This is due to the fact that viewstate encryption keys are auto generated and as a result, the encryption from WEBSITE1 will be different than the viewstate encryption from WEBSITE2 and as a result WEBSITE1 can not decpiher the viewstate generated from WEBSITE2 and vice versa. You end up getting an error message like this:
Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that <machinekey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Web.HttpException: Validation of viewstate MAC failed.

If this application is hosted by a Web Farm or cluster, ensure that <machinekey> configuration specifies the same validationKey and validation algorithm. AutoGenerate cannot be used in a cluster. Now, if you do a search on the web - the common solution is to add the following to your web.config:

<pages enableviewstatemac="false"></pages>

In my opinion - not the right thing to do as it is possible then for a visitor to hack your viewstate and possible data injections will be the result. Instead it is really simple to add the following under (Note key is only an example and will not work as is)

<machinekey decryptionkey="0B3757F0FA339A7933D601790BB5CA412B52E9F7EB899" validation="SHA1" validationkey="9133E0987FCA19C001E33F3B30FAD930B099F50712BF9BC9E1DA989F0DA2CD6CBF7">

Use this site to generate a key for you: Copy the key to your web config, and then copy that web.config to each website on each server in your cluster. (if you are using web gardens - then nothing additional is required as there are no multiple copies).

This is important because this 'static machineKey' will allow every server in your cluster or application instance in your web garden - to decrypt the viewstate regardless where which server or application instance generates the originating viewstate. It is recommended that a different machine key be used for each distinct website unless you intend on sharing user information across them. As long as this machine key is duplicated to the mirror sites on the other servers - you will be fine.
About 'web gardens', you can configure web gardens in the "Application Pools" snap-in of the IIS MMC. Web Gardens basically spawn a seperate instance of your application in its own dedicated thread. One reason you may want to do this is for fault tolerance. If one instance crashes - hopefully all remaining connections will be sent to the other instance until the crashed instance restarts. Performance wise - you will not get any gains from using web gardens. This has been my experience in load testing and stressing out sites with multiple web gardens. In some cases performance could suffer by using web gardens.

Hopefully this article will shed some light on how to scale your website in the scenarios listed. Fairly easy really and with the CSK - since there are no real complex session issues that really need to be considered, this should work for most people.

Thursday, October 18, 2007

Development tools & Frameworks for ASP.Net

Development tools for ASP.Net Several available software packages exist for developing ASP.NET applications: Microsoft Expression Web, part of the Microsoft Expression Studio application suite. Visual Studio .NET or Visual Studio 2005 or Visual Web Developer 2005 Express Edition (for ASP.NET 2.0) ASP.NET Web Matrix (ASP.NET 1.x only, was free, now no longer supported: replaced by the free Visual Web Developer 2005 Express Edition) Macromedia Dreamweaver MX, Macromedia Dreamweaver MX 2004, or Macromedia Dreamweaver 8 (doesn't support ASP.NET 2.0 features, and produces very inefficient code for ASP.NET 1.x: also, code generation and ASP.NET features support through version 8.0.1 was little if any changed from version MX: version 8.0.2 does add changes to improve security against SQL injection attacks) Macromedia HomeSite 5.5 (For ASP Tags) Microsoft SharePoint Designer 12 Delphi 2006 MonoDevelop (Free/Open Source) SharpDevelop (Free/Open Source) Frameworks of ASP.Net It is not essential to use the standard webforms development model when developing with ASP.NET. Noteworthy frameworks designed for the platform include: Castle Monorail, an open-source MVC framework with an execution model similar to Ruby on Rails. The framework is commonly used with Castle ActiveRecord, an ORM layer built on NHibernate. Spring.NET, a port of the Spring framework for Java.

Common misconceptions in ASP.Net

Misconception: "ASP.NET is interpreted or semi-interpreted" Fact: ASP.NET (and indeed, .NET as such) applications executes fully compiled. The misconception stems from the fact that this compilation is a two-step process, where ASP.NET is first compiled into intermediate language (IL). This can be done using a compiler such as the C# compiler. Only just before actual execution on the target machine does the .NET CLR take over and compile the IL into machine instructions optimized for the target architecture. The developer has no control of this process. The ASP.NET runtime will then cache the compiled code for subsequent executions. Misconception: "ASP.NET relies heavily on code generation" Fact: ASP.NET is a highly abstracted framework for web development with feature rich components (widgets). Visual Studio will assist in configuring properties for these widgets, but in general they come with good defaults. Hence, VS has editors for special file formats, but no code generation in the sense that it spews out C# or VB.NET code which must be manually edited to suit different needs afterwards with the risk of losing custom changes when the code needs to be once again generated. In a number of places ASP.NET relies on metaprogramming, examples of this are: Compiling an .aspx markup file into a partial class, compiling a XML schema (representing a dataset) into .NET classes. One exception where code generation could be said to take place is when you define a dataset from an existing database by dragging and dropping tables from the database schema to the XML schema file. Misconception: "ASP.NET relies heavily on Visual Studio" Fact: An ASP.NET web site/application can easily be created using any text editor. Since compilation is handled by the server the markup files can be uploaded as source code to the server. Documentation (or experience) will be required to use the web controls/widgets in this way. For example, no vendor has implemented Intellisense.

Performance & Criticisms of ASP.Net

Performance of ASP.Net ASP.NET aims for performance benefits over other script-based technologies (including ASP Classic) by compiling the server-side code to one or more DLL files on the web server. This compilation happens automatically the first time a page is requested (which means the developer need not perform a separate compilation step for pages). This feature provides the ease of development offered by scripting languages with the performance benefits of a compiled binary. However, the compilation might cause a noticeable delay to the web user when the newly-edited page is first requested from the web server. The ASPX and other resource files are placed in a virtual host on an Internet Information Services (or other compatible ASP.NET servers; see Other Implementations, below). The first time a client requests a page, the .NET framework parses and compiles the file(s) into a .NET assembly and sends the response; subsequent requests are served from the dll files. By default ASP.NET will compile the entire site in batches of 1000 files upon first request. If the compilation delay is causing problems, the batch size or the compilation strategy may be tweaked. Developers can also choose to pre-compile their code before deployment, eliminating the need for just-in-time compilation in a production environment. Criticisms of ASP.NET Active Server Pages Classic (ASP) and ASP.NET can be run side-by-side in the same web application. This approach allows developers to migrate applications slowly instead of all at once. On IIS 6.0 and lower, pages written using different versions of the ASP framework can't share Session State without the use of third-party libraries. This criticism does not apply to ASP.NET and ASP applications running side by side on IIS 7. With IIS 7, modules may be run in an integrated pipeline that allows modules written in any language to be executed for any request. In some cases ASP.NET runtime will recycle the worker process (e.g. if it becomes unresponsive or if an application runs amok and causes the worker process to use more than 60% of available RAM). It can also be configured to recycle the process proactively after a certain number of requests, time period etc. In these cases users may lose session state if the application is configured to use in-process sessions. If the application relies on session state to store authentication information (bad practice since cookie based authentication and membership is built into the framework) and the application is configured to use in-process sessions, the user may be logged out if the process is recycled. ASP.NET 2.0 produces markup that passes W3C validation, but it is debatable as to whether this increases accessibility; one of the benefits of a semantic XHTML page + CSS representation. Several controls, such as the Login controls and the Wizard control, use HTML tables for layout by default. Microsoft has now gone some way to solve this problem by releasing the ASP.NET 2.0 CSS Control Adapters, a free add-on that produces compliant accessible XHTML+CSS markup. However, some controls still rely on JavaScript.

ASP.NET compared to ASP classic

ASP.NET attempts to simplify developers' transition from Windows application development to web development by offering the ability to build pages composed of controls similar to a Windows user interface. A web control, such as a button or label, functions in very much the same way as its Windows counterpart: code can assign its properties and respond to its events. Controls know how to render themselves: whereas Windows controls draw themselves to the screen, web controls produce segments of HTML and JavaScript which form part of the resulting page sent to the end-user's browser. ASP.NET encourages the programmer to develop applications using an event-driven GUI paradigm (event-driven GUI model), rather than in conventional web-scripting environments like ASP and PHP. The framework attempts to combine existing technologies such as JavaScript with internal components like "ViewState" to bring persistent (inter-request) state to the inherently stateless web environment. Other differences compared to ASP classic are: Compiled code means applications run faster with more design-time errors trapped at the development stage. Significantly improved run-time error handling, making use of exception handling using try-catch blocks. Similar metaphors to Windows applications such as controls and events, which make development of rich user interfaces, previously only found on the desktop, possible. An extensive set of controls and class libraries allows the rapid building of applications, plus user-defined controls allow commonly used templates, such as menus. Layout of these controls on a page is easier because most of it can be done visually in most editors. ASP.NET leverages the multi-language capabilities of the .NET CLR, allowing web pages to be coded in VB.NET, C#, J#, etc. Ability to cache the whole page or just parts of it to improve performance. Ability to use the code-behind development model to separate business logic from presentation. If an ASP.NET application leaks memory, the ASP.NET runtime unloads the AppDomain hosting the erring application and reloads the application in a new AppDomain. Session state in ASP.NET can be saved in a SQL Server database or in a separate process running on the same machine as the web server or on a different machine. That way session values are not lost when the web server is reset or the ASP.NET worker process is recycled. Previous versions of ASP.NET (1.0 and 1.1) were criticized for their lack of standards compliance. The generated HTML and JavaScript sent to the client browser would not always validate against W3C/ECMA standards. In addition, the framework's browser detection feature sometimes incorrectly identified web browsers other than Microsoft's own Internet Explorer as "downlevel" and returned HTML/JavaScript to these clients with some of the features removed, or sometimes crippled or broken. However, in version 2.0, all controls generate valid HTML 4.0, XHTML 1.0 (the default) or XHTML 1.1 output, depending on the site configuration. Detection of standards-compliant web browsers is more robust and support for Cascading Style Sheets is more extensive. Web Server Controls: these are controls introduced by for providing the UI for the web form. These controls are state managed controls and are WYSIWYG (What You See Is What You Get) controls.

Directory Structure of ASP.Net

In general, the ASP.NET directory structure can be determined by the developer's preferences. Apart from a few reserved directory names, the site can span any number of directories. The structure is typically reflected directly in the urls. Although ASP.NET provides means for intercepting the request at any point during processing, the developer is not forced to funnel requests through a central application or front controller. The special directory names are: App_Browsers holds site-specific browser definition files. App_Code This is the "raw code" directory. The ASP.NET server will automatically compile files (and subdirectories) in this folder into an assembly which is accessible in the code of every page of the site. App_Code will typically be used for data access abstraction code, model code and business code. Also any site-specific http handlers and modules and web service implementation go in this directory. As an alternative to using App_Code the developer may opt to provide a separate assembly with precompiled code. App_Data default directory for databases, such as Access mdb files and SQL Server mdf files. This directory is usually the only one with write access for the application. App_LocalResources Contains localized resource files for individual pages of the site. E.g. a file called holds localized resources for the french version of the CheckOut.aspx page. When the UI culture is set to french, ASP.NET will automatically find and use this file for localization. App_GlobalResources Holds resx files with localized resources available to every page of the site. This is where the ASP.NET developer will typically store localized messages etc. which are used on more than one page. App_Themes holds alternative themes of the site. App_WebReferences holds discovery files and WSDL files for references to web services to be consumed in the site.

Characteristics of ASP.Net

ASPX file format ASPX is a text file format used to create Webform pages; in programming jargon, the ASPX file typically contains static HTML or XHTML markup, as well as markup defining Web Controls and Web User Controls where the developers place all the required static and dynamic content for the web page. Additionally, dynamic code which runs on the server can be placed in a page within a block which is similar to other web development technologies such as PHP, JSP, and ASP, but this practice is generally frowned upon by Microsoft except for the purposes of data binding since it requires more calls when rendering the page. The method recommended by Microsoft for dealing with dynamic program code is to use the code-behind model, which places this code in a separate file or in a specially designated script tag. Code-behind files are typically named something to the effect of MyPage.aspx.cs or MyPage.aspx.vb based on the ASPX file name (this practice is automatic in Microsoft Visual Studio and other IDEs). When using this style of programming, the developer writes code to respond to different events, like the page being loaded, or a control being clicked, rather than a procedural walk through the document. Rendering technique ASP.NET uses a visited composites rendering technique. During compilation the template (.aspx) file is compiled into initialization code which will build a control tree (the composite) representing the original (static) template. Literal text goes into instances of the Literal control class, server controls are represented by instances of a specific control class. The initialization code is combined with user-written code (usually by the assembly of multiple partial classes) and results in a class specific for the page. The page doubles as the root of the control tree. Actual requests for the page are processed through a number of steps. First, during the initialization steps, an instance of the page class is created and the initialization code is executed. This produces the initial control tree which is now typically manipulated by the methods of the page in the following steps. As each node in the tree is a control represented as an instance of a class, the code may change the tree structure as well as manipulate the properties/methods of the individual nodes. Finally, during the rendering step a visitor is used to visit every node in the tree, asking each node to render itself using the methods of the visitor. The resulting HTML code is sent to the client. After the request has been processed, the instance of the page class is discarded and with it the entire control tree. Other files Other file extensions associated with different versions of ASP.NET include: asax Global.asax, used for application-level logic and event handling ascx Web UserControls: custom controls to be placed onto web pages. ashx custom HTTP handlers asmx web service pages. axd when enabled in web.config requesting trace.axd outputs application-level tracing. Also used for the special webresource axd handler which allows control/component developers to package a component/control complete with images, script, css etc. for deployment in a single file (an 'assembly') browser browser capabilities files stored in XML format; introduced in version 3.0. ASP.NET 2 includes many of these by default, to support common web browsers. These specify which browsers have which capabilities, so that ASP.NET 2 can automatically customize and optimize its output accordingly. Special .browser files are available for free download to handle, for instance, the W3C Validator, so that it properly shows standards-compliant pages as being standards-compliant. Replaces the harder-to-use BrowserCaps section that was in machine.config and could be overridden in web.config in ASP.NET 1.x. config web.config is the only file in a specific Web application to use this extension by default (machine.config similarly affects the entire Web server and all applications on it), however ASP.NET provides facilities to create and consume other config files. These are stored in XML format, so as to allow configuration changes to be made with simplicity. cs/vb In ASP.NET 2 any cs/vb files placed inside the App_Code folder are dynamically compiled and available to the whole application. master Master Pages; introduced in version 2.0 sitemap sitemap configuration files skin theme skin files. resx resource files for internationalization and localization. Resource files can be global (e.g. messages) or "local" which means specific for a single aspx or ascx or file.

Wednesday, October 17, 2007

Get started with ASP.Net

ASP.NET is a web application framework marketed by Microsoft that programmers can use to build dynamic web sites, web applications and XML web services. It is part of Microsoft's .NET platform and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime, meaning programmers can write ASP.NET code using any Microsoft .NET language. Microsoft ASP.NET is a free technology that allows programmers to create dynamic web applications. ASP.NET can be used to create anything from small, personal websites through to large, enterprise-class web applications. All you need to get started with ASP.NET is the free .NET Framework and the free Visual Web Developer