InternetException

About coding and whatnot.

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;
        }
    }