Cross-Page post backs using ASP.NET 3.5

By Mohammad Mahdi Ramezanpour at August 30, 2008 02:06
Filed Under: ASP.NET

Some developers are still want to use cross page post backs that we used it in the classic version of ASP. For example: you may want to create a page that contains a form and add them to your database in another page like ASP classic.

In this post I want to show how to do such a thing in ASP.NET and how you can make it easier in ASP.NET 3.5.

Imagine that I have a Default.aspx file that shows a form and users can enter their name and company name; and also I have another page named DataTransfer.aspx that shows user's information in some labels.

Here is my Default.aspx page:

<%@ Page Language="C#" 
AutoEventWireup="true" 
CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="text-align: center;">
        Name:<br />
        <asp:TextBox runat="server" ID="nameTextBox"></asp:TextBox><br />
        Company name:<br />
        <asp:TextBox runat="server" ID="companyTextBox"></asp:TextBox><br />
        <asp:Button runat="server" ID="submitButton"
         Text="Save" 
         PostBackUrl="DataTransfer.aspx" />
    </div>
    </form>
</body>
</html>

As you can see, I have two textboxes named "nameTextBox", "companyTextBox" and also a button named "submitButton" that are normal and there is nothing unusual in it. The interesting part in the PostBackUrl of my button that links this page to our second page.

There is nothing to do more in the first page, so lets take a look at our second page "DataTransfer.aspx":

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataTransfer.aspx.cs" Inherits="DataTransfer" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <h3>User's information</h3>
    <div>
        Name : 
        <asp:Label runat="server" ID="nameLabel"></asp:Label><br />
        Company : 
        <asp:Label runat="server" ID="companyLabel"></asp:Label>
    </div>
    </form>
</body>
</html>

Very simple, just two labels in order to show the user's information. I have to write some code in the code-behind section in order to bind information to labels. Here is my code-behind of my DataTransfer.aspx:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class DataTransfer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Create an instance of our previous page's controls that we want to get.
        TextBox name = null;
        TextBox company = null;
        
        // Fill variables with the values in the previous page using FindControl method of Previous Page property.
        name = (TextBox)this.PreviousPage.FindControl("nameTextBox");
        company = (TextBox)this.PreviousPage.FindControl("companyTextBox");
 
        // Bind lables using values in textboxes.
        nameLabel.Text = name.Text;
        companyLabel.Text = company.Text;
    }
}

In the code above I used PreviousePage property available in every ASP.NET page and FindControl method of that property. With FindControl you can get the object you want by it's ID from your previous page. But because the information returns from FindControl are objects and no specific types, you must cast it as I did.

If you launch your application now, you will see you can gather the information from first page and show them in the second page.

Now let's change it a little bit by add a new directive to our second page. This directive name PreviousPageType and it's new with ASP.NET 3.5 and let you specify your previous page path. So you can have all public or internal (Friend in VB) classes, methods, properties or any other objects in your second page. This is my second page after a little changes:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataTransfer.aspx.cs" Inherits="DataTransfer" %>
<%@ PreviousPageType VirtualPath="~/Default.aspx" %>
...

You know, because I'm always trying to be organized :D, I want to create two properties in my first page that holds values in textboxes:

    public string Name
    {
        get { return nameTextBox.Text; }
    }
 
    public string CompanyName
    {
        get { return companyTextBox.Text; }
    }

Now you can get values of textboxes in Default.aspx page much easier. It means that Visual Studio can identify our first page objects and you can use code hints in order to access your objects in the second page as shown in the picture below:

ASPNET35 Previous Page Inteligency

And our second page's code-behind will change to the following:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class DataTransfer : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Fill variables with the values in the previous page using properties.
        nameLabel.Text = PreviousPage.Name;
        companyLabel.Text = PreviousPage.CompanyName;
    }
}

Now you know that with the PreviousPageType new directive in ASP.NET 3.5, it's much easier to access you object in a page from another page.

Internet Explorer 8 beta 2 released

By Mohammad Mahdi Ramezanpour at August 29, 2008 00:04
Filed Under: Other

Internet Explorer 8 beta 2

 

Today Microsoft released the latest version of Internet Explorer (8 beta 2) and it's now available for download. But before download, lets take a look at some of new features in this release of Internet Explorer:

InPrivate Browsing:

Keep Internet Explorer 8 from adding any sites you visit to Browsing History with InPrivate Browsing. Now you can shop for that special gift with confidence knowing your family won’t accidentally find out.

Search suggestions:

Search smarter with detailed suggestions from your favorite search providers and browsing history. See visual previews and get suggested content topics while you type in the enhanced Instant Search Box.

Compatibility View:

Internet Explorer 8’s built-in Compatibility View button enables you to display websites that were designed for older browsers. Simply press the Compatibility View button if you see display problems on a website like misaligned text, images, or text boxes. It’s located next to the Refresh button on the Address Bar.

SmartScreen Filter:

New security features help to protect you against deceptive and malicious websites which can compromise your data, privacy, and identity.

Web Slices:

Keep up with changes to the sites you care about most. Add a Web Slice and you won’t have to go back to the same website again and again for updates on news, stock quotes, online auctions, weather, or even sports scores.

Accelerators:

Accelerators let you complete your everyday browsing activities more quickly and even discover new services. Start mapping, translating, emailing, and more in just a few mouse clicks.

 

For more information about features and download it check out Internet Explorer 8 home page : http://www.microsoft.com/ie8

Four hours free ASP.NET 3.5 training

By Mohammad Mahdi Ramezanpour at August 28, 2008 01:00
Filed Under: ASP.NET

ASP_net_logo

This is a special news to some of you who want to start developing ASP.NET. APPDEV, released 4 hours of free ASP.NET training and it's now available for download.

The best part is that these courses are available in both VB.NET and C#. So it doesn't matter which programming language you're using.

Download training courses by click the following link:

http://www.appdev.com/promo.asp?page=SN00040

The most interesting features in SQL Server 2008

By Mohammad Mahdi Ramezanpour at August 25, 2008 23:11
Filed Under: SQL Server

Maybe some of you want to ask me: OK. SQL Server 2008 is the latest version of SQL Server but what's new in it?

Today I want to introduce you to some of top features available in SQL Server 2008. This is an screen shot of a SQL Server 2008 query. You can see some of new features you can use in the latest version of SQL Server:

scrn-SQL08

As you saw, there are some amazing features has been added to the new version. Here is a list of most interesting features that implemented in the latest version of SQL Server:

  • Increase the precision of storing and managing DATE and TIME information.

  • Store semi-structured and sparsely populated sets of data efficiently, using Sparse Columns.

  • New fully integrated Full-Text Indexes enable high-performance, scalable, and manageable Full-Text Indexing.

  • Create large User-Defined Types and User-Defined Aggregates greater than 8 KB.

  • Pass large amounts of data easily to functions or procedures using new Table-Value Parameters.

  • Perform multiple operations efficiently with the new MERGE command.

  • Model hierarchical data, such as org charts, or files and folders, using the new HierarchyID data type.

  • Build powerful location-aware applications, using SQL Server’s new standards-compliant spatial data types and spatial indexing capabilities.

  • Manage files and documents efficiently with full SQL Server security and transaction support, using the powerful new FILESTREAM data type.

  • Easily identify dependencies across objects and databases, using New Dependency Management.

  • Experience faster queries and reporting with Grouping Sets through powerful ANSI standards-compliant extensions to the GROUP BY clause.

  • Experience efficient, high-performance data access, using new Filtered Indexes for subsets of data.

  • LINQ to SQL: How to execute command in a transaction

    By Mohammad Mahdi Ramezanpour at August 23, 2008 22:28
    Filed Under: LINQ, SQL Server

    It may happen to everyone; sometimes you may want to execute your LINQ to SQL commands in one transaction like you do it in SQL Server as following:

     

    BEGIN TRANSACTION
     
    IF ([something happend])
    begin
        -- Your code is here
    end
    ELSE
    begin
        -- Restore to original
        ROLLBACK TRANSACTON
    end
     
    COMMIT TRANSACTION

    In this post I want to show how you can do it using LINQ to SQL:

    Create your LINQ to SQL project and write some code in order to do something ex.: Add a new record to a database. You should pass the following steps in order to manage transactions in LINQ to SQL:

    First, You must add a new reference named System.Transactions to your project:

    SelectingSytem_Transactions_Reference

    Then, you must create a new variable from System.Transactions.TransactionScope like this:

     

    using (TransactionScope ts = new TransactionScope())
    {
         // Your code comes here.
    }

    After that you must add your insert code between using tags:

    using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        Post p = new Post();
                        p.title = title;
                        p.keywords = keywords;
                        p.shortDesc = shortDesc;
                        p.content = content;
                        p.startRate = Convert.ToByte(startRate);
                        p.enableComments = enableComments;
                        p.usersCanRate = usersCanRate;
                        p.createDate = DateTime.Now;
                        p.lastModifyDate = DateTime.Now;
                        c.Posts.InsertOnSubmit(p);
                        c.SubmitChanges();
                        
                        Guid postId = p.postId;
     
                        foreach (var author in authors)
                        {
                            Posts_AddAuthorRelation(postId, author.AuthorID);
                        }
     
                        foreach (var category in categories)
                        {
                            Posts_AddCategoryRelation(postId, category.CategoryID);
                        }
     
                        foreach (var source in sources)
                        {
                            Posts_AddSourceRelation(postId, source.SourceID);
                        }
     
                        foreach (var media in medias)
                        {
                            Posts_AddMediaRelation(postId, media.MediaID);
                        }
                    }
                    catch
                    {
                        Transaction.Current.Rollback();
                    }
                }

    As you can see I put a try...catch statements to my code. In try section I just wrote my insert code. If there is any error with my database or something. It will goes to my catch block.
    Because I insert to more than one table, I should delete all inserted tables if there is any exception(s).

    So you must use System.Transactions.Transaction.Rollback() method in order roll it back like SQL Server's ROLLBACK TRANSACTION command that we talked about it above.

    With System.Transactions, you can manage your LINQ to SQL commands in transactions.

    Currently Reading

    Quote of the day

    Send Persian SMS