Problems with SQLServer Session State

October 15th, 2009

Intro. In my last entry I discussed changing the session state mode from the default InProc which stores Session variables in memory to SQLServer which stores Session variables in a sql database.

The Problem. I had a lot of problems after doing that. Data that I was storing in session variables wasn't being saved. It turns out that the sql session does not work exactly like the memory session, although I never saw this documented anywhere.

The Solution. After diagnosing it and trying things for a few days, I ended up writing a program to store/retrieve variables to/from my own sql table.

By the way, here are some electronics components we have for sale on our website: LMH6645MF, EEU-FC1V101, ZHB6718TA, IRFI9Z34GPBF, CD74HC109E, NLV32T-100J-PF, 1N5242B-T.

Change to SQLServer Session State

September 16th, 2009

Intro. One of our subscription websites saves quite a bit of information in Session variables. This website is now ready to go to beta test, so it is time to change the session state mode from the default InProc which stores Session variables in memory to SQLServer which stores Session variables in a sql database.

The Problem. I followed the instructions I found on msdn.microsoft.com, but that resulted in several errors sending me to google to search for possible solutions. One error that I got was:

Failed to login to session state SQL server for user 'TESTSERVER\ASPNET'

where TestServer is our test webpage server. This error reminded me that TestServer is using IIS 5, so I moved the test to our production webpage server, Laurel, which is running IIS 6. The new error was:

Failed to login to session state SQL server for user 'NT AUTHORITY\NETWORK SERVICE'

That's the IIS 6 error, and it was solved by setting up the sessionState tag correctly, as shown below.

The Solution. Here are the steps that worked for me. Note this usage: our webpage server is Laurel, sql database server is Hardy, MyUser is an existing user on Hardy with db_owner access to the databases used by the new website, MyPass is MyUser's password. Also note that our web.config does not use impersonation and that our authentication mode="Forms".

1. Open a command window on Laurel, change directories, and run the setup:

    cd C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727

    aspnet_regsql.exe -S Hardy -E -ssadd

This created a database on Hardy named ASPState which contains all the stored procedures needed to do SQLServer session state. The data will actually be stored in tempdb, a system database.

2. We already had this in the web.config within the system.web and configuration tags:

< sessionState timeout="60" />

So, I changed it to:

< sessionState timeout="60" mode="SQLServer" sqlConnectionString="Data Source=HARDY;User Id=MyUser;Password=MyPass;" />

3. I used SQL Server Management Studio on Hardy to go to Security | Logins | MyUser | Properties | User Mapping. I checked the boxes for ASPState and db_owner, and tempdb and db_owner, and clicked OK.

I browsed to the webpage and everything worked fine.

Fixing My PayPal "Add To Cart" Button

August 25th, 2009

Intro. I previously blogged about how to create a PayPal "Add To Cart" button at runtime. We use this button on our Buy Now pages. To see an example, click on the following link, and then click any of the Buy Now links:

http://www.edxelectronics.com/PartSearch/PartSearch.aspx?SearchPart=AD5

On this page you'll see the "Add To Cart" button which is created at runtime.

The Problem. This week our users started reporting the following error from paypal.com after they clicked our "Add To Cart" button:

"Sorry — your last action could not be completed"

Yikes! Nobody can buy our products online.

A bunch of googling revealed that PayPal did an upgrade and changed some urls that we were using. And they didn't even tell us!

The Solution. We changed our runtime generated url's from:

    https://www.paypal.com/cart/add=1 . . .

to:

    https://www.paypal.com/cgi-bin/webscr?cmd=_cart&add=1 . . .

and everything went back to normal.

Sys.WebForms.PageRequestManagerServerErrorException

June 16th, 2009

Intro.  My company has a private webpage where subscribers search for some specialized information and then can use the search results to update database records.  The page has many textboxes used to allow the user to define search criteria, filter the results, and add and update records.  The textboxes are in AJAX UpdatePanels and there are many buttons which submit the data to the webpage server.

The Problem.  If the user types a "less than" character ( < ) followed by a letter in any textbox, clicking any of the buttons will result in this popup error message:

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server. The status code returned from the server was: 500.

A little research revealed that an error occurs because the system is trying to prevent the user from entering an html tag.  And the user get a popup message (instead of a full error page) because the submit button is within an UpdatePanel, and I have no customErrors page defined for a 500 error.   Unfortunately, the error message above does not convey to my users that they must put a space after the < . 

Rejected Ideas. So how can I fix this problem?  Some blogs recommended that I simply turn off the test for html by adding:

ValidateRequest="false"

in the tag < %@ Page ...%>, but I didn't think this was a very good idea because then the page would be open to HTML injection.

I also considered the question, "Can I prevent users from entering html into my textboxes?", and looked at javascript ways to change or remove the < characters. 

The Solution. I decided, though, that it is better to let the user fix the problem.  A popup error message is perfect, as I don't want my users navigating away from my page.  So, I just needed a way to change the text of the error message to something the users will understand.  Insert this code in your .aspx just below your asp:ScriptManager line:

< !-- Code to replace text of 500 error -->
< script type="text/javascript">
  Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
    function(sender, e)
    {
      if (e.get_error())
      {
        if (e.get_response().get_statusCode() == 500)
        {
          alert("A potentially dangerous value was detected from the client. Note that every < must have a space after it. ");
          e.set_errorHandled(true);
        }
      }
    }
  )
< /script>

 


rolex watch outlets
rolex japan
rolex 3130
rolex 5510 dial
certified rolex dealers california
rolex and 5513
submarine gold band silver face rolex watch
boston rolex
rolex ladt datejust
rolex real and fake comparisons
dp 2008 rolex
cheap rolex replicas
rolex dealers nyc
rolex cellini replica
rolex buenos aires rio de janeiro race
replica rolex dials
knock off rolex watch
rolex gmt swiss eta 2632 2
pictures of rolex submariner
daytona rolex 24 hr 2008
used rolex gmt ii
rolex 6694 gold 1210
rolex dealers in missouri
iced out rolex watch
rolex 24 hour sport car race
rolex etched glass
rolex authorised dealer in scotland
rolex wristwatches
rolex technology
rolex pictures
rolex official site
how to tell a real rolex from a fake rolex
rolex oyster perpetual yacht master ii
rolex fake watch bands
rolex 24 hour
value of rolex factory service on vintage watch
check rolex serial number
rolex replica asia
how a rolex president watch band works
rolex explorer 1165
rolex 24 hours daytona garage access
rolex golf
rolex houston
van conversion ims rolex
unworn rolex
ladies rolex watcher silver
rolex dealer price
rolex serial numbers ageing
preoned rolex watches
rolex oyster quartz day date watch with diamonds
grand am rolex 24
rolex 1016
rolex retailers
rolex dateadjust
rolex daytona 24
rolex jubilee bracelet 62523h
rolex watches orange county
rolex yacht master watch
what does rolex 16203 mean?
rolex 24 atlanta
rolex submariner owners manual
cheap grade 3 rolex fakes
rolex repair vacaville
ladies rolex watches
womens rolex date just graqdual red diamond dial quick set
rolex 24 hour of daytona
rolex platinum
rolex soffit
wallace that runs the rolex series
rolex factory diamond bezel
rolex 24 race
rolex ure submarine
rolex watch resale
rolex 16013
rolex 18k daytona
authorized rolex dealers nj
rolex rose gold
reputable rolex replica watch sites
rolex ball
rolex 31mm datejust in platinum
identify fake rolex
rolex awards winners
rolex date just 31 mm
rolex fei world cup finals
rolex president diamond bezel gold nugget band
rolex dealers delaware
ladies rolex date adjust sapphire watch
rolex watch submariner
stores in atlanta that sell rolex watcher
rolex retail outlets
datejust rolex 31mm
gold weight datejust rolex
rolex hyannis jewelers
imitation rolex watches in hong kong
swiss rolex replica
authorized rolex dealer austin texas
most expensive rolex

cheap rolex
rolex official web site
after market rolex watch band
rolex quickstep starts
rolex 7206 bracelet
rolex gmt master new
rolex stainless steel black dial
rolex paperweight
rolex watch band screws
rolex daytona cosmograph
rolex gmt ceramic bezel
rolex brand cil
fake rolex sub mariner
vintage lady dress rolex watch
rolex world headquarters
two tone rolex
rolex replica cellini
backstage 2009 rolex world cup
rolex oyster perpetual lady
used ladies rolex watches
fei rolex
rolex watch band adjustment
rolex 24 hr
vintage rolex forum
rolex daytona 6265
rolex hulen texas 4747 s hulen
cheap rolex watch
selling rolex customized watches
how do i set a rolex watch
rolex band 16610
ladies rolex stainless steel date just watch salmon dial
leather band rolex
rolex watch instructions
rolex replica from china
set rolex datejust watch
rolex datejust special edition price
rolex yachtmaster
price of a rolex submariner
rolex certification
rolex air king diamond bezel
spot a fake rolex
rolex history
rolex military pocket watch
rolex oyster perpetual watch
dealers rolex watches
rolex professional
rolex bracellet types
grand america rolex sport car series
best priced rolex watches
vintage rolex 6084
rolex eventing accident
chinese fake rolex
rolex news
pictures rolex oysterdate precision
rolex watch serial number
hands with french cuffs and rolex
rolex comex uk
warranty rolex daytona f series
how do i remove the back off my rolex daytona
rolex gucci cartier designer watches
vintage rolex case number movement
rolex box sets
rolex service and cleaning
rolex 18338
grand am rolex sprots car series
rolex daytona watches cost
rolex 6022
rolex mens 18k stainless date
rolex watches cape
rolex milgauss 1019
vintage rolex toronto
does rolex ladies datejust 179173 have laser etching
how do i get the back off my rolex
preowned rolex watches
rolex carbon rear wing
steel rolex made 16233
rolex new york
exact replicas of rolex watches
rolex replica gmt italian
rolex grand am
rolex 176200 roma
rolex advertisement 2007 architectural digest
rolex oyster speedking
rolex styles
rolex authorized service centers
winners rolex yachtsman of the year
rolex precision history
rolex oyster 93250 watch band
rolex look alike watches
platinum rolex watches replicas
rolex oyster perpentual cosmograph daytona 18k gold
how to find out if your rolex is stollen
rolex pepsi
rolex 69178 tappered bracelet
rolex tudor mini sub
watches that look like rolexes
rolex president 1823
rolex replica parts
rolex sertvice
rolex automatic
rolex 69714
rolex 116713
rolex submariner watches
rolex 24 corvette finishes 2008
rolex black face
rolex signature
grand american racing rolex
aftermarket rolex watches
rolex watch band parts
rolex cse numbers to movements
watches rolex australia used
rolex 68288
rolex dealer in new york
rolex uk
identify a vintage rolex
rolex printed watch box
new rolex
rolex smooth bezel 69173
rolex screensavers
looks like a rolex
rolex mid size
rolex north america website
rolex gmt ii photo
ramsey new jersey rolex watch stores
previously owned rolex
hong kong rolex watches
rolex dial makers
ladies tudor sub rolex
rolex tudor ladies watch
magazines featuring rolex
rolex womens
used rolex watch value
rolex daytona for sale in dubai
rolex model 6505
rolex watch value
rolex oyster viceroy precision
rolex 69298
rolex mariner wrist watch box
rolex vintage london
rolex dealers san diego
average cost of a rolex
grand am rolex sports car
rolex ss date just men
rolex equestrian
rolex gmt history
ladys rolex watch
rolex danaos replica
rolex 13mm tappered bracelet
rolex president model with bark finish bezel
used rolex submariner
rolex 116200
does a rolex watch band have a number
borrow money payday loan resource site cash advance now
payday cash loan savings account onlin
quick cash loan bad credit
apple fast cash payday loans
personal cash loans
cash advance chicago preferred payday loan
cash loan yankton
money right away fast money money fast quickest cash loan
fast cash easy payday loan borrow money now
advance cash lawsuit loan payday
new jersey fast cash nj online payday loans nj online
advance america cash loans
minnesota cash advance and payday loans
payday loan personal loans online cash advances pa
payday loan florida cash advance now
no faxing payday cash advance loans
fast money cash loan simplepaydayloan com
florida online cash advance loans
as seen on tv cash loans
connecticut cash advance payday loans software
payday loan 500 personal loans cash advances prefe
cash advance loans no faxing
advance cash loan military payday
cash until payday loans
payday cash advance loans online
online emergency cash loans
advance cash loan new payday
no teletrack cash advance payday loan
advance cash loans payday short term
california cash advance payday loan personal
connecticut venture loan cash advance shop
online payday cash advance instant loans
idaho fast cash advance payday loan
cash for structured settlement debt consolidation loan
instantemergency personal cash loans approve in minutes no
cash fast loan need
cash loan no paperwork
advance advance cash loan loan paycheck payday
online payday cash loan
fast payday cash loans online
fast cash loans annapolis md
cash loan without haveing a job
advance cash internet loan payday
payday cash loan au
cash advance loan delaware
quick easy cash loans
fast cash bad credit loans near renton
cash loans till payday in the uk
best refinance mortgage rate cash out refinance home loan
military loans military cash advance military cash
texas cash advance payday loans software
cash advance payday loan to 1000
related ezinearticles com emergency cash loan consider a
your source fastest cash advance payday loans online
i need cash loan now
online fast quick cash loan payday advance
faxless fast cash loans
cash wi auto title loans
payday cash loan savings account payda
njfastcash payday loan fast cash paydayloanpagesco
nevada online cash advance loans
alabama cash advance payday loans
payday loan cash loans
personal cash loan
online payday loans pay day fax cash advance
fast cash loans washington
where can i cash bank of america student loan checks
abbey national cash advance loans
fast cash instant loans
advanve adcanve cash loan paychrck payday
cash loans online business hosting web
no fax payday loans no fax cash advance faxless payday
personal finance cash loans us
fast cash loans dallas tx
bad credit cash loan htm
til payday no fax cash loans
renovation cash loan
low cost fast cash loans
carolina cash loan quick south money
cash pay day loans
fast cash loans for people with bad credit
cash loans for women
kostners cash loans
ford extended warranty car cash loan title
advance advance cash day line loan pay payday y
cash central payday loans
farm property loans for cash
quick cash loan wisconsin
tennessee advance cash loan payday quick
private cash now loan love and light borrow
easy payday loan cash advance i need cash
cash advance loan illinois fast cash advance prefe
no faxing payday loan easy cash advance simplepayd
fast and easy cash loans
emergency advance payday hold personal check cash loans
military fast cash loans
fast cash online paycheck advance bad credit payday loans
payday loan online fast cash loans western union
advance bz cash loan payday
military loans online payday loans cash a1paydayad
pay day cash advance loans
texas cash advance and payday loans
cash advance payday loans borrow cash paycheck advances
money tree payday loan no fax cash advance
cash advance ms loan
cash advance ny loan
cash payday loan company
easy cash advance book guest inurl loan payday
fast cash advance payday loan
ringtone payday cash advance loan
cash advance loan no fax 500
small personal cash advance loans
fast cash loans company
cash loans by credit card
cash loans no references
cash loan idaho
bath room refit cash loan uk
cash loan in 1 hour
instant online cash loan
advance cash fast in loan payday
bankruptcy cash loan
cash advance at paydayloantoday com payday loan
loans online no fax cash advance
fast cash faxing loans
faxless private cash loan
cash loans in the uk
no fax payday loans online for a fast cash advance
quick cash loans in poway
instant decision fast cash loans
cash loans wired through western union
faxless payday loans faxless cash advance no fax p
fast auto title cash loans arkansas
cash fast fax loan money no
florida cash advance payday loans software
business cash advance loan leads
west virginia cash advance loans
short term payday problem with preferred cash loan
fast cash loans in new york faxless online
easy payday loan no teletrack cash in
custom cash loans
payday cash loans fast usa only
cash pointe car title loans maryland
no fax cash in 1 hour payday loans
same as cash loan for federal taxes
advance cash loans payday service
cash loan while in bankruptcy
cash apply fastest payday loans online
no fax cash advance payday loans
pay day loans amp cash advances
fast cash payday loan payday loans loan
cash easy fast loan xxasdf
i need a cash loan now
loan cash for mnc executive
minnesota advance cash loan payday quick
cash available to loan for buying real estate
cash advance loan without employment
military cash advance loans
connecticut cash advance and payday loans
cash fast florida loan
biggest cash payday loans
advance cash loan online payday quick toda
new mexico cash advance and payday loans
fast cash loan rhode island
fast cash loan bad credit home equity loan fast mo
simple payday loan service cash advance easy cash advance
online instant cash loans
bad credit repo large cash loans auto
fast cash loans in canada
payday advance pay day online cash loans searches
cash advance loan new jersey
anaheim emergency loans and cash
pensacola and cash advance or payday loans
cash advance online payday loan payday loans
advance cash check hold loan payday personal
cash advance loan illinois payday loans online pay
instant no fax military payday cash advances or loans
instant cash loan
quick cash loans for bad credit
cash out mortgage loan
uk fast cash loans
oklahoma fast cash advance payday loan
advance cash fast in loan online payday quick unti
cash loans for cars
debt free cash advance cash advance loans online
cash advance payday loan cash advance america fast cash
louisiana cash advance payday loans software
emergency cash loans with no checking account
cash advance chicago preferred payday loans cash a
virginia cash advance payday loans software
one stop payday loan cash advance
online cash advance payday loans cash advance choo
no credit check guarenteed approval cash loans
mississippi cash advance payday loans
unsecured signature loan not payday or check cashing
advance cash improved loan new payday
long beach instant cash loans
till payday cash loans online
cash advance payday loans today
south dakota fast cash advance loan
fast cash loan instant advance loans online for good or

Cross-thread operation not valid

September 30th, 2008

Intro.  I am upgrading some old programs from VS2003 to VS2005.  These are old Windows apps that run either continuously or on a scheduled basis with little user involvement.  They have escaped upgrading up until this point because they work.

The Problem.  After upgrading a program I got this error when I ran it:

Cross-thread operation not valid: Control 'TextBox1' accessed from a thread other than the thread it was created on.

The program did have "Imports System.Threading" in it, but only so it could use "Thread.Sleep(x)".  The program had no intention of being multi-threaded – it thought it was single-threaded.  I removed these lines as a test, but the error did not go away.

The Solution.  The program also contained "Imports System.Timers" and "Dim oTimer As New System.Timers.Timer" and it turns out that this timer runs on a different thread than the rest of the program.  To avoid the error, add this line where you initialize the timer:

oTimer.SynchronizingObject = Me

 

Prevent Backspace From Going to Previous Page

June 30th, 2008

Intro.  We have one website that is accessible only by subscribers who have a username and password.  The subscriber is presented with lots of data and has the opportunity to add and modify text.

The Problem.  If the subscriber hits the backspace key while the focus is not in an editable field, the website goes back to the previous page.  This causes the subscriber to lose any data that has been entered but not yet saved.  Since there is no reason to return to the previous page, I needed to stop the backspace from going back a page.

The Solution.  I added the following javascript to the < head> section of my webpage (note that I added a space after every "<" so that this editor wouldn't interpret my html):

< script type="text/javascript">
//code to catch the backspace and stops the back default action
if (typeof window.event == 'undefined'){
  document.onkeypress = function(e)
  {
    var test_var=e.target.nodeName.toUpperCase();
    if (e.target.type) var test_type=e.target.type.toUpperCase();
    if ((test_var == 'INPUT' && test_type == 'TEXT') ||(test_var == 'INPUT' && test_type == 'PASSWORD')|| test_var == 'TEXTAREA')
    {
      if ((e.keyCode == 8 ) && (e.target.readOnly == true))
      {
        e.preventDefault();
      }
      else
      {
        return e.keyCode;
      }
    }
    else if (e.keyCode == 8 )
    {
      e.preventDefault();
    }
  }
}
else
{
  document.onkeydown = function()
  {
    var test_var=event.srcElement.tagName.toUpperCase();
    if (event.srcElement.type) var test_type=event.srcElement.type.toUpperCase();
    if ((test_var == 'INPUT' && test_type == 'TEXT') ||(test_var == 'INPUT' && test_type == 'PASSWORD') || test_var == 'TEXTAREA')
    {
      if ((event.keyCode == 8 ) && (event.srcElement.readOnly == true))
      {
        event.returnValue=false;
      }
      else
      {
        return event.keyCode;
      }
    }
    else if (event.keyCode == 8 )
    {
      event.returnValue=false;
    }
  }
}
< /script>

Access DotNetNuke Passwords From Second App

April 2nd, 2008

Intro.  We have one website based on DotNetNuke (FirstSite) with some functions that are available only to the paid subscribers. We have another website (SecondSite) being written in vb.net that needs to be password protected.

The Problem.  The usernames and passwords are stored in the DotNetNuke table aspnet_Membership in an encrypted format (this is optional, but we want encrypted for security).  How can SecondSite access the usernames and passwords of FirstSite in a clear text format for its login page?

The Solution.  The password encrypt/decrypt is handled by the asp.net framework, so I tapped into that.  I added my data source info to my SecondSite's web.config within the < connectionStrings> tag.  I just copied this from FirstSite's web.config (note that I added a space after every "<" so that this editor wouldn't interpret my html):

< add name="SiteSqlServer"
    connectionString=" (your connection string) "
    providerName="System.Data.SqlClient"/>

Then I added these lines within the < system.web> tag.  Again, I just copied these from FirstSite's web.config:

< machineKey (your machine key line) />
< membership defaultProvider="AspNetSqlMembershipProvider"  
    userIsOnlineTimeWindow="15">
   < providers>
      < clear/>
      < add name="AspNetSqlMembershipProvider"
         type="System.Web.Security.SqlMembershipProvider"
         connectionStringName="SiteSqlServer"
         enablePasswordRetrieval="true"
         enablePasswordReset="true"
         requiresQuestionAndAnswer="false"
         minRequiredPasswordLength="7"
         minRequiredNonalphanumericCharacters="0"
         requiresUniqueEmail="false"
         passwordFormat="Encrypted"
         applicationName="DotNetNuke"
         description="Stores and retrieves membership data
         from the local Microsoft SQL Server database"/>
   < /providers>
< /membership>
 

Then I added these lines to SecondSite's login.aspx.vb:

Dim aspnetUser As System.Web.Security.MembershipUser = _
    System.Web.Security.Membership.GetUser(txtUsername.Text.Trim)
If Not aspnetUser Is Nothing Then
    Password = aspnetUser.GetPassword()
End If
If Password <> txtPassword.Text.Trim Then DoInvalidLogin()

Works like a champ!

 

Convert XML Object to DataTable

March 11th, 2008

Intro.  I have a legacy program that returns an object containing data in XML format.  A new requirement came down for this data to be shown in a grid on a new webpage. 

The Task.  Write a new webpage that calls the legacy program and then uses the resulting XML Object as the datasource for a gridview.

What Didn't Work.  I tried to cast the XML Object (MyXMLObject) to a DataSet or a DataTable using CType, but that just gave me this error:

System.InvalidCastException: {"Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.DataSet'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface."}

The Solution.  The first helpful thing that I ran into was this function:

Microsoft.VisualBasic.Information.TypeName(MyXMLObject)  

which return the name of the data type.  For me, it returned "IXMLDOMSelection".  MSDN gave me the members and related information.  My key discoveries were that MyXMLObject.item(0) contains the schema, and MyXMLObject.item(1) contains the data.  Here is my working code:

Dim MyXmlDataDoc As New System.Xml.XmlDataDocument
Dim sr As System.IO.StringReader
'First fetch and load the schema
sr = New System.IO.StringReader(MyXMLObject.item(0).xml)
MyXmlDataDoc.DataSet.ReadXmlSchema(sr)
'Then fetch and load the data.
sr = New System.IO.StringReader(MyXMLObject.item(1).xml)
MyXmlDataDoc.DataSet.ReadXml(sr)
'Attach the data to the grid.
Me.grdResultsGrid.DataSource = MyXmlDataDoc.DataSet.Tables(0)
Me.grdResultsGrid.DataBind()

See an example of the resulting grid here:

http://www.edxelectronics.com/PartSearch/PartSearch.aspx?SearchPart=LM393

 

Convert aspx to html

November 29th, 2007

Intro.  I wanted to set up a simple (no vb code needed), feeder website with links to our main site.  The webmaster said to give him html pages so he could easily put it on a linux server.  I've been developing in Visual Studio using master pages, so I decided to develop in aspx and then convert to html.

The Solution.  Here are the steps I used:

  • Develop in Visual Studio using a master page.  Don't use any aspx controls – use Html controls instead.
  • Build and run the project in debug mode.
  • Navigate to each page, rt-click, and View Source.
  • Save the source to pagename.html.
  • In all of the resultant html pages replace all .aspx with .html.
  • Ftp the html pages, the images, and the style sheet to the host.

Here is my resulting website:

http://www.leadfreesupplier.com/

 

Set Focus to Target Web Page

September 28th, 2007

Intro.  I have a web page that displays a gridview of sales order information for the user.  The user can click on the sales order number (sono) to display more information about any order.  The original code opens a new web page (target="_blank") for each click.

The Problem.  IE7 takes too long to load.  Users that want to look at the details for several orders have to suffer the long load time for each click.

What Didn't Work.  The original gridview had a HyperLinkField under the < Columns> tag (note that I added a space after every "<" so that this editor wouldn't interpret my html):

< asp:HyperLinkField DataNavigateUrlFields="sono"
    DataTextField="sono" HeaderText="Order Number"
    SortExpression="sono" Target="_blank"
    DataNavigateUrlFormatString="orderdetails.aspx?sono={0}" >
    < ItemStyle HorizontalAlign="Center" />
< /asp:HyperLinkField>

I replaced Target="_blank" with Target="OrdDetail".  This made the browser reuse the same web page window for every click instead of opening a new page.  Very fast!

However, the target page does not receive focus after the first use.  So, the question now is how to set focus to the target web page, or how to bring the target web page to the front.

The older DataGrid component used to allow javascript in the DataNavigateUrlFormatString field, so I tried setting it to:

"javascript:window.open('orderdetails.aspx?sono={0}')"

This didn't work.  The order numbers were no longer links.  I found a couple of blogs that said that this was a known Microsoft bug.

The Solution.  What finally worked was replacing the HyperLinkField with a TemplateField:

< asp:TemplateField HeaderText="Order Number" SortExpression="sono">
    < ItemStyle HorizontalAlign="Center" />
    < ItemTemplate>
        < a href="javascript:w=window.open
            ('orderdetails.aspx?sono=< %# Eval("sono") %>',
            'OrdDetail','width=100,height=100');
            w.focus();">< %# Eval("sono") %>
        < /a>
    < /ItemTemplate>
< /asp:TemplateField>

The javascript calls the orderdetails.aspx page, passing the sales order number (sono), and using the same window (OrdDetail) over and over, and then calls w.focus to bring the target page to the front.  Very fast, and very cool!