Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

messagebox

Posted on 2010-08-18
31
Medium Priority
?
801 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Fill in the form and get your FREE NFR key NOW!

Veeam® is happy to provide a FREE NFR server license to certified engineers, trainers, and bloggers.  It allows for the non‑production use of Veeam Agent for Microsoft Windows. This license is valid for five workstations and two servers.

 
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
 
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 2000 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

DFW AZURE MEETUP TONIGHT FRI 6PM

We will be discussing what Azure Stack is, how does it fit into the suit of offerings that Azure has currently, and where can it fit into your organizations technology stack. We will also be discussing limitations of the platform while covering various applicable scenarios.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

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…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Video by: ITPro.TV
In this episode Don builds upon the troubleshooting techniques by demonstrating how to properly monitor a vSphere deployment to detect problems before they occur. He begins the show using tools found within the vSphere suite as ends the show demonst…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…

705 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