Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C# 4.0

Synchronous Web Service Calls with Silverlight: Dispelling the async-only myth

Rate me:
Please Sign up or sign in to vote.
4.95/5 (47 votes)
16 Nov 2008LGPL311 min read 424.4K   4K   81  
In this article, we look at the asynchronous web service model in Silverlight, and how it can be augmented to allow synchronous web service calls. We also explore efficient channel caching, and asynchronous Silverlight Unit Tests.
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:2.0.50727.3053
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

// 
// This code was auto-generated by Microsoft.Silverlight.ServiceReference, version 2.0.5.0
// 
namespace DanielVaughan.Silverlight.Examples.SimpleServiceReference {
    
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    [System.ServiceModel.ServiceContractAttribute(Namespace="DanielVaughan.Silverlight.Examples", ConfigurationName="SimpleServiceReference.ISimpleService")]
    public interface ISimpleService {
        
        [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="DanielVaughan.Silverlight.Examples/IServiceContract/ConnectFromClient", ReplyAction="DanielVaughan.Silverlight.Examples/IServiceContract/ConnectFromClientResponse")]
        System.IAsyncResult BeginConnectFromClient(string arbitraryIdentifier, System.AsyncCallback callback, object asyncState);
        
        string EndConnectFromClient(System.IAsyncResult result);
        
        [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="DanielVaughan.Silverlight.Examples/ISimpleService/GetGreeting", ReplyAction="DanielVaughan.Silverlight.Examples/ISimpleService/GetGreetingResponse")]
        System.IAsyncResult BeginGetGreeting(string name, System.AsyncCallback callback, object asyncState);
        
        string EndGetGreeting(System.IAsyncResult result);
    }
    
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public interface ISimpleServiceChannel : DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService, System.ServiceModel.IClientChannel {
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public partial class ConnectFromClientCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
        
        private object[] results;
        
        public ConnectFromClientCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
                base(exception, cancelled, userState) {
            this.results = results;
        }
        
        public string Result {
            get {
                base.RaiseExceptionIfNecessary();
                return ((string)(this.results[0]));
            }
        }
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public partial class GetGreetingCompletedEventArgs : System.ComponentModel.AsyncCompletedEventArgs {
        
        private object[] results;
        
        public GetGreetingCompletedEventArgs(object[] results, System.Exception exception, bool cancelled, object userState) : 
                base(exception, cancelled, userState) {
            this.results = results;
        }
        
        public string Result {
            get {
                base.RaiseExceptionIfNecessary();
                return ((string)(this.results[0]));
            }
        }
    }
    
    [System.Diagnostics.DebuggerStepThroughAttribute()]
    [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "3.0.0.0")]
    public partial class SimpleServiceClient : System.ServiceModel.ClientBase<DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService>, DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService {
        
        private BeginOperationDelegate onBeginConnectFromClientDelegate;
        
        private EndOperationDelegate onEndConnectFromClientDelegate;
        
        private System.Threading.SendOrPostCallback onConnectFromClientCompletedDelegate;
        
        private BeginOperationDelegate onBeginGetGreetingDelegate;
        
        private EndOperationDelegate onEndGetGreetingDelegate;
        
        private System.Threading.SendOrPostCallback onGetGreetingCompletedDelegate;
        
        private BeginOperationDelegate onBeginOpenDelegate;
        
        private EndOperationDelegate onEndOpenDelegate;
        
        private System.Threading.SendOrPostCallback onOpenCompletedDelegate;
        
        private BeginOperationDelegate onBeginCloseDelegate;
        
        private EndOperationDelegate onEndCloseDelegate;
        
        private System.Threading.SendOrPostCallback onCloseCompletedDelegate;
        
        public SimpleServiceClient() {
        }
        
        public SimpleServiceClient(string endpointConfigurationName) : 
                base(endpointConfigurationName) {
        }
        
        public SimpleServiceClient(string endpointConfigurationName, string remoteAddress) : 
                base(endpointConfigurationName, remoteAddress) {
        }
        
        public SimpleServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : 
                base(endpointConfigurationName, remoteAddress) {
        }
        
        public SimpleServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : 
                base(binding, remoteAddress) {
        }
        
        public event System.EventHandler<ConnectFromClientCompletedEventArgs> ConnectFromClientCompleted;
        
        public event System.EventHandler<GetGreetingCompletedEventArgs> GetGreetingCompleted;
        
        public event System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs> OpenCompleted;
        
        public event System.EventHandler<System.ComponentModel.AsyncCompletedEventArgs> CloseCompleted;
        
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
        System.IAsyncResult DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService.BeginConnectFromClient(string arbitraryIdentifier, System.AsyncCallback callback, object asyncState) {
            return base.Channel.BeginConnectFromClient(arbitraryIdentifier, callback, asyncState);
        }
        
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
        string DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService.EndConnectFromClient(System.IAsyncResult result) {
            return base.Channel.EndConnectFromClient(result);
        }
        
        private System.IAsyncResult OnBeginConnectFromClient(object[] inValues, System.AsyncCallback callback, object asyncState) {
            string arbitraryIdentifier = ((string)(inValues[0]));
            return ((DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService)(this)).BeginConnectFromClient(arbitraryIdentifier, callback, asyncState);
        }
        
        private object[] OnEndConnectFromClient(System.IAsyncResult result) {
            string retVal = ((DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService)(this)).EndConnectFromClient(result);
            return new object[] {
                    retVal};
        }
        
        private void OnConnectFromClientCompleted(object state) {
            if ((this.ConnectFromClientCompleted != null)) {
                InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
                this.ConnectFromClientCompleted(this, new ConnectFromClientCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
            }
        }
        
        public void ConnectFromClientAsync(string arbitraryIdentifier) {
            this.ConnectFromClientAsync(arbitraryIdentifier, null);
        }
        
        public void ConnectFromClientAsync(string arbitraryIdentifier, object userState) {
            if ((this.onBeginConnectFromClientDelegate == null)) {
                this.onBeginConnectFromClientDelegate = new BeginOperationDelegate(this.OnBeginConnectFromClient);
            }
            if ((this.onEndConnectFromClientDelegate == null)) {
                this.onEndConnectFromClientDelegate = new EndOperationDelegate(this.OnEndConnectFromClient);
            }
            if ((this.onConnectFromClientCompletedDelegate == null)) {
                this.onConnectFromClientCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnConnectFromClientCompleted);
            }
            base.InvokeAsync(this.onBeginConnectFromClientDelegate, new object[] {
                        arbitraryIdentifier}, this.onEndConnectFromClientDelegate, this.onConnectFromClientCompletedDelegate, userState);
        }
        
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
        System.IAsyncResult DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService.BeginGetGreeting(string name, System.AsyncCallback callback, object asyncState) {
            return base.Channel.BeginGetGreeting(name, callback, asyncState);
        }
        
        [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
        string DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService.EndGetGreeting(System.IAsyncResult result) {
            return base.Channel.EndGetGreeting(result);
        }
        
        private System.IAsyncResult OnBeginGetGreeting(object[] inValues, System.AsyncCallback callback, object asyncState) {
            string name = ((string)(inValues[0]));
            return ((DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService)(this)).BeginGetGreeting(name, callback, asyncState);
        }
        
        private object[] OnEndGetGreeting(System.IAsyncResult result) {
            string retVal = ((DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService)(this)).EndGetGreeting(result);
            return new object[] {
                    retVal};
        }
        
        private void OnGetGreetingCompleted(object state) {
            if ((this.GetGreetingCompleted != null)) {
                InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
                this.GetGreetingCompleted(this, new GetGreetingCompletedEventArgs(e.Results, e.Error, e.Cancelled, e.UserState));
            }
        }
        
        public void GetGreetingAsync(string name) {
            this.GetGreetingAsync(name, null);
        }
        
        public void GetGreetingAsync(string name, object userState) {
            if ((this.onBeginGetGreetingDelegate == null)) {
                this.onBeginGetGreetingDelegate = new BeginOperationDelegate(this.OnBeginGetGreeting);
            }
            if ((this.onEndGetGreetingDelegate == null)) {
                this.onEndGetGreetingDelegate = new EndOperationDelegate(this.OnEndGetGreeting);
            }
            if ((this.onGetGreetingCompletedDelegate == null)) {
                this.onGetGreetingCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnGetGreetingCompleted);
            }
            base.InvokeAsync(this.onBeginGetGreetingDelegate, new object[] {
                        name}, this.onEndGetGreetingDelegate, this.onGetGreetingCompletedDelegate, userState);
        }
        
        private System.IAsyncResult OnBeginOpen(object[] inValues, System.AsyncCallback callback, object asyncState) {
            return ((System.ServiceModel.ICommunicationObject)(this)).BeginOpen(callback, asyncState);
        }
        
        private object[] OnEndOpen(System.IAsyncResult result) {
            ((System.ServiceModel.ICommunicationObject)(this)).EndOpen(result);
            return null;
        }
        
        private void OnOpenCompleted(object state) {
            if ((this.OpenCompleted != null)) {
                InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
                this.OpenCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
            }
        }
        
        public void OpenAsync() {
            this.OpenAsync(null);
        }
        
        public void OpenAsync(object userState) {
            if ((this.onBeginOpenDelegate == null)) {
                this.onBeginOpenDelegate = new BeginOperationDelegate(this.OnBeginOpen);
            }
            if ((this.onEndOpenDelegate == null)) {
                this.onEndOpenDelegate = new EndOperationDelegate(this.OnEndOpen);
            }
            if ((this.onOpenCompletedDelegate == null)) {
                this.onOpenCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnOpenCompleted);
            }
            base.InvokeAsync(this.onBeginOpenDelegate, null, this.onEndOpenDelegate, this.onOpenCompletedDelegate, userState);
        }
        
        private System.IAsyncResult OnBeginClose(object[] inValues, System.AsyncCallback callback, object asyncState) {
            return ((System.ServiceModel.ICommunicationObject)(this)).BeginClose(callback, asyncState);
        }
        
        private object[] OnEndClose(System.IAsyncResult result) {
            ((System.ServiceModel.ICommunicationObject)(this)).EndClose(result);
            return null;
        }
        
        private void OnCloseCompleted(object state) {
            if ((this.CloseCompleted != null)) {
                InvokeAsyncCompletedEventArgs e = ((InvokeAsyncCompletedEventArgs)(state));
                this.CloseCompleted(this, new System.ComponentModel.AsyncCompletedEventArgs(e.Error, e.Cancelled, e.UserState));
            }
        }
        
        public void CloseAsync() {
            this.CloseAsync(null);
        }
        
        public void CloseAsync(object userState) {
            if ((this.onBeginCloseDelegate == null)) {
                this.onBeginCloseDelegate = new BeginOperationDelegate(this.OnBeginClose);
            }
            if ((this.onEndCloseDelegate == null)) {
                this.onEndCloseDelegate = new EndOperationDelegate(this.OnEndClose);
            }
            if ((this.onCloseCompletedDelegate == null)) {
                this.onCloseCompletedDelegate = new System.Threading.SendOrPostCallback(this.OnCloseCompleted);
            }
            base.InvokeAsync(this.onBeginCloseDelegate, null, this.onEndCloseDelegate, this.onCloseCompletedDelegate, userState);
        }
        
        protected override DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService CreateChannel() {
            return new SimpleServiceClientChannel(this);
        }
        
        private class SimpleServiceClientChannel : ChannelBase<DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService>, DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService {
            
            public SimpleServiceClientChannel(System.ServiceModel.ClientBase<DanielVaughan.Silverlight.Examples.SimpleServiceReference.ISimpleService> client) : 
                    base(client) {
            }
            
            public System.IAsyncResult BeginConnectFromClient(string arbitraryIdentifier, System.AsyncCallback callback, object asyncState) {
                object[] _args = new object[1];
                _args[0] = arbitraryIdentifier;
                System.IAsyncResult _result = base.BeginInvoke("ConnectFromClient", _args, callback, asyncState);
                return _result;
            }
            
            public string EndConnectFromClient(System.IAsyncResult result) {
                object[] _args = new object[0];
                string _result = ((string)(base.EndInvoke("ConnectFromClient", _args, result)));
                return _result;
            }
            
            public System.IAsyncResult BeginGetGreeting(string name, System.AsyncCallback callback, object asyncState) {
                object[] _args = new object[1];
                _args[0] = name;
                System.IAsyncResult _result = base.BeginInvoke("GetGreeting", _args, callback, asyncState);
                return _result;
            }
            
            public string EndGetGreeting(System.IAsyncResult result) {
                object[] _args = new object[0];
                string _result = ((string)(base.EndInvoke("GetGreeting", _args, result)));
                return _result;
            }
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Engineer
Switzerland Switzerland
Daniel is a former senior engineer in Technology and Research at the Office of the CTO at Microsoft, working on next generation systems.

Previously Daniel was a nine-time Microsoft MVP and co-founder of Outcoder, a Swiss software and consulting company.

Daniel is the author of Windows Phone 8 Unleashed and Windows Phone 7.5 Unleashed, both published by SAMS.

Daniel is the developer behind several acclaimed mobile apps including Surfy Browser for Android and Windows Phone. Daniel is the creator of a number of popular open-source projects, most notably Codon.

Would you like Daniel to bring value to your organisation? Please contact

Blog | Twitter


Xamarin Experts
Windows 10 Experts

Comments and Discussions