protected override void OnActionCompleted(IAsyncResult asyncResult, MyMasterServiceClient client)
        {
            Debug.Assert((EndAction != null && EndActionWait == null) || (EndAction == null && EndActionWait != null), "Set only one of EndAction, EndActionWait");

            if (EndActionWait != null)
            {
                var innerAction = EndActionWait(client, asyncResult);
                if (innerAction != null)
                {
                    innerAction.ActionSuccess += RaiseActionSuccess;
                    innerAction.ActionFailed += RaiseActionFailed;
                }
                else
                {
                    RaiseActionSuccess();
                }
            }
            else if (EndAction != null)
            {
                // When error occures, OnError is called
                EndAction(client, asyncResult);
                RaiseActionSuccess();
            }
            CloseScreen();
        }
 static void SafeClose()
 {
     try
     {
         if(m_instance != null) m_instance.Close();
     }
     catch (Exception) { }
     m_instance = null;
 }
        public static MyMasterServiceClient GetCheckedInstance()
        {
            Debug.Assert(HasCredentials, "Set credential prior getting instance method");

            if (m_instance == null || m_instance.State == CommunicationState.Faulted || m_instance.State == CommunicationState.Closed || m_instance.State == CommunicationState.Closing)
            {
                SafeClose();
                m_instance = CreateInstance();
            }
            return m_instance;
        }
        public static MyMasterServiceClient GetCheckedInstance()
        {
            Debug.Assert(HasCredentials, "Set credential prior getting instance method");

            if (m_instance == null || m_instance.State == CommunicationState.Faulted || m_instance.State == CommunicationState.Closed || m_instance.State == CommunicationState.Closing)
            {
                SafeClose();
                m_instance = CreateInstance();
            }
            return(m_instance);
        }
 static void SafeClose()
 {
     try
     {
         if (m_instance != null)
         {
             m_instance.Close();
         }
     }
     catch (Exception) { }
     m_instance = null;
 }
 void OnRegister(IAsyncResult result, MyMasterServiceClient client)
 {
     try
     {
         client.EndRegister(result);
         client.Close();
         HandleRegister();
     }
     catch (FaultException<MyRegistrationFault> fault)
     {
         HandleRegisterError(fault.Detail.ErrorCode);
     }
     catch (Exception exception)
     {
         client.Abort();
         MyMwcLog.WriteLine(exception);
         HandleRegisterError(MyMwcRegisterResponseResultEnum.UNKNOWN_ERROR);
     }
     CloseScreen();
 }
        private static MyMasterServiceClient CreateInstance()
        {
            var uri = String.Format("net.tcp://{0}:{1}", MyMwcFinalBuildConstants.MASTER_SERVER_ADDRESS, MyMwcNetworkingConstants.NETWORKING_PORT_MASTER_SERVER_NEW);

            MyMwcLog.WriteLine("Creating master service client, url: " + uri);

            // create the URI which is used as the service endpoint
            Uri tcpBaseAddress = new Uri(uri);

            if (MyFakes.TEST_DNS_UNAVAILABLE)
            {
                tcpBaseAddress = new Uri("d23>?<'12`/.,;'l,;l"); // Non sense URL
            }

            // create the net.tcp binding for the service endpoint
            NetTcpBinding ntcBinding = new NetTcpBinding();

            ntcBinding.Security.Mode                = SecurityMode.None;
            ntcBinding.MaxBufferPoolSize            = MyMwcNetworkingConstants.MAX_WCF_MESSAGE_POOL_SIZE;
            ntcBinding.MaxBufferSize                = MyMwcNetworkingConstants.MAX_WCF_MESSAGE_SIZE;
            ntcBinding.MaxConnections               = MyMwcNetworkingConstants.MAX_WCF_CONNECTIONS;
            ntcBinding.MaxReceivedMessageSize       = MyMwcNetworkingConstants.MAX_WCF_MESSAGE_SIZE;
            ntcBinding.ReaderQuotas.MaxArrayLength  = MyMwcNetworkingConstants.MAX_WCF_MESSAGE_SIZE;
            ntcBinding.ReaderQuotas.MaxBytesPerRead = MyMwcNetworkingConstants.MAX_WCF_MESSAGE_SIZE;
            ntcBinding.SendTimeout    = MyMwcNetworkingConstants.WCF_TIMEOUT_DISCONNECT;
            ntcBinding.ReceiveTimeout = MyMwcNetworkingConstants.WCF_TIMEOUT_DISCONNECT;
            ntcBinding.Security.Mode  = SecurityMode.Message;
            ntcBinding.Security.Message.ClientCredentialType   = MessageCredentialType.UserName;
            ntcBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            ntcBinding.Security.Transport.ProtectionLevel      = System.Net.Security.ProtectionLevel.None;

            var decoratedBinding = MyCustomBinding.DecorateBinding(ntcBinding);

            MyMasterServiceClient client = new MyMasterServiceClient(decoratedBinding, new EndpointAddress(tcpBaseAddress, EndpointIdentity.CreateDnsIdentity(MyMwcNetworkingConstants.WCF_MASTER_SERVER_CN)));

            client.ClientCredentials.UserName.UserName = m_username;
            client.ClientCredentials.UserName.Password = m_passwordHash;
            client.ClientCredentials.ServiceCertificate.Authentication.CustomCertificateValidator = new MyCertificateValidator(MyMwcNetworkingConstants.WCF_MASTER_SERVER_HASH);
            client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode  = System.ServiceModel.Security.X509CertificateValidationMode.Custom;
            return(client);
        }
        private static void OnSteamLoginEnd(MyMasterServiceClient client, IAsyncResult result, Action loginSuccessAction)
        {
            try
            {
                string username, token;
                if (MyMwcFinalBuildConstants.STEAM_DEMO)
                {
                    username = client.EndSteamDemoLogin(out token, result);
                }
                else
                {
                    username = client.EndSteamLogin(out token, result);
                }
                var screen = new MyGuiScreenLoginProgress(username, token, () =>
                    {
                        MyClientServer.LoggedPlayer.LoggedUsingSteam = true;
                        MyClientServer.LoggedPlayer.SetDisplayName(new StringBuilder(MySteam.UserName));
                        loginSuccessAction();
                    }, null);
                screen.CloseScreenBeforeCallingHandler = true;
                screen.PasswordHash = token;
                MyGuiManager.AddScreen(screen);

                m_loginInProgress = false;
            }
            catch (FaultException<MySteamFault> e)
            {
                if (e.Detail.SteamFaultCode == SteamFaultCode.NotRegistered)
                {
                    MyMasterServerAction registerAction = new MyMasterServerAction(MyTextsWrapperEnum.LoginInProgressPleaseWait);
                    registerAction.SetPublicCredentials();
                    if (String.IsNullOrEmpty(MySteam.SerialKey))
                    {
                        m_loginInProgress = false;
                        OnSteamRegisterError(new InvalidOperationException("Cannot obtain CD key from Steam"));
                    }
                    else
                    {
                        registerAction.BeginAction = (c) => c.BeginSteamRegister(MySteam.UserId, MySteam.SessionTicket, MySteam.SerialKey, MySteam.UserName, null, c);
                        registerAction.EndAction = (c, r) => c.EndSteamRegister(r);
                        registerAction.ActionSuccess += () => OnSteamRegister(loginSuccessAction);
                        registerAction.ActionFailed += OnSteamRegisterError;
                        registerAction.ShowErrorMessage = false;
                        registerAction.Start();
                    }
                }
                else if (e.Detail.SteamFaultCode == SteamFaultCode.NoMW1ProductsOwned)
                {
                    m_loginInProgress = false;
                    MyGuiManager.AddScreen(new MyGuiScreenMessageBox(MyMessageBoxType.ERROR, MyTextsWrapperEnum.SteamNoProductsText, MyTextsWrapperEnum.SteamNoProductsCaption, MyTextsWrapperEnum.Ok, null));
                }
                else if (e.Detail.SteamFaultCode == SteamFaultCode.InvalidTicket)
                {
                    m_loginInProgress = false;
                    MySteam.RefreshSessionTicket();
                    MyGuiManager.AddScreen(new MyGuiScreenMessageBox(MyMessageBoxType.ERROR, MyTextsWrapperEnum.SteamInvalidTicketText, MyTextsWrapperEnum.SteamInvalidTicketCaption, MyTextsWrapperEnum.Ok, null));
                }
                else
                {
                    m_loginInProgress = false;
                    throw;
                }
            }
            finally
            {
                m_loginInProgress = false;
            }
        }
 protected override void ServiceProgressStart(MyMasterServiceClient client)
 {
     AddAction(BeginAction(client));
 }
        protected override void OnError(Exception exception, MyMasterServiceClient client)
        {
            MyMwcLog.WriteLine(exception); // log exception

            if (EnableRetry)
            {
                ShowRetryDialog(exception);
            }
            else
            {
                RaiseActionFailed(exception);
                if (ShowErrorMessage)
                {
                    MyGuiManager.AddScreen(new MyGuiScreenMessageBox(MyMessageBoxType.ERROR, ErrorMessageText, ErrorCaptionText, MyTextsWrapperEnum.Ok, null));
                }
                CloseScreen();
                if (OnErrorReturnToMainMenu)
                {
                    MyGuiManager.BackToMainMenu();
                }
            }
        }
 protected override void ServiceProgressStart(MyMasterServiceClient client)
 {
     AddAction(client.BeginRegister(m_playerName, MyMwcUtils.GetHashedPassword(m_password), m_email, m_sendMeNewsletters, null, client), OnRegister);
 }
        private static MyMasterServiceClient CreateInstance()
        {
            var uri = String.Format("net.tcp://{0}:{1}", MyMwcFinalBuildConstants.MASTER_SERVER_ADDRESS, MyMwcNetworkingConstants.NETWORKING_PORT_MASTER_SERVER_NEW);

            MyMwcLog.WriteLine("Creating master service client, url: " + uri);

            // create the URI which is used as the service endpoint
            Uri tcpBaseAddress = new Uri(uri);

            if (MyFakes.TEST_DNS_UNAVAILABLE)
            {
                tcpBaseAddress = new Uri("d23>?<'12`/.,;'l,;l"); // Non sense URL
            }

            // create the net.tcp binding for the service endpoint
            NetTcpBinding ntcBinding = new NetTcpBinding();
            ntcBinding.Security.Mode = SecurityMode.None;
            ntcBinding.MaxBufferPoolSize = MyMwcNetworkingConstants.MAX_WCF_MESSAGE_POOL_SIZE;
            ntcBinding.MaxBufferSize = MyMwcNetworkingConstants.MAX_WCF_MESSAGE_SIZE;
            ntcBinding.MaxConnections = MyMwcNetworkingConstants.MAX_WCF_CONNECTIONS;
            ntcBinding.MaxReceivedMessageSize = MyMwcNetworkingConstants.MAX_WCF_MESSAGE_SIZE;
            ntcBinding.ReaderQuotas.MaxArrayLength = MyMwcNetworkingConstants.MAX_WCF_MESSAGE_SIZE;
            ntcBinding.ReaderQuotas.MaxBytesPerRead = MyMwcNetworkingConstants.MAX_WCF_MESSAGE_SIZE;
            ntcBinding.SendTimeout = MyMwcNetworkingConstants.WCF_TIMEOUT_DISCONNECT;
            ntcBinding.ReceiveTimeout = MyMwcNetworkingConstants.WCF_TIMEOUT_DISCONNECT;
            ntcBinding.Security.Mode = SecurityMode.Message;
            ntcBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            ntcBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            ntcBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.None;

            var decoratedBinding = MyCustomBinding.DecorateBinding(ntcBinding);

            MyMasterServiceClient client = new MyMasterServiceClient(decoratedBinding, new EndpointAddress(tcpBaseAddress, EndpointIdentity.CreateDnsIdentity(MyMwcNetworkingConstants.WCF_MASTER_SERVER_CN)));
            client.ClientCredentials.UserName.UserName = m_username;
            client.ClientCredentials.UserName.Password = m_passwordHash;
            client.ClientCredentials.ServiceCertificate.Authentication.CustomCertificateValidator = new MyCertificateValidator(MyMwcNetworkingConstants.WCF_MASTER_SERVER_HASH);
            client.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.Custom;
            return client;
        }