Friday, September 12, 2008

Easy way to parse enums?

This is how to do it:

MyEnum x = (MyEnum)Enum.Parse( typeof( MyEnum ), "SomeString" );

Thursday, June 19, 2008

How to avoid the javascript alert on error when using UpdatePanel with Timer

By default on error during async request UpdatePanel shows an annoying alert messagebox. There is a way to avoid that and handle errors on your own. Here is how to handle errors in ASP.NET AJAX (This is not only for UpdatePanels). The trick is to add handler to endRequest to the PageRequestManager:

<script type="text/javascript">
function EndRequestHandler( sender, args )
{
if ( args.get_error() != undefined )
{
// set error is handled in order to avoid the messagebox
args.set_errorHandled( true );
}
}

function AppLoad()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest( EndRequestHandler );
}

Sys.Application.add_load( AppLoad );
</script>

Tuesday, June 17, 2008

UpdatePanel doing full postback when it should not!

I had an UpdatePanel with a Timer for AsyncPostBackTrigger. But although my ScriptManager had EnablePartialRendering="true", my page always got refreshed. The problem was a setting in my web.config. I removed this line:

<xhtmlConformance mode="Legacy"/>

This setting was something that probably I forgot to remove when migrating from asp.net 1.1 to asp.net 2.0.

Monday, June 9, 2008

Javascript dump object

This is a simple javascript function to dump an object:

function dumpObject( object, depth, max )
{
depth = depth || 0;
max = max || 2;

if ( depth > max )
return false;

var indent = \'\';
for ( var i = 0; i < depth; i++ ) indent += \' \';

var output = \'\';
for ( var key in object )
{
output += \'\\n\' + indent + key + \': \';
switch (typeof object[key])
{
case \'object\':
output += dumpObject(object[key], depth + 1, max);
break;

case \'function\':
output += \'function\';
break;

default:
output += object[key];
break;
}
}

return output;
}

Monday, April 21, 2008

Use className="myclass" rather than setAttribute("class", "myclass")

I had to build dynamic html using javascript and I came up with this problem - setAttribute("class", "myclass") didn't work. You should use className instead. The same with setAttribute("onclick","myfunc") - will not work. You should use onclick directly.

Tuesday, March 18, 2008

Keeping Session Alive With ASP.NET AJAX

I needed to keep session alive as long as a customer is viewing a page, no matter if he/she clicks somewhere on the page. With asp.net ajax, this was very easy.

First, you need a ScriptManager on your page with EnablePageMethods set to true:

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
</form>


Second, define in your code behind a simple method that does nothing but keeps session alive like this.

[WebMethod]
[ScriptMethod]
public static void KeepAlive()
{
// just keep session alive
}


Note that you have to use WebMethod and ScriptMethod attributes to make this method avaliable for using in scripts.

Third, you have to define javascript methods to call a page method that is going to keep your session alive.

<script type="text/javascript">
function RegisterKeepAlive( sec )

{
setInterval( "PageMethods.KeepAlive( OnComplete, OnTimeOut, OnError )", sec*1000 );
}
function OnComplete( arg ) {}
function OnTimeOut( arg ){}
function OnError( arg ) {}
</script>


Last, just call RegisterKeepAlive with for example 10 seconds on load event of the body:

<body onload="RegisterKeepAlive( 10 )">

You can also use UpdatePanel with Timer control, but this way is better, because you have more options for processing timeout and errors.

Monday, March 17, 2008

Great Javascript Resources

Here are some of the javascript resources I found on the net.

Yahoo! User Interface Library - a huge library with many controls and functions, including animation, effects, menus, calendar and so on.

script.aculo.us - has some basic effects that are really nice to use like fading in, fading out, folding, shaking, pulsating and so on.

Smooth Gallery - a great piece of javascript code that is perfect for showing pictures.

Lightbox2 - great for showing photos!

Shadowbox - ideal for photos or galleries, shows even flash and movies.

Carousels for showing large content.

Master Page PreInit Event Work Around

Because master pages are actually user controls, they do not have PerInit event. But this is the only time when you can change the MasterPageFile property. So, what can we do if we have sophisticated hierarchy of master pages and we need to change the master page of some master page within this master page? The only way to do this is to handle PreInit event of the page, find the appropriate master page and change its master page. But if you still want to have the logic which master page should be used runtime within the master page file, here is one solution to do that with reflection. Override page OnPreInit method and write this code:

// simulates PreInit event for Master pages
MasterPage master = Master;
while ( master != null )
{
   MethodInfo mi = master.GetType().GetMethod( "PreInit" );

   if ( mi != null )
   {
      mi.Invoke( master, null );
   }

   master = master.Master;
}

Then, in the .master file which you would like to change its master page runtime, you should define method like this:

<script runat="server" type="text/C#">
public void PreInit()
{
   Account acc = LoggedAccount.GetFromSession( Session );
   MasterPageFile = string.Format( "~/local/en-US/{0}/Main.master", acc.Group );
}
</script>

CodeFile vs Codebehind?

I have just migrated one vs2005 web site project to vs2005 web application project and noticed that instead of CodeFile attribute, tha Page/Control directive uses Codebehind and searched to find something more about these two.

CodeBehind
Specifies the name of the compiled file that contains the class associated with the control. This attribute is not used at run time.
Note:
This attribute is included for compatibility with previous versions of ASP.NET, to implement the code-behind feature. In ASP.NET version 2.0, you should instead use the CodeFile attribute to specify the name of the source file, along with the Inherits attribute to specify the fully qualified name of the class.

CodeFile
Specifies a path to the referenced code-behind file for the control. This attribute is used together with the Inherits attribute to associate a code-behind source file with a user control. The attribute is valid only for compiled controls.

Enable Edit and Continue in VS2005 Web Application Project

You must have used to keeping your project debugging while you write code. This is for sure because of the timeconsuming build that you could afford just once a day. But now with using web application project this is a bit different. First, it builds faster, second, you can enable edit and continue mode. This is how to do that:

1. Go to project Properties, tab Web. Check Enable and Continue. Note that this is available only when debugging in local VS dev server, but not IIS web server.

2. Go to Tools/Options/Debugging/General and check Break all processes when one process breaks.

3. Make sure you start your project in Debug mode.

4. Set a breakpoint in the page that you would like to edit. When the process stops at this breakpoint, you can edit this page (and only this page!)

See more about web application project and edit and continue
here.

Migrating to VS2005 Web Application Project Problems

When I was trying to migrate to my VS2005 Web Site Project to VS2005 Web Application Project, I had a weird problem. I had one user control that uses asp.net ajax and a page that uses this control. While the control itself succeeded in Converto To Web Application operation (from the context menu of the project), the page did not. What solved the problem was adding a Register directive to the page (just for generating the designer file) and removing it after that:

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

Another thing that took me some time was that I had to change manually the Build Action for all my files from App_Code from Content to Compile.

More for migrating from vs2005 web site project to vs2005 web app project can find here. If you want to migrate vs2003 web project to vs2005 web app project, see here.

How to Access UserControl from shared code in VS2005?

If you use the standard model - web site with App_Code directory, you could access a UserControl if you implement an interface that also belongs to App_Code. This is because asp.net compiles App_Code in one assembly, and the other folders (or every single page/control) in other assemblies. Other ugly way to do this is by using reflection, which I do not recommend. The best way is to migrate to Web Application Project which is very similar to the old good time of VS2003 projects that we all are used to. This goes with service pack 1 of the studio. You get a single assembly and thus all your pages and controls are visible to your utils classes.

Thursday, January 10, 2008

Accessing IFrames

Here is a sample how to access elements in an iframe from the parent document and how to access parent elements from the iframe.

This is how I get the value of the textbox in the iframe from its parent:

document.getElementById('myFrame').contentDocument.getElementById('tbText').value

And this is how I get the value of the textbox in the parent document from the iframe:

parent.top.document.getElementById('tbText').value
eXTReMe Tracker