Saturday, August 27, 2005

Use JavaScript in Your Code Behind Files.

By Daniel N. Egan (DotNetDoc)

There are many new things that can be accomplished in ASP.Net that would take you quite a bit of coding if you were to try to accomplishthem in regular ASP. Among the advancements that ASP.net has brought to web programming is the use of code behind files. A Code behindfile helps us to separate our visual presentation layer from our business layer. If you programmed in ASP then you remember the spaghetticode that inevitably occurred when you added even the simplest functionality to your web pages. A code behind file gives you a wonderfulway of separating your code from your HTML tags. Even with its great power there are still times when you want action to happen on theclient-side of your web application (No trip to the server). For this you will want to use the tried and true web developer’s friend:JavaScript. You can still go into the HTML section and add JavaScript tags where you would like them to be; however, this still requiresdealing with spaghetti code, which makes things difficult to read and debug. A better solution in some situations is to add JavaScript toyour pages dynamically. That’s how the .Net framework classes do it. In this article I will show three scenarios in which you could useJavaScript to have client side functionality and I will show you how to do it in the code behind files.

Our first example is very simple. Here is the scenario:

When users click on a button or link on your aspx page, that is used to delete a record, you want to have a pop -up message ask them toverify if they are sure. In windows applications this is done with a MessageBox. But the messagebox class in not available to us in a webapplication. To accomplish this in an Asp.Net you will need to use a JavaScript confirm box. Instead of having to add an onClickattribute to your HTML tags, you can place them in your code behind file as shown below. To add a client side attribute to a button orlink on your form you can use the “Attrubutes.Add()” method of the control. It takes two parameters: the type of action, onClick,onBlur, etc..., and the JavaScript itself. This particular JavaScript will pop up a confirm box (Yes/No). The JavaScript functioncalled “Return” has two possible outcomes, true or false. The confirm box will return a true if “Yes” is pressed and false if “No” ispressed. If the users click on “No” then nothing happens. If they click on “Yes” then the application will proceed.

Our second scenario delves deeper into the process:

Most web sites have forms that users need to fill out. Some examples of this are comment forms and registration forms. When users reachthat page you want to make sure that the cursor in sitting in the correct textbox for them to start. This is a convenience for theusers. This eliminates the need to use their mouse to click in the textbox and also directs them to the place you want them to start.

The code below shows a sub procedure in a code behind file. It has a single parameter; “ctrl As System.Web.UI.Control”. All that isrequired to call this method is to pass the name of the textbox that you want to receive the focus. We begin by building the JavaScript.

This requires a little more code than our first example.

You will notice that the first thing I do is create a StringBuilder object. You could use a string to do this as well, but it is moreefficient using a StringBuilder. (StringBuilders will be covered in more detail in a later article). Suffice it to say that it is easyto use and is more efficient than concatenating strings. We start by creating the beginning script tag. The next line calls thedocument.getElementById function and concatenates it with the control that we are passing to the procedure. The third line is just theending script tag.

 

cmdDelete.Attributes.Add("onClick", "javascript:return confirm(' Sure You Wish To Delete?');")

 

You may have noticed that at the end of each line I have added a vbCrlf (Carriage Return Line Feed). This is so that when it writes outthe JavaScript to the page that is rendered it will put each part of the script on a separate line. This is not needed for scriptfunctionality but readability. With a short script like this it might not make much difference but as you create larger scripts you willwant to be able to read the script in case you need to debug it. Please remember, as opposed to Vb.Net, JavaScript is case -sensitive.Calling the method is simple. You just call SetFocus() in your Page_Load and pass it the name of textbox that you want to have thefocus. In the example below I have taken that just a bit farther. The aspx page loads the email that the user had entered into a cookie(code not shown). This is so that when users return to the page, they do not have to retype their email. When the page loads it checks to see if the cookie exists. If it exists, the password textbox receives the focus. If it does not exist then the email textbox receivesthe focus. This is to show you that you can set focus to a textbox dynamically in your code.

 

Private Sub SetFocus(ByVal ctrl As System.Web.UI.Control)

Dim s As New System.Text.StringBuilder

s.Append("<SCRIPT language=""javascript"">" & vbCrLf)

s.Append("document.getElementById('" + ctrl.ID + "').focus() " & vbCrLf)

s.Append("</SCRIPT>" & vbCrLf)

RegisterStartupScript("focus", s.ToString)

End Sub 'SetFocus

‘No carriage return’s

<SCRIPT language="javascript">document.getElementByI ('txtEmail').focus() </SCRIPT>

‘With carriage return’s

<SCRIPT language="javascript">

document.getElementById('txtEmail').focus()

</SCRIPT>

Our third scenario will complete the article:

You have a form where users submit information to you either by email or in a database. You want to be able to give them a confirmationbut you don’t want to send them to another page to do this. When they have submitted something successfully you would like to give thema message and then send them to the homepage. The sample below is overly simplified so that we can focus on the JavaScript itself. Ifthis was for a real application we would add more error checking. Please follow the comments in the code for a line by line detail ofwhat the code is doing.

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

'Put user code to initialize the page here

If Not Page.IsPostBack Then

Try

If IsDBNull(Request.Cookies("JGA_Email")) = False Then

email.Text = Request.Cookies("JGA_Email").Value

SetFocus(txtPassword)

Else

SetFocus(txtEmail)

End If

Catch

SetFocus(txtEmail)

End Try

End If

End Sub

Private Sub cmdUpdate_Click(...) Handles cmdUpdate.Click

' Boolean variable will flag if an error was encountered

Dim bNoError As Boolean = True

Try

' Your code would go here.

Catch ex As Exception

' This will catch your exception and change the Boolean flag to false

bNoError = False

Finally

' The Finally section of a Try Catch will run no matter what. Error or No Error

' First we need to create a StringBuilder object to hold our JavaScript

Dim sJSCode As New System.Text.StringBuilder

' If no error was encountered then ...

If (bNoError) Then

'Start creating our JavaScript by creating our opening tag.

sJSCode.Append(" <script language=""javascript"">" & vbCrLf)

' Here we are creating a variable to hold our message

sJSCode.Append(" var sMessage = 'Your Question has been submitted.';" & vbCrLf)

' In this line we are creating two JavaScript functionsan alert(OK Messagebox)

' that will show our message and a window location method that will send our user to

' the page we are looking to go. If you tried to add a

' Response.Redirect or a Server.Transfer here it would not work.

' Your alert script would never get processed

sJSCode.Append(" alert(sMessage);window.location = 'Home.aspx'" & vbCrLf)

' Here is our closing tag

sJSCode.Append(" </script>" & vbCrLf)

' We need to then register our code. This will make sure it runs when

' we do a postback

RegisterStartupScript("MyJSCode", sJSCode.ToString)

Else

' This code does the same thing but tells the user there was an error.

sJSCode.Append(" <script language=""javascript"">" & vbCrLf)

sJSCode.Append(" var sMessage = 'An error was encountered';" & vbCrLf)

sJSCode.Append(" alert(sMessage);window.location = 'Home.aspx'" & vbCrLf)

sJSCode.Append(" </script>" & vbCrLf)

RegisterStartupScript("MyJSCode", sJSCode.ToString)

End If

 

End Try

End Sub

I hope that this gives you a jumping-off point to start learning how to use JavaScript in your code behind files. Client Side

functionality will greatly enhance any Asp.Net application that you create.

DotNetDoc

posted on Saturday, August 27, 2005 7:11:59 AM (GMT Daylight Time, UTC+01:00)  #    Comments [6] Trackback
Wednesday, August 24, 2005

I am used to reading the reviews of my book on amazon.com but it is always great to come across them other places. This time I came across This Review on EggheadCafe.com.

I was really excited to read it for a couple of reasons.

1) It was a good review of my book ;)

2) It was from Peter A. Bromberg, Ph.D. I read his stuff on EggHeadCafe ALL the time. They are fantastic articles on many of the hard to find techniques in .Net. Every time I Google to find a solution to a particular problem, his articles always come front and center. The really cool thing is that he is a real hard core C# guy so the fact that he still liked my book was cool. Here is a quote from his review:

"I give this one a hearty "Thumbs Up" -- not only does it cover the subject extensively, it also promotes best-practices programming methodology. Pick up a copy of "Building Websites with VB.NET and DotNetNuke 3.0", by Dan(iel) Egan"

Cool!!!!!

Happy Programming

Doc

 

posted on Thursday, August 25, 2005 2:55:01 AM (GMT Daylight Time, UTC+01:00)  #    Comments [2] Trackback

Carl Franklin and the DotNetRocks Road trip will be stoping by our place in Southern California on November 4th. Stop by the SoCal DotNetRocs website for more information and to register for the event.

Doc

posted on Thursday, August 25, 2005 1:49:34 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
Tuesday, August 23, 2005

DotNetNuke version 3.1.1 has been released.  I am installing it right now (well a clean install on my local box anyway) and I will let you know what I think. It is packed with many bug fixes and some cool new stuff as well.

They are supposed to release a new forums module today too. I will test it out, the beta was really nice. I wish they would work on a eCommerce module that comes default with DNN. This is the one thing that DNN is really missing.

Anyway, I will let you know what I think.

Doc

posted on Tuesday, August 23, 2005 8:06:09 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
Monday, August 22, 2005

Well we finally have an "OFFICIAL" date for the Southern California Code Camp. We will be having a 2 Day event hosted at Cal State Fullerton the 21st and 22nd of Jan 2006. We already have some fantastic speakers lined up as well as some cool door prizes. Go to the Code Camp Site and register for more information. We will post updates on that site regularly.

See you all there!!!

Doc

posted on Tuesday, August 23, 2005 1:49:52 AM (GMT Daylight Time, UTC+01:00)  #    Comments [4] Trackback
Sunday, August 21, 2005

I know, I know this is another semi-worthless post but I just had to put this up here. I am usually one to hop onto the front end of new gadgets. Anything that would help out my general geekyness! New phones, headsets, batman utility belts, you get the picture. Well for some reason I was resisting the desktop search programs (Google or MSN). I mean, I could not live through my day without using Google to find something I need for one of my projects, so I don't know why I was resisting it.

Anyway, I was talking to Woody at the Indigo event the other night and we started talking about the desktop search. He uses the MSN one and was talking about all the cool features. But what really caught my ear was the fact that in addition to all of your normal files, it will also search your email!. Now this is not a "Review" post, this is just a "what was I thinking" post. I know, y'all have been using one of these for months now so this is no big deal to you, but MAN what the heck was I waiting for!!!  With a couple of clicks of my keyboard, I can have everything I need brought up before my eyes!!!

If by some really odd chance you have not downloaded one of these, you must do this now.

Doc

posted on Sunday, August 21, 2005 11:33:01 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback

I have been using Skype for quite a while. For those of you who have been sitting in a darkened room for a while, Skype is a FREE internet phone system. Yes, I said FREE!!  I use it to call my Publisher in the UK as well as others I know across the US.

It has cool stuff like Skype IN and Skype OUT that lets you use it like a real phone too. (But that costs of course)

Anyway, I went to their site (haven't been there in a while) and I noticed that they have some new cool stuff (Plug-ins and things). Included in this is the ability to show my status right on the website (Upper left hand corner). When I change my status, it will change on the site. So if you see me online, feel free to send an IM or Skype Call (Although I don't usually have a headset plugged in)

Anyway, Cool Stuff. Check it out.

Doc

posted on Sunday, August 21, 2005 9:29:39 AM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
Saturday, August 20, 2005

Hey, Check this out from the Channel 9 Guys.

Show Off .  It's pretty cool. Basically, you put together a cool 5 minute video of some tip, trick, time-saver, gadget, really anything geeky and they will show it at the PDC. That is really cool. I am looking forward to seeing what they pick to show.

Doc

posted on Saturday, August 20, 2005 4:46:49 AM (GMT Daylight Time, UTC+01:00)  #    Comments [5] Trackback
Thursday, August 18, 2005

I went to the Indigo User Group Tour tonight. It was a great presentation and I look forward to the options that Indigo gives the .Net developer although I will wait until it gets a little closer to realease date before getting too excited. For now I will continue to use my old Remoting/Webservices skills.

Indigo.jpg

Mike Vincent, Me, Dave Foderick at Indigo UG Tour Event.

posted on Thursday, August 18, 2005 12:23:42 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback
Wednesday, August 17, 2005

I recently received this question from one of the users of a messageboard that I answer questions for:

>>Hi,

>>I'm trying to open up a form and set it's top and left property
to be the same as one of my panels on my form. However,
it's not working out the way i >>planned. I even tried adding
up the top of form1 and the top of the panel but that didn't
work either. Any help on this would be appreciative.

His original code is below.

Private Sub lbl_LinkClicked( ByVal sender As System. Object , _
ByVal e As System.Windows.Forms.LinkLabelLinkClickedEventArgs) _
Handles lbl.LinkClicked

Dim frmForm As New Form2
With Form2
    .Show()
    .Width = Me .Panel1.Width
    .Height = Me .Panel1.Height
    .Top = Me .Top + Me .Panel1.Top
    .Left = Me .Left + Me .Panel1.Left

End With

End Sub

At first glance of the code it looks like this should work.
He makes the form's width the same as the panel, then
makes it the same height as well. Now it is time to place
it on top of where the panel is located. He then sets the
Top of the form equal to the Top of the current form plus
the top of the panel on the form. This should place it right
on top of the panel right? Well no, actually he forgot to take
into account the forms menubar and side border.

So this should work for him right. Well yes it does but who
wants to hard code that kind of detail. What if the size of
the menubar or border changes?

Dim frmForm As New Form2
        With frmForm
           .Show()
           .Width = Me .Panel1.Width
           .Height = Me .Panel1.Height
           .Top = Me .Top + Me .Panel1.Top + 30
           .Left = Me .Left + Me .Panel1.Left +

        End With

To get the exact size you can use the
System.Windows.Forms.SystemInformation Namespace.
You can use the FrameBorderSize.Width and the
CaptionHeight (Menubar) to accomplish this. Make sure that
you add the CaptionHeight and FrameBorderWidth together for
the Top calculation because the border goes around the whole form.

Dim frmForm As New Form2
        With frmForm
           .Show()
           .Width = Me .Panel1.Width
           .Height = Me .Panel1.Height
            Dim intBorder As Integer
           intBorder = System.Windows.Forms. _
           SystemInformation.FrameBorderSize.Width

            Dim intMenuHeight As Integer
            intMenuHeight = System.Windows.Forms. _
            SystemInformation.CaptionHeight


           .Top = Me.Top +  _
                 
Me.Panel1.Top + _
                 
intBorder + _
                 
intMenuHeight
           .Left = Me.Left + _
                  
Me.Panel1.Left + _
                  
intBorder

        End With

So this got me to thinking. What else can the SystemInformation
Namespace do for me? Well quite a bit actually.
below I have detailed out some of the information you
can get using this namespace.

What is the computer name?
SystemInformation.ComputerName

Is a connection to a network present?
Network : SystemInformation.Network

What is the users Domain Name
SystemInformation.UserDomainName

What is the UserName?
SystemInformation.UserName

What was the boot mode (Normal, Safe Mode etc...)
SystemInformation.BootMode.ToString

Adjusting the disply for multiple monitors.
SystemInformation.MonitorCount.ToString
SystemInformation.MonitorsSameDisplayFormat.ToString
SystemInformation.ArrangeDirection.ToString
SystemInformation.PrimaryMonitorSize.ToString


Questions about the mouse.
MousePresent : SystemInformation.MousePresent.ToString
MouseButtonsSwapped : SystemInformation.MouseButtonsSwapped.ToString
MouseButtons: SystemInformation.MouseButtons.ToString

There are other items in there as well. Check out the help
files to see all the things this namespace can give you.

Happy Programming,

DotNetDoc


 

posted on Wednesday, August 17, 2005 10:46:10 PM (GMT Daylight Time, UTC+01:00)  #    Comments [1] Trackback

I just checked the PDC website and it looks like it is SOLD OUT.  Glad I got my ticket early. I can't wait to go. It is great that it is in my backyard this year. No hotel or plane travel !!!!. There are a lot of events surrounding the PDC so it should be a fun week.

Doc

posted on Wednesday, August 17, 2005 1:21:02 PM (GMT Daylight Time, UTC+01:00)  #    Comments [0] Trackback