Exploring the depths and potentials of ASP.NET RSS 2.0 or Subscribe to .BenRush by Email
 Tuesday, April 03, 2007

If you look within the ASP.Net AJAX framework you will find no methods for registering UpdatePanels with the ScriptManager; why? The reason is because UpdatePanels register themselves with the page's ScriptManager control in their OnInit method:

protected override void OnInit(EventArgs e)
{
    base.OnInit(e);
    this.RegisterPanel();
    this.CreateContents(base.DesignMode);
}


What this means is that when an UpdatePanel responds to the Init event, it will register itself with the ScriptManager for that page. You can get the exception detailed above when you have inadvertantly registered an UpdatePanel (because it was added to the page), but it was never rendered to the page. What happens is locally (that is, within the browser) the ASP.Net AJAX script runtime will execute as if the UpdatePanel was in the page DOM; but since it isn't an exception gets thrown, which is the exception you see above.

Two ways to fix this:

1) Dynamically add the UpdatePanel to your page only when you need it,
2) Set the UpdateMode of the panel to Conditional.



Recommended reading:

kick it on DotNetKicks.com
Tuesday, April 03, 2007 12:22:58 PM (Central Standard Time, UTC-06:00)  #    Comments [2] - Trackback
AJAX | ASP.Net | Programming

I'll go into the reason why this happens in a second, but sometimes you'll encounter an exception like this:

"InvalidCastException was unhandled by user code: unable to cast object of type 'ASP.xxxx' to type 'xxxx'". It looks like this:



You might think the way to fix this exception would be by casting to the ASP.home_aspx (in this example) type (which I'll explain to you a minute), but often this does not work either. Why? What's going on?

This is all the result of the dynamic build nature of ASP.Net. What's happening is that types are being automatically generated for you by the ASP.net runtime in some temp directory on your disk. Occasionally this system gets mucked up and you run into typing conflicts.

The way it all works is that ASP.home_aspx (in this example) is the final class that is executed by the ASP.Net runtime when it asks to render out the home.aspx. home_aspx inherits from the class as defined in the .cs/.vb/.aspx files you actually hand-write. ASP.Net inherits from your class so that it can add various other bells and whistles to the class to actually run correctly within the runtime (lots of details here).

...the only thing I can reason that happens when you get a TYPING conflict in this scenario is that the base class the runtime is using for, in this situation, home_aspx is actually a stale object; one that wasn't properly cleaned up by the runtime/Visual Studio. To fix this situation, you generally need to only clean out the temporary asp.net files for this particular site under:

C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\

Interesting how this looks like a bug in the .Net runtime, but it's actually a bug in the build environments.

Recommended reading:


kick it on DotNetKicks.com
Tuesday, April 03, 2007 12:06:05 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
ASP.Net | Programming

Put here for antiquity's sake.

    <connectionStrings>
        <add name="SqlServerDB"
       connectionString="Data Source=SOMECOMPUTER\SQLEXPRESS;Initial Catalog=UserStore;Integrated Security=True"
      providerName="System.Data.SqlClient"/>
    </connectionStrings>

    <membership>
            <providers>
                <clear/>
                <add name="AspNetSqlMembershipProvider"
         type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"
          connectionStringName="SqlServerDB"
          enablePasswordRetrieval="false"
          enablePasswordReset="true"
          requiresQuestionAndAnswer="false"
          applicationName="MyRandomWebApplication"
          requiresUniqueEmail="false"
          passwordFormat="Hashed"
          maxInvalidPasswordAttempts="5"
          minRequiredPasswordLength="7"
          minRequiredNonalphanumericCharacters="1"
          passwordAttemptWindow="10"
          passwordStrengthRegularExpression=""/>
            </providers>
        </membership>

Recommended reading:

kick it on DotNetKicks.com
Tuesday, April 03, 2007 10:43:56 AM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
ASP.Net | Programming
 Monday, April 02, 2007

It's really easy; some may not know how to do it though, so I'll write a quick entry on it.

Say you have a GridView, and you want to respond (with server code) to someone clicking an item in the GridView (an image link, text link, etc). First thing you do is setup a handler for the GridView's OnRowCommand event:

<asp:GridView id="GridView_Views" .....
    OnRowCommand="GridView_Views_RowCommand" ....>

You then implement the event handler. You can find the row number for the object that was clicked, and retrieve data that you store in the DataKeys collection for that row this way:

    protected void GridView_Views_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        ....
        Int32 index = Int32.Parse((String)e.CommandArgument);
        String uniqueID = (String)this.GridView_Views.DataKeys[index].Value;
        ....

For more information on the DataKeys property, see here. For more information on the RowCommand event, see here.

Recommended reading:

kick it on DotNetKicks.com
Monday, April 02, 2007 7:33:01 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
ASP.Net | Programming
 Sunday, April 01, 2007

  1. Verify that you have installed ASP.Net AJAX on the server and/or development machine (click here).
  2. Verify that your Web.Config file has all of the appropriate entries in it for ASP.net AJAX once the package is installed (see here for an example one that works for me).
  3. Verify you can add the ScriptManager control to your ASP.Net web form.
  4. Verify EnablePartialRendering on the ScriptManager is True.

I will continue adding more checklist items as I continue to encounter problems people are having via the newsgroups, etc. Feel free to leave a comment on this post and I'll make sure I add it to the main list. Thx.

Recommended reading:

kick it on DotNetKicks.com
Sunday, April 01, 2007 9:24:31 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
AJAX | ASP.Net | Programming

This is technically something you may want to do sometime, especially if you have a webcontrol that is grabbing a stash of data, doing some kind of organzing algorithm on it, and then displaying it to the page. If the webcontrol has any store of data within it (such as a list of items, etc) you may want to "bind" to that data from another control. How?

To do this, I simply created a UserControl that contains a ListBox with some predefined values in it:



I then had the user control implement both IEnumerable and IEnumerator:

public partial class WebUserControl :
    System.Web.UI.UserControl, IEnumerable, IEnumerator
{
    ....
}


From within the IEnumerator code, I enumerate the contents of the ListBox (technically I could probably just return the enumerator for the ListBox within the user control BACK to the object binding to the user control, but that's not exactly the point here, the point is implementing this so someone can generically bind to your user control.

    Int32 _CurrentItem;

    public object Current
    {
        get {
            return this.ListBox1.Items[_CurrentItem];
        }
    }

    public bool MoveNext()
    {
        if ((_CurrentItem + 1) < this.ListBox1.Items.Count)
        {
            _CurrentItem++;
            return true;
        }
        else
            return false;
    }

    public void Reset()
    {
        _CurrentItem = 0;
    }



Now that this is in place, I simply set the data source for some other object (in this case, another ListBox) to the user control:

    protected void Page_Load(object sender, EventArgs e)
    {
        this.ListBox1.DataSource = this.WebUserControl1;
        this.ListBox1.DataBind();
        return;
    }

The result is two listboxes on the page, one inside my user control, with the same content:



Now, as an added twist, how about doing it declaratively? Well, we simply implement IDataSource:

public partial class WebUserControl :
    System.Web.UI.UserControl, IEnumerable, IEnumerator, IDataSource
{
    ...
}

...and now return a DataSourceView object from our class:

    public class MyDataSourceView : DataSourceView
    {
        public MyDataSourceView(IDataSource owner, string name) : base(owner, name)
        {

        }
        public IEnumerable EnumerableObject;
        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments arguments)
        {
            return EnumerableObject;
        }
    }

    public DataSourceView GetView(string viewName)
    {
        MyDataSourceView dv = new MyDataSourceView(this, "Default");
        dv.EnumerableObject = this;
        return dv;  
    }

    public ICollection GetViewNames()
    {
        ArrayList al = new ArrayList();
        al.Add("default");
        return (ICollection)al;
    }


Most of the meat of the DataSourceView class is unnecessary in this example, so generic strings are past, etc. The result is the same, a fully databound object - but this time it can be done declaratively.
Recommended reading:

kick it on DotNetKicks.com
Sunday, April 01, 2007 1:35:09 PM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
ASP.Net | Programming

You will get this error if the ASP.Net AJAX framework isn't installed properly on your machine (Sys is the root namespace of ASP.Net AJAX), or if your web.config file isn't configured properly to include the properl libraries needed for ASP.Net AJAX to execute on your server.

If you look at your ASP.Net AJAX page, you'll see a series of script/web references being made like this (the hashes change, be aware of that):

<script src="/WebResource.axd?d=3ue6Jup1QMviboHN8KuVNg2&amp;t=632962405372187500" type="text/javascript"></script>

You must be able to paste this reference into your browser and get back a script file; if this does not work then the libraries are not installed, or you don't have the site configured properly for ASP.Net AJAX to operate.



kick it on DotNetKicks.com
Sunday, April 01, 2007 12:06:28 AM (Central Standard Time, UTC-06:00)  #    Comments [1] - Trackback
AJAX | ASP.Net | Programming
 Saturday, March 31, 2007

Say you have a situation like this:



Here you see we have a master/content page scenario with the content page containing an UpdatePanel and the master page containing a ScriptManager. If you look at the bottom of the master page, you'll also see a LinkButton creatively named "LinkButton". Within the UpdatePanel on the content page, you'll see a Label.

What we want to do is handle the LinkButton click event asynchronously (through ASP.net AJAX) so that the Label within the UpdatePanel on the content page refreshes seamlessly. The catch, however, is that you want to centralize all your code for handling the click event from within the ContentPage. How would you do this?

First, within the Page_Load event for the MasterPage control, you would do this:

    protected void Page_Load(object sender, EventArgs e)
    {
        this.ScriptManager1.RegisterAsyncPostBackControl(
            LinkButton1);
        return;
    }


You see here that we're registering the LinkButton with the ScriptManager control as one that should generate asynchronous postbacks. We then publicize the LinkButton by actually creating an accessor property for it directly within the code for the MasterPage as follows:

    public LinkButton MyLinkButton
    {
        get
        {
            return LinkButton1;
        }
    }


This let's us interact with the LinkButton on the master page strongly (as opposed to using the FindControl method and locating it "weakly" or by name).

The Page_Load event for the content page, then, will look like this:

    protected void Page_Load(object sender, EventArgs e)
    {
        MasterPage mp = (MasterPage)this.Master;
        mp.MyLinkButton.Click += new EventHandler(OnButtonClick);
    }


We grab a reference to the MasterPage object and type it to our particular variant on the MasterPage class (remember we have modified it to have the MyLinkButton property above). Once we have a valid reference, we use the MyLinkButton reference to grab a reference to the LinkButton itself and register an event handler for its click event from within our ContentPage.

We then actually write the event handler within the ContentPage itself:

    private void OnButtonClick(Object sender, EventArgs args)
    {
        this.Label1.Text = DateTime.Now.ToString();
        return;
    }


The result is a control on the MasterPage firing an asynchronous postback event that is then handled properly from the ContentPage (the arrow in the picture points to the region that was asynchronously updated):


Recommended reading:

kick it on DotNetKicks.com
Saturday, March 31, 2007 1:27:16 AM (Central Standard Time, UTC-06:00)  #    Comments [0] - Trackback
AJAX | ASP.Net | Programming

Computers Blogs - Blog Top Sites

Archive
<April 2007>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345
Blogroll
About the author/Disclaimer

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2009
Benjamin Rush
Sign In
Statistics
Total Posts: 444
This Year: 0
This Month: 0
This Week: 0
Comments: 128
Themes
Pick a theme:
All Content © 2009, Benjamin Rush
DasBlog theme 'Business' created by Christoph De Baene (delarou)