Cross-Page post backs using ASP.NET 3.5

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/ file that shows a form and users can enter their name and company name; and also I have another page named DataTransfer/ that shows user’s information in some labels.

Here is my Default/ page:

<%@ Page Language="C#" 
AutoEventWireup="true" 
CodeFile="Default/.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/" />
    </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/":

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataTransfer/.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/:

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/.cs" Inherits="DataTransfer" %>
<%@ PreviousPageType VirtualPath="~/Default/" %>
...

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/ 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

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

The most interesting features in SQL Server 2008

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

    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.

    I created a twitter account

    Today I decided to create a twitter account for myself so I implemented a new twitter section in my website so that you can keep in touch with me in twitter too.

    I order to do that, you can use "Follow me on twitter" link on right side of my website:

    followmeontwitter

    With twitter, you can get you friend's current status and inform that what is your friend doing or did.

    .NET Framework 3.5 SP1 changes

    I was checking ASP.NET official website and I saw a new post from Brada about changes in .NET Framework 3.5 SP1. It was nice and I have to thank him for his amazing post.

    Lets take a look at .NET Framework 3.5 SP1 changes represented in the following link: what changed in .NET Framework 3.5 SP1

    I just select some interesting parts:

    # Assemblies    112
    # Namespaces    919 to 935      (+16   +1.7%)
    # Types    39 988 to 40 513      (+525   +1.3%)
    # Methods    387 421 to 386 790      (-631   -0.2%)
    # Fields    241 567 to 246 795      (+5 228   +2.2%)
    # IL instructions    8 598 933 to 8 620 940      (+22 007   +0.3%)

    Here is a 9000×1200 poster where methods where code was changed are located in blue (we degraded the quality to have a 2MB image file instead of 13MB):

    And here is a list of coupling update for assemblies:

    1. A blue cell means: {the X Assembly} is using {the Y assembly}.
    2. Weight of a blue cell means: W members (methods and fields) of the {the X Assembly} are used by {the Y assembly}.
    3. A green cell means: {the Y Assembly} is used by {the X assembly}.
    4. Weight of a green cell means: W methods of the {the Y Assembly} are using {the X assembly}.
    5. A black cell means: {the X Assembly} and {the Y assembly} are using each others.
    6. A red tick on a cell means: the coupling has been changed.
    7. A red tick with a plus on a cell means: the dependency has been created.
    8. A red tick with a minus on a cell means: the dependency has been removed.
    9. An assembly name underlined means that its code has been changed.

    Retire after a full-of-work week

    Rest on weekends

    I don’t know exactly why I’m feeling tired these weeks. I planned to do some personal works but unfortunately I couldn’t. Today I decided to write a new post and talk about what a person should do on his/her weekends, in my opinion.

    The first thing you have to consider about is try not to do the things you’re doing on weekdays; For example I’m a developer and I’m developing about 12-15 hours a day, I have to quit developing on my weekends. You know in my opinion it will help you to have more creativity in the following week.

    So what can I do on my weekends?

    In my opinion it’s better to do the following things on our weekends:

    · Reading books (Read books you think they can help you out in your future).

    · Going out with friends and family.

    · Watch some movies (Action movies recommended).

    · Organize your works (You can also plan for the following week on weekends). If you are a organize person you can fill out you calendar on your weekends.

    · Clean up you room or home (If you have any).

    · Check out some ways of succeeds.

    · …

    It’s very important to not to think about your current or following work on weekends because it will give you stresses and you cannot enjoy your weekend.

    Validation of ViewState MAC failed error has been solved

    VS2008

    You may got this exception before: Validation of ViewState MAC failed

    You will get this exception when you click on a LinkButton or such a thing on a page when your page load has not completed yet.

    In ASP.NET 1.1, 2, 3 and 3.5, you can solve this issue by set some attributes in your web.Config file:

    <pages enableeventvalidation="false" viewstateencryptionmode="Never">
    

    It' will work fine and will not get Validation of ViewState MAC failed exception, but it has some security issues; So what should we do?

    Microsoft solved this problem in .NET Framework 3.5 SP1, so that you'll never need to add something like attributes above.

    Now I think it's better to get started and use SP1 of Microsoft .NET Framework and Visual Studio.

    The power of XLINQ in Visual Basic 2008

    Using LINQ to XML (XLINQ) will help you to access your XML data very easier, like never before. But I don't know why, using XLINQ in Visual Basic is more interesting than C# for me.

    In this post I want to show you how easy can be for VB to generate an XML file than C#.

    Assume that we want to generate an XML file like following:

    <?xml version="1.0" encoding="utf-8" ?>
    
    <configs>
    
        <config name="Mohammad Mahdi Ramezanpour"></config>
    
    </configs>
    

     

    In order to generate such a thing in C#, you will need to write something like this:

    XDocument xdoc = new XDocument();
    
    XElement xroot = new XElement("configs");
    
    XElement xitem = new XElement("config", 
    
                     new XAttribute("Name", "Mohammad Mahdi Ramezanpour"));
    
    xroot.Add(xitem);
    
    xdoc.Add(xroot);
    
    xdoc.Save("C:\\sample.xml");
    

    As you can see, I just created a new XDocument and then add some XElements to it. All things are very routine and then I saved the data into an XML file "C:\sample.xml".

    Now, lets check such the code above in Visual Basic:

    Dim xdoc As New XDocument
    
    Dim xroot As XElement = <configs></configs>
    
    Dim xitem As XElement = <config name="Mohammad Mahdi Ramezanpour"></config>
    
    xroot.Add(xitem)
    
    xdoc.Add(xroot)
    
    xdoc.Save("C:\sample.xml")
    

    in the code above I created an XML file exactly like our previous exmple and the result will be equal.

    Lets take a look at this code snippet; In Visual Basic when you declare a variable as XElement, you can write your XML content exactly like the syntax you're using in an XML file. It means that you can use XML tags (<configs></configs>) straight in your code.

    As I said in my previous posts, I like VB more than C# and I thing VB is much powerful than C# at least in this part :).