:::: MENU ::::

Monday, March 24, 2008

With the forums flooded with questions of opening a popup window, passing values to the popup window and then return values back to the parent page using both Internet Explorer and Firefox, I decided to take a plunge into the subject and experiment with an easy implementation. This article explains how to transfer values between the Parent page and a Pop-up window. The code has been tested against IE7 and Firefox.

 

Internet Explorer(IE) contains the showModalDialog() method which proves very effective while creating a modal dialog box and displaying a html document in it. One caveat being, showModalDialog() is not a W3C implementation. So it is not supported in Firefox (as of version 2.0.0.11). Firefox supports the window.open() method. However there is no built in functionality in Firefox that keeps the popup modal. At the most, you can use ‘modal=yes’ to make the popup appear in front. However unlike the showModalDialog() in IE, you cannot restrict the user to access the parent page when the popup is opened in Firefox. In short, it is not truly modal. There are different ways to get around this problem, however in this article, we will only focus on exchanging values between the parent and popup page.

 

In this article, we will see how to take a simple approach and create a popup window using both IE and Firefox. In the first part, we will pass in the first name from the parent page to the popup window. In the second part, the popup window will reverse the name and return the reversed string to the parent window. All set!! Let us get started.

 

Part 1 - Passing value to Popup window

Step 1: Open Visual Studio. Create a new website (File > New > Website). Set the location, filename and language of the project.

 

Step 2: In your Default.aspx, add a label (lblFName), textbox (txtFName) and a button (btnPopup). Set the ‘Text’ property of the label to ‘FirstName’. Similarly set the ‘Text’ property of the button control to ‘Show Popup’.

 

Step 3: Now add the popup form. Right click your project > Add New Item > Web Form > Rename form as ‘PopupWin.aspx’ and click on Add.

 

Step 4: In the PopupWin.aspx, add a textbox (txtReverse) and a button (btnReverse).

Well now we have two pages, Default.aspx which is the parent page and PopupWin.aspx which will be the popup page. Let us now pass a value from Default.aspx to the popup window.

 

Step 5: We will invoke the popup window on the button (btnPopup) click of Default.aspx. To do so, we will use Button.Attribute.Add and call a javascript function that will open the popup window. The javascript function will be contained in a seperate pop.js file which we will create shortly. Add this code in the code behind file of your Default.aspx.

C#

protected void Page_Load(object sender, EventArgs e)

    {

        btnPopup.Attributes.Add("onClick", "javascript:InvokePop('" + txtFName.ClientID + "');");

    } 

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        btnPopup.Attributes.Add("onClick", "javascript:InvokePop('" & txtFName.ClientID & "');")

    End Sub

Over here we are passing the ClientID of the textbox. ClientID is the identifier of the server control, generated by ASP.NET. You must be wondering why I am not passing the value of the textbox directly. Well passing the control has an advantage where there is more than one control that is passed to the popup page. While returning back the values from the popup to the parent page; it helps you to decide and determine which control receives which value. Even though we will be using only one textbox for simplicity, I thought of creating a sample which can be extended later by you to suit your needs. If the use of ClientID is not clear to you, wait till we get to part 2 of this article, and I will again touch upon the subject.

 

Step 6: Let us now create the javascript functionality which will open the Popup. Right click your project > Add New Item > Jscript file > Rename the file to pop.js. Add the following function to the pop.js file

function InvokePop(fname)

{

        val = document.getElementById(fname).value;

        // to handle in IE 7.0          

        if (window.showModalDialog)

        {      

            retVal = window.showModalDialog("PopupWin.aspx?Control1=" + fname + "&ControlVal=" + val ,'Show Popup Window',"dialogHeight:90px,dialogWidth:250px,resizable:yes,center:yes,");

            document.getElementById(fname).value = retVal;

        }

        // to handle in Firefox

        else

        {     

            retVal = window.open("PopupWin.aspx?Control1="+fname + "&ControlVal=" + val,'Show Popup Window','height=90,width=250,resizable=yes,modal=yes');

            retVal.focus();           

        }         

}

This function accepts the textbox control, retrieve’s the value of the textbox that needs to be reversed and passes the textbox control and its value to PopupWin.aspx through query string. This is the function which will be called on the btnPopup click.

 

Step 7: To wire up the .js with your asp.net pages, add a link to the javascript file in both the pages as shown below:

Default.aspx

<head runat="server">

    <title>Parent Page</title>

    <script type="text/javascript" src="pop.js"></script>

</head>

PopupWin.aspx

<head runat="server">

    <title>Popup Page</title>

    <script type="text/javascript" src="pop.js"></script>

</head>

 

Step 8: In the code behind file of PopupWin.aspx, add the following code at the Page_Load() to retrieve the value from the querystring and display the value in the TextBox ‘txtReverse’, placed in the popup window.

C#

protected void Page_Load(object sender, EventArgs e)

    {

        txtReverse.Text = Request.QueryString["ControlVal"].ToString();

    }

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        txtReverse.Text = Request.QueryString("ControlVal").ToString()

    End Sub

If you are eager to test the value going from Parent page to the popup window, you can do so now. Make Default.aspx as ‘Set as Start page’ and run the sample. Enter your name in txtFName TextBox and click on Show Popup button. A popup window opens with the value entered in the Parent page.

 

Part 2 - Passing value from Popup window to the Parent page

In this second part, we will reverse the string and pass the reversed string back to the parent page. To do so, follow these steps:

 

Step 1: Add additional functions to the pop.js file which will reverse the string and return the string back to the parent page.

// pop.js

function ReverseString()

{

         var originalString = document.getElementById('txtReverse').value;

         var reversedString = Reverse(originalString);

         RetrieveControl();

         // to handle in IE 7.0

         if (window.showModalDialog)

         {             

              window.returnValue = reversedString;

              window.close();

         }

         // to handle in Firefox

         else

         {

              if ((window.opener != null) && (!window.opener.closed))

              {              

                // Access the control.       

                window.opener.document.getElementById(ctr[1]).value = reversedString;

              }

              window.close();

         }

}

 

function Reverse(str)

{

   var revStr = "";

   for (i=str.length - 1 ; i > - 1 ; i--)

   {

      revStr += str.substr(i,1);

   }

   return revStr;

}

 

function RetrieveControl()

{

        //Retrieve the query string

        queryStr = window.location.search.substring(1);

        // Seperate the control and its value

        ctrlArray = queryStr.split("&");

        ctrl1 = ctrlArray[0];

        //Retrieve the control passed via querystring

        ctr = ctrl1.split("=");

}

As you saw in part 1, the value was passed from the parent window to the popup window and was kept in the txtReverse TextBox. The function ReverseString() retrieves the value from this textbox and passes the string to the Reverse() function which reverses the string. The reversed string is then kept in the ‘reversedString’ variable. The ‘RetrieveControl’ splits the query string and identifies the control in the parent page to which the reversed string value is to be sent.

Note: If you observe, in the IE implementation, I am not really making use of the RetrieveControl(), however in Firefox I am. If you remember, in the beginning of part1 , I had mentioned the use of ClientID, using which both controls and their values can be passed to determine which control recieves which value. This is especially needed when there are multiple controls. Well the RetrieveControl seperates the different controls and you can use the variables in this method to return values to the respective contro.l

The value is then returned to the parent window and the popup window is closed.

 

Step 2: Now in order to use these newly added javacript functions, just call the ReverseString() function on the btnReverse click. To do so, add the onclick attribute to the btnReverse.

<input class="button" type="button" id="btnReverse" value="Reverse value back" onclick="ReverseString();"/>

That’s it. Now test the code. Pass your name from the Parent window to the Popup window and then reverse the string and pass it back to the Parent window.

I would like to mention that there are multiple ways of doing the task demoed in this article. I have seen some cool examples by experts. One of them I would like to mention is that of NC01 where he makes use of properties and ViewState, to pass values to the Popup window. I would encourage you to use this article as a base and try out your own implementations that would work on multiple browsers.

 

Thursday, March 20, 2008

PowerCommands for Visual Studio 2008 is now available for free download, along with source code and a readme document. PowerCommands, is a set of useful extensions for the Visual Studio 2008 adding additional functionality to various areas of the IDE.

The source code, which requires the VS SDK for VS 2008 installed, can be used to modify the exisitng PowerCommands functionality or to use as a reference sample for creating additional custom menu extensions.

PowerCommands is the type of extension for Visual Studio that contains additional command menu functions for the VS IDE that most VS developers would use regularly. Some of these cool menu commands are being considered for new IDE features in the next version of Visual Studio. PowerCommands makes a great complementary PowerToy utility to both StickyNotes and the Source Code Outliner PowerToy.

 

Below is a list of the included in PowerCommands for Visual Studio 2008 version 1.0. Refer to the Readme document which includes many additional screenshots.

Collapse Projects
This command collapses a hierarchy in the solution explorer starting from the root selected node. It can be executed from three different places: solution, solution folders and project nodes respectively.

Copy Class
This command copies a selected class entire content to the clipboard. It can be executed from a single project item or a project item with dependent sub items.

Paste Class
This command pastes a class entire content from the clipboard. It can be executed from a project or folder node.

Copy References
This command copies a reference or set of references to the clipboard. It can be executed from the references node, a single reference node or set of reference nodes.

Paste References
This command pastes a reference or set of references from the clipboard. It can be executed from different places depending on the type of project. For CSharp projects it can be executed from the references node. For Visual Basic and Website projects it can be executed from the project node.

Copy As Project Reference
This command copies a project as a project reference to the clipboard. It can be executed from a project node.

Edit Project File
This command opens the MSBuild project file for a selected project inside Visual Studio. It can be executed from a project node.

Open Containing Folder
This command opens a Windows Explorer window pointing to the physical path of a selected item. It can be executed from a project item node

Open Command Prompt
This command opens a Visual Studio command prompt pointing to the physical path of a selected item. It can be executed from four different places: solution, project, folder and project item nodes respectively.

Unload Projects
This command unloads all projects in a solution. It can be executed from the solution node.

Reload Projects
This command reloads all unloaded projects in a solution. It can be executed from the solution node.

Remove and Sort Usings
This command removes and sort using statements for all classes given a project. It can be executed from a solution node or a single project node.
Note: The Remove and Sort Usings feature is only available for C# projects since the C# editor implements this feature as a command in the C# editor (which this command calls for each .cs file in the project). The Visual Basic IDE implements this functionality for Imports in an interactive way: Project properties, go to the References tab, then click the Unused References... button, then select which references you want removed via a listbox.

Extract Constant
This command creates a constant definition statement for a selected text. It can be executed from the code window over a selected text.

Clear Recent File List
This command clears the Visual Studio recent file list.

Clear Recent Project List
This command clears the Visual Studio recent project list.

Transform Templates
This command executes the associated custom tool with text templates items. It can be executed from a DSL project node or a folder node.

Close All
This command closes all documents. It can be executed from a document tab.

When you need to exclude a file in a project from source control, you can select that file in the Solution Explorer window, then go to File > Source Control > Exclude [filename] from Source Control. A red icon should appear to the left of that file in the Solution Explorer window to tell you that it's excluded from source control. This option doesn't show up in the context menu of the file, just as other options that only show up in File > Source Control.

Monday, March 17, 2008

With few exceptions, developers like using the latest tools and technologies, but are often constrained by the development or production environment. There are many reasons organizations are unwilling or slow to adopt new technology, and these can range from financial to cultural or political. A good developer can survey the landscape, put the success of the project and customer above his own interests, and know when to campaign for change and when to accept constraints. This article will help developers make informed decisions by providing a quick reference of the features that were introduced in each version of the C# language and the .Net Framework.

There are two key questions a .Net application developer must answer at the beginning of any project because of the potential impacts to the development approach and application architecture.

  • What version of Visual Studio (or other tools) is available to me?
  • What version of the .Net Framework is (or can be) installed on the target machine(s)?

We typically think of .Net versioning in terms of the Framework, "this will be a 2.0 development project," but it is important to understand there are actually three independently versioned components to consider:

  • Language (such as C#)
  • Common Language Runtime (CLR)
  • .Net Framework

The following matrix shows the relationship between component versions:

C# Version

CLR Version

Framework Version

1.0

1.0

1.0

1.1

1.1

1.1

2.0

2.0

2.0

3.0

 

 

3.0

2.0 (updated)

3.5

Before the introduction of .Net 3.0, these components were released as a logical unit, but things got out of sync when the 3.0 Framework did not include a new version of C# or the CLR. For this reason, some think.Net 3.0 should have been released as ".Net 2.5." So what is the 3.0 Framework then? It's a set of libraries (formerly WinFX) that depend on and extend the .Net 2.0 Framework and provide revolutionary technologies such as Windows Communication Foundation (WCF), Windows Workflow Foundation (WF) and Windows Presentation Foundation (WPF).

Developers can exploit the.Net version synchronicity issue by utilizing 3.0 and 3.5 Framework features on a machine that only has the .Net 2.0 Framework installed. Although I am not advocating this technique (especially to circumvent configuration or security controls), it can be accomplished by referencing libraries such as System.Core and using the copy local feature of Visual Studio to deploy selective Framework assemblies with your application without updating the Framework on the target machine. An additional point that should be evidenced from this technique is that language enhancements such as LINQ are actually "syntactic sugar" that can be written using only C# 2.0 code.

The following matrix identifies in which C# version a given significant feature was introduced:

 

C# Version

Feature

1.0

"Cool"

1.1

2.0

"C# 2005"

3.0

"C# 2008"

Generics

 

 

X

 

Aliases

 

 

X

 

Static classes

 

 

X

 

Asymmetric Property Accessors

 

 

X

 

Anonymous Methods

 

 

X

 

Iterators

 

 

X

 

Partial Types

 

 

X

 

Nullable Types

 

 

X

 

Delegate Inference

 

 

X

 

Covariance and Contravariance

 

 

X

 

Captured Variables

 

 

X

 

Friend Assemblies

 

 

X

 

#pragma warning

 

 

X

 

Lambda Expressions

 

 

 

X

Extension Methods

 

 

 

X

Implicitly Typed Local Variables

 

 

 

X

Implicitly Typed Arrays

 

 

 

X

LINQ Query Expressions

 

 

 

X

Anonymous Types

 

 

 

X

Object and Collection Initializers

 

 

 

X

Auto-Implemented Properties

 

 

 

X

Partial Methods

 

 

 

X

Expression Trees

 

 

 

X

The following matrix indentifies in which Framework version a given significant feature was introduced:

 

Framework Version

Feature

1.0

1.1

2.0

3.0

3.5

Side-by-Side Execution

 

X

 

 

 

Asp.Net Mobile Controls

 

X

 

 

 

IPv6 Support

 

X

 

 

 

64-Bit Platform Support

 

 

X

 

 

C# Edit and Continue Debugging

 

 

X

 

 

Click-Once Deployment

 

 

X

 

 

Strongly-Typed Application Settings

 

 

X

 

 

Windows Workflow Foundation

 

 

 

X

 

Windows Presentation Foundation

 

 

 

X

 

Windows Communication Foundation

 

 

 

X

 

Windows Cardspace

 

 

 

X

 

Microsoft AJAX Library

 

 

 

 

X

Add-In and Extensibility

 

 

 

 

X

Peer-To-Peer Networking

 

 

 

 

X

LINQ

 

 

 

 

X

HashSet Collection

 

 

 

 

X

Windows Forms Support for Asp.Net Membership

 

 

 

 

X

Suite B Cryptographic Support

 

 

 

 

X

Durable Services

 

 

 

 

X

It's not always possible to use the latest tools and technologies. In these situations, it's important for both the developer and the customer to understand what features are affected by these constraints. I hope this article will help with making an informed decision.

References: