Solved

messagebox

Posted on 2010-08-18
31
780 Views
Last Modified: 2013-12-17
hey does any know how to display a message box on the sever side?
i am using update panlel

C# coding and AsyncPostBackTrigger,  PostBackTrigger

i need a class that i can call a messagebox(STRING) in c# code

i have found messagebox class on the net, but i am having problem with the post back trigger,
it works fine in the update panel with "PostBackTrigger"
but "AsyncPostBackTrigger" does not work, give me this java error:
Error: Sys.WebForms.PageRequestManagerServerErrorException: Input string was not in a correct format.




this is my messagebox class:

using System;
using System.Web.UI;
using System.Web;
using System.Text;
using System.Collections;


/// <summary>
/// ASP.NET JavaScript message box class
/// </summary>
public class MessageBox
{
    private static Hashtable m_executingPages = new Hashtable();

    private MessageBox() { }

    public static void Show(string sMessage)
    {
        // If this is the first time a page has called this method then
        if (!m_executingPages.Contains(HttpContext.Current.Handler))
        {
            // Attempt to cast HttpHandler as a Page.
            Page executingPage = HttpContext.Current.Handler as Page;

            if (executingPage != null)
            {
                // Create a Queue to hold one or more messages.
                Queue messageQueue = new Queue();

                // Add our message to the Queue
                messageQueue.Enqueue(sMessage);

                // Add our message queue to the hash table. Use our page reference
                // (IHttpHandler) as the key.
                m_executingPages.Add(HttpContext.Current.Handler, messageQueue);

                // Wire up Unload event so that we can inject some JavaScript for the alerts.
                executingPage.Unload += new EventHandler(ExecutingPage_Unload);
            }
        }
        else
        {
            // If were here then the method has allready been called from the executing Page.
            // We have allready created a message queue and stored a reference to it in our hastable.
            Queue queue = (Queue)m_executingPages[HttpContext.Current.Handler];

            // Add our message to the Queue
            queue.Enqueue(sMessage);
        }
    }


    // Our page has finished rendering so lets output the JavaScript to produce the alert's
    private static void ExecutingPage_Unload(object sender, EventArgs e)
    {
        // Get our message queue from the hashtable
        Queue queue = (Queue)m_executingPages[HttpContext.Current.Handler];

        if (queue != null)
        {
            StringBuilder sb = new StringBuilder();

            // How many messages have been registered?
            int iMsgCount = queue.Count;

            // Use StringBuilder to build up our client slide JavaScript.
            sb.Append("<script language='javascript'>");

            // Loop round registered messages
            string sMsg;
            while (iMsgCount-- > 0)
            {
                sMsg = (string)queue.Dequeue();
                sMsg = sMsg.Replace("\n", "\\n");
                sMsg = sMsg.Replace("\"", "'");
                sb.Append(@"alert( """ + sMsg + @""" );");
            }

            // Close our JS
            sb.Append(@"</script>");

            // Were done, so remove our page reference from the hashtable
            m_executingPages.Remove(HttpContext.Current.Handler);

            // Write the JavaScript to the end of the response stream.
            HttpContext.Current.Response.Write(sb.ToString());
        }
    }
}



0
Comment
Question by:JCWEBHOST
  • 15
  • 14
  • +1
31 Comments
 
LVL 15

Expert Comment

by:angus_young_acdc
ID: 33462037
That error message seems just like your passing either illegal characters, or not passing a string at all.  Have you been able to see what you're actually trying to populate the message with?  It could be that you're passing an object which isn't getting successfully converted to a string.
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462052
(http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx)By calling Response.Write() directly from your messagebox class you are bypassing the normal rendering mechanism of ASP.NET controls. The bits you write are going straight out to the client without further processing (well, mostly...). This means that UpdatePanel can't encode the data in its special format.
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462056
you have 2 options to solve this:If you must use ⿿Response.Write⿝ you can get a similar solution by using a Label control and update it instead of using ⿿Response.Write⿿.If you use ⿿Response.Write⿝ in markup pages (ASPX or ASCX) replace them with either the ⿿=⿝ syntax (<% = MyProperty %>) or use the same solution mentioned above, adding a Label control and updating it in the code behind.(http://dotnetdebug.net/2006/12/28/syswebformspagerequestmanagerparsererrorexception/)
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462070
another option i found is using LiteralControl but i haven't tested it...
0
 

Author Comment

by:JCWEBHOST
ID: 33462109
i am lost? i little help plz?
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462121
please follow the links i've posted, they describe in details how to overcome this issue.

(http://dotnetdebug.net/2006/12/28/syswebformspagerequestmanagerparsererrorexception/)
0
 

Author Comment

by:JCWEBHOST
ID: 33462123
i cant find Response.Write() in the code?
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462154
why not?
here's the link content:

Having “Response.Write” in the code behind in an event that is fired on an Async postback like Page_Load, Page_Render or the handler that handles that exact event can cause the same problem.

If you must use “Response.Write” you can get a similar solution by using a Label control and update it instead of using “Response.Write“.

If you use “Response.Write” in markup pages (ASPX or ASCX) replace them with either the “=” syntax (<% = MyProperty %>) or use the same solution mentioned above, adding a Label control and updating it in the code behind.
0
 

Author Comment

by:JCWEBHOST
ID: 33462156
can ural give me the code which i need to be changed?
0
 

Author Comment

by:JCWEBHOST
ID: 33462179
this is a Class:

using System;
using System.Text;
using System.Collections;
using System.Web;
using System.Web.UI;
 
public class WebMsgBox
{
  protected static Hashtable handlerPages = new Hashtable();
 
  private WebMsgBox() { }
 
  public static void Show(string Message)
  {
     if (!(handlerPages.Contains(HttpContext.Current.Handler)))
     {
        Page currentPage = (Page)HttpContext.Current.Handler;
        if (!((currentPage == null)))
        {
           Queue messageQueue = new Queue();
           messageQueue.Enqueue(Message);
           handlerPages.Add(HttpContext.Current.Handler, messageQueue);
           currentPage.Unload += new EventHandler(CurrentPageUnload);
        }
     }
     else
     {
        Queue queue = ((Queue)(handlerPages[HttpContext.Current.Handler]));
        queue.Enqueue(Message);
     }
  }
 
  private static void CurrentPageUnload(object sender, EventArgs e)
  {
     Queue queue = ((Queue)(handlerPages[HttpContext.Current.Handler]));
     if (queue != null)
     {
        StringBuilder builder = new StringBuilder();
        int iMsgCount = queue.Count;
        builder.Append("<script language='javascript'>");
        string sMsg;
        while ((iMsgCount > 0))
        {
           iMsgCount = iMsgCount - 1;
           sMsg = System.Convert.ToString(queue.Dequeue());
           sMsg = sMsg.Replace("\"", "'");
           builder.Append("alert( \"" + sMsg + "\" );");
        }
        builder.Append("</script>");
        handlerPages.Remove(HttpContext.Current.Handler);
        HttpContext.Current.Response.Write(builder.ToString());
     }
  }
}



this is how you call it, there is no "Response.Write"?
0
 

Author Comment

by:JCWEBHOST
ID: 33462184
how i call the messbox : WebMsgBox.Show("How to show alert message!");
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462230
yes u have, the last line:

HttpContext.Current.Response.Write(builder.ToString());
0
 

Author Comment

by:JCWEBHOST
ID: 33462274
so that must change to?

HttpContext.Current.Response.Write(builder.ToString());

please help.
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462300
whem u get the javascript error, which line it refer to?
0
 

Author Comment

by:JCWEBHOST
ID: 33462306
i do not kwon
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 42

Expert Comment

by:sedgwick
ID: 33462332
on the webpage u should see the JS error icon (yellow warning sign) on the left-bottom corner, dbl-click it and u get the JS error description with the line where the exception triggered.
0
 

Author Comment

by:JCWEBHOST
ID: 33462341
ok
0
 

Author Comment

by:JCWEBHOST
ID: 33462368
   protected void showMessageBox(string message)
    {
        string sScript;
        message = message.Replace("'", "\'");
        sScript = String.Format("alert('{0}');", message);
        ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", sScript, true);
    }


i have found that this works but, in my title of my message box it say: " message from this page"
how can i can it?
0
 
LVL 6

Expert Comment

by:Neeraj Soni
ID: 33462384
this could be an issue of special chars in your string to be displayed.

When you pass a string to any JS function, do encode/encrypt the string otherwise chars like single quote or double quote will create problem. for example:


from serverside, you have assigned value to hidden var
    hdnName.Value = "'" + "I'am " + name + "'";     //inJS the value will be like this 'I'am Adam'

and in client side JS, you call a function:
    alert(document.getElementById("hdnName").value);

you will get an error  Input string was not in a correct format.

check if this is the case in your app also. if so, then you have to escape the chars.
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462401
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462416
here's the code.
change the title of the messagebox (replace "ClientScript" with whatever u like).
public static void MessageBox(string MyMessage)
{
//This method pops a message box onto the screen to display whatever
//text you pass into the method via the input parameter.
string ScriptString = "alert('" + MyMessage + "');";

System.Web.UI.Page page = HttpContext.Current.Handler as System.Web.UI.Page;
page.ClientScript.RegisterStartupScript(typeof(System.Web.UI.Page), "ClientScript", ScriptString, true);

}

Open in new window

0
 

Author Comment

by:JCWEBHOST
ID: 33462486
 it does not seem to be working, nothing is been displayed?

  public static void showMessageBox(string MyMessage)
    {
        string ScriptString = "alert('" + MyMessage + "');";

        System.Web.UI.Page page = HttpContext.Current.Handler as System.Web.UI.Page;
        page.ClientScript.RegisterStartupScript(typeof(System.Web.UI.Page), "Household Realty", ScriptString, true);

    }
0
 

Author Comment

by:JCWEBHOST
ID: 33462528
its still not changing?

why?

and it does not work for anysc postback trigger only displaying for postback with out the title been changed.
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462544
try:

public static void showMessageBox(string MyMessage)
{
System.Web.UI.Page page = HttpContext.Current.Handler as System.Web.UI.Page;
page .ClientScript.RegisterStartupScript(typeof(System.Web.UI.Page), "Household", "<script
language='JavaScript'>alert('" + MyMessage + "');", true);
}
0
 

Author Comment

by:JCWEBHOST
ID: 33462598
nope nothing is been displayed now
0
 

Author Comment

by:JCWEBHOST
ID: 33462622
theres no error to, why?
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33462642
that should work:

protected void showMessageBox(string message)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Household Realty", "alert('" + message + "');", true);
}
0
 

Author Comment

by:JCWEBHOST
ID: 33462665
it's working but "Household Realty", still not displaying
0
 
LVL 42

Expert Comment

by:sedgwick
ID: 33463170
no title at all?
0
 

Author Comment

by:JCWEBHOST
ID: 33463421
nope just says: message from web page
0
 
LVL 42

Accepted Solution

by:
sedgwick earned 500 total points
ID: 33463537
it seems that the title of the alert box cannot be changed.
you would have to create a custom messagebox to accomplish this.
check this post:
http://www.acejs.com/scriptsfolder/121015/121015.html
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now