Archive for February, 2010

Session Time Out Tricks

I recently received an email from a developer who needed to implement a behavior around a user’s session timeout behavior.

As you probably know, we can configure our application to “expire” a user’s session at any interval that we wish.

Example:

<system.web>
<sessionState timeout="10" />
........
</system.web>

We can add a specification to our application’s web.config file to change the default session expiration time from 20 minutes to a time span of our own choosing. (10 minutes in the example above.)

The session timeout value is a sliding value; on each request the timeout period is set to the current time plus the timeout value.

This means that if a user submits a request after the timeout period expires, the session will have been terminated and the user will no longer be authenticated. If the user’s “post-back” is requesting a secured resource, they will be redirected to the “login” page since the application sees this request as from an anonymous user. (When a session expires the user is de-authenticated.)

The problem in this cast is that the application requirements required that the user be AUTOMATICALLY redirected when the session times out.

This is a sound security practice in certain applications.

For example, lets suppose the application’s user has displayed the results of a query of “sensitive” information. If the user then walks away from their PC, that sensitive data will stay displayed indefinably.

The application that I was contacted about needed the user’s browser to be automatically be redirected when the session timed out.

The problem, of course, is that browser based applications are innately stateless sine they run on HTTP ( a stateless protocol). The browser (client) and the sever only communicate when the CLIENT specifically makes a request of the server.

To meet the applications requirements we can add a timer in JavaScript to be run in the browser.

In our master page (so that the JavaScript will be included in, and executed by every page in our application) we can include the following client side script:

   1:  <head runat="server">
   2:      <title></title>
   3:      <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
   4:      <script type="text/javascript" language="javascript">
   5:      <!--
   6:              var secs
   7:              var timerID = null
   8:              var timerRunning = false
   9:              var delay = 1000
  10:   
  11:              function InitializeTimer() 
  12:              {
  13:                  if (typeof HeadLoginName != 'undefined') {
  14:                  // Set the length of the timer, in seconds
  15:                  secs = 630
  16:                  StopTheClock()
  17:                  StartTheTimer()    
  18:                  }
  19:              }
  20:   
  21:              function StopTheClock() 
  22:              {
  23:                  if (timerRunning)
  24:                      clearTimeout(timerID)
  25:                  timerRunning = false
  26:              }
  27:   
  28:              function StartTheTimer()
  29:              {
  30:                  if (secs == 0) 
  31:                  {
  32:                      StopTheClock()
  33:                      window.location = "default.aspx"
  34:                  }
  35:                  else 
  36:                  {
  37:                      self.status = secs
  38:                      secs = secs - 1
  39:                      timerRunning = true
  40:                      timerID = self.setTimeout("StartTheTimer()", delay)
  41:                  }
  42:              }
  43:      //-->
  44:      </script>
  45:   
  46:      <asp:ContentPlaceHolder ID="HeadContent" runat="server">
  47:      </asp:ContentPlaceHolder>
  48:  </head>

Then we add an “onload” to our html body tag as so:

<body onload="InitializeTimer()">

Note that the client side timer is set to 10 minutes and 30 seconds. This is a plus 30 second complement to the server side setting of 10 minutes so that we should be sure that when the client code “times out” the session on the server will have already expired.

When the client side timer counts down to zero this line of JavaScript code:

  33:                      window.location = "default.aspx"

causes the browser to request the application’s default page.

We could, of course, just post back to the “current” page and let the application’s authentication configuration redirect the user to the application’s login page.

Note that this method is a loose synchronization of the applications session. If we absolutely needed an exact synchronization we could implement an AJAX service method and query the server as to whether or not the REAL .NET session has expired, but we’re not going to do that here since it creates some unnecessary (for most applications)  http traffic.

We could of course do other things form our client side code and do things like black the browser window and pop up a dialog (like a screen saver) or really whatever we want. jQuery is great for this kind of powerful client side work.

Here is a quick bit of sample code that shows the technique – [ DOWNLOAD HERE ].

 

Technorati Tags: ASP.NET Sessions Tips & Tricks

DiscountASP.NET Adds & Enhanced Microsoft IIS Database Manager Support

Historically, working with databases on shared hosting accounts has been problematic.

DiscountASP.net has implemented the IIS Database manager with some additions. Now you can manage your own databases and do things like Backup & Restore yourself.

[ For more information about the IIS Database Manager, and other cool IIS Extensions – Click HERE ]

[ For more info about DiscountASP.NET’s DB Manager Integration -  Read HERE ]

Apigee – Analytics and Protection for APIs and Mashups

I thought this was a cool idea ad thought I’d share it.

Apigee is a website that provides analytics, protection and control for APIs.  Apigee enables API providers to understand usage, protect their app, and enforce API terms of use.  Developers using APIs can use Apigee to get visibility into the actual service levels of the APIs they consume.

http://apigee.com/

Postback Text Processing with the AJAX Modal Dialog

image

I’ve started blogging simple tips when I get a question from a developer that’s a bit tricky.

This is one of those. Simple to do, but not always simple to find the answer.

In this case the developer wanted to use an AJAX Editor Control inside a ModalPopup control.

This isn’t a problem but, the user needed to clicking the OK button to cause a post-back so that he could execute some server –side logic.

The ”Ok” Button is an ASP.NET control but adding a Click Event Handler for the button didn’t solve the problem because it didn’t get executed when the use Clicked on the “Ok” button.

Normally the ModalPopupExtender would be used like this.

<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="LinkButton1"
PopupControlID="Panel1"
BackgroundCssClass="modalBackground"
DropShadow="true"
1.)         OkControlID="OkButton"
2.)         OnOkScript="onOk()"
CancelControlID="CancelButton" />

Line number 1 tells the control to catch the click event for the Ok Button Control instance and line 2 specifies when CLIENT SIDE JavaScript code to execute when the control specifies in line 1 is clicked.

The post-back doesn’t happen (even if the ASP.NET Button control hasd a click event handler defined in code behind because the control doesn’t propagate it.

So Just delete those two lines !

It turns out that they are optional and if you delete them the click event is not trapped and the code behind will execute as expected.

So just nake it look like this:

<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="LinkButton1"
PopupControlID="Panel1"
BackgroundCssClass="modalBackground"
DropShadow="true"
CancelControlID="CancelButton" />

Simple !

[ Download working C# Code HERE ]

Technorati Tags: ASP.NET AJAX Tips & Tricks

Podcast – Jesse Liberty on Silverlight Hyper Video

Jesse Liberty on Silverlight Hyper Video

In this episode The Misfit Geek talks with Sr. PM, Jesse Liberty about his Open Source Video Player Project with a Social Networking Twist.

 Resources ……


 To Catch Jesse at MIX 2010 : Look for this guy !

If you are interested in advertising, have suggestions, or advice…. Please CLICK HERE and send them to me. 


Download Now !

Download MP3 Download WMA Download WMA-Fi Download ACC

Site Authentication Required, Except Default.aspx

What happens when you need to protect your whole site so that only Authenticated users can access our site.

Since I received this question twice this week I thought I’d share a tip.

To allow ONLY authenticated access to your site using Forms authentication you can add a section like this on e to your application’s web.config file.

<authentication mode="Forms">
<forms loginUrl="Login.aspx" name="Login" protection="All"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>

 

The problem is that it seems lots of folks don’t want users to automatically redirect to the Login.aspx page when they navigate to their site home page.

To require authentication for all the pages in your web application EXCEPT the home page (Default.aspx)) 

Also add a location section to your web.config file that explicitly allows anonymous users to access JUST the default.aspx page.

<location path="default.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>

You can use the web.config location element to specify folders as well as pages which makes it a very powerful construct.

 

Technorati Tags: Microsoft ASP.NET Security Tips & Tricks

Teach, Learn and Play with Small Basic from Microsoft DevLabs

This week someone referred me to this blog post about Small Basic.

What a cool idea for playing teaching beginners of kids about programming or just playing around.

image

You can even build Silverlight application with it and “Graduate” your Small Basic” code to Visual Basic.net / Visual Studio

You can even share your work on the site like this Tetris Game written in Small Basic.

image 

What fun !

Trapping Intentional Cross Site Scripting (XSS) Attempts in ASP.NET

So I’m building an ASP.NET application to host Podcasts and in the post submission logic I want folks to be able to submit markup, but not JavaScript.

image

ASP.NET automatically traps suspicious posts to the server, but the results have to unfortunate defines.

First is the ugly resulting page. We’ve all seen them.

image

And the second is that I may want to be able to add some SPECIFIC logic to handling that Security exception because it probably means someone is intentionally trying to hack my web site.

It turns out that this is another that ASP.NET makes easy to solve.

First, add a Global.asax file to your solution and code the global Application_Error event handler as follows.

   1:  protected void Application_Error(object sender, EventArgs e)
   2:  {
   3:      Exception objErr = Server.GetLastError().GetBaseException();
   4:      string err = objErr.Message.ToString();
   5:   
   6:      string secError = "A potentially dangerous Request.Form value was detected";
   7:      string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority +
                                          Request.ApplicationPath.TrimEnd('/') + '/';
   8:      Server.ClearError();
   9:   
  10:      if (err.IndexOf(secError) != -1)
  11:      {
  12:          Response.Redirect(baseUrl + "SecurityError.aspx");
  13:      }
  14:      else
  15:      {
  16:   
  17:          Response.Redirect(baseUrl + "Error.aspx");
  18:      }
  19:  }

When the specific form validation error is encountered we redirect to a specific web page. (SecurityError.aspx)

The user gets a much better experience.

image 

This solves the second problem with the default handling. Even without additional work on my part the IIS Server Logs will be able to tell me how many times this happens along with information about the requests that generate them.

If I want to get more specific I can forward the originals HTTP request and exception info to SecurityError.aspx and take some action.

If the form can only be submitted by a user who is logged in to my application, even better. I can count how many times then cause this eror to happen and then based on that data I can warn them, log them off or ban them from my site completely

Do you add security specific error handling to your site ? If so, let me know.

Technorati Tags: ASP.NET Security Tips & Tricks

The Misfit Geek Podcast on Zune Social

image

Yes, the MisfitGeek Podcast still lives.

I’ve recovered from a catastrophic audio hardware failure and learned how to record podcast interviews over Skype.

I’ve got several scheduled and they should start appearing here soon.

In the meantime I thought I’d share that that the Podcast is now listed on Zune Social.

YOU can check it out on Zune Social [ HERE

If you have show suggestions for me PLEASE send them to me [ HERE ]

I get many (MANY) email from customers who are struggle to answer specific technical problems. As time permits I’m going to start answering them here,

I recently received an email from a developer building an application using the Ajax Control Toolkit and he needed his page to contain an Accordion Control in which all Panes were CLOSED when the page was initially loaded.

Like this ……

image

The Accordion Control in the earliest versions of the Ajax Control Toolkit lacked this ability but now it’s pretty easy.

By default, the Accordion Control requires one of it’s contained Panes must be open at all times.

So, there are two things we need to do in our Accordion Control configuration.

  1. Configure the control so that it does NOT require at least one open Pane.
  2. Set the default Pane index to one that does not exist so that NO Pane will be open when the page loads.

Luckily, the Control exposes the properties that we need.

Here is the control syntax.

<ajaxToolkit:Accordion ID="MyAccordion" runat="server"                        

HeaderCssClass="accordionHeader" ContentCssClass="accordionContent" 

FadeTransitions="true" FramesPerSecond="40" TransitionDuration="250" 

AutoSize="None" RequireOpenedPane="false" SelectedIndex="-1">

 

The bottom two attributes are the ones that interest us.

RequireOpenPane=”false” – Tells the Accordion control that it’s OK for all the contained Panes to be closed. 

SelectedIndex=”-1” – Tells the Accordion control to set as Active the Panel whose index is –1 (which doesn’t exist”.

These two settings combine to offer the startup effect that you see in th epicture above.

[ Click HERE to download a sample project of this technique. ]

Technorati Tags: Microsoft ASP.NET AJAX Controls Accordion Tips & Tricks