Exemple #1
0
        private async Task <SessionCreatedParameters> CreateSession()
        {
            ConnectionDetails details = new ConnectionDetails()
            {
                UserName     = "******",
                Password     = "******",
                DatabaseName = "msdb",
                ServerName   = "serverName"
            };

            SessionCreatedParameters sessionResult = null;

            serviceHostMock.AddEventHandling(CreateSessionCompleteNotification.Type, (et, p) => sessionResult = p);
            CreateSessionResponse result = default(CreateSessionResponse);
            var contextMock = RequestContextMocks.Create <CreateSessionResponse>(r => result = r).AddErrorHandling(null);

            connectionServiceMock.Setup(c => c.Connect(It.IsAny <ConnectParams>()))
            .Returns((ConnectParams connectParams) => Task.FromResult(GetCompleteParamsForConnection(connectParams.OwnerUri, details)));

            ConnectionInfo connectionInfo       = new ConnectionInfo(null, null, null);
            string         fakeConnectionString = "Data Source=server;Initial Catalog=database;Integrated Security=False;User Id=user";

            connectionInfo.AddConnection("Default", new SqlConnection(fakeConnectionString));
            connectionServiceMock.Setup((c => c.TryFindConnection(It.IsAny <string>(), out connectionInfo))).
            OutCallback((string t, out ConnectionInfo v) => v = connectionInfo)
            .Returns(true);

            connectionServiceMock.Setup(c => c.Disconnect(It.IsAny <DisconnectParams>())).Returns(true);
            await service.HandleCreateSessionRequest(details, contextMock.Object);

            await service.CreateSessionTask;

            return(sessionResult);
        }
Exemple #2
0
        private async Task <CreateSessionResponse> CreateSessionAsyncInternalAsync(
            Context context,
            string name,
            string cacheName,
            ImplicitPin implicitPin,
            string?serializedConfig,
            string?pat)
        {
            Func <Task <CreateSessionResponse> > func = async() =>
            {
                var request = new CreateSessionRequest
                {
                    CacheName    = cacheName,
                    SessionName  = name,
                    ImplicitPin  = (int)implicitPin,
                    TraceId      = context.TraceId,
                    Capabilities = (int)_clientCapabilities,
                    // Protobuff does not support setting null values.
                    SerializedConfig = serializedConfig ?? string.Empty,
                    Pat = pat ?? string.Empty
                };

                return(await CreateSessionAsync(request));
            };

            CreateSessionResponse response = await SendGrpcRequestAsync(context, func);

            return(response);
        }
Exemple #3
0
 private Task <Result <SessionData> > CreateSessionDataAsync(
     OperationContext context,
     string name,
     string cacheName,
     ImplicitPin implicitPin,
     bool isReconnect)
 {
     return(context.PerformOperationAsync(
                Tracer,
                async() =>
     {
         CreateSessionResponse response = await CreateSessionAsyncInternalAsync(context, name, cacheName, implicitPin);
         if (string.IsNullOrEmpty(response.ErrorMessage))
         {
             SessionData data = new SessionData(response.SessionId, new DisposableDirectory(FileSystem, new AbsolutePath(response.TempDirectory)));
             return new Result <SessionData>(data);
         }
         else
         {
             return new Result <SessionData>(response.ErrorMessage);
         }
     },
                traceOperationStarted: true,
                extraStartMessage: $"Reconnect={isReconnect}",
                extraEndMessage: r => $"Reconnect={isReconnect}, SessionId={(r ? r.Value!.SessionId.ToString() : "Error")}"
                ));
 }
        private void OnCreateSessionSucceded(CreateSessionResponse response)
        {
            Debug.Log("Create session succeded");
            UserInfo.gameId = response.game_id.ToString();

            SceneManager.LoadScene("Logical Gates Game");
        }
Exemple #5
0
        internal async Task HandleCreateSessionRequest(ConnectionDetails connectionDetails, RequestContext <CreateSessionResponse> context)
        {
            try
            {
                Logger.Write(LogLevel.Verbose, "HandleCreateSessionRequest");
                Func <Task <CreateSessionResponse> > doCreateSession = async() =>
                {
                    Validate.IsNotNull(nameof(connectionDetails), connectionDetails);
                    Validate.IsNotNull(nameof(context), context);
                    return(await Task.Factory.StartNew(() =>
                    {
                        string uri = GenerateUri(connectionDetails);

                        return new CreateSessionResponse {
                            SessionId = uri
                        };
                    }));
                };

                CreateSessionResponse response = await HandleRequestAsync(doCreateSession, context, "HandleCreateSessionRequest");

                if (response != null)
                {
                    RunCreateSessionTask(connectionDetails, response.SessionId);
                }
            }
            catch (Exception ex)
            {
                await context.SendError(ex.ToString());
            }
        }
Exemple #6
0
        /// <summary>
        /// Login an Ampla users using username and password
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public AmplaUser SimpleLogin(string userName, string password, out string message)
        {
            message = null;
            AmplaUser user = amplaUserStore.GetUserByName(userName);

            if (user != null)
            {
                user = Renew(user);
            }

            if (user == null)
            {
                CreateSessionRequest request = new CreateSessionRequest {
                    Username = userName, Password = password
                };

                Exception             exception;
                CreateSessionResponse response = CatchExceptions(() => securityWebService.CreateSession(request), out exception);
                if (response != null)
                {
                    user = new AmplaUser(response.Session.User, response.Session.SessionID, true, "Username/Password");
                    amplaUserStore.StoreUser(user);
                }

                if (user == null)
                {
                    message = exception.Message;
                }
            }

            return(user);
        }
Exemple #7
0
        public AmplaUser IntegratedLogin(out string message)
        {
            message = null;
            AmplaUser user = FindCurrentUser();

            if (user != null)
            {
                user = Renew(user);
            }

            if (user == null)
            {
                CreateSessionRequest request = new CreateSessionRequest();

                Exception             exception;
                CreateSessionResponse response = CatchExceptions(() => securityWebService.CreateSession(request), out exception);
                if (response != null)
                {
                    user = new AmplaUser(response.Session.User, response.Session.SessionID, true, "Integrated");
                    amplaUserStore.StoreUser(user);
                }

                if (user == null)
                {
                    message = exception.Message;
                }
            }

            return(user);
        }
Exemple #8
0
        private async Task <SessionCreatedParameters> CreateSession()
        {
            SessionCreatedParameters sessionResult = null;

            serviceHostMock.AddEventHandling(CreateSessionCompleteNotification.Type, (et, p) => sessionResult = p);
            CreateSessionResponse result = default(CreateSessionResponse);
            var contextMock = RequestContextMocks.Create <CreateSessionResponse>(r => result = r).AddErrorHandling(null);

            connectionServiceMock.Setup(c => c.Connect(It.IsAny <ConnectParams>()))
            .Returns((ConnectParams connectParams) => Task.FromResult(GetCompleteParamsForConnection(connectParams.OwnerUri, details)));

            ConnectionInfo connectionInfo = new ConnectionInfo(null, null, details);

            connectionInfo.AddConnection("Default", new SqlConnection(fakeConnectionString));
            connectionServiceMock.Setup((c => c.TryFindConnection(It.IsAny <string>(), out connectionInfo))).
            OutCallback((string t, out ConnectionInfo v) => v = connectionInfo)
            .Returns(true);

            connectionServiceMock.Setup(c => c.Disconnect(It.IsAny <DisconnectParams>())).Returns(true);
            await service.HandleCreateSessionRequest(details, contextMock.Object);

            await service.CreateSessionTask;

            return(sessionResult);
        }
        public static CreateSessionResponse Unmarshall(UnmarshallerContext context)
        {
            CreateSessionResponse createSessionResponse = new CreateSessionResponse();

            createSessionResponse.HttpResponse = context.HttpResponse;
            createSessionResponse.RequestId    = context.StringValue("CreateSession.RequestId");
            createSessionResponse.Session      = context.StringValue("CreateSession.Session");

            return(createSessionResponse);
        }
Exemple #10
0
    /// <summary>
    /// This method creates a Session for an outgoing call or message.
    /// </summary>
    private void CreateSession()
    {
        try
        {
            NameValueCollection parameters = new NameValueCollection();
            if (!string.IsNullOrEmpty(txtNumberToDial.Text))
            {
                parameters.Add("numberToDial", txtNumberToDial.Text);
            }
            if (!string.IsNullOrEmpty(txtNumberForFeature.Text))
            {
                parameters.Add("featurenumber", txtNumberForFeature.Text);
            }
            if (!string.IsNullOrEmpty(txtMessageToPlay.Text))
            {
                parameters.Add("messageToPlay", txtMessageToPlay.Text);
            }
            if (lstTemplate.SelectedValue != "")
            {
                parameters.Add("feature", lstTemplate.SelectedValue.ToString());
            }

            CreateSessionResponse responseObject = this.requestFactory.CreateSession(parameters);
            if (null != responseObject)
            {
                lblSessionId.Text = responseObject.Id;
                NameValueCollection displayParam = new NameValueCollection();
                displayParam.Add("id", responseObject.Id);
                displayParam.Add("success", responseObject.Success.ToString());
                this.DrawPanelForSuccess(pnlCreateSession, displayParam, string.Empty);
            }
            else
            {
                this.DrawPanelForFailure(pnlCreateSession, "Unable to create session.");
            }
        }
        catch (InvalidScopeException ise)
        {
            this.DrawPanelForFailure(pnlCreateSession, ise.Message);
        }
        catch (InvalidResponseException ire)
        {
            this.DrawPanelForFailure(pnlCreateSession, ire.Body);
        }
        catch (Exception ex)
        {
            this.DrawPanelForFailure(pnlCreateSession, ex.Message);
        }
    }
Exemple #11
0
        public async Task <IResponse> Process(IRequest request)
        {
            try
            {
                CreateSessionRequest  rq       = request as CreateSessionRequest;
                CreateSessionResponse response = new CreateSessionResponse();
                if (rq.SessionKey == string.Empty) //noSession
                {
                    ActorId userActorId = new ActorId(rq.UserId);
                    var     userProxy   = userActorId.Proxy <IUser>();
                    if (await userProxy.isCreatedAsync())
                    {
                        var SessionProxy = userActorId.Proxy <ISession>();
                        if (await SessionProxy.CreateSessionAsync(userActorId, ""))
                        {
                            await SessionProxy.SetUsedAsync();

                            response.SessionKey = await SessionProxy.GetSessionHashAsync();

                            response.Status = System.Net.HttpStatusCode.OK;
                        }
                        else
                        {
                            await SessionProxy.SetUsedAsync();

                            response.SessionKey = await SessionProxy.GetSessionHashAsync();

                            response.Status = System.Net.HttpStatusCode.OK;
                        }
                    }
                    else
                    {
                        response.Status     = System.Net.HttpStatusCode.Forbidden;
                        response.SessionKey = string.Empty;
                    }
                }
                else //Validate session
                {
                }
                return(await Task.FromResult(response));
            }
            catch (Exception E)
            {
                E.Log();
                ErrorResponse errorresponse = new ErrorResponse(E.Message);
                return(errorresponse);
            }
        }
Exemple #12
0
        private async Task <CreateSessionResponse> CreateSessionAsyncInternalAsync(
            Context context,
            string name,
            string cacheName,
            ImplicitPin implicitPin)
        {
            CreateSessionResponse response = await RunClientActionAndThrowIfFailedAsync(context, async() => await _client.CreateSessionAsync(
                                                                                            new CreateSessionRequest
            {
                CacheName    = cacheName,
                SessionName  = name,
                ImplicitPin  = (int)implicitPin,
                TraceId      = context.Id.ToString(),
                Capabilities = (int)_clientCapabilities
            }));

            return(response);
        }
Exemple #13
0
        /// <summary>
        /// Unmarshaller the response from the service to the response class.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
        {
            CreateSessionResponse response = new CreateSessionResponse();

            context.Read();
            int targetDepth = context.CurrentDepth;

            while (context.ReadAtDepth(targetDepth))
            {
                if (context.TestExpression("session", targetDepth))
                {
                    var unmarshaller = SessionDataUnmarshaller.Instance;
                    response.Session = unmarshaller.Unmarshall(context);
                    continue;
                }
            }

            return(response);
        }
Exemple #14
0
        public async Task <BoolResult> CreateSessionAsync(
            Context context,
            string name,
            string cacheName,
            ImplicitPin implicitPin)
        {
            var startupResult = await StartupAsync(context, 5000);

            if (!startupResult)
            {
                return(startupResult);
            }

            CreateSessionResponse response = await CreateSessionAsyncInternalAsync(context, name, cacheName, implicitPin);

            if (string.IsNullOrEmpty(response.ErrorMessage))
            {
                var         sessionId = response.SessionId;
                SessionData data      = new SessionData {
                    SessionId = sessionId, TemporaryDirectory = new DisposableDirectory(FileSystem, new AbsolutePath(response.TempDirectory))
                };
                SessionState = new SessionState(() => CreateSessionDataAsync(context, name, cacheName, implicitPin), data);

                // Send a heartbeat iff both the service can receive one and the service was told to expect one.
                if ((_serviceCapabilities & Capabilities.Heartbeat) != 0 &&
                    (_clientCapabilities & Capabilities.Heartbeat) != 0)
                {
                    _heartbeatTimer = new IntervalTimer(() => HeartbeatAsync(context, sessionId), _heartbeatInterval, message =>
                    {
                        Tracer.Debug(context, $"[{HeartbeatName}] {message}. OriginalSessionId={sessionId}");
                    });
                }

                Tracer.Info(context, $"Created a session with SessionId={sessionId}.");

                return(BoolResult.Success);
            }
            else
            {
                return(new BoolResult(response.ErrorMessage));
            }
        }
Exemple #15
0
        public async Task CreateSessionAsyncTest()
        {
            var waitHandle = new ManualResetEvent(false);
            CreateSessionResponse response = null;

            response = await(new CreateSessionRequest()
            {
                APIKey = TestConfiguration.ApiKey
            }).ExecuteAsync();
            waitHandle.Set();

            var isTimedOut = waitHandle.WaitOne(10000);

            Assert.IsTrue(isTimedOut, "Operation timed out.");
            Assert.IsNotNull(response, "Response cannot be null.");
            Assert.IsNotNull(response.Session, "Response.Session is null.");
            Assert.IsNotNull(response.Status, "Response.Status is null.");
            Console.WriteLine("Session token: {0}", response.Session.SessionKey);
            Console.WriteLine("Time taken: {0} seconds", response.TimeTaken);
        }
Exemple #16
0
        private async Task <CreateSessionResponse> CreateSessionAsyncInternalAsync(
            Context context,
            string name,
            string cacheName,
            ImplicitPin implicitPin)
        {
            Func <Task <CreateSessionResponse> > func = async() => await CreateSessionAsync(
                new CreateSessionRequest
            {
                CacheName    = cacheName,
                SessionName  = name,
                ImplicitPin  = (int)implicitPin,
                TraceId      = context.Id.ToString(),
                Capabilities = (int)_clientCapabilities
            });

            CreateSessionResponse response = await SendGrpcRequestAsync(context, func);

            return(response);
        }
Exemple #17
0
        /// <inheritdoc />
        public async Task <BoolResult> CreateSessionAsync(
            Context context,
            string name,
            string cacheName,
            ImplicitPin implicitPin)
        {
            var startupResult = await StartupAsync(context, 5000);

            if (!startupResult.Succeeded)
            {
                return(startupResult);
            }

            CreateSessionResponse response = await CreateSessionAsyncInternalAsync(context, name, cacheName, implicitPin);

            if (string.IsNullOrEmpty(response.ErrorMessage))
            {
                Task <ObjectResult <SessionData> > sessionFactory() => CreateSessionDataAsync(context, name, cacheName, implicitPin);

                SessionData data = new SessionData {
                    SessionId = response.SessionId, TemporaryDirectory = new DisposableDirectory(_fileSystem, new AbsolutePath(response.TempDirectory))
                };
                _sessionState = new SessionState(sessionFactory, data);

                // Send a heartbeat iff both the service can receive one and the service was told to expect one.
                if ((_serviceCapabilities & Capabilities.Heartbeat) != 0 &&
                    (_clientCapabilities & Capabilities.Heartbeat) != 0)
                {
                    _heartbeatTimer = new IntervalTimer(() => SendHeartbeatAsync(context), _heartbeatInterval, message =>
                    {
                        _tracer.Debug(context, $"[{HeartbeatName}] {message}");
                    });
                }

                return(new StructResult <int>(response.SessionId));
            }
            else
            {
                return(new StructResult <int>(response.ErrorMessage));
            }
        }
Exemple #18
0
        private async Task <ObjectResult <SessionData> > CreateSessionDataAsync(
            Context context,
            string name,
            string cacheName,
            ImplicitPin implicitPin)
        {
            CreateSessionResponse response = await CreateSessionAsyncInternalAsync(context, name, cacheName, implicitPin);

            if (string.IsNullOrEmpty(response.ErrorMessage))
            {
                SessionData data = new SessionData()
                {
                    SessionId = response.SessionId, TemporaryDirectory = new DisposableDirectory(FileSystem, new AbsolutePath(response.TempDirectory))
                };
                return(new ObjectResult <SessionData>(data));
            }
            else
            {
                return(new ObjectResult <SessionData>(response.ErrorMessage));
            }
        }
Exemple #19
0
        public async Task <CreateSessionResponse> CreateSessionAsync(CreateSessionRequest createSessionRequest)
        {
            UpdateRequestHeader(createSessionRequest, true, "CreateSession");
            CreateSessionResponse createSessionResponse = null;

            try
            {
                if (UseTransportChannel)
                {
                    var serviceResponse = await Task <IServiceResponse> .Factory.FromAsync(TransportChannel.BeginSendRequest, TransportChannel.EndSendRequest, createSessionRequest, null).ConfigureAwait(false);

                    if (serviceResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }
                    ValidateResponse(serviceResponse.ResponseHeader);
                    createSessionResponse = (CreateSessionResponse)serviceResponse;
                }
                else
                {
                    var createSessionResponseMessage = await Task <CreateSessionResponseMessage> .Factory.FromAsync(InnerChannel.BeginCreateSession, InnerChannel.EndCreateSession, new CreateSessionMessage(createSessionRequest), null).ConfigureAwait(false);

                    if (createSessionResponseMessage == null || createSessionResponseMessage.CreateSessionResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }
                    createSessionResponse = createSessionResponseMessage.CreateSessionResponse;
                    ValidateResponse(createSessionResponse.ResponseHeader);
                }
            }
            finally
            {
                RequestCompleted(createSessionRequest, createSessionResponse, "CreateSession");
            }
            return(createSessionResponse);
        }
    /// <summary>
    /// This method creates a Session for an outgoing call or message.
    /// </summary>
    private void CreateSession()
    {
        try
        {
            CreateSessionClass createSessionData = new CreateSessionClass();
            createSessionData.numberToDial = txtNumberToDial.Value;
            if (!string.IsNullOrEmpty(scriptType.Value))
            {
                createSessionData.feature = scriptType.Value.ToString();
            }
            else
            {
                createSessionData.feature = string.Empty;
            }
            createSessionData.messageToPlay = txtMessageToPlay.Value.ToString();
            createSessionData.featurenumber = txtNumber.Value.ToString();
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
                new System.Web.Script.Serialization.JavaScriptSerializer();

            string         requestParams = oSerializer.Serialize(createSessionData);
            string         createSessionResponse;
            HttpWebRequest createSessionRequestObject = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + "/rest/1/Sessions");
            createSessionRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken);

            createSessionRequestObject.Method      = "POST";
            createSessionRequestObject.ContentType = "application/json";
            createSessionRequestObject.Accept      = "application/json";

            UTF8Encoding encoding  = new UTF8Encoding();
            byte[]       postBytes = encoding.GetBytes(requestParams);
            createSessionRequestObject.ContentLength = postBytes.Length;

            Stream postStream = createSessionRequestObject.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            HttpWebResponse createSessionResponseObject = (HttpWebResponse)createSessionRequestObject.GetResponse();
            using (StreamReader createSessionResponseStream = new StreamReader(createSessionResponseObject.GetResponseStream()))
            {
                createSessionResponse = createSessionResponseStream.ReadToEnd();
                if (!string.IsNullOrEmpty(createSessionResponse))
                {
                    JavaScriptSerializer  deserializeJsonObject = new JavaScriptSerializer();
                    CreateSessionResponse deserializedJsonObj   = (CreateSessionResponse)deserializeJsonObject.Deserialize(createSessionResponse, typeof(CreateSessionResponse));
                    if (null != deserializedJsonObj)
                    {
                        sessionIdOfCreateSessionResponse  = deserializedJsonObj.id.ToString();
                        Session["CsharpRestfulsessionId"] = sessionIdOfCreateSessionResponse;
                        successOfCreateSessionResponse    = deserializedJsonObj.success.ToString();
                    }
                    else
                    {
                        createSessionErrorResponse = "Got response but not able to deserialize json" + createSessionResponse;
                    }
                }
                else
                {
                    createSessionErrorResponse = "Success response but with empty ad";
                }

                createSessionResponseStream.Close();
            }
        }
        catch (WebException we)
        {
            string errorResponse = string.Empty;

            try
            {
                using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                {
                    errorResponse = sr2.ReadToEnd();
                    sr2.Close();
                }
            }
            catch
            {
                errorResponse = "Unable to get response";
            }

            createSessionErrorResponse = errorResponse + Environment.NewLine + we.ToString();
        }
        catch (Exception ex)
        {
            createSessionErrorResponse = ex.ToString();
        }
    }
Exemple #21
0
        /// <summary cref="IServiceMessage.CreateResponse" />
        public object CreateResponse(IServiceResponse response)
        {
            CreateSessionResponse body = response as CreateSessionResponse;

            if (body == null)
            {
                body = new CreateSessionResponse();
                body.ResponseHeader = ((ServiceFault)response).ResponseHeader;
            }

            return new CreateSessionResponseMessage(body);
        }
Exemple #22
0
    /// <summary>
    /// This method creates a Session for an outgoing call or message.
    /// </summary>
    private void CreateSession()
    {
        try
        {
            CreateSessionClass createSessionData = new CreateSessionClass();
            createSessionData.numberToDial = txtNumberToDial.Text.ToString();
            if (lstTemplate.SelectedValue != "")
            {
                createSessionData.feature = lstTemplate.SelectedValue.ToString();
            }
            else
            {
                createSessionData.feature = string.Empty;
            }
            createSessionData.messageToPlay = txtMessageToPlay.Text.ToString();
            createSessionData.featurenumber = txtNumberForFeature.Text.ToString();
            System.Web.Script.Serialization.JavaScriptSerializer oSerializer =
                new System.Web.Script.Serialization.JavaScriptSerializer();

            string         requestParams = oSerializer.Serialize(createSessionData);
            string         createSessionResponse;
            HttpWebRequest createSessionRequestObject = (HttpWebRequest)System.Net.WebRequest.Create(string.Empty + this.endPoint + "/rest/1/Sessions");
            createSessionRequestObject.Headers.Add("Authorization", "Bearer " + this.accessToken);

            createSessionRequestObject.Method      = "POST";
            createSessionRequestObject.ContentType = "application/json";
            createSessionRequestObject.Accept      = "application/json";

            UTF8Encoding encoding  = new UTF8Encoding();
            byte[]       postBytes = encoding.GetBytes(requestParams);
            createSessionRequestObject.ContentLength = postBytes.Length;

            Stream postStream = createSessionRequestObject.GetRequestStream();
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            HttpWebResponse createSessionResponseObject = (HttpWebResponse)createSessionRequestObject.GetResponse();
            using (StreamReader createSessionResponseStream = new StreamReader(createSessionResponseObject.GetResponseStream()))
            {
                createSessionResponse = createSessionResponseStream.ReadToEnd();
                if (!string.IsNullOrEmpty(createSessionResponse))
                {
                    JavaScriptSerializer  deserializeJsonObject = new JavaScriptSerializer();
                    CreateSessionResponse deserializedJsonObj   = (CreateSessionResponse)deserializeJsonObject.Deserialize(createSessionResponse, typeof(CreateSessionResponse));
                    if (null != deserializedJsonObj)
                    {
                        lblSessionId.Text = deserializedJsonObj.id.ToString();
                        NameValueCollection displayParam = new NameValueCollection();
                        displayParam.Add("id", deserializedJsonObj.id);
                        displayParam.Add("success", deserializedJsonObj.success.ToString());
                        this.DrawPanelForSuccess(pnlCreateSession, displayParam, string.Empty);
                    }
                    else
                    {
                        this.DrawPanelForFailure(pnlCreateSession, "Got response but not able to deserialize json" + createSessionResponse);
                    }
                }
                else
                {
                    this.DrawPanelForFailure(pnlCreateSession, "Success response but with empty ad");
                }

                createSessionResponseStream.Close();
            }
        }
        catch (WebException we)
        {
            string errorResponse = string.Empty;

            try
            {
                using (StreamReader sr2 = new StreamReader(we.Response.GetResponseStream()))
                {
                    errorResponse = sr2.ReadToEnd();
                    sr2.Close();
                }
            }
            catch
            {
                errorResponse = "Unable to get response";
            }

            this.DrawPanelForFailure(pnlCreateSession, errorResponse + Environment.NewLine + we.ToString());
        }
        catch (Exception ex)
        {
            this.DrawPanelForFailure(pnlCreateSession, ex.ToString());
        }
    }
Exemple #23
0
 /// <summary>
 /// Initializes the message with the body.
 /// </summary>
 public CreateSessionResponseMessage(CreateSessionResponse CreateSessionResponse)
 {
     this.CreateSessionResponse = CreateSessionResponse;
 }
Exemple #24
0
        /// <summary>
        /// Invokes the CreateSession service.
        /// </summary>
        public IServiceResponse CreateSession(IServiceRequest incoming)
        {
            CreateSessionResponse response = null;

            CreateSessionRequest request = (CreateSessionRequest)incoming;

            NodeId sessionId = null;
            NodeId authenticationToken = null;
            double revisedSessionTimeout = 0;
            byte[] serverNonce = null;
            byte[] serverCertificate = null;
            EndpointDescriptionCollection serverEndpoints = null;
            SignedSoftwareCertificateCollection serverSoftwareCertificates = null;
            SignatureData serverSignature = null;
            uint maxRequestMessageSize = 0;

            response = new CreateSessionResponse();

            response.ResponseHeader = ServerInstance.CreateSession(
               request.RequestHeader,
               request.ClientDescription,
               request.ServerUri,
               request.EndpointUrl,
               request.SessionName,
               request.ClientNonce,
               request.ClientCertificate,
               request.RequestedSessionTimeout,
               request.MaxResponseMessageSize,
               out sessionId,
               out authenticationToken,
               out revisedSessionTimeout,
               out serverNonce,
               out serverCertificate,
               out serverEndpoints,
               out serverSoftwareCertificates,
               out serverSignature,
               out maxRequestMessageSize);

            response.SessionId                  = sessionId;
            response.AuthenticationToken        = authenticationToken;
            response.RevisedSessionTimeout      = revisedSessionTimeout;
            response.ServerNonce                = serverNonce;
            response.ServerCertificate          = serverCertificate;
            response.ServerEndpoints            = serverEndpoints;
            response.ServerSoftwareCertificates = serverSoftwareCertificates;
            response.ServerSignature            = serverSignature;
            response.MaxRequestMessageSize      = maxRequestMessageSize;

            return response;
        }
Exemple #25
0
        /// <summary>
        /// Initializes the message with a service fault.
        /// </summary>
        public CreateSessionResponseMessage(ServiceFault ServiceFault)
        {
            this.CreateSessionResponse = new CreateSessionResponse();

            if (ServiceFault != null)
            {
                this.CreateSessionResponse.ResponseHeader = ServiceFault.ResponseHeader;
            }
        }
Exemple #26
0
        public async Task <bool> StoreItem(BackupItem item, Stream source)
        {
            string path = Path.Combine(Folder, item.FullPath);

            if (item.FullPath.StartsWith("/"))
            {
                path = Path.Combine(Folder, item.FullPath.Substring(1));
            }

            var client = await Client.GetClient();

            using (HttpClient httpClient = new HttpClient())
            {
                CreateSessionResponse createSessionResponse = null;
                try
                {
                    CreateSessionRequest createSession = new CreateSessionRequest(item.Name);

                    HttpRequestMessage createSessionHttpRequest = new HttpRequestMessage(HttpMethod.Post, string.Format(API_URL, path));
                    createSessionHttpRequest.Content = new StringContent(JsonConvert.SerializeObject(createSession), Encoding.UTF8, "application/json");

                    await client.AuthenticateRequestAsync(createSessionHttpRequest);

                    HttpResponseMessage createSessionHttpResponse = await httpClient.SendAsync(createSessionHttpRequest);

                    string createSessionHttpResponseString = await createSessionHttpResponse.Content.ReadAsStringAsync();

                    createSessionResponse = JsonConvert.DeserializeObject <CreateSessionResponse>(createSessionHttpResponseString);
                }
                catch (Exception)
                {
                    // TODO: logging in providers
                    return(false);
                }

                try
                {
                    int    readSize = 0;
                    byte[] buffer   = new byte[327680 * 6];

                    while ((readSize = source.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        HttpRequestMessage uploadRequest = new HttpRequestMessage(HttpMethod.Put, createSessionResponse.UploadUrl);
                        uploadRequest.Content = new ByteArrayContent(buffer, 0, readSize);
                        uploadRequest.Content.Headers.Add("Content-Range", $"bytes {source.Position - readSize}-{source.Position - 1}/{source.Length}");

                        await client.AuthenticateRequestAsync(uploadRequest);

                        HttpResponseMessage uploadResponse = await httpClient.SendAsync(uploadRequest);

                        if (uploadResponse.StatusCode != HttpStatusCode.Accepted && uploadResponse.StatusCode != HttpStatusCode.Created)
                        {
                            throw new Exception(await uploadResponse.Content.ReadAsStringAsync());
                        }
                    }
                }
                catch (Exception)
                {
                    // TODO: send cleanup cmd to onedrive (https://docs.microsoft.com/en-us/onedrive/developer/rest-api/api/driveitem_createuploadsession)

                    // TODO: logging in providers
                    return(false);
                }
            }

            return(true);
        }
Exemple #27
0
 public BinderSession(CreateSessionResponse createSessionResponse)
 {
     _createSessionResponse = createSessionResponse;
 }
Exemple #28
0
        public void ProcessResponse(ClientGateResponse response)
        {
            _recievedResonses++;
            if (response.ResultCode == (int)HttpStatusCode.OK)
            {
                switch ((RequestProcessorEnum)response.Kind)
                {
                case RequestProcessorEnum.Session:
                {
                    CreateSessionResponse csresp = response.JsonPayload.Deserialize <CreateSessionResponse>();
                    if (csresp.Status == HttpStatusCode.OK)
                    {
                        _SessionKey = csresp.SessionKey;
                        m_client.Invoke("Map", _UserId.ToString());
                    }
                }
                break;

                case RequestProcessorEnum.UserExists:
                {
                    UserExistsResponse r = response.JsonPayload.Deserialize <UserExistsResponse>();
                    if (!r.Exists)
                    {
                        //Create user
                        CreateUserRequest cr = new CreateUserRequest();
                        cr.UserName = _UserName;
                        cr.Password = _Password;
                        m_client.Invoke("Exec", cr.CreateRequest(RequestProcessorEnum.CreateUser, _UserId).Serialize());
                    }
                    else
                    {
                        LoginUserRequest lr = new LoginUserRequest();
                        lr.UserName = _UserName;
                        lr.Password = _Password;
                        m_client.Invoke("Exec", lr.CreateRequest(RequestProcessorEnum.LoginUser, _UserId).Serialize());
                    }
                }
                break;

                case RequestProcessorEnum.CreateUser:
                    CreateUserResponse cresp = response.JsonPayload.Deserialize <CreateUserResponse>();
                    if (cresp.Sucessful)
                    {
                        _UserId = cresp.UserId;
                        CreateSessionRequest csesr = new CreateSessionRequest();
                        csesr.UserId     = _UserId;
                        csesr.SessionKey = string.Empty;
                        m_client.Invoke("Exec", csesr.CreateRequest(RequestProcessorEnum.Session, _UserId).Serialize());
                    }
                    break;

                case RequestProcessorEnum.LoginUser:
                {
                    LoginUserResponse lur = response.JsonPayload.Deserialize <LoginUserResponse>();
                    if (lur.Status == HttpStatusCode.OK)
                    {
                        _UserId = lur.UserId;
                        CreateSessionRequest csesr = new CreateSessionRequest();
                        csesr.UserId     = _UserId;
                        csesr.SessionKey = string.Empty;
                        m_client.Invoke("Exec", csesr.CreateRequest(RequestProcessorEnum.Session, _UserId).Serialize());
                    }
                }
                break;

                case RequestProcessorEnum.TankPosition:
                {
                    TankPosistionResponse tr = response.JsonPayload.Deserialize <TankPosistionResponse>();
                    if (OnActionTrack != null)
                    {
                        OnActionTrack(tr.TankId, new Vector3(tr.x, tr.y, tr.z), tr.r);
                    }
                }
                break;

                case RequestProcessorEnum.FireShell:
                {
                    FireShellResponse fr = response.JsonPayload.Deserialize <FireShellResponse>();
                    if (OnActionFire != null)
                    {
                        OnActionFire(new Vector3(fr.pos.x, fr.pos.y, fr.pos.z),
                                     new Quaternion(fr.rot.x, fr.rot.y, fr.rot.z, fr.rot.w),
                                     new Vector3(fr.vel.x, fr.vel.y, fr.vel.z));
                    }
                }
                break;

                case RequestProcessorEnum._System_MapConnection:
                {
                    //Map
                    _isMapped = true;
                }
                break;

                case RequestProcessorEnum.TakeDamage:
                {
                    TakeDamageResponse tdr = response.JsonPayload.Deserialize <TakeDamageResponse>();
                    if (OnActionSetDamage != null)
                    {
                        OnActionSetDamage(tdr.TankId, tdr.Health);
                    }
                }
                break;

                case RequestProcessorEnum.JoinOrCreateGame:
                {
                    //Join or create game session
                    JoinOrCreateGameSessionResponse jcr = response.JsonPayload.Deserialize <JoinOrCreateGameSessionResponse>();
                    //Test if to run or wait
                    _CurrentGameSessionId = jcr.GameSessionId;
                    if (jcr.start)
                    {
                        int cnt = jcr.SessionPlayers.Count;
                        if (OnStartSession != null)
                        {
                            OnStartSession(jcr.SessionPlayers);
                        }
                    }
                    else
                    {
                        //used for single instance debug
                        //Create second request and link to same session enable single instance tests
                        //JoinOrCreateGameSessionRequest jcrr = new JoinOrCreateGameSessionRequest();
                        //jcrr.UserId = _UserId;
                        //m_client.Invoke("Que", jcrr.CreateRequest( RequestProcessorEnum.JoinOrCreateGame, _UserId).Serialize());
                    }
                }
                break;

                case RequestProcessorEnum.StartRound:
                {
                    StartRoundResponse srr = response.JsonPayload.Deserialize <StartRoundResponse>();
                    if (OnStartRound != null)
                    {
                        OnStartRound(srr.TankId, srr.RoundNum);
                    }
                }
                break;

                case RequestProcessorEnum.BeginRound:
                {
                    BeginRounResponse brr = response.JsonPayload.Deserialize <BeginRounResponse>();
                    if (OnRoundBegins != null)
                    {
                        OnRoundBegins(brr.RoundNum);
                    }
                }
                break;

                case RequestProcessorEnum.GetCanStartRound:
                {
                    CanStartRoundResponse crr = response.JsonPayload.Deserialize <CanStartRoundResponse>();
                    if (OnRoundBegins != null)
                    {
                        OnRoundBegins(crr.RoundNum);
                    }
                }
                break;

                default:
                    break;
                }
            }
            if (response.Kind != (int)RequestProcessorEnum.TankPosition)
            {
                UnityEngine.Debug.Log(response.Kind.ToString() + " time:" + response.TimeTaken.ToString() + " total calls:" + _recievedResonses.ToString() + " Json:" + response.JsonPayload);
            }
            //UnityEngine.Debug.Log(response.Kind.ToString() + " time:" + response.TimeTaken.ToString() + " Json:" + response.JsonPayload);
        }