Labels

Monday, August 31, 2009

Why do ASP.NET AJAX page methods have to be static?

Hi,

 

For using the Page Methods the methods has to be defined using ‘Static’.

Now whey Static??

 

Understanding what the Page class is, and why we have it

 

Contorting the stateless HTTP protocol to accommodate ASP.NET’s WebForm paradigm was a considerable task for the ASP.NET team to accomplish. On top of that, going from the inline execution model of ASP classic to the event-driven model of ASP.NET also required major changes.

As such, the ubiquitous WebForms Page class was created to solve these various problems. Take this snippet, for example:

 

public partial class _Default : System.Web.UI.Page 
{
  protected void Page_Load(object sender, EventArgs e) 
  { 
    // Hello World.
  }
}
 

One of the Page’s most powerful features: Persistence

 

The Page brings a lot to the table. However, to answer the question of why page methods must be static, we need to focus on persistence.

Consider this example:

<asp:Label runat="server" id="Label1" />
<asp:Button runat="server" id="Button1" OnClick="Button1_Click" />
protected void Button1_Click(object sender, EventArgs e)
{
  Label1.Text += DateTime.Now.ToString();
}
 

Each time the button is clicked, the label will have the current time and date appended to its current contents. Even this elementary example illustrates how the WebForms Page automatically provides persistence for us.

 

Understanding how the Page does this

 

To implement this encompassing layer of persistence, the ViewState was created.

Each time a page is rendered to the browser, the Page serializes the state of its controls and then includes that information in the returned HTML, via a hidden form field named __ViewState. When a postback occurs, this hidden field can then be de-serialized to create an instance of the Page in the same state that it was at the end of the last request.

 

Oversimplifying, you can envision this constructor being used to re-instantiate the Page, at the beginning of every postback:

 
Page _Default = new Page(Request["__ViewState"]);
 

This re-instantiation of the Page from the ViewState is what keeps the entire WebForms machine rolling, postback after postback.

 

What does it mean that a method is static?

 

The key difference to understand is that a static method can be called without setting up a proper instance of the class it belongs to.

In a sense, it is a stateless method.

 

If you’re implementing page methods, you’re probably well aware of their excellent performance. They are especially performant compared to the UpdatePanel’s partial postbacks.

They are efficient largely because they do not require the ViewState to be POSTed and they do not create an instance of the Page, while partial postbacks do both of these things. As we now know, a page method couldn’t create an instance of the page even if desired, since the ViewState isn’t provided in the request.

 

This is exactly why they must be marked as static. They cannot interact with the instance properties and methods of your Page class, because a page method call creates no instance of the Page or any of its controls. Page methods are roughly equivalent to shorthand for standalone web services. In fact, the ScriptManager even calls them exactly as it would a regular web service.

 

Reference: LInk

 

Thanks & Regards,

Arun Manglick || Senior Tech Lead

 

 

Why not AJAX

This article will try to shed some light on what AJAX really is, where you should use it and where you shouldn't

 

Logic Behind AJAX:

 

·          At the heart of the AJAX method of communicating with the server lies the AJAX engine.

·          This is nothing more than some JavaScript code that instantiates and uses the XMLHttpRequest object.

·          This is a JavaScript object that allows sending, receiving and processing HTTP requests to and from the server without refreshing the entire page.

·          In AJAX-powered applications, HTTP requests for data can be made completely in the background, without the user experiencing any interruptions. The XMLHttpRequest object was implemented as an ActiveX object in Internet Explorer, and has later become a native JavaScript object in most modern browsers (FireFox, Safari).

·          Although adding an extra layer to any kind of model should add to the response time, this is an exception.

·          Through the use of this new layer – the AJAX engine – response time shortens and the user interface seems much more connected to the application logic. Moreover, the user no longer has to wait around for the page to load.

 

 

Why use AJAX?

 

·          Building a web application that employs AJAX is more difficult than building it the classic way.

·          The decision whether an application would benefit from using AJAX or not is entirely up to the developer.

·          Here are a few hints to help you take the right decision.

 

 

The Benefits of AJAX -

 

To help you decide whether AJAX is for you or not, here are some of the advantages it has over classic web development techniques:

 

More Responsive

The interface is much more responsive, as only a small part of the page is transferred at a time.

 

Multiple Connection Threads

·          In a classic web application, when the web server sends a web page to the browser, it can use multiple connection threads to speed up delivery.

·          However, this happens for content only – what is between the <body> tags. All script and CSS files linked in the page's <head> section are transferred using only one connection thread, which diminishes performance.

·          With AJAX, you only have to load the basic scripts and CSS files, and request the rest as content, through multiple connections.

 

Waiting time is reduced

Waiting time is reduced – the user can still work while the data is being submitted

Fails graciously

·          If a page section encounters an error, other sections are not affected and the data already entered by the user is not lost. This way, the application fails graciously, without causing head-aches for the users.

 

Traffic is reduced

·          Traffic is reduced considerably – The bandwidth usage is most likely to decrease.

 

 

 

The Disadvantages of AJAX

 

As with most new web development techniques, AJAX has its critics. There are a couple of disadvantages that need to be considered before considering an AJAX-based solution:

 

 

Increase in development time and costs

·          It is usually considered more difficult than building a classic web application, because of the mixture of technologies and the special concern about everything going smoothly. However, because it is dealing with relatively known technologies, AJAX is not rocket science.

 

Available frameworks and components still need to completely mature

·          Although AJAX relies on existing and mature technologies like Javascript, HTML and CSS, the available frameworks and components still need to completely mature. Tools like the Dojo toolkit or the Rico framework are just a milestone on this long road. More frameworks that target a specific area are likely to come your way

 

Security and user privacy

·          Not all concerns regarding security and user privacy have been answered. This fueled a wave of criticism about how safe is the AJAX way of building applications. Earle Castledine points out some of his concerns regarding user privacy in this article from DevX.com.

 

Existing page conflicts – Back button

·          Using AJAX to asynchronously load bits of content into an existing page conflicts with the way we are used to navigate and create bookmarks in modern browsers. Because viewing some part of the page information no longer corresponds to a newly loaded page, the browser history and bookmarks will not be able to restore the exact page state. Also, clicking the Back button in a browser might not have any effect, since the URL was unchanged (even if parts of the page were changed). To overcome these problems you must implement a way to save the current page state so that it can be restored later on, when called from a bookmark or from the browser history.

 

Google cannot index it

·          AJAX is not meant to be used in every application. One of the main reasons for this stays in the fact that Google cannot index it. Consider this basic example that Alexandru Costin, the co-founder of InterAKT Online, pointed out: "Suppose you are building an e-commerce site. A complete AJAX application would be a mistake because search engines won't be able to index it. And without a search engine, a site won't be able to sell products." Keeping this in mind, a much better idea than creating complete AJAX applications would be to scatter AJAX features within the application.

 

Support for JavaScript or the XMLHttpRequest object

·          The biggest concern with AJAX is accessibility. This is because not all browsers (especially older ones) have complete support for JavaScript or the XMLHttpRequest object. Some of the visitors do have browsers with the required features, but they choose or have to turn off JavaScript support. When you design the application you must make sure that a fail-safe solution exists for those users, so it can be accessed by anyone. Further more, the way to access and use the XMLHttpRequest object in Internet Explorer and other browsers is different, which leads to a fork in the code and the need to treat each case separately.

 

Multi Server

·          The last disadvantage lies in the actual XMLHttpRequest object itself. Due to security constraints, you can only use it to access information from the host that served the initial page. If you need to display information from another server, it is not possible within the AJAX paradigm.

 

 

 

 

Regards,

Arun Manglick || Technical Leader || Monetrics - MDE || 620

 

Wednesday, August 26, 2009

Build Automation Tool - BuildIT

Check here – Link

 

Thanks & Regards,

Arun Manglick || Senior Tech Lead

 

 

IntelliSpell - Spell Checker

Hi,

 

This is about introducing an integrated spell checker tool for .Net IDE.

 

Microsoft Visual Studio is the most powerful and popular software development environment. However, it lacks spell-checking capabilities that exist in popular authoring packages.

Realizing developers’ needs, ComponentOne presents ComponentOne IntelliSpell™. The spell-checking add-in enables you to spell-check code, comments, strings, HTML, XML, resources, and general text in both Visual Studio 2008 and Visual Studio 2005. With IntelliSpell, you have the power to deliver products free of spelling errors.  Get started today with IntelliSpell Community Edition, and spell-check your files in Visual Studio at no cost.

 

ComponentOne IntelliSpell comes in two editions:

 

-          The Community Edition is a free version that allows you to check one file at a time. You can use it for as long as you like, and share it with your friends and co-workers.

-          The Professional Edition can check entire projects and solutions, including localize applications.

 

 

Here is the feature set.

 

 Features

IntelliSpell

Xml File Spell Check

Y

HTM File Spell Check

Y

JS Spell check

Y

C#/VB.Net Spell Check

Y

CSS Spell Check

N

Resource File Spell Check

Y

ASPX File Spell Check

Y

Checks String in quotes

Y

Checks function/variable name

No

Checks in comments (single and multiline)

Y

Mixed Case Spell Check

Y

Word with number Spell Check

Y

Ignore Word Option

Y

Compile Time Spell Check

No

Design Time Spell Check

Y

Need to run separately

N

Can run separately (for integration with Automated Build)

N

Custom Configuration Available

Y

VS Version

2005, 2008

Need MS Word Installed

N

Dictionary Customization

N (In Free Tool)

 

 

Installation –

 

-          It will be installed at  - C:\Program Files\ComponentOne\IntelliSpell (Unless other path is chosen)

 

 

Getting Started –

 

Once you've installed C1IntelliSpell, use any one of the following methods to start spell checking your projects in Visual Studio:

 

1.      From the Visual Studio menu: Select Tools | ComponentOne IntelliSpell.

2.      From the C1IntelliSpell Visual Studio toolbar: Right-click an empty part of the Visual Studio toolbar area and make sure the ComponentOne IntelliSpell toolbar is checked. Then select a command from the toolbar to begin spell checking.

3.      From the Visual Studio Task List: Select View | Task List and make sure the ComponentOne IntelliSpell item is selected on the list.

 

The C1IntelliSpell toolbar offers the following commands:

 

 

 

 

 

 

Note – As we have the community edition only the ‘Check Active Document’ feature will be enabled.

 

 

Spell-Checking Options

 

ComponentOne IntelliSpell is a flexible tool. You can configure it using the Options command (available on the C1IntelliSpell menu, toolbars, and Task List). The command shows the ComponentOne IntelliSpell Options dialog box, which looks like this:

 

 

Help Manual –

 

There is lot more you can learn about the tool using the help.

 

Once installed the help can be found at - C:\Program Files\ComponentOne\IntelliSpell\Help.

Otherwise the online help can be found at - http://helpcentral.componentone.com/nethelp/c1intellispell/

 

For any further help, feel free to contact.

 

Thanks & Regards,

Arun Manglick || Senior Tech Lead

 

Monday, August 24, 2009

PRB: Many Websites starts Many Web Server Instances

Debugging Website in a Solution with Many Websites Starts Many Web Server Instances

When you have multiple websites configured under a single solution file, debugging one web site starts other instances as well.

i.e. Debugging a website in a solution containing other several websites starts many instances of the development web server start up for each of them.

 

Here is a workaround can avoid multi-instance of “ASP.NET Development Server” to start. The Development Server by default starts for every file system project with different port. So we can set each project to use the same port number. After does that, only one instance of Development Sever will start for the startup project.

 

To specify a port for the ASP.NET Development Server

  1. In Solution Explorer, click the name of the application.
  2. In the Properties pane, click the down-arrow beside Use dynamic ports and select False from the dropdown list.

This will enable editing of the Port number property.

  1. In the Properties pane, click the text box beside Port number and type in a port number.
  2. Click outside of the Properties pane. This saves the property settings.

If you change the startup project, please be sure also stop the Development Server in status notification area. Because it is being used for current project.

 

Hope this helps.

 

Reference: Link

 

Thanks & Regards,

Arun Manglick || Senior Tech Lead

 

 

Friday, August 21, 2009

PRB: Linq to SQL Database Connection String Issue

Hi,

While creating a DBML, if you’re Data Layer is a class library project then connection strings are stored in Settings File & App.Config File.

However if your need is to store the connection strings in Web.config, you need to do slight tweaking with the code.

  • Set the “Connection” Property for the “.dbml” designer file to “Null”
  • Create a partial class for your DataContext class and have the constructor with base constructor reading the connection string from web.config file

public partial class DataClasses1DataContext

{

public DataClasses1DataContext() : base (ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString)

{

OnCreated();

}

}

Make sure you have Connection string in your web.config.

Thats it. Simple !!! Happy Coding…

Update: The next time when you try to add a Stored Procedure or Table to the DataContext Designer, you still have to go to the properties of the DataContext and tell it not to read from “appsettings” and set the connection string to null/empty string. I wish there is a permanent way to say, do not populate these values.

Reference: Link

Thanks & Regards,

Arun Manglick Senior Tech Lead

Thursday, August 20, 2009

C# 4.0 : Co-variance and Contra-variance

Hi,

This is about new feature in C# 4.0 (VS 2010)

CoVariance

If you have a class hierarchy, Parent and Child (as name mentioned). Now ideally you can assign Child to any Parent object as Parent is larger type and hold properties of Child.
Now if you try to write come code as mentioned below,

namespace CoVarinace
{
    class Vegetable { }
    class Potato : Vegetable { }

    class Program
    {
        delegate T MyFunc<T>();

         static void Main(string[] args)
         {
             //Covariance
             MyFunc<Potato> potato1 = () => new Potato();

             MyFunc<Vegetable> veg = potato1;
         }
    }
}

This code will fail with the below error message
“Cannot implicitly convert type ' CoVarinace.Program.MyFunc<CoVarinace.Potato>' to 'CoVarinace.Program.MyFunc<CoVarinace.Vegetable>'      C:\..\CoVarinace\Program.cs”   
Now in Visual Studio 2010 with a minor change this code will work.

delegate T MyFunc<out T>();

Now with the modified code it will look like,
CoVariance
namespace CoVarinace
{
    class Vegetable { }
    class Potato : Vegetable { }

    class Program
    {
        delegate T MyFunc<out T>();

         static void Main(string[] args)
         {
             //Covariance
             MyFunc<Potato> potato1 = () => new Potato();

             MyFunc<Vegetable> veg = potato1;
         }
    }
}


With no error, the support is only from Visual Studio 2010.

ContraVariance

This works with generic delegate which returns nothing but takes a parameter.

If you write the code,
namespace ContraVarinace
{
    class Vegetable { }
    class Potato : Vegetable { }

    class Program
    {
        delegate void MyAction<T>(T a);

        static void Main(string[] args)
        {
            MyAction<Vegetable> action1 = (veg) => {Console.WriteLine(veg); };

            MyAction<Potato> potato1 = action1;
        }
    }
}

This will throw you an error,
Cannot implicitly convert type 'ContraVarinace.Program.MyAction<ContraVarinace.Vegetable>' to ' ContraVarinace.Program.MyAction<ContraVarinace.Potato>'         C:\..\ContraVarinace\Program.cs
With a little modification the below code will work without any issue, you just need to put the keyword in.

delegate void MyAction<in T>(T a);

ContraVariance
namespace ContraVarinace
{
    class Vegetable { }
    class Potato : Vegetable { }

    class Program
    {       
        delegate void MyAction<in T>(T a);

        static void Main(string[] args)
        {
            MyAction<Vegetable> action1 = (veg) => { Console.WriteLine(veg); };

            MyAction<Potato> potato1 = action1;
        }
    }
}



Thanks & Regards,
Arun Manglick || Senior Tech Lead