Solved

Getting a "web service is undefined" error when making JavaScript call to a web service.

Posted on 2010-09-08
16
1,448 Views
Last Modified: 2012-05-10
I have an ASP.NET application developed in Visual Studio 2008 with VB.net.
In this app I have a master page with a link on it that when clicked calls a JavaScript function named YourAre().  This function calls a web service named HelpService that returns a string of HTML.

The problem is that periodically but not always I will get an error message that says,
"Line: 54 Error: 'HelpService' is undefined"
 
This happens on both my development machine and the production machine.  This is an internal app and we use IE7 and 8, it happens with both.  I've attached the HTML and JavaScript for the master page and the VB for the web service.  Line 54 is where the error occurs, Line 153 of the HTML is where the reference to the web service is made and line 190 is where the link that calls the YourAre function is made.
It seems that sometimes the browser is not seeing the reference to the web service but if I look at the source of the page I can see it.  Any assistance with this would be greatly appreciated.

$(function()
{
    $("a").click(function()
    {
        window.onbeforeunload = null;
    });

//    $("input").click(function()
//    {
//        window.onbeforeunload = null;
//    });
});

function confirmExit() 
{
    return "\r\n                                                                                 YOU HAVE NOT LOG OFF CORRECTLY.\r\nPLEASE\ CLICK THE CANCEL BUTTON BELOW AND THEN LOG OFF BY CLICKING THE LOG OFF LINK IN THE PANEL ON THE LEFT OF THE SCREEN.\r\n";
}

function checkspell() 
{
    try 
    {
        var ieSpell = new ActiveXObject('ieSpell.ieSpellExtension');
        ieSpell.CheckAllLinkedDocuments(document);
    }
    catch (exception) 
    {
        if (exception == '[object Error]') 
        {
            document.write("The ieSpell spellchecker is not installed on your computer.  <strong>Call the IT help desk at 817-7200 and ")
            document.write("someone will help you install it.</strong> If you have not saved your changes click ")
            document.write("<a href= 'javascript:history.back()'>here</a> to return to the previous page.")
        }
        else 
        {
            document.write(exception)
        }
    }
}

var Message = ""
var MessageTitle
function YouAre() 
{
    if (MessageTitle == "You Are") 
    {
        $('div#divHelp').dialog("open")
    }
    else 
    {
            $get("ctl00_UpdateProgressButton").style.display = "block";
            $get("ctl00_UpdateProgressButton").style.visibility = "visible";
            $('div#divHelp').dialog("close")
            HelpService.YouAre(YouAreCallBack);
            var t = setTimeout("SetHelpDialog(100,200)", 2000);
    }
}

function YouAreCallBack(result) 
{
    if (result.substring(0,5) == "Error")
    {
        divHelp.title = result.substring(0, 5);
        MessageTitle = "Error";
    }
    else
    {
        divHelp.title = "You Are";
        MessageTitle = "You Are";
    }
        Message = result;
}

function SetHelpDialog(x, y) 
{
    divHelp.innerHTML = Message;
    
    $('div#divHelp').dialog({
        height: "auto",
        modal: true,
        overlay: { background: '#fff', opacity: '0.7'}
    });
    HelpDialog = $('div#divHelp');
    
    var TopDialogPadding = HelpDialog.parent().find('div.ui-dialog-content').css('padding-top').replace("px", "");
    var BottomDialogPadding = HelpDialog.parent().find('div.ui-dialog-content').css('padding-bottom').replace("px", "");
    var DialogPadding = (parseInt(TopDialogPadding) + parseInt(BottomDialogPadding));
    
    var TitleBarHeight = HelpDialog.parent().find('div.ui-dialog-titlebar').css('height').replace("px", "");
    
    var DialogTopMargin = parseInt($('div.ui-dialog').css("margin-top").replace("px", ""));
    var DialogBottomMargin = parseInt($('div.ui-dialog').css("margin-bottom").replace("px", ""));
    var DialogMargins = DialogTopMargin + DialogBottomMargin;
    
    var AdjustedContentHeight = $('#divMainContent').outerHeight() - DialogPadding - TitleBarHeight - DialogMargins;
    HelpDialog.css("max-height", (AdjustedContentHeight) + "px"); 
   
    var SideBarWidth = $('#divSideBar').outerWidth();
    var ContentWidth = $('#divMainContent').outerWidth();
    var HelpDialogWidth = HelpDialog.outerWidth();
    var xPosition = SideBarWidth + ((ContentWidth - HelpDialogWidth) / 2);
    
    var HeadersHeight = $('#divHeaderOne').outerHeight() + $('#divMenu').outerHeight() + $('#divHeaderTwo').outerHeight();
    var HelpDialogHeight = HelpDialog.outerHeight();
    var yPosition = HeadersHeight + (AdjustedContentHeight - HelpDialogHeight + DialogPadding) / 2;
    HelpDialog.dialog('option', 'position', [xPosition, yPosition]);
    if (yPosition == HeadersHeight)
    {
        HelpDialog.css("overflow", "scroll");
        HelpDialog.css("overflow-x", "hidden");
    }
    
    var divHelpInner = $("#divHelp > div");
    divHelpInner.css("float", "left");
    divHelpInner.css("width", divHelpInner.width());
    divHelpInner.css("float", "none");
    divHelpInner.css("text-align", "left");
    $get("ctl00_UpdateProgressButton").style.display = "none";
    alert(  "HeadersHeight = " + HeadersHeight +
            "\r\nAdjustedContentHeight = " + AdjustedContentHeight +
            "\r\nHelpDialogHeight = " + HelpDialogHeight + 
            "\r\nyPosition = " + yPosition +
            "\r\nContentHeight = " + $('#divMainContent').outerHeight() +
            "\r\nMax Height = " + HelpDialog.css("max-height") +
            "\r\nInner Div Height = " + divHelpInner.outerWidth());
}

<%@ Master Language="VB" CodeFile="ClientTrack.master.vb" Inherits="ClientTrack" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Site Master Page</title>
    <asp:ContentPlaceHolder id="head" runat="server"></asp:ContentPlaceHolder>
   
    <link href="~/Styles/Master.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/Dialog.css" rel="stylesheet" type="text/css" />

    <script src="/WebApps/ClientTrack3.5/js/jquery/jquery-1.4.2.js" type="text/javascript"></script>    
    <script src="/WebApps/ClientTrack3.5/js/jquery/jquery-1.4.2-vsdoc.js" type="text/javascript"></script>
    <script src="/WebApps/ClientTrack3.5/js/jquery/jQueryUI.js" type="text/javascript"></script>
    <script src="/WebApps/ClientTrack3.5/js/Master.js" type="text/javascript"></script>  
    <script type="text/javascript">
        window.onbeforeunload = confirmExit;
    </script>
    
</head>
<body>
    <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server">
            <Services>
                <asp:ServiceReference Path="~/WebServices/HelpService.asmx" />
            </Services>
        </asp:ScriptManager>
        <div id="divPageWrapper">
            <div id="divHeaderOne">
                <asp:Image runat="server" ID="HeaderImage" CssClass="HeaderOneImage" ImageUrl="~/Images/MasterHeader.gif"
                    AlternateText="Logo" />
            </div>
            <div id="divMenu">
                <asp:Menu CssClass="MainMenu" ID="MasterMenu" runat="server" DataSourceID="SiteMapDataSource1"
                    Orientation="Horizontal" StaticEnableDefaultPopOutImage="False">
                    <StaticSelectedStyle CssClass="StaticSelectedStyle" />
                    <StaticMenuItemStyle CssClass="StaticMenuItemStyle" ItemSpacing="0px" />
                    <StaticHoverStyle CssClass="StaticHoverStyle" />
                    <DynamicMenuStyle CssClass="DynamicMenuStyle" />
                    <DynamicMenuItemStyle CssClass="DynamicMenuItemStyle" />
                    <DynamicHoverStyle CssClass="DynamicHoverStyle" />
                </asp:Menu>
            </div>
            <div id="divHeaderTwo">
                <asp:Label ID="lblFormTitle" runat="server" Text="FormTitle"></asp:Label>
            </div>
            <div id="divHeaderThree">
                <asp:UpdatePanel ID="UpdatePanelDDL" runat="server">
                    <ContentTemplate>
                        Records For
                        <asp:DropDownList ID="ddlRecordsFor" runat="server" Width="150px" CssClass="RecordsFor" AutoPostBack="True">
                            <asp:ListItem>1</asp:ListItem>
                            <asp:ListItem>2</asp:ListItem>
                            <asp:ListItem>3</asp:ListItem>
                        </asp:DropDownList>
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
            <div id="divSideBar">
                <asp:LinkButton ID="LogOff" runat="server">Log Off</asp:LinkButton>
                <a id="SpellCheck" onclick="checkspell()">Spell Check</a><br />
                <a id="YouAre" onclick="YouAre()">You Are</a>
                <asp:HyperLink ID="YouCan" runat="server">You Can</asp:HyperLink>
                <asp:HyperLink ID="WhoCan" runat="server">Who Can</asp:HyperLink>
                <asp:HyperLink ID="HowCan" runat="server">How Can</asp:HyperLink>
                <asp:UpdateProgress ID="UpdateProgressButton" runat="server">
                    <ProgressTemplate>
                        <div class="Progress">
                        </div>
                        <br />
                        <div class="PleaseWait"> Please Wait...</div>
                    </ProgressTemplate>
                </asp:UpdateProgress>
            </div>
            <div id="divMainContent">
                <asp:ContentPlaceHolder ID="cp1" runat="server">
                    Under Construction
                </asp:ContentPlaceHolder>
            </div>
            <div id="divFooter">
                <asp:UpdatePanel ID="UpdatePanelButton" runat="server">
                    <ContentTemplate>
                        <asp:Button ID="btnDivideByZero" runat="server" Text="Divide by Zero" Width="125px" />
                        <asp:Button ID="btnPageNotFound" runat="server" Text="Page Not Found" Width="133px" />
                        <asp:Button ID="btnDatabaseError" runat="server" Text="Data base Error" Width="125px" />
                    </ContentTemplate>
                </asp:UpdatePanel>
            </div>
        </div>
        <div id="divHelp" visible="false"></div>
        <asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" ShowStartingNode="False" />
    </form>
</body>
</html>


Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://People-Inc.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class HelpService
    Inherits System.Web.Services.WebService

    <WebMethod(EnableSession:=True)> _
    Public Function YouAre() As String
       Dim CurrentUser As User = System.Web.HttpContext.Current.Session("CurrentUser")
        Try
            With CurrentUser
                Dim Title As String
                If .Title = "" Then
                    Title = "You have no title listed in Ultipro. To see more information on this topic click <a onclick=""DownLoadFile('http://Intranet/WebApps/ClientTrack3.5/Help/ClientTrackManual.pdf#ProgInfGeneral')"">here.</a>"
                Else
                    Title = .Title
                End If

                Dim JobDescription As String
                If .JobDescription = "" Then
                    JobDescription = "You have no Job Description listed in Ultipro. To see more information on this topic click <a onclick=""DownLoadFile('http://Intranet/WebApps/ClientTrack3.5/Help/ClientTrackManual.pdf#ProgInfGeneral')"">here.</a>"
                Else
                    JobDescription = .JobDescription
                End If

                Dim Supervisor As String
                If .Supervisor = "" Then
                    Supervisor = "You have no Supervisor listed in Ultipro."
                Else
                    Supervisor = .Supervisor
                End If

                Dim Programs As String
                If .Programs = "" Then
                    Programs = "There are no programs on the Program Information page for which you are listed as a staff. To see more information on this topic click <a onclick=""DownLoadFile('http://Intranet/WebApps/ClientTrack3.5/Help/ClientTrackManual.pdf#ProgInfGeneral')"">here.</a>"

                Else
                    Programs = .Programs
                End If

                Return String.Format("<u>YOU ARE:</u><br />{0} {1}<br /><br />" _
                                    & "<u>YOUR LOGIN NAME IS:</u><br />{2}<br /><br />" _
                                    & "<u>YOUR TITLE IS:</u><br />" & Title & "<br /><br />" _
                                    & "<u>YOUR JOB DESCRIPTION IS:</u><br />" & JobDescription & "<br /><br />" _
                                    & "<u>YOUR SUPERVISOR IS:</u><br />" _
                                    & "(If incorrect click " & "<a onclick=""DownLoadFile('http://Intranet/WebApps/ClientTrack3.5/Help/ClientTrackManual.pdf#ProgInfGeneral')"">here.</a>)<br />" _
                                    & "{5}<br /><br />" _
                                    & "<u>THE PROGRAM(S) YOU ARE A {6} FOR ARE:</u><br /><div >" & Programs & "</div>", _
                                    .FirstName, .LastName, _
                                    .UserName, _
                                    .Title, _
                                    .JobDescription, _
                                    .Supervisor, _
                                    .Title.ToUpper, _
                                    .Programs)
            End With
        Catch ex As Exception
            Return "Error<br />The following error has occurred in the You Are function of the Help Service Web Service<br /><br />'" & ex.Message & "'<br /><br />Copy and paste this message into an e-mail to the IT help desk or call the IT help desk and read this exact message to them."
        End Try
    End Function

End Class

Open in new window

0
Comment
Question by:leskelly
  • 11
  • 5
16 Comments
 
LVL 30

Expert Comment

by:MlandaT
ID: 33631811
I think you just need to fully qualify the web service reference.

Try changing this:

            HelpService.YouAre(YouAreCallBack);

to for example (assuming your web project/application is called WebApplication1):

            WebApplication1.HelpService.YouAre(YouAreCallBack);

==================================================================================================

For example... with a web service defined as:

namespace InterfaceTraining {
    [System.Web.Script.Services.ScriptService]
    [WebService(Namespace = "http://xmlforasp.net")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class CustomersService : System.Web.Services.WebService {

        [WebMethod]
        public Customer[] GetCustomersByCountry(string country)
        {
            return Biz.BAL.GetCustomersByCountry(country);
        }
    }
}

you would access this javascript object as:

    InterfaceTraining.CustomersService.GetCustomersByCountry(country, OnWSRequestComplete);

===================================================================================================

However, not that you do not necessarily need to include the "namespace InterfaceTraining". Your application typically creates a 'default' root namespace. If you right click on your project and go to properties and check on the Application tab, you will see root namespace. That is the namespace which you can use.

0
 

Author Comment

by:leskelly
ID: 33638308
Hello and thanks for your response.

The name of the Website is "ClientTrack3Point5" so I tried changing
HelpService.YouAre(YouAreCallBack); to
ClientTrack3Point5.HelpService.YouAre(YouAreCallBack);
but now I get the error
"Line: 54
Error: 'ClientTrack3Point5' is undefined"

Even if I didn't get this error I'm not sure if it would resolve my problem as, if I needed to fully qualify the web service reference wouldn't it fail every time and not just some of the time.  The odd thing is that in the same application I have another call to a web service that is set up the same way except it is run when the applications start but it never fails whereas this one that is only run after the page is completely rendered does fail.
0
 
LVL 30

Expert Comment

by:MlandaT
ID: 33638381
There have to be other differences between the webpages (maybe some additional Javascript). What happens if in this webpage you call the web service when the application starts as well... like you do on the 'other' page which is working? Do we get teh same error?
0
 

Author Comment

by:leskelly
ID: 33638401
Unfortunately I can't do that as the other service is what allows the user to login so until that is done the help service can be run.
0
 

Author Comment

by:leskelly
ID: 33638585
Actually I misstated what happens with the other web service.  A Jquery dialog automatically opens when the application starts and the only thing the user can do is enter their user name and password and click a button that runs the web service.  I'm going to examine the differences between the code that calls the services and see if I get any clues.  This would be a lot easier to figure out if the error happened every time.  Right now it's not happening.
0
 
LVL 30

Expert Comment

by:MlandaT
ID: 33638602
Well in that case there is little I can go by here. Perhaps there are javascript errors. I notice you have some lines not terminated by semi-colons (;). Can we fix all those up, and also cross check all your {}. It is not uncommon for Javascript errors to affect the creation of other Javascript objects on the same page.
0
 

Author Comment

by:leskelly
ID: 33641461
I've terminated each line withe a ; an checked the {} but I still get the error periodically.  I attached the JavaScript that calls the two web services but I don't see any significant difference between the two of them.

function Login(UserName, Password, Toggle)
{
    $get("ctl00_UpdateProgressButton").style.display = "block";
    $get("ctl00_UpdateProgressButton").style.visibility = "visible";
    LoginService.Login(UserName, Password, Toggle, LoginCallBack);
}

function YouAre() {

    if (MessageTitle == "You Are") 
    {
        $('div#divHelp').dialog("open");
    }
    else {
            $get("ctl00_UpdateProgressButton").style.display = "block";
            $get("ctl00_UpdateProgressButton").style.visibility = "visible";
            HelpService.YouAre(YouAreCallBack);
            var t = setTimeout("SetHelpDialog()", 2000);
    }
}

Open in new window

0
 
LVL 30

Expert Comment

by:MlandaT
ID: 33641585
"I still get the error periodically" am afraid I cannot help you further on this one... not sure why it would behave in that way. i can't quite think of anything that would cause that.
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 

Author Comment

by:leskelly
ID: 33641625
Thanks anyway I appreciate your efforts.
0
 

Author Comment

by:leskelly
ID: 33677341
I noticed that the problem only occurs if the link is clicked at the beginning of a session before navigating to another page.  I was then able to reproduce the problem by logging out of the application, deleting the cookie for the app and then logging back in.  As the issue only occurs if the user clicks on the link when first logging in I was able to come up with the following solution.  In the YourAre function I added a try catch block and if the error "'HelpService' is undefined" occurs  I set window.name to "Redo You are" and reload the page.  Then in the function that runs when the master page is loaded I added a test to see if window.name == "Redo You are".  if it does the HelpService web service is called again.  Because the page has been reloaded it runs now.  I've included the code below. It's certainly not the optimum solution so if anyone reading this has a better one I'd like to see it.
$(function() {
    if (window.name == "Redo You are") 
    {
        $get("ctl00_UpdateProgressButton").style.display = "block";
        $get("ctl00_UpdateProgressButton").style.visibility = "visible";
        try
        {
            HelpService.YouAre(YouAreCallBack);
            var t = setTimeout("SetHelpDialog()", 2000);
        }
        catch (e) {
            if (e.description == "'HelpService' is undefined") {
                alert("e.description = " + e.description);
            }
            else {
                alert("Exception = " + e.number + " " + e.description);
            }
        }
        window.name = "";
    }
});

var Message = "";
var MessageTitle;
function YouAre() {

    if (MessageTitle == "You Are") 
    {
        $('div#divHelp').dialog("open");
    }
    else {
            $get("ctl00_UpdateProgressButton").style.display = "block";
            $get("ctl00_UpdateProgressButton").style.visibility = "visible";
            try
            {
                HelpService.YouAre(YouAreCallBack);
                var t = setTimeout("SetHelpDialog()", 2000);
            }
            catch(e)
            {
                if (e.description == "'HelpService' is undefined") 
                {
                    window.onbeforeunload = null;
                    window.name = "Redo You are";
                    location = "/WebApps/ClientTrack3Point5/CoreInformation.aspx";
                }
                else
                {
                    alert("Exception = " + e.number + " " + e.description);
                }
            }
    }
}

Open in new window

0
 
LVL 30

Expert Comment

by:MlandaT
ID: 33679274
In that case how about disabling the link and only enabling it AFTER the document has finished loading and the DOM is ready... using the jQuery document.ready function... so by default the Link is visible, but disabled, then you enable it in the document ready function.

$(document).ready() or $( function(){} )
0
 

Author Comment

by:leskelly
ID: 33681725
That's an interesting idea but how do you disable and enable a link?
0
 

Author Comment

by:leskelly
ID: 33682671
I tried you suggestion but the same issue occurred which makes since as the problem happens after the link is clicked and the link isn't clicked until the page is totally rendered.  What I did was:
Remove the onlclick attribute of the link so that it is just
                <a id="YouAre">You Are</a>
Added the following JavaScript:
$(document).ready(function() {
    $("#YouAre").click(function() { YouAre(); });});
But as I said when I click on the link I get the same error.
0
 

Accepted Solution

by:
leskelly earned 0 total points
ID: 33684111
I found another solution.  While I was looking at this I remembered difference between the Login Service and the Help Service.  I had allowed anonymous access to the Login service in the web.config file.  This obviously had to be done as the user is not yet authenticated when logging in.  When I did the same for the Help service I no longer got the error.  The question is why does this happen only prior to the user navigating to another page and not after.  Even if they navigate back to the initial page it doesn't happen.
0
 

Author Comment

by:leskelly
ID: 33684425
I've re posted this question and restated it to more clearly reflect the problem.
0
 

Author Comment

by:leskelly
ID: 33684436
The ID for the new post is 26475473.
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
To properly understand GitHub, let’s divide it into two words ‘Git’ and ‘Hub’. Git is basically a ‘Distribution Version Control’ (DVC) and ‘Source Code Management’ (SCM) system widely used by software programmers while Hub means the efficient centre…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

743 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

11 Experts available now in Live!

Get 1:1 Help Now