Home > Tags > Programming
Page 3

Creating and Manipulating Modal Popups Part II

In the last post, Creating and Manipulating Modal Popups, I discussed what the JavaScript method showModalDialog is used for and how to implement it in your website.

Part two of this topic will focus on using popups to manipulate data and pass information from the child page back to the parent.

User Experience

Manipulating data in the popup window can be tricky, because modal windows do not function like normal ones. In a normal window, when your page does a postback, the postback is rendered in the same window as the original page.  In a modal popup window, the postback opens a brand new window to re-render the popup. However, the original popup window does not close. In addition, this new window does not conform to the window feature settings defined in the parent page’s showModalDialog(), instead it opens based on the browser’s default for new windows.

Not good. Now your user is looking at two versions of the popup, the original (opened by the parent.htm page) and a second normal sized “non-modal” view of it (opened by the postback), which leaves the user with a poor experience of your website.  To circumvent this catastrophe, you’ll want to use the <base> tag in the head of your popup page.  Here is the syntax of the <base> tag:

<head> <base target=”_self” /> </head>

This simple tag will ensure all postbacks of the child page are re-rendered within the same popup window object.

The Pass Back

Next, let’s examine the window.returnValue property, which is used to return a value or object back to the parent window. The showModalDialog method returns a value back to the parent window only when the window.returnValue property has been set in the popup.

Below is the parent.htm page which includes the javascript to open the child window and a textbox in the body which will be used to display data passed in from the child.htm page.  Try it by copying the markup into a new page.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Modal Popup Example</title> <script type="text/javascript" language="javascript"> function openPopUpWithSize(theURL, title, heightInPX, widthInPX) { document.getElementById("MyParentTextbox").value = window.showModalDialog(theURL, title, 'dialogHeight=' + heightInPX + 'px;dialogWidth='+ widthInPX + 'px'); } </script> </head> <body style="text-align: center;"> Modal Popup Example <br/> Parent Page <br/> <br/> <input...
more →

Creating and Manipulating Modal Popups

Occasionally, I have needed a web page to call a child page in order to display information or to be used in a way to maintain information that will then be re-displayed back on the parent page. I didn’t want the user to be able to get back to the parent page until they have performed some function on the child page.

One solution for this scenario is to use Modal Popups. 

In this tutorial, I will show how to use JavaScript’s window.showModalDialog() to create a Popup window and display information. Then return to the parent window.  We will learn about window features and how to use them to control the window’s properties, such as width and height.

In JavaScript, a window object is an open window in a browser.  A modal popup window acts like a standard dialog just like alert() or confirm() where the user cannot get back to the calling or parent window until the dialog has been dismissed.  Don’t confuse a modal window with a modeless window.  A modeless window will stay on top of its parent and allow the parent to regain focus. Modeless windows are often used to display Help information or Guidelines about the website.

Now let’s take a look at the showModalDialog method and its arguments. The syntax to create a modal popup is:

window.showModalDialog(URL of web page, arguments, features);

URL of web page is the url of the document or web page to open as a modal popup. Arguments are any objects or values being passed to the new window. Features is a list of display options for the modal popup window.  These options are separated by a semicolon.

Here’s an example:

window.showModalDialog(‘mysimplemodalpopup.htm’, window, ‘dialogWidth:300px; dialogHeight:400px;center:yes;resizable:no;status:no;scrollbars:no;menubar:no;titlebar:no;toolbar:no;’);

In the example are the most popular features of the modal popup window.  Center will center the new window on the user’s screen. DialogWidth and dialogHeight tell the window what size it should be. The rest of the features shown indicate whether the specified feature is available in the popup window.  Browsers can also interpret the numbers 0 and 1 for the feature values (0 being a ‘no’ and 1 being a ‘yes’.)  However, it is common practice to use ‘yes’ or ‘no’ for code readability.

Now let’s walk through how to use this method:

First, create an html file called ‘parent.htm’ and add this JavaScript function to the head of the document:

<script type="text/javascript" language="javascript"> function openPopUpWithSize(theURL, title, heightInPX, widthInPX) { window.showModalDialog(theURL, title, 'dialogHeight=' + heightInPX + 'px;dialogWidth='+ widthInPX + 'px'); } </script>

Notice how the function accepts the arguments to input the width and height dynamically.

Next, in the body of ‘parent.htm’, add a button element with an onclick event that calls the ‘openPopupWithSize’ function.

<input type="button" id="OpenPopupButton" value="Open Modal Popup" onclick="openPopUpWithSize('child.htm', 'Simple Modal Popup Example', 400, 500);" />

Now, create another ‘html’ called ‘child.htm’ which will serve as the modal popup window.  Decide what the width and height will be.  These will be the values used in the parent.htm document when calling the ‘openPopupWithSize’ function.

Next, in ‘child.htm’, add the below function to the head of the document.

<script type="text/javascript" language="javascript"> function closePopup() { window.close();...
more →
Kim Teeple says: There is a method called showModelessDialog which works like showModalDialog.

Make Legacy VB 6 Components Work With .NET Applications

Most IT professionals do not work in state of the art design shops with all the latest developer suites available to them.

Many of us have to make older applications and components work with newer technologies.  I found myself in this predicament last year when I was required to make a new ASP.NET (3.5) web application work with a ten year old VB6.0 COM Plus Component.

When I suggested to management that I re-write the component, they said:  There’s no time. I know you can make it work. By the way, we need it by Friday. Story of a developer’s life, huh?

I got lucky.  A developer friend of mine had done just this and it turns out to be fairly simple. In order to call a VB 6.0 component or dynamic link library (.dll) from a .NET application, you need to generate a Runtime Callable Wrapper (RCW) for the older .dll using .NET’s Type Library Importer (tlbimp.exe) and reference the wrapper created by the importer in your .NET app.

The primary function of the RCW is to expose the older COM app to .NET’s Common Runtime Language (CLR).  The RCW exposes the older app to the CLR using the .NET Interfaces: INew and INewer.  These interfaces are used by the RCW to police the cache of pointers to the COM object and keep track of when they need cleaned up by the .NET garbage collection process.

Another function of the RCW is to interpret and validate types between the Unmanaged COM object and your Managed .NET application. The RCW must review method arguments and return codes and translate them into the equivalent .NET types.  Microsoft calls this reviewing process marshaling.

Next I’ll walk you through the steps to create the RCW.  In this example, my .NET Client is called MyEnterpriseWebApp and the COM object is called OldLogger.dll.

Step 1: Open a Command Window with Administrative Access.

Step 2: Change Directory (CD) to the Bin folder of the version of Visual Studio you use. This is where you will find the Type Library Importer program.  On my computer it is found here:  “c:\program files\Microsoft Visual Studio 8\SDK\v2.0\Bin\tlbimp.exe”.

Step 3: Enter the command to create the RCW as seen below.  The ‘out’ parameter is the name of your wrapper dll file.

C:\<path to tblimp.exe file>>tlbimp C:\<path to your COM Object>\COMOBJ_NAME.dll /out:C:\<path to your RCWrapper File>\WRAPPER_NAME.dll

NOTE: If you leave out the <path to your RCWrapper File>, the new wrapper file will be placed in the same folder as tlbimp.exe.

Now that the wrapper has been created let’s take a look at how to hook it up to your .NET Client application.  This wrapper can be used in any type of .NET app.

Step 1: Add a reference to your new wrapper assembly in your .NET app by right-clicking on the Project in Solution Explorer and selecting “Add Reference”.  Click the “Browse” tab and navigate to the place you put the wrapper.dll.

Step 2: Import the reference to your class.  Here is an example of importing using C#:

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using LoggerRCW;

Step 3: In your .NET class access your COM Object as its Interface requires.  Here’s an example of how the OldLogger COM works.

namespace MyEnterpriseWebApp { public partial class _Default : System.Web.UI.Page { protected void Page_Load(Object sender, EventArgs e) { //Create Logger Object LoggerRCW.clsApplogClass oLog = new clsApplogClass(); try { //Page Load code here. } catch(Exception ex) { oLog.logMessage("Message to Log"); } finally { //Clean up Logger Object. } } } }

Viola!  Access to your old COM object from your new .NET app!

–Happy Coding

...
more →
says: What specifically did you have trouble with? We can certainly have the author answer any questions.

Common C# Build-Time Errors Part II: Inheritance and Interfaces

In our last lesson, we saw many of the most basic build-time errors in C#.

In this session, we will look at some of the errors related to:

classes subclasses inheritance

Once we address some of the more common errors we will take a look at how you can fix them.

#1 Hidden Method Name Creates Overload

This conflict arises when a base class and its subclass have a function of the same name

public class MyBaseClass { public void Function() { // function code goes here } { public class MySubClass : MyBaseClass { public void Function() { // function code goes here } } public class YourClass { public void YourFunction() { SubClass ysb = new MySubClass; ysb.Function(); } }

The function YourFunction() cannot access the MyBaseClass.Function() from MySubClass because MySubClass.Function() hides it.

If the MySubClass.Function() is supposed to be hidden, the line that creates MySubClass.Function() should contain the keyword “new” to differentiate it from the MyBaseClass.Function():

public class MySubClass : MyBaseClass { new public void Function() { // function code goes here } }

If the MySubClass.Function() is supposed to be inherited polymorphically from MyBaseClass, the line that creates MySubClass.Function() should contain the keyword “override” and the MyBaseClass.Function() line should contain the keyword “virtual” to allow for the override:

public class MyBaseClass { public virtual void Function() { // function code goes here } } public class MySubClass : MyBaseClass { public override void Function() { // function code goes here } }

#2 Cannot Inherit from Sealed Class, Method or Variable

Programmers typically seal classes to protect them from modification from inherited classes, so they do not define their classes that are expected to pass methods and variables through inheritance as sealed.

public class Xray { protected virtual void Function() { Console.WriteLine("Xray.Function"); } protected virtual void Function2() { Console.WriteLine("Xray.Function2"); } } // end of class Xray public class Yankee : Xray { sealed protected override void Function()...
more →

Common C# Build-Time Errors: Part I

Here’s the situation:

You’ve written a program in C#. You’ve checked the flowcharts, examined your coding and developed your user interface.

You’re anticipating that everything will flow as smooth as silk. You’re ready to create a build of the program and, instead of seeing a beautiful, efficient result, you get several (often incomprehensible) error message. How did this happen?

Here are SOME ways that these errors occur:

#1 Undeclared Variables

C# throws an error message on undeclared variables. This most frequently happens in one of three ways:

1) The variable is not assigned a type. The code in a “for-next loop” that reads like this:

for (nextStep = 0; nextStep < 20; nextStep++) { // loop process }

should read like this:

for (int nextStep = 0; nextStep < 20; nextStep++) { // loop process }

2) The variable name is spelled differently. Variables are case sensitive in C#, which can lead to some careless errors:

for (int nextStep = 0; nextStep < 20; nextStep++) { int workerID = nextStep; Console.WriteLine("Worker ID #:" + WorkerId); }

The compiler will view “workerID” and “WorkerId” as two different variables and view “WorkerId” as undeclared.

3) The variable is declared in a different scope. In order to use variables both inside and outside a routine (such as a “for” loop or a “while “ loop), the variable must be declared outside the routine.

for (int nextStep = 0; nextStep < 20; nextStep++) { int workerID = nextStep; } Console.WriteLine("Worker ID #:" + workerID);

This code will not display the final number in the sequence, but will throw an error due to the workerID variable’s declaration sitting inside the for loop.

#2 Variable Conversion Errors

For developers new to C#, especially those coming from more intuitive platforms such as VB.Net or ASP.Net, the lack of flexibility with variable types can be a hurdle.

Here’s an example of a variable conversion that throws a build-time error:

class MyClass { static public float TripleFloat(float t) { float fResult = 3.0 * t; return fResult; } }

Since 3.0 is a “double”-type variable, the operation will return a “double”, not a “float”, and create a build-time error. The operation needs to recast the result as a “float” to avoid the conflict:

class MyClass { static public float TripleFloat(float t) { float fResult = (float)(3.0 * t); return fResult; } }

#3 Protection Level Conflicts

Some programmers may forget that the default protection level for a class is “internal” and the default level for any member in that class is “private”.

class MyFirstClass //default protection = internal { public void NameFunction(){ MySecondClass sc = new MySecondClass(); sc.strFirstName = "Harry"; sc.strLastName = "Potter"; Console.WriteLine("Name: " + sc.strFirstName...
more →
Benjamin Paul says: Surely the Visual Studio IDE should minimise the risk of most of these? These should be clearly obvious to the developer while...

PHP User Survey Part V: Administration Layer

In the last piece on our PHP online user poll, we look at the administrative service and how the site supervisor enters, deletes and manages the poll data.

The first poll administrative page checks if the administrator is logged in. You can choose from Session variables or Cookies to check the site administrator login status.

Once the application has confirmed the identity of the site administrator, the page lists the available polls.

The first step is to use the class methods and variables in the class.polls.php file:

<?php require_once("class.polls.php");

The next steps include instantiating the poll object and retrieving the poll data:

// instantiate polls class $oPolls = new polls; // get polls and poll count $aPolls = $oPolls->getPolls("created_dt desc", $iCursor); $iCnt = $oPolls->getPollsCount();

We create an array to hold and display the data from the polls table in the database:

// check for polls if (count($aPolls)) { // build page data array $i = 0; while ($i < count($aPolls)) { $aData[$i]["Id"] = $aPolls[$i]["Poll Id"]; $aData[$i]["Name"] = $aPolls[$i]["Question"]; $aData[$i]["Status"] = $aPolls[$i]["Status"]; $aData[$i]["Created"] =$aPolls[$i]["Created Date"]; ++$i; } }

For a given poll ID number, we can delete, activate or deactivate a selected poll:

// check for id if ($id) { // assign poll id $oPolls->setPollId($id); // check operation type if (!strcmp($op, "del")) { // try delete poll and redirect $oPolls->deletePoll(); header("Location: ".SELF); } elseif (!strcmp($op, "act")) { // try activate poll and redirect $oPolls->activatePoll();...
more →
Logo Design Contest says: Good to read about administration concept which makes an incredible changes in the environment of reputable firms.

PHP User Survey Part IV: Presentation Layer

So far in this series, we have developed the data layer (database tables) and the business layer (PHP methods) for manipulating the data.

In this piece, we will look at the presentation layer that is used to display the poll question and poll results.

The HTML header will check for the presence of a cookie (in case the user has voted previously) and refresh the page if it has timed out.

<!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" xml:lang="en" lang="en"> <head> <? if (!empty($_COOKIE["cACCOUNT"])) { ?> <meta http-equiv="Refresh" content="<?php print TIMEOUT / 2 ?>; url=devdrivepoll.php" /> <? } ?> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Developer Drive Poll</title> </head>

We will include the file that pulls the poll data from the database tables:

<? require_once("class.polls.php"); // class functions for polls

We can now instantiate a new “polls” class and start pulling the active poll data:

// instantiate polls class $oPolls = new polls; // get poll data $aPoll = $oPolls->getActivePolls($iCursor); $iCnt = $oPolls->getPollsCount(true);

Since we are using the same page to display results as we are to show the form, we will check to see if the user has already voted and record their results.

if ($_POST) { // assign poll...
more →
Wojciech Soczyński says: This series is quite informative, but unfortunately it teaches new users some bad habits which they should avoid coding real...