CrossPagePostBack Insights

By default any ASP.NET page will post back to itself. But in ASP.NET 2.0 you can configure the page to post back to a different page. This behavior is known as CrosspagePostBack. There are 2 steps involved in configuring this behavior.

1. Identify the controls that can cause PostBack. Example: Button Controls (in particular, those that implement the IButtonControl)

2. Set the PostBackURL property of the controls to the target page.

The following code block shows how you can configure this for a button control.

image

 

When you configure this the ASP.NET runtime binds a new Javascript function WebForm_DoPostBackWithOptions instead of the normal WebForm_doPostBack for the button control. Below is the HTML rendered for the above button control.

image

How can we access any controls on the SourcePage (Default.aspx) from the TargetPage (in this case Default2.aspx)?

We can use the PreviousPage property on the TargetPage(Default2.aspx) to get access to the SourcePage (Default.aspx). In the following example I am accessing the text box control I have on the SourcePage and setting the text value on the TargetPage from the SourcePage textbox value.

Below is the code snippet for the same in Default2.aspx page.

image

There is one more way in which we can access the Sourcepage controls i.e. through the @PreviousPageType directive. If you know the target page in advance this is the best method. But for this to work you need to expose the controls as public properties in the SourcePage(Default.aspx)

So I rewrite my code by exposing the textbox control as follows.

image

 

Then in the target page I did the following changes.

In the HTML section I added the @PreviousPageType directive as follows.

image

Then in the .CS file I can directly access the SourcePage Control as follows.

image

Now comes the interesting part. How can you identify whether a Page has been rendered as a part of normal request or is it due to a CrossPagePostback?

We have a property called IsCrossPagePostback. This tells whether the current page has called any other page. So to identify whether the current page has been called by the CrossPagePostback we have to use a combination of PreviousPage property (I discussed above) and this property.

So to identify whether Default2.aspx has been called due to CrossPagePostback I use the combination as follows.

image

 

So I you reached the TargetPage (Default2.aspx) by means of CrossPagePostBack you will see the text box value the same as the SourcePage. If you browsed the TargetPage independently you will see its value as “This is a normal request”.

I hope this article will help you

Advertisements
Posted in Interesting Stuff | Leave a comment

Some Interesting facts about MasterPages

We all know that MasterPages are generally used for uniform look and feel in Web Applications. In this blog post I want to show some interesting facts about MasterPages in a Q&A format. So lets get started.

  • Can a MasterPage and a ContentPage be developed in 2 different languages? i.e. Suppose can I have a master page developed in VB.NET and a content page in C#.NET?

    Ans: Yes this is perfectly possible. Because the @Master directive doesn’t override the attributes set at the @Page directive level.

  • How is the relation established between a Master Page and a content page at runtime?

    Ans : The link is established through the ContentPlaceHolderID. Say for example I have a MasterPage called Default.Master , there is a section for ContentPlaceHolders with ID=”PageContent”. Now say for example I create a .aspx page and set the MasterPage as Default.Master, the ContentPlaceholderID in the Content Page will be “PageContent”. The following diagram details the same.

     

    MasterPage Source

    <%@
    Master
    Language=”C#” AutoEventWireup=”true” CodeFile=”MasterPage.master.cs” Inherits=”MasterPage”
    %>

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

    http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;

    <html><head
    id=”Head1″ runat=”server”>


    <title>Hello, master pages</title>

    </head>

    <body>

    <form
    id=”form1″ runat=”server”>


    <asp:contentplaceholder
    id=”PageBody” runat=”server”>

    <!– derived pages will define content for this placeholder –>


    </asp:contentplaceholder>


    </form>

    </body></html>

     

    Derived Page(whose master has been set above) Source:

    <%@
    Page
    Title=”” Language=”C#” MasterPageFile=”~/MasterPage.master” AutoEventWireup=”true” CodeFile=”Default2.aspx.cs” Inherits=”Default2″
    %>

    <asp:Content
    ID=”Content1″ ContentPlaceHolderID=”PageBody” Runat=”Server”>

    </asp:Content>

 

Here the link is established through the ContentPlaceHolderID =”PageBody”.

 

  • I want all the pages in my application derive from a single master page. How can we achieve this without specifying the MasterPage for each of these pages.

    You can set this in the configuration file as below.

<configuration>

<system.web>

<pages
master=MasterPage.master />

</system.web>

</configuration>

  • How to access a control in a MasterPage from a derived page.

    This can be achieved through a combination of the Master Property and the @MasterType directive. Say for example I have a label in my master and I want to set the title of that label from my derived page. So I will add the @MasterType directive in my content page as follows

<%@
MasterType
VirtualPath=”~/Nested.master”
%>

 

Now you can access the control from the derived page as follows

    Master.TitleBoxText = “This is the Master Page value”;

Posted in Interesting Stuff | Leave a comment

RESTORE VERIFY ONLY

In one of our project modules I am currently working on there is a requirement to backup and restore the databases as and when required. They are doing it programmatically from the application side. Everything went well with the backup. But when they are restoring we need to validate whether the .BAK file that they are passing is a valid one or not. How to validate this? In SQL Server we have an option while restoring the database RESTORE VERIFY ONLY. It will not restore the backup but it will check whether the backup is complete and readable. I used the following script to do the same.

declare @verifystatement nvarchar(250)

declare @backupdevice nvarchar(250)

declare @err int

set @backupdevice =‘C:\Temp\TestDB.bak’ –Select the .bak file path here

set @verifystatement =‘RESTORE VERIFYONLY FROM DISK = ”’+ @backupdevice + ””

exec sp_executesql @verifystatement

SELECT @err = @@error

if @err <> 0

 begin

   PRINT ‘Database backup is corrupt’

 end

else

begin

  PRINT ‘Database backup is valid’

End

From the application side they can put this in a function and call this to identify whether the database backup file is corrupt or not. Based on the result from this function they can take whether to backup or throw an exception.

For more details please refer to http://msdn.microsoft.com/en-us/library/aa238412(SQL.80).aspx

Posted in Interesting Stuff | Leave a comment

Some ASP.NET Interview Questions

Here I find a good link that contains a list of good ASP.NET interview questions. These are ideal for people whi want brush up their topics in the free time and who are planning to switch jobs.

Posted in Interesting Stuff | 1 Comment

SQL Server 2008 MERGE will improve performance

One of the new features of SQL Server 2008 is the MERGE statement. Basically MERGE will insert data  to a target table from a source if the data is not there other wise it will update/delete from the target table. Using the MERGE statement will actually improves the performance a lot.

1. To further illustrate I have created a table called Mobiles as follows.

 

   CREATE TABLE Mobiles (
   ProductID   INT PRIMARY KEY,

   ManufacturerName     NVARCHAR(200), 

    Price             INT

)

 

2. I inserted the following sample data into the table 

 

INSERT
INTO Mobiles VALUES (1,‘Nokia’,10000),

                    (2,‘Samsung’,2000),

                    (3,‘Motorola’,3000)    

3. Next I created a table type which will be used as a table valued input parameter for the stored procedures that I create.

 

CREATE TYPE MobileType AS  TABLE

(

    MobileID         INT PRIMARY KEY,

    MobileName     NVARCHAR(200),

    MobilePrice     INT

)

 GO

4. Next I created a stored procedure which will insert/update the details of the Mobiles. This procedure accepts the MobileType table valued parameter that I created in the previous step as input.

CREATE
PROCEDURE UpdateMobileDetails

@Mobiles MobileType READONLY

AS

 UPDATE M
SET
M.ManufacturerName=LM.MobileName,
M.Price=LM.MobilePrice
FROM Mobiles M
INNER
JOIN @Mobiles LM
ON M.ProductID=LM.MobileID
 

INSERT
INTO Mobiles
(
    ProductID,
    ManufacturerName,
    Price
)

SELECT

   LM.MobileID,

    LM.MobileName,
    LM.MobilePrice
FROM Mobiles M
LEFT OUTER JOIN @Mobiles LM
    ON M.ProductID=LM.MobileID
WHERE M.ProductID IS NULL    

This procedure will update the records if they are already existing in the table otherwise it will insert them

5. You can achieve the same functionality using the MERGE statement of the SQL Server 2008.

CREATE
PROCEDURE UpdateMobileDetails_Merge

@Mobiles MobileType READONLY

AS

 MERGE Mobiles M
USING @Mobiles LM ON M.ProductID = LM.MobileId
WHEN MATCHED THEN
UPDATE
SET
M.ManufacturerName=LM.MobileName,
M.Price=LM.MobilePrice    
 WHEN NOT MATCHED THEN
INSERT

(

    ProductID,

    ManufacturerName,

    Price

)

VALUES(

    LM.MobileID,

    LM.MobileName,

    LM.MobilePrice    );    

If the record matches it updates, if it is not matched it will insert into the table.

6. Next I opened two separate query windows to test these two procedures and analyze the performances. I created the following test scripts in these two windows.

–To test the normal procedure

    –Test script

DECLARE @ltblMobiles MobileType

INSERT
INTO @ltblMobiles VALUES (1,‘Nokia N Series’,20000),

                        (4,‘Sony Ericssion’,5000)                                

EXEC UpdateMobileDetails    

@Mobiles=@ltblMobiles    

 

SELECT
*
FROM Mobiles

 

To test the MERGE procedure

DECLARE @ltblMobiles MobileType

INSERT
INTO @ltblMobiles VALUES (6,‘BENQ’,12000),

                        (7,‘iPhone’,5000)

                                

EXEC UpdateMobileDetails_Merge    

@Mobiles=@ltblMobiles    

 

SELECT
*
FROM Mobiles

7. Now go to the Object Explorer. Right Click the database where you have created the table in Step 1.

Right Click database->Reports->Standard Reports ->Object Execution Statistics.

Object Execution statics window will open in a new tab. In that you can see the one which uses MERGE has less Logical I/O.

 


 

 

 

Posted in SQL Server | Leave a comment

Table valued parameters in SQL Server 2008

In this article I will demonstrate how we can ultilise the new feature called table valued parameters in SQL Server 2008. These are great addition to the SQL sever 2008 that allows us to pass multiple rows of data to the stored procedure. In earlier versions we acheived this functionality by  converting the data into XML or calling the stored procedure mulitple times or by many different means. Lets see how this new feature works in SQL server 2008.

 

tvp

Basically what we have done here is as follows:

1.Created a table called Mobiles

2.Created a new type called MobileTable

3. Created a new stored procedure which accepts a parameter of type MobileTable and inserts records into the Mobiles table.

4.Executed the stored procedure

This  new feature will be a great benefit for the SQL server developers and client side developers working on ASP.NET or any other client interface where they can send the whole bunch of tables as parameters to the stored procedures without converting them into XML or any other client side modifications.  I hope this article helps you…

Posted in SQL Server | Leave a comment

When will our policy makers think like this?

I recently came across an article written by Thomas L. Friedman, a Newyork Times Editor and the author of books like “The World is Flat” , “The Lexus and the Olive Tree” and “From Beirut to Jerusalem“.

You can read the article here. This article tells about the authors experiences while travelling to a small country called CostaRice. It fulfils it 95% of its energy requirements from renewable energy sources.It discovered its oil reserves five years ago and still it banned drilling citing pollution to the environment. Can anyone think of a country which discovered its own natural treasure and forbid it because it may cause damage to the environment?  It started the process of investing in renewable energy sources like Hydro-electric power, Geo-Thermal power and wind energy in the 1990s and now it enjoys the benefits of having a long term vision for the sustainable development of the country. Can you imagine the same thing happening in India? Do our policy makers think on those lines? Food for thought…..

Posted in Interesting Stuff | Leave a comment