InternetException

About coding and whatnot.

Global UpdatePanel loading indicator in ASP.NET

clock December 21, 2012 10:48 by author n.podbielski

When I started working on application I am working right now, one of first things I noticed, that was not entirely wrong but was inconvenient: when user clicked on some button that triggers update panel you was not entirely sure it worked or not. Why? Because of three things:

1. I don't know who was developing application before me but sufice to say this person was not thorough with work :) So in many places code worked like Ash in Pokemon (Catch'em all!) with big try catch in whole methods. When exception happend it was not propagated to browser. Maybe it worked, or failed or is still working, you would never known.

2. Code was not optimized. It was slow actually. When it should just add simple entity to DB it was running several seconds. User was not aware of that.

3. Use of UpdatePanels with asynchronous postback and without loading indicator.

 

Changing code to get rid of all 'pokemon error catching' it was work for several days. Not solution I was looking for. It had to be done but not in that moment. Same thing with code optimization.

So I had to add some loading gif. But how to add it to all UpdatePanels? In ASP.NET there is UpdateProgress control but it is associated with single UpdatePanel and useless in that case.

What about ASP.NET Ajax API? PageRequestManager have several events for handling such things.

 

In that particular case it have one usefull event: add_endRequest.

 

Enough with rumbling! Let's jump to the code! :)

 

First we have to create some html code to show  when loading is pending. I used this great site to obtain simple .gif image to show: http://www.ajaxload.info/

With generated image i created HTML like this:

<div id="loadDialog" class="hidden">
    <div class="center height100per width100per">
        <img class="loadingImg height100per" src="<%=Page.ResolveUrl("~/image/loadingCircle.gif") %>"
            alt="Loading" />
    </div>
</div>



And some CSS to style this:

/*miscelanous*/
.hidden
{
    display:none;
}
.center
{
    text-align:center;
    margin:auto;
}
.width100per
{
    width:100%;
}
.height100per
{
    height:100%;
}
/*load dialog*/
div.loadDialog img.loadingImg
{
    height: 100%;
}


Wait, it's not there yet. This is just html, initially hidden. To show this I used jQueryUI modal dialog. This will prevent users clicking here and there. They might broke something, you know. Here is JS snippet I used:

    var dialogSelector = '#loadDialog';
    jQuery(function () {
        jQuery(dialogSelector)
                    .removeClass("hidden")
                    .dialog(
                        {
                            modal: true,
                            draggable: false,
                            closeOnEscape: false,
                            resizable: false,
                            width: 10,
                            height: 100
                        }).parent().css(
                        {
                            position: 'fixed'
                        });
        jQuery(dialogSelector).parent().find('.ui-dialog-titlebar').hide();
        jQuery(dialogSelector).dialog('close');
    });

    var pageManager = Sys.WebForms.PageRequestManager.getInstance();
    pageManager.add_beginRequest(function () {
        loadTimeOut = setTimeout(function () {
            jQuery(dialogSelector).dialog();
        }, 2000);
    });
    pageManager.add_endRequest(function () {
        if (loadTimeOut) {
            clearTimeout(loadTimeOut);
        }
        jQuery(dialogSelector).dialog('close');
    });


This function will run on load, show our loading dialog and instantly hide it again. This way it will show dialog without second initialization when it's gonna be really needed. First initialization is somewhat complicated so I decided to do it once. To show dialog after that I just call:

jQuery(dialogSelector).dialog();



Now let's explain what is happening in initialization. jQueryUI have solution for hiding html elements, so first thing I do is to remove my 'hidden' class. Then I create dialog with modal option, disabled dragging and resizing, closing on [ESC] key press. This will disable any user interaction with dialog itself and whole page.
Great. Width and height options are to make it as small possible (it will scale to image size anyway). After that setting position as fixed will assure that our dialog is always on center of the page. jQueryUI creates some nifty title bar for dialogs we don't want, so line:

jQuery(dialogSelector).parent().find('.ui-dialog-titlebar').hide();



will make it go away.
After that dialog is closed.
I decided that is also good thing to not flash with this dialog user every time something, even smallest thing is updating. User attention span is about 2 seconds. After that they start wondering and clicking again. So 2 seconds is good time to show dialog. For that is timeout:

    var pageManager = Sys.WebForms.PageRequestManager.getInstance();
    pageManager.add_beginRequest(function () {
        loadTimeOut = setTimeout(function () {
            jQuery(dialogSelector).dialog();
        }, 2000);
    });

 And to handle end request event:

 

    pageManager.add_endRequest(function () {
        if (loadTimeOut) {
            clearTimeout(loadTimeOut);
        }
        jQuery(dialogSelector).dialog('close');
    });


which will clear timeout of request with completion time < 2s and then closes dialog it time was more then 2 seconds. That's all. In my case it give nice looking dialog like this:




Better algorithm for finding UpdatePanel that will be updated during page request.

clock December 13, 2012 15:50 by author n.podbielski

Other day I was experimenting with finding which UpdatePanel will be updated during page post back.

I found out that my solution was not working correctly for complex triggers, like user controls with custom events, which will trigger async postbacks and update of panel.

Or for grids with buttons. It was big issue. Also it was not pointing to correct UpdatePanel if name of control was not entirely unique (for example when you have multiple same custom controls on page). It would return first panel, even if it wasn't updating.

So here is updated code:

 

      

        public static UpdatePanel FindAsyncPostBackUpdatePanel(this Page page)
        {
            var scriptManager = ScriptManager.GetCurrent(page);
            var pageRequestMngr = scriptManager.GetNonPublicProperty<object>("PageRequestManager");
            var updatePanels = pageRequestMngr.GetNonPublicField<List<UpdatePanel>>("_allUpdatePanels");
            var source = page.FindControl(scriptManager.AsyncPostBackSourceElementID);
            UpdatePanel parentUp = null;
            //check if is child of update parent with children as triggers
            Control parent = source.Parent;
            while (parent != null && parentUp == null)
            {
                parent = parent.Parent;
                parentUp = parent as UpdatePanel;
                if (parentUp != null && (CheckIfPostbackSourceInTriggers(source, parentUp) || parentUp.ChildrenAsTriggers
                    || (parentUp.IsInPartialRendering || parentUp.GetNonPublicProperty<bool>("RequiresUpdate"))))
                {
                    break;
                }
                parentUp = null;
            }
            if (parentUp != null) return parentUp;
            foreach (var up in updatePanels)
            {
                if (CheckIfPostbackSourceInTriggers(source, up))
                    return up;
            }
            return null;
        }

        private static bool CheckIfPostbackSourceInTriggers(Control source, UpdatePanel up)
        {
            foreach (var trigger in up.Triggers)
            {
                var t = trigger as AsyncPostBackTrigger;
                if (t == null)
                {
                    continue;
                }
                if (t.GetNonPublicField<Control>("_associatedControl").UniqueID == source.UniqueID)
                {
                    return true;
                }
            }
            return false;
        }

 

What have changed?

1. I added code for traversing parent controls of our source control. Most of the time control that is causing post back is children of UpdatePanel. Such a loop is much quicker then finding out all of UpdatePanels, and checking its triggers.

Also if grid with some grid-specific event caused UpdatePanel to update, this grid probably will be child of UpdatePanel and so will be button from that grid. Still it's not ideal. If you have grid with some entities (customers for example), and you want to clicking at some customer will open it's edit view in UpdatePanel in some other part of page. Source and UpdatePanel are not in child-parent relation.

If source is child of UpdatePanel method will check if ChildrenAsTriggers is true - panel will be updated cause it's triggered by child.

If IsInPartialRendering flag and RequiresUpdate, after some test I can say that that this flags indicates if UpdatePanel will be updated. Interesting thing that first flag was not true even if given UpdatePanel was indeed updating. I don't know why. But second flag non-public property was true in those situations.

2. Checking only for control Id was not reliable since it doesn't must be unique for page. That's why I am checking for unique id, of non-public field with trigger control instance and source unique id. That have to give correct answer only for one control, but is much slower since is using reflection.

 

That's it for now but I fill that I will have to revise that code once again soonSmile



Display message on client from anywhere in code with ASP.NET

clock December 10, 2012 09:20 by author n.podbielski

When I was working with WinForms application in previous work I have found one of most useful feature, ability to show some message to the client. For example user cannot edit some entity in particular time (it is being edited by someone else) or should change pasword because it will exprire in x days. I wanted to do something similar in my web application.

To do that I started with creating control with html code of new message window. Sure you can use just JS alert() function, but I find this really annoying. So instead I used jQuery UI dialog.

<script language="javascript" type="text/javascript">
    function showMessage(message) {
        if (typeof (message) !== "undefined" && message) {
            jQuery('#messageContent').html(message);
            jQuery('#messageDialog').dialog({
                width: 600,
                height: 300
            });
        }
    };
</script>
<div id="messageDialog" class="hidden">
    <div class="ui-widget center height100per width100per">
        <div style="padding: 0 .7em;" class="ui-state-highlight ui-corner-all">
            <p>
                <span style="float: left; margin-right: .3em;" class="ui-icon ui-icon-info"></span>
                <strong>Information:</strong> <span id="messageContent"></span>
            </p>
        </div>
    </div>
</div>

I decided to put this control called WUC_MessageDoalog in Site.Master file. That way JS function showMessage will be available for all pages using master page (in my application that was all desired pages).If it is not enaough it is possible to inject this control and JS code into page whenever it will be needed, but it was not necessary in my case.

Now we can execute showMessage function when we need to show some message. To do that we have to use Page.RegisterStartupScript method. 

Page.ClientScript.RegisterStartupScript(page.GetType(), key, string.Format("<script type='text/javascript'>{0}</script>", script));

To abstract this code an made it available in whole application I made extension method of Page type.

public static void AddStartupScripts(this Page page, string key, string script)
{
    if (!page.ClientScript.IsStartupScriptRegistered(key))
    {
        page.ClientScript.RegisterStartupScript(page.GetType(), key,
            string.Format("<script type='text/javascript'>{0}</script>", script));
    }
}

 

After using this function it will render <script type="text/javascript"> tag with our desired code. To execute showMessage we have to insert JS code to our AddStartupScripts method:

jQuery().ready(function () {
    {
        showMessage("I am a message!");
    }
});

I made another extension method from this.

public static void AddClientReadyScript(this Page page, string key, string script)
{
    page.AddStartupScripts(key, string.Format(
        @"jQuery().ready(function () {{
            {0}
        }});", script));
}

But still it will only work for full HTTP Postback. How to make this work with AJAX? Things are more trickier from here. To execute JS code after UpdatePanel AJAX PostBack, we have to use method ScriptManager.RegisterClientScriptBlock.

I encapsulated this in similar way likeAddStartupScripts method.

public static void AddUpdateScript(this UpdatePanel panel, string key, string script)
{
    if (!panel.Page.ClientScript.IsClientScriptBlockRegistered(key))
    {
        ScriptManager.RegisterClientScriptBlock(
            panel, typeof(UpdatePanel), key, script, true);
    }
}

JS code injected into page like this does not need further encapsulating so we leave it like that. But we still have to know which UpdatePanel will be updated to inject JS into it. How to do that? Sadly there is no easy solution. After some Google reasearch, and few hours I managed to create another extension method (yes I like them a lot!):

 

public static UpdatePanel FindAsyncPostBackUpdatePanel(this Page page)
{
    var scriptManager = ScriptManager.GetCurrent(page);
    var pageRequestMngr = scriptManager.GetNonPublicProperty<object>("PageRequestManager");
    var updatePanels = pageRequestMngr.GetNonPublicField<List<UpdatePanel>>("_allUpdatePanels");
    var source = page.FindControl(scriptManager.AsyncPostBackSourceElementID);
    foreach (var up in updatePanels)
    {
        foreach (var trigger in up.Triggers)
        {
            var t = trigger as AsyncPostBackTrigger;
            if (t == null)
            {
                continue;
            }
            if (t.ControlID == source.ID)
            {
                return up;
            }
        }
    }
    return null;
}


If you wondering what are GetNonPublicField and GetNonPublicProperty methods do you can find about the here:
post/2012/12/09/Getting-private-field-or-property-from-object.aspx

I found this working fine for me, but still it have some obvious drawbacks:

1. It founds update panel only by its explicitly defined triggers. So it will not work for triggers that are children of update panel. Still I recomend you to not do that. Nested panels with ChildrensAsTriggers = true will cause to update, panel which is most higher in controls tree hierarchy. So biggest update panel (for example containing whole page) will update. Why even bother with nested panels in that case or even AJAX at all then?

2. It uses control id that is not unique. When you will use not unique ids for your controls (i.e. button1, textbox1), you will end up adding script to first update panel that will pop up. And it will not work. But if you writing your site like this I bet that you have bigger problems :)

3. It will not work with RegisterAsyncPostBackControl method and control outside of panel. But if it is static relation it can be placed inside of update panel triggers collection.

Anyway, with this method mostly working we can write yet another extension to Page:

public static void ShowClientMessage(this Page page, string message)
{
    if (page.Master != null)
    {
        var siteMasterDialog = page.Master.FindControl("wucMessageDialog");
        const string messageScriptKey = "clientDialogMessage";
        if (siteMasterDialog != null)
        {
            var jsCode = string.Format("showMessage('{0}');", message.Replace("'", "\\'"));
            if (page.IsPostBack && ScriptManager.GetCurrent(page).IsInAsyncPostBack)
            {
                var up = page.FindAsyncPostBackUpdatePanel();
                up.AddUpdateScript(messageScriptKey, jsCode);
            }
            else
            {
                page.AddClientReadyScript(messageScriptKey, jsCode);
            }
        }
    }
}

And finally with right tools we can abstract this further to stand alone class. If we will be using only ASP.NET Page handlers, current page instance can be obtain from HTTPContext object via Handler property:

 
public class ClientMessage
{
    public void ShowWarning(string message)
    {
        var page = ((Page)HttpContext.Current.Handler);
        page.ShowClientMessage(message);
    }
}

That is all about magic. To show message from some code in our site just call:

 new ClientMessage().ShowWarning("I am message!");

If everything is working fine you'll end up with dialog like this:

And that's all.Smile



Getting private field or property from object

clock December 9, 2012 07:26 by author n.podbielski

Yesterday I was playing with finding all UpdatePanel controls on page during generating response in ASP.NET. Since object with this information is private itself and collection of panels is private in that object, I had to write some code to extract that data. I ended up with to extension methods for Object type, for getting private field an private property. It's pretty straightforward, besides one thing: since member is private. And we don't know in witch type exactly (every type in base/descendent hierarchy have it's one private members) we have to search them all. So this is final code:

    public static class ObjectExtensions
    {
        public static TRet GetNonPublicField<TRet>(this object o, string fieldName)
        {
            var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField;
            return (TRet)IterateTypesForMember(o, fieldName, bindingFlags);
        }

        public static TRet GetNonPublicProperty<TRet>(this object o, string propertyName)
        {
            var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetProperty;
            return (TRet)IterateTypesForMember(o, propertyName, bindingFlags);
        }

        private static object IterateTypesForMember(object o, string memberName, BindingFlags bindingFlags)
        {
            Type type = o.GetType();
            MemberInfo[] memberInfo;
            do
            {
                memberInfo = type.GetMember(memberName, bindingFlags);
                if (memberInfo.Length == 0)
                {
                    type = type.BaseType;
                }
            } while (memberInfo.Length == 0 && type != null);
            var member = type.InvokeMember(memberName, bindingFlags, null, o, null);
            return member;
        }
    }