Skip to main content

Microsoft Silverlight

Answered Question Can't make WCF service calls during Application Exit?RSS Feed

(0)

Eric Willeke
Eric Wil...

Member

Member

34 points

28 Posts

Can't make WCF service calls during Application Exit?

I've subscribed an event to the application exit event as follows:
            Application.Current.Exit += new EventHandler(Application_Exit);

I've then implemented that method to perform a single WCF call to my service, essentially saving the user's most recent work. However, this call is not making it to the server in either IE or FF using Silverlight 2.0 beta 2. The same call works flawlessly any time other than during exit.

  1. Is there a better point to intercept in order to make this call?
  2. Is it being blocked by browser security or something in Silverlight?
  3. Does anybody see a solution that does not involve preventing them from leaving the page using one of the various "Are you sure you want to exit?" approaches that have been posted lately?


 

IlkkaP
IlkkaP

Member

Member

129 points

26 Posts

Re: Can't make WCF service calls during Application Exit?

As the documentation states "An Exit event handler should not include long-running, re-entrant, or cyclic code, such as resetting the Silverlight plug-in control's Source property", I'd expect that async calls are out of question.

 If you need to store user's work, you might consider to use isolated storage, and when user comes back, upload it to the server. Isolated storage works in app.exit event.

Hope it helps.

Ilkka

 

 


Ilkka
-----------------------------
http://developer.trilogica.it

Eric Willeke
Eric Wil...

Member

Member

34 points

28 Posts

Re: Can't make WCF service calls during Application Exit?

I appreciate the long-running issues, but I'm not looking for any sort of response, I just want to fire a dispatch. Is there some way to make the call "OneWay" or no-reply? Isolated storage wouldn't really apply in this case since there's a good chance that the user may use a different computer on the next visit.

 

Allen Chen – MSFT
Allen Ch...

Star

Star

13873 points

1,803 Posts

Answered Question

Re: Can't make WCF service calls during Application Exit?

Hi:

  This feature request has been logged. I'll update here if any new information is available.

Regards

Sincerely,
Allen Chen
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.

scgm11
scgm11

Member

Member

13 points

30 Posts

Re: Re: Can't make WCF service calls during Application Exit?

any update with this issue?? we are now in RTW.

 

Thanks

prujohn
prujohn

Contributor

Contributor

3579 points

704 Posts

Re: Re: Can't make WCF service calls during Application Exit?

I too am interested in this feature.

rajat.barik
rajat.barik

Member

Member

14 points

11 Posts

Re: Re: Can't make WCF service calls during Application Exit?

Well I am also looking for a answer for this kind of situation, Is there any way to call the database services or web services, if any user close the browser directly in silverlight application.

 Thanks for your reply in advanced.

neaflo
neaflo

Member

Member

45 points

35 Posts

Re: Re: Can't make WCF service calls during Application Exit?

I subscribe to this issue too. A logoff action invoking a web service on application exit is such a common scenario ... we must have a way to do this! I believe I could invoke the web service without using the proxy and use IAsyncResult for waiting for the call completion.

cce1911
cce1911

Member

Member

8 points

17 Posts

Re: Re: Re: Can't make WCF service calls during Application Exit?

I'm joining the club. I want to record a logout in my database when the user closes the browser.

sl_ananya
sl_ananya

Member

Member

16 points

21 Posts

Re: Re: Re: Can't make WCF service calls during Application Exit?

Any update on this feature??

kobruleht
kobruleht

Member

Member

162 points

584 Posts

Re: Re: Re: Can't make WCF service calls during Application Exit?

I'm also subscribing to this.

I need to track logged in users and thus execute web service call if user closes browser window.

Is it possible to send some sync notification to server like HTTP GET request in Exit event ?

 http://silverlight.net/forums/p/69833/168604.aspx#168604

 

SilverDK
SilverDK

Member

Member

6 points

11 Posts

Re: Re: Re: Can't make WCF service calls during Application Exit?

Any news on this ? This message thread is quite old and I am in this exact situation.

 

KurtJulius
KurtJulius

Member

Member

4 points

2 Posts

Re: Can't make WCF service calls during Application Exit?

Hi,

i need a solution for this problem too. Writing a silverlight/wcf application for my bachelor degree, it would be nice, if someone can help me out.

Allen Chen – MSFT
Allen Ch...

Star

Star

13873 points

1,803 Posts

Re: Can't make WCF service calls during Application Exit?

Just an update for this issue. Bad news is it's considered as by design because there is no mechenism to prevent a page from being unloaded. Good news is we probably can use XMLHttpRequest to workaround it.

http://www.w3schools.com/ajax/ajax_browsers.asp


 

Sincerely,
Allen Chen
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.

SilverDK
SilverDK

Member

Member

6 points

11 Posts

Re: Can't make WCF service calls during Application Exit?

Allen Chen – MSFT:

Just an update for this issue. Bad news is it's considered as by design because there is no mechenism to prevent a page from being unloaded. Good news is we probably can use XMLHttpRequest to workaround it.

http://www.w3schools.com/ajax/ajax_browsers.asp

 

 Could you give an example on how you can have a last contact with the WCF service on the silverlight application exit ?


Allen Chen – MSFT
Allen Ch...

Star

Star

13873 points

1,803 Posts

Re: Can't make WCF service calls during Application Exit?

Hi,

Instead of do that in Application_Exit we can call web service in the body's onunload event. Here's a sample:

aspx:

<%@ Page Language="C#" AutoEventWireup="true" %>

<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls"

TagPrefix="asp" %>

<!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" style="height:100%;">

<head runat="server">

<title>SilverlightApplication2</title>

<script type="text/javascript">

var block = true;

function onSuccess(result) {

block = false;

}

function Call() {

var obj = new WcfService1.IService1();

var q = obj.DoWork(onSuccess);while (block) { alert('Log to server.. Please wait..') }

}

 

 

</script> </head>

<body style="height:100%;margin:0;" onunload="Call();">

<form id="form1" runat="server" style="height:100%;" >

 

<asp:ScriptManager ID="ScriptManager1" runat="server">

<Services>

<asp:ServiceReference Path="~/Service1.svc" /></Services>

</asp:ScriptManager>

<div style="height:100%;">

<asp:Silverlight ID="Xaml1" runat="server" Source="~/ClientBin/SilverlightApplication2.xap" MinimumVersion="2.0.31005.0" Width="100%" Height="100%" />

</div>

 

 

</form> </body>

</html>

web.config:

<system.serviceModel>

<bindings>

<webHttpBinding>

<binding name="default"/>

</webHttpBinding>

</bindings>

<services>

<service name="WcfService1.Service1" behaviorConfiguration="MyServiceTypeBehaviors">

<endpoint address="" binding="webHttpBinding" bindingConfiguration="default" contract="WcfService1.IService1" behaviorConfiguration="webScriptEnablingBehavior"/>

</service>

</services>

<behaviors>

<endpointBehaviors>

<behavior name="webScriptEnablingBehavior">

<enableWebScript/>

</behavior>

</endpointBehaviors>

<serviceBehaviors>

<behavior name="MyServiceTypeBehaviors">

<serviceMetadata httpGetEnabled="true"/>

</behavior>

</serviceBehaviors>

</behaviors> <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>

</system.serviceModel>

Service1.svc.cs:

using System.ServiceModel.Activation;

using System.ServiceModel;

using System.IO;

using System;

namespace WcfService1

{

 

[
ServiceBehavior(IncludeExceptionDetailInFaults = true)] [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class Service1 : IService1

{

public void DoWork()

{

File.WriteAllText("C:\\1.txt", DateTime.Now.ToString() + "\r\n");

}

 

}

}

IService1.cs:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.Text;

using System.ServiceModel.Web;

namespace WcfService1

{

// NOTE: If you change the interface name "IService1" here, you must also update the reference to "IService1" in Web.config.

[ServiceContract(Namespace = "WcfService1")]

public interface IService1

{

[
WebGet]

[OperationContract]

void DoWork();

}

}

 

Sincerely,
Allen Chen
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help.

hyaki
hyaki

Member

Member

5 points

4 Posts

Re: Can't make WCF service calls during Application Exit?

Waw.. thanks for the sample... I have problem with the call.

The service i'm trying to call is required parameter. Could you kindly give me example with parameter call.

 

Thanks :)

TriumphOfTruth
TriumphO...

Member

Member

23 points

61 Posts

Re: Can't make WCF service calls during Application Exit?

Thanks for your workaround via the call through aspx. However my problem (as it seems many of those who contributed to this thread before) is that I need to save data which are stored within my silverlight control. So there are two question

- Is it possible at all to get these data from outside (which means from the aspx page) in order so send the to some place?

- And if this is possible, is it still possible in the unload event or is that too late?

As others had the same problem, I need to write the Logout information of the currently logged in user into my database that is talked to through the WCF service. So for this I need to send to my WCF service the currently logged in user as a parameter. Additionally I would like to save the latest data changes back to the backend.

NadineNDS
NadineNDS

Member

Member

7 points

10 Posts

Re: Re: Can't make WCF service calls during Application Exit?

I join the others. I also have to log off my users in the WCF Service with information inside the Silverlight part. Isn't there really another way?

Cheers.

Aaron Edwards
Aaron Ed...

Member

Member

39 points

61 Posts

Re: Can't make WCF service calls during Application Exit?

The workaround is actually quite simple, and only requires some basic browser integration:

  1. In the HTML, declare the Body tag as follows: <Body onBeforeUnload="pageUnloading();">
  2. Include the following JavaScript in your HTML: 
            var blocking = true;
    
            function pageUnloading() {
                var control = document.getElementById("<%= Xaml1.ClientID%>"); // Needed if you use master pages 
                control.content.Page.finalSave();
                while (blocking)
                    alert('Saving data to server');
            }
    
            function allowClose() {
                blocking = false;
            }
    
     
  3. Expose your Silverlight page to JavaScript by (1) decorating the class with the [ScriptableType()] attribute, and (2) in the SilverLight page's constructor or Page_Load event, register the page as follows: 
    HtmlPage.RegisterScriptableObject("Page", this); 
     
  4. Add the finalSave() method to your SilverLight page's code-behind and decorate it with the [ScriptableMember()] attribute.  Also add the completed method which will call the JavaScript allowClose() method: 
            [ScriptableMember()]
            public void finalSave()
            {
                proxy.saveDataAsync(currentObject);
            }
    
            void proxy_saveDataCompleted(object sender, saveDataCompletedEventArgs e)
            {
                // tells JavaScript to stop blocking
                HtmlPage.Window.CreateInstance("allowClose");
            }
That's pretty much it. Of course you'll need to register your proxy's saveDataCompleted event handler. I do that in the page's constructor.
 
What happens when the user tries to close the browser, or navigate away from the page is this:
  1. The browser fires the onBeforeUnload event which calls the pageUnloading() method.
  2. pageUnloading() calls the finalSave() method in your Silverlight Application. It also keeps displaying alert messages until the global JavaScript variable blocking is no longer set (in reality, it will probably only display this once, unless the WCF call is really, really slow).
  3. The SilverLight finalSave() method saves the data to the server using WCF. When the call returns, the SilverLight application uses browser integration to call the JavaScript allowClose() method.
  4. The JavaScript allowClose() method clears the blocking variable. Now, the next time the user clicks OK in the alert popup, the page is free to close.

Aaron

kobruleht
kobruleht

Member

Member

162 points

584 Posts

Re: Can't make WCF service calls during Application Exit?

Thank you. Questions:

1. This requires that html page is processed by asp.net since contains <%= tag. How to use it  in reqular html page, without asp net tag ?

2. How to modify this code so it works in OOB application also?

Andrus.

devisk
devisk

Member

Member

6 points

3 Posts

Re: Can't make WCF service calls during Application Exit?

Thank you Aaron,

I was also looking for a workaround to disconnect the client on closing the browser.

I tried your proposed solution and it does not seem to be working for me. First, I get an error while running the app at document.getElementById("<%= Xaml1.ClientID%>"); . What is supposed to be in the parameter?

Aaron Edwards
Aaron Ed...

Member

Member

39 points

61 Posts

Re: Can't make WCF service calls during Application Exit?

The use of document.getElementById("<%= Xaml1.ClientID%>") isn't required.  If you're using ASP.NET MasterPages or UserControls, it simplifies things a lot, because ASP will generate different ID's for the DOM-level objects at runtime.  For Example, if your SIlverlight control is located within a User Control, located within a MasterPage, the actual ID of the rendered Silverlight object might be something like MyMasterPage$MyUserControl$MySilverlightClient.  And of course that's the ID that the JavaScript getElementById function would have to find.

You can always hard code the ID directly into your JavaScript, as in document.getElementById("MyMasterPage$MyUserControl$MySilverlightClient").  Nothing wrong with that.  Just look at the source code from the rendered page and copy the ID from there.

Aaron

devisk
devisk

Member

Member

6 points

3 Posts

Re: Re: Can't make WCF service calls during Application Exit?

Thank you Aaron,

I was using the default test.aspx page created by Silverlight project. By default the "object" tag did not had the ID attribute so I added.

kobruleht
kobruleht

Member

Member

162 points

584 Posts

Re: Can't make WCF service calls during Application Exit?

Silverlight shows some exceptions javascript error handler in default page.

Can we use this method also to forward those errors to SL application which calls web method to store errors in server database for easy error tracking ?

Andrus.

Aaron Edwards
Aaron Ed...

Member

Member

39 points

61 Posts

Re: Can't make WCF service calls during Application Exit?

Sure, why not?

brauliod
brauliod

Participant

Participant

1169 points

472 Posts

Silverlight MVP

Re: Re: Can't make WCF service calls during Application Exit?

Hello,

 Has this been finally fixed on Silverlight 3.0?

 If not.. it would be a pain in the neck implementing an autosave functionallity. 

 Thanks

   Braulio

// ---------------------------------
    Braulio Diez

    http://www.dbschemaeditor.com
    Free Silverlight Based Database Schema Editor
/// ---------------------------------

Daze55
Daze55

Member

Member

227 points

111 Posts

Re: Re: Can't make WCF service calls during Application Exit?

Hello,
I have the necessity to decrease the number of connected users when the Silverlight application is closed.
I tried Aaron's solution and it worked BUT I absolutely need to get rid of the alert message, the web service must be called and the app must be close immediately whatever the result of the call, it must be 100% transparent to the user.
I tried everything and nothing worked, do you know how to allow the call to the web service without any "alert" message box ?

Aaron Edwards
Aaron Ed...

Member

Member

39 points

61 Posts

Re: Re: Can't make WCF service calls during Application Exit?

If you find a way to do it without the alert box, let us know.  I tried many different things, but nothing worked consistently.

Aaron

Daze55
Daze55

Member

Member

227 points

111 Posts

Re: Re: Can't make WCF service calls during Application Exit?

Actually Aaron I set my last hope in that forum.
I worked with my company Javascript most expert in order to solve the issue and we have not succeeded.
The problem is that Javascript is mono-thread and that we have no way to hold the application from closing and to let it work at the same time.
I really hope that something will be done for that in the next release because it's a rather serious issue IMHO.
How should I determine the number of connected user now, that’s a good question...

kobruleht
kobruleht

Member

Member

162 points

584 Posts

Re: Can't make WCF service calls during Application Exit?

Aaron solution issues/questions:

a. It works in IE only. How to make it work in all browsers ?

b. We need to show localized exit message according to user language.
How to pass custome message from silverlight application to alert box ?

c. if server or connection goes down, only way to close browser is use task manager.
How to add timeout so that if there is no response from server, alert box closes after some time?

Of cource, best solution would be to remove alert box.

Andrus

prujohn
prujohn

Contributor

Contributor

3579 points

704 Posts

Re: Can't make WCF service calls during Application Exit?

I recall that turbotax.com is able to do this somehow.  Whenever you are in a tax return and close the browser, they pop up another browser window that says "closing connection..." or something like that.  Then after a moment, that window closes as well.  Not sure if they are using ActiveX though...

  • Unanswered Question
  • Answered Question
  • Announcement
Microsoft Communities