Inheritance: AmazonLambdaRequest
示例#1
0
        public async Task <object> FunctionHandler(ILambdaContext context)
        {
            try
            {
                using (AmazonLambdaClient client = new AmazonLambdaClient(RegionEndpoint.APSoutheast1))
                {
                    var request = new Amazon.Lambda.Model.InvokeRequest
                    {
                        FunctionName = "test_call_rest_api",
                        Payload      = ""
                    };

                    var response = await client.InvokeAsync(request);

                    using (var sr = new StreamReader(response.Payload))
                    {
                        var unit = JsonConvert.DeserializeObject(sr.ReadToEndAsync().Result,
                                                                 new JsonSerializerSettings {
                            NullValueHandling = NullValueHandling.Ignore
                        });

                        return(unit);
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
示例#2
0
    public void UpdateRedis(bool serverTerminated = false)
    {
        var gameServerStatusData = new GameServerStatusData();

        gameServerStatusData.taskArn            = this.taskDataArnWithContainer;
        gameServerStatusData.currentPlayers     = this.server.GetPlayerCount();
        gameServerStatusData.maxPlayers         = Server.maxPlayers;
        gameServerStatusData.publicIP           = this.publicIP;
        gameServerStatusData.port               = Server.port;
        gameServerStatusData.serverTerminated   = serverTerminated;
        gameServerStatusData.gameSessionsHosted = Server.hostedGameSessions;

        var lambdaConfig = new AmazonLambdaConfig()
        {
            RegionEndpoint = this.regionEndpoint
        };

        lambdaConfig.MaxErrorRetry = 0; //Don't do retries on failures
        var lambdaClient = new Amazon.Lambda.AmazonLambdaClient(lambdaConfig);

        // Option 1. If TCPListener is not ready yet, update as not ready
        if (!this.server.IsReady())
        {
            Debug.Log("Updating as not ready yet to Redis");
            gameServerStatusData.ready       = false;
            gameServerStatusData.serverInUse = false;
        }
        // Option 2. If not full yet but, update our status as ready
        else if (this.server.IsReady() && this.server.GetPlayerCount() < Server.maxPlayers)
        {
            Debug.Log("Updating as ready to Redis");
            gameServerStatusData.ready       = true;
            gameServerStatusData.serverInUse = false;
        }
        // Option 3. If full, make sure the available key is deleted in Redis and update the full key
        else
        {
            Debug.Log("Updating as full to Redis");
            gameServerStatusData.ready       = true;
            gameServerStatusData.serverInUse = true;
        }

        // Call Lambda function to update status
        var request = new Amazon.Lambda.Model.InvokeRequest()
        {
            FunctionName   = "FargateGameServersUpdateGameServerData",
            Payload        = JsonConvert.SerializeObject(gameServerStatusData),
            InvocationType = InvocationType.Event
        };

        // NOTE: We could catch response to validate it was successful and do something useful with that information
        lambdaClient.InvokeAsync(request);
    }
示例#3
0
    private void HandleWaitingForTermination()
    {
        this.waitingForTerminateCounter += Time.deltaTime;
        // Check the status every 5 seconds
        if (waitingForTerminateCounter > 5.0f)
        {
            this.waitingForTerminateCounter = 0.0f;

            Debug.Log("Waiting for other servers in the Task to finish...");

            var lambdaConfig = new AmazonLambdaConfig()
            {
                RegionEndpoint = this.regionEndpoint
            };
            var lambdaClient = new Amazon.Lambda.AmazonLambdaClient(lambdaConfig);

            // Call Lambda function to check if we should terminate
            var taskStatusRequestData = new TaskStatusData();
            taskStatusRequestData.taskArn = this.taskDataArn;
            var request = new Amazon.Lambda.Model.InvokeRequest()
            {
                FunctionName   = "FargateGameServersCheckIfAllContainersInTaskAreDone",
                Payload        = JsonConvert.SerializeObject(taskStatusRequestData),
                InvocationType = InvocationType.RequestResponse
            };

            // As we are not doing anything else on the server anymore, we can just wait for the invoke response
            var invokeResponse = lambdaClient.InvokeAsync(request);
            invokeResponse.Wait();
            invokeResponse.Result.Payload.Position = 0;
            var sr             = new StreamReader(invokeResponse.Result.Payload);
            var responseString = sr.ReadToEnd();

            Debug.Log("Got response: " + responseString);

            // Try catching to boolean, if it was a failure, this will also result in false
            var allServersInTaskDone = false;
            bool.TryParse(responseString, out allServersInTaskDone);

            if (allServersInTaskDone)
            {
                Debug.Log("All servers in the Task done running full amount of sessions --> Terminate");
                Application.Quit();
            }
        }
    }
示例#4
0
文件: ChatPage.cs 项目: Un1XX388/LOSS
        async private Task LoadMessagesFromServer() //Function to create a Json object and send to server using a lambda function
        {
            try
            {
                UserInfoItem message = new UserInfoItem { Item = new MessageLst { ToFrom = Helpers.Settings.ToFromArn, Time = Constants.date.ToString("yyyy-MM-dd HH:mm:ss:ffff") } }; //Helpers.Settings.EndpointArnSetting
                UserInfoJson messageJson = new UserInfoJson { operation = "read", tableName = "Message", payload = message };
                string args = JsonConvert.SerializeObject(messageJson);
                var ir = new InvokeRequest()
                {
                    FunctionName = Constants.AWSLambdaID,
                    PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                    InvocationType = InvocationType.RequestResponse
                };

                InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
                resp.Payload.Position = 0;
                var sr = new StreamReader(resp.Payload);
                var myStr = sr.ReadToEnd();
                try
                {
                    System.Diagnostics.Debug.WriteLine("Returned Messages : " + myStr);
                    var response = JsonConvert.DeserializeObject<ConversationResponse>(myStr);
                    if (response.Success == "true")
                    {
                        var messages = response.MessageList;
                        messagesFromServer(messages);
                    }
                }
                catch (Exception e)
                {

                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error:" + e);
            }

        }
示例#5
0
文件: ChatPage.cs 项目: Un1XX388/LOSS
        //-------------------------Server----------------------------------
        async private Task PushMessage(string text) //Function to create a Json object and send to server using a lambda function
        {
            try
            {
                MessageItem message = new MessageItem { Item = new ChatMessage { ToFrom = Helpers.Settings.ToFromArn, Text = text } };
                MessageJson messageJson = new MessageJson { operation = "create", tableName = "Message", payload = message };
                string args = JsonConvert.SerializeObject(messageJson);
                //System.Diagnostics.Debug.WriteLine(args);
                var ir = new InvokeRequest()
                {
                    FunctionName = Constants.AWSLambdaID,
                    PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                    InvocationType = InvocationType.RequestResponse
                };
                //System.Diagnostics.Debug.WriteLine("Before invoke: " + ir.ToString());


                InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
                resp.Payload.Position = 0;
                var sr = new StreamReader(resp.Payload);
                var myStr = sr.ReadToEnd();

                //                System.Diagnostics.Debug.WriteLine("Status code: " + resp.StatusCode);
                //                System.Diagnostics.Debug.WriteLine("Response content: " + myStr);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error: " + e);
            }
        }
 private Amazon.Lambda.Model.InvokeResponse CallAWSServiceOperation(IAmazonLambda client, Amazon.Lambda.Model.InvokeRequest request)
 {
     Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS Lambda", "Invoke");
     try
     {
         #if DESKTOP
         return(client.Invoke(request));
         #elif CORECLR
         return(client.InvokeAsync(request).GetAwaiter().GetResult());
         #else
                 #error "Unknown build edition"
         #endif
     }
     catch (AmazonServiceException exc)
     {
         var webException = exc.InnerException as System.Net.WebException;
         if (webException != null)
         {
             throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
         }
         throw;
     }
 }
示例#7
0
        /**
         * Called when the end conversation button is pressed by the user
         * Generates request to server, which then terminates the conversation 
         * for both users.
         */
        async private Task terminateConversation()
        {
            //ID = is from ToFrom Field
            UserInfoItem message = new UserInfoItem { Item = new UserInfo { ID = Helpers.Settings.ToFromArn } }; //Helpers.Settings.EndpointArnSetting
            UserInfoJson messageJson = new UserInfoJson { operation = "stopConversation", tableName = "User", payload = message };
            string args = JsonConvert.SerializeObject(messageJson);
            System.Diagnostics.Debug.WriteLine("stopConversation: " + args);
            var ir = new InvokeRequest()
            {
                FunctionName = Constants.AWSLambdaID,
                PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                InvocationType = InvocationType.RequestResponse
            };


            InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
            resp.Payload.Position = 0;
            var sr = new StreamReader(resp.Payload);
            var myStr = sr.ReadToEnd();
            System.Diagnostics.Debug.WriteLine("stopConversation : " + myStr);
            Helpers.Settings.ToFromArn = "";
            Constants.conv.name = "";
            Constants.conv.id = "";
        }
示例#8
0
        internal InvokeResponse Invoke(InvokeRequest request)
        {
            var marshaller = new InvokeRequestMarshaller();
            var unmarshaller = InvokeResponseUnmarshaller.Instance;

            return Invoke<InvokeRequest,InvokeResponse>(request, marshaller, unmarshaller);
        }
示例#9
0
 /// <summary>
 /// Initiates the asynchronous execution of the Invoke operation.
 /// </summary>
 /// 
 /// <param name="request">Container for the necessary parameters to execute the Invoke operation on AmazonLambdaClient.</param>
 /// <param name="callback">An Action delegate that is invoked when the operation completes.</param>
 /// <param name="options">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
 ///          procedure using the AsyncState property.</param>
 public void InvokeAsync(InvokeRequest request, AmazonServiceCallback<InvokeRequest, InvokeResponse> callback, AsyncOptions options = null)
 {
     options = options == null?new AsyncOptions():options;
     var marshaller = new InvokeRequestMarshaller();
     var unmarshaller = InvokeResponseUnmarshaller.Instance;
     Action<AmazonWebServiceRequest, AmazonWebServiceResponse, Exception, AsyncOptions> callbackHelper = null;
     if(callback !=null )
         callbackHelper = (AmazonWebServiceRequest req, AmazonWebServiceResponse res, Exception ex, AsyncOptions ao) => { 
             AmazonServiceResult<InvokeRequest,InvokeResponse> responseObject 
                     = new AmazonServiceResult<InvokeRequest,InvokeResponse>((InvokeRequest)req, (InvokeResponse)res, ex , ao.State);    
                 callback(responseObject); 
         };
     BeginInvoke<InvokeRequest>(request, marshaller, unmarshaller, options, callbackHelper);
 }
示例#10
0
        //==================================================== update password on server ==============================================================

        public async void updatePassword(String oldPass, String newPass)
        {
            if (Helpers.Settings.SpeechSetting == true)
            {
                CrossTextToSpeech.Current.Speak("Change Password");
            }

            try
            {
                UserItem user = new UserItem { Item = new UserLogin { Email = Helpers.Settings.EmailSetting.ToLower(), Password = oldPass.TrimEnd(), NewPassword = newPass, Arn = "" + Helpers.Settings.EndpointArnSetting } };
                MessageJson messageJson = new MessageJson { operation = "update", tableName = "User", payload = user };
                string args = JsonConvert.SerializeObject(messageJson);

                //System.Diagnostics.Debug.WriteLine(args);
                var ir = new InvokeRequest()
                {
                    FunctionName = Constants.AWSLambdaID,
                    PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                    InvocationType = InvocationType.RequestResponse
                };
                //System.Diagnostics.Debug.WriteLine("Before invoke: " + ir.ToString());

                InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
                resp.Payload.Position = 0;
                var sr = new StreamReader(resp.Payload);
                var myStr = sr.ReadToEnd();

                System.Diagnostics.Debug.WriteLine("Status code: " + resp.StatusCode);
                System.Diagnostics.Debug.WriteLine("Response content: " + myStr);


                UserDialogs.Instance.ShowSuccess("Password updated successfully.");
                await Navigation.PopAsync();
                
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error:" + e);
            }
        }
示例#11
0
        /// <summary>
        /// Logout functionality, sends relevant user information to server to log out and update settings constants
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Logout_Clicked(object sender, EventArgs e)
        {

            if (Helpers.Settings.SpeechSetting == true)
            {
                CrossTextToSpeech.Current.Speak("Logout");
            }
            try
            {
                System.Diagnostics.Debug.WriteLine(Helpers.Settings.EndpointArnSetting);
                UserItem user = new UserItem { Item = new UserLogin { Arn = Helpers.Settings.EndpointArnSetting } };
                MessageJson messageJson = new MessageJson { operation = "logout", tableName = "User", payload = user };
                string args = JsonConvert.SerializeObject(messageJson);
                //System.Diagnostics.Debug.WriteLine(args);
                var ir = new InvokeRequest()
                {
                    FunctionName = Constants.AWSLambdaID,
                    PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                    InvocationType = InvocationType.RequestResponse
                };
                //System.Diagnostics.Debug.WriteLine("Before invoke: " + ir.ToString());


                InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
                resp.Payload.Position = 0;
                var sr = new StreamReader(resp.Payload);
                var myStr = sr.ReadToEnd();

                System.Diagnostics.Debug.WriteLine("Status code: " + resp.StatusCode);
                System.Diagnostics.Debug.WriteLine("Response content: " + myStr);

                response tmp = JsonConvert.DeserializeObject<response>(myStr);
                if (tmp.Success == "true")
                {
                    Helpers.Settings.IsVolunteer = false;
                    Helpers.Settings.LoginSetting = false;
                    UserDialogs.Instance.ShowSuccess("You have been successfully logged out.");
                    ((RootPage)App.Current.MainPage).NavigateTo();
                }
                else
                {
                    UserDialogs.Instance.ShowError("Unable to log out.");
                }
            }
            catch (Exception e2)
            {
                System.Diagnostics.Debug.WriteLine("Error:" + e2);
            }

        }
示例#12
0
        }//end GeneralAccountPage()

        //=============================================== FUNCTIONS ======================================================

        /// <summary>
        /// When username changes text, it updates username, pushing it onto the server
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void Username_TextChanged(object sender, TextChangedEventArgs e)
        {
            Helpers.Settings.UsernameSetting = username.Text;
            try
            {
                UserItem user = new UserItem { Item = new UserLogin { Nickname = username.Text } };
                MessageJson messageJson = new MessageJson { operation = "update", tableName = "User", payload = user };
                string args = JsonConvert.SerializeObject(messageJson);
                //System.Diagnostics.Debug.WriteLine(args);
                var ir = new InvokeRequest()
                {
                    FunctionName = Constants.AWSLambdaID,
                    PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                    InvocationType = InvocationType.RequestResponse
                };
                //System.Diagnostics.Debug.WriteLine("Before invoke: " + ir.ToString());


                InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
                resp.Payload.Position = 0;
                var sr = new StreamReader(resp.Payload);
                var myStr = sr.ReadToEnd();

            }
            catch (Exception e2)
            {
                System.Diagnostics.Debug.WriteLine("Error:" + e2);
            }

        }
示例#13
0
        /**
         * Generates or updates user account when the page is accessed or information is changed.
         * Sends request to server which updates the user table.
         */
        async private Task Handshake() 
        {
            try
            {
                string operation;
                if (!Helpers.Settings.HandShakeDone)
                {
                    operation = "create";
                    Helpers.Settings.HandShakeDone = true;
                }
                else
                {
                    operation = "update";
                }
                UserInfoItem message;
                if (Helpers.Settings.IsVolunteer)
                {
                    if(Helpers.Settings.ChatActiveSetting){
                        message = new UserInfoItem { Item = new UserInfo { Latitude = latitude, Longitude = longitude, Nickname = Helpers.Settings.UsernameSetting, Arn = Helpers.Settings.EndpointArnSetting, Available = true } };
                    }else{
                        message = new UserInfoItem { Item = new UserInfo { Latitude = latitude, Longitude = longitude, Nickname = Helpers.Settings.UsernameSetting, Arn = Helpers.Settings.EndpointArnSetting, Available = false } };
                    }
                }
                else{
                    message = new UserInfoItem { Item = new UserInfo { Latitude = latitude, Longitude = longitude, Nickname = this.nameEntry.Text, Arn = Helpers.Settings.EndpointArnSetting, Available = true } }; //Helpers.Settings.EndpointArnSetting
                }
                Helpers.Settings.UsernameSetting = this.nameEntry.Text;
                UserInfoJson messageJson = new UserInfoJson { operation = operation, tableName = "User", payload = message };
                string args = JsonConvert.SerializeObject(messageJson);
                var ir = new InvokeRequest()
                {
                    FunctionName = Constants.AWSLambdaID,
                    PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                    InvocationType = InvocationType.RequestResponse
                };
                
                InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
                resp.Payload.Position = 0;
                var sr = new StreamReader(resp.Payload);
                var myStr = sr.ReadToEnd();


                //                System.Diagnostics.Debug.WriteLine("Status code: " + resp.StatusCode);
                //                System.Diagnostics.Debug.WriteLine("Response content: " + myStr);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Error:" + e);
            }
            
        }
示例#14
0
        /**
         * Queries the server for active conversations, called when the page is loaded
         * if there exists an active conversation, returns conversation information to
         * user and activates continue conversation option.
         */
        async private Task queryServerActiveConversation()
        {
            UserInfoItem message = new UserInfoItem { Item = new UserInfo {} }; //Helpers.Settings.EndpointArnSetting
            UserInfoJson messageJson = new UserInfoJson { operation = "currentConversations", tableName = "User", payload = message };
            string args = JsonConvert.SerializeObject(messageJson);

            System.Diagnostics.Debug.WriteLine("currentConversation: " + args);
            var ir = new InvokeRequest()
            {
                FunctionName = Constants.AWSLambdaID,
                PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                InvocationType = InvocationType.RequestResponse
            };


            InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
            resp.Payload.Position = 0;
            var sr = new StreamReader(resp.Payload);
            var myStr = sr.ReadToEnd();
            Boolean failure = false;
            try
            {

                var response = JsonConvert.DeserializeObject<ConversationResponse>(myStr);
                System.Diagnostics.Debug.WriteLine("currentConversations : " + myStr);
                if (response.Success == "true")
                {
                    if (response.Conversations[0].ID != Helpers.Settings.ToFromArn)
                    {
                        Constants.conv.name = response.Conversations[0].Nickname;
                        Constants.conv.id = response.Conversations[0].ID;
                        Helpers.Settings.ToFromArn = response.Conversations[0].ID;
                        Constants.conv.msgs.Clear();
                    }
                    else
                    {
                        Constants.conv.name = response.Conversations[0].Nickname;
                        Constants.conv.id = response.Conversations[0].ID;
                    }
                    continueConversationPath();
                }
                else if (response.Success == "false")
                {
                    Helpers.Settings.ToFromArn = "";
                    startConversationPath();
                }
                else
                {
                    await DisplayAlert("Error", "No active conversations.", "OK");
                }
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine(e);
                failure = true;
            }
            if (failure) { await DisplayAlert("Error", "No active conversations", "OK"); }
        }
示例#15
0
        }//LoginPage()

        public async void ForgotPassword()
        {
            var s = await UserDialogs.Instance.PromptAsync(new PromptConfig
            {
                Message = "Enter E-Mail",
                Placeholder = "*****@*****.**",
                InputType = InputType.Email
            });
            var stat = s.Ok ? "Success" : "Cancelled";
            // System.Diagnostics.Debug.WriteLine(stat, s);
           
            if (stat == "Success")
            {
                System.Diagnostics.Debug.WriteLine(stat + s.Text);

                try
                {
                    UserItem user = new UserItem { Item = new UserLogin { Email = s.Text.TrimEnd().ToLower(), Arn = "" + Helpers.Settings.EndpointArnSetting } };
                    MessageJson messageJson = new MessageJson { operation = "forgotPassword", tableName = "User", payload = user };
                    string args = JsonConvert.SerializeObject(messageJson);

                    //System.Diagnostics.Debug.WriteLine(args);
                    var ir = new InvokeRequest()
                    {
                        FunctionName = Constants.AWSLambdaID,
                        PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                        InvocationType = InvocationType.RequestResponse
                    };
                    //System.Diagnostics.Debug.WriteLine("Before invoke: " + ir.ToString());

                    InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
                    resp.Payload.Position = 0;
                    var sr = new StreamReader(resp.Payload);
                    var myStr = sr.ReadToEnd();

                    System.Diagnostics.Debug.WriteLine("Status code: " + resp.StatusCode);
                    System.Diagnostics.Debug.WriteLine("Response content: " + myStr);

                    response tmp = JsonConvert.DeserializeObject<response>(myStr);
                    //System.Diagnostics.Debug.WriteLine("Success: " + tmp.Success);

                    if (tmp.Success == "true")
                    {
                        UserDialogs.Instance.ShowSuccess("Your password has been reset. Please check your email.");

                    }
                    else
                    {
                        UserDialogs.Instance.ShowError("Incorrect email. Please try again.");
                    }

                //                System.Diagnostics.Debug.WriteLine("Status code: " + resp.StatusCode);
                //                System.Diagnostics.Debug.WriteLine("Response content: " + myStr);
                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("Error:" + e);
                }

            }
        }
示例#16
0
        async private Task PushUser() 
        {
            //Function to create a Json object and send to server using a lambda function
                getLocation();
                try
                {
                    UserItem user = new UserItem { Item = new UserLogin { Latitude = latitude, Longitude = longitude, Password = password.Text, Email = email.Text.ToLower(), Arn = "" + Helpers.Settings.EndpointArnSetting } };
                    MessageJson messageJson = new MessageJson { operation = "update", tableName = "User", payload = user };
                    string args = JsonConvert.SerializeObject(messageJson);
                    //System.Diagnostics.Debug.WriteLine(args);
                    var ir = new InvokeRequest()
                    {
                        FunctionName = Constants.AWSLambdaID,
                        PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                        InvocationType = InvocationType.RequestResponse
                    };
                    //System.Diagnostics.Debug.WriteLine("Before invoke: " + ir.ToString());


                    InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
                    resp.Payload.Position = 0;
                    var sr = new StreamReader(resp.Payload);
                    var myStr = sr.ReadToEnd();

                    System.Diagnostics.Debug.WriteLine("Status code: " + resp.StatusCode);
                    System.Diagnostics.Debug.WriteLine("Response content: " + myStr);

                    response tmp = JsonConvert.DeserializeObject<response>(myStr);
                    //System.Diagnostics.Debug.WriteLine("Success: " + tmp.Success);

                    if (tmp.Success == "true")
                    {
                        Helpers.Settings.LoginSetting = true;
                        ((RootPage)App.Current.MainPage).NavigateTo();
                        if (tmp.ActualUserType == "Volunteer")
                        {
                            Helpers.Settings.IsVolunteer = true;
                        }
                        Helpers.Settings.EmailSetting = email.Text;
                        Helpers.Settings.UserIDSetting = tmp.ID;
                        Helpers.Settings.UsernameSetting = tmp.OldNickname;
                    }
                    else
                    {
                        UserDialogs.Instance.ShowError("Incorrect credentials. Please try again.");
                    }

                }
                catch (Exception e)
                {
                    System.Diagnostics.Debug.WriteLine("Error:" + e);
                }
        }
示例#17
0
      /// <summary>
      /// Send user information such as email, username, and password to the server, checking if the account is created.
      /// </summary>
      /// <param name="sender"></param>
      /// <param name="e"></param>
        async private void CreateAccount_Clicked(object sender, System.EventArgs e)
        {
            if (Helpers.Settings.SpeechSetting == true)
            {
                CrossTextToSpeech.Current.Speak("Create Account");
            }

            await getLocation();
            if(String.IsNullOrWhiteSpace(nickname.Text) || String.IsNullOrWhiteSpace(email.Text) || String.IsNullOrEmpty(password.Text))
            {
                UserDialogs.Instance.ShowError("Please enter correct information in all fields.");
            }
            else
            {
                try
                {
                    UserItem user = new UserItem { Item = new UserLogin { Nickname = nickname.Text, Email = email.Text.ToLower(), Password = password.Text,Longitude = longitude, Latitude = latitude, UserType = usertype } };
                    MessageJson messageJson = new MessageJson { operation = "create", tableName = "User", payload = user };
                    string args = JsonConvert.SerializeObject(messageJson);
                    //System.Diagnostics.Debug.WriteLine(args);
                    var ir = new InvokeRequest()
                    {
                        FunctionName = Constants.AWSLambdaID,
                        PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                        InvocationType = InvocationType.RequestResponse
                    };
                    //System.Diagnostics.Debug.WriteLine("Before invoke: " + ir.ToString());

                    InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
                    resp.Payload.Position = 0;
                    var sr = new StreamReader(resp.Payload);
                    var myStr = sr.ReadToEnd();

                    UserDialogs.Instance.ShowLoading();
                    UserDialogs.Instance.SuccessToast("Thank you for signing up!", "Please check your email for verification.", 3000);
                    ((RootPage)App.Current.MainPage).NavigateTo();
                    Helpers.Settings.UsernameSetting = nickname.Text;
                    Helpers.Settings.EmailSetting = email.Text;

                    //                System.Diagnostics.Debug.WriteLine("Status code: " + resp.StatusCode);
                    System.Diagnostics.Debug.WriteLine("Response content: " + myStr);
                }
                catch (Exception e2)
                {
                    System.Diagnostics.Debug.WriteLine("Error:" + e2);
                }
            }

        }
示例#18
0
        /// <summary>
        /// Initiates the asynchronous execution of the Invoke operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the Invoke operation on AmazonLambdaClient.</param>
        /// <param name="callback">An AsyncCallback delegate that is invoked when the operation completes.</param>
        /// <param name="state">A user-defined state object that is passed to the callback procedure. Retrieve this object from within the callback
        ///          procedure using the AsyncState property.</param>
        /// 
        /// <returns>An IAsyncResult that can be used to poll or wait for results, or both; this value is also needed when invoking EndInvoke
        ///         operation.</returns>
        public IAsyncResult BeginInvoke(InvokeRequest request, AsyncCallback callback, object state)
        {
            var marshaller = new InvokeRequestMarshaller();
            var unmarshaller = InvokeResponseUnmarshaller.Instance;

            return BeginInvoke<InvokeRequest>(request, marshaller, unmarshaller,
                callback, state);
        }
        public object Execute(ExecutorContext context)
        {
            System.IO.MemoryStream _PayloadStreamStream = null;

            try
            {
                var cmdletContext = context as CmdletContext;
                // create request
                var request = new Amazon.Lambda.Model.InvokeRequest();

                if (cmdletContext.Payload != null)
                {
                    request.Payload = cmdletContext.Payload;
                }
                if (cmdletContext.ClientContext != null)
                {
                    request.ClientContext = cmdletContext.ClientContext;
                }
                if (cmdletContext.ClientContextBase64 != null)
                {
                    request.ClientContextBase64 = cmdletContext.ClientContextBase64;
                }
                if (cmdletContext.FunctionName != null)
                {
                    request.FunctionName = cmdletContext.FunctionName;
                }
                if (cmdletContext.InvocationType != null)
                {
                    request.InvocationType = cmdletContext.InvocationType;
                }
                if (cmdletContext.LogType != null)
                {
                    request.LogType = cmdletContext.LogType;
                }
                if (cmdletContext.PayloadStream != null)
                {
                    _PayloadStreamStream  = new System.IO.MemoryStream(cmdletContext.PayloadStream);
                    request.PayloadStream = _PayloadStreamStream;
                }
                if (cmdletContext.Qualifier != null)
                {
                    request.Qualifier = cmdletContext.Qualifier;
                }

                CmdletOutput output;

                // issue call
                var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
                try
                {
                    var    response       = CallAWSServiceOperation(client, request);
                    object pipelineOutput = null;
                    pipelineOutput = cmdletContext.Select(response, this);
                    output         = new CmdletOutput
                    {
                        PipelineOutput  = pipelineOutput,
                        ServiceResponse = response
                    };
                }
                catch (Exception e)
                {
                    output = new CmdletOutput {
                        ErrorResponse = e
                    };
                }

                return(output);
            }
            finally
            {
                if (_PayloadStreamStream != null)
                {
                    _PayloadStreamStream.Dispose();
                }
            }
        }
示例#20
0
        /// <summary>
        /// Initiates the asynchronous execution of the Invoke operation.
        /// </summary>
        /// 
        /// <param name="request">Container for the necessary parameters to execute the Invoke operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task<InvokeResponse> InvokeAsync(InvokeRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller = new InvokeRequestMarshaller();
            var unmarshaller = InvokeResponseUnmarshaller.Instance;

            return InvokeAsync<InvokeRequest,InvokeResponse>(request, marshaller, 
                unmarshaller, cancellationToken);
        }
示例#21
0
        /**
         * Called when the start button is tapped, generates request to server
         * checks response and either actives enter conversation mode or prompts
         * user with failed to start message.
         */
        async private Task initiateConversation(){
                UserInfoItem message = new UserInfoItem { Item = new UserInfo { } }; //Helpers.Settings.EndpointArnSetting
                UserInfoJson messageJson = new UserInfoJson { operation = "newConversation", tableName = "User", payload = message };
                string args = JsonConvert.SerializeObject(messageJson);
                System.Diagnostics.Debug.WriteLine("newConversation: " + args);
                var ir = new InvokeRequest()
                {
                    FunctionName = Constants.AWSLambdaID,
                    PayloadStream = AWSSDKUtils.GenerateMemoryStreamFromString(args),
                    InvocationType = InvocationType.RequestResponse
                };

                InvokeResponse resp = await AmazonUtils.LambdaClient.InvokeAsync(ir);
                resp.Payload.Position = 0;
                var sr = new StreamReader(resp.Payload);
                var myStr = sr.ReadToEnd();
                Boolean failure = false;
                try {
                    System.Diagnostics.Debug.WriteLine("newConversations : " + myStr);
                    var response = JsonConvert.DeserializeObject<ConversationResponse>(myStr);
                    if (response.Success == "true")
                    {
                        Constants.conv.name = response.Nickname;
                        Constants.conv.id = response.ID;
                        Constants.conv.msgs.Clear();
                        Helpers.Settings.ToFromArn = response.ID;
                        continueConversationPath();
                        var stack = Navigation.NavigationStack;
                        if (stack[stack.Count - 1].GetType() != typeof(ChatPage))
                            await Navigation.PushAsync(new ChatPage(), false);
                    }
                    else
                    {
                        await DisplayAlert("Error", "No available volunteers, please try again later.", "OK");
                    }
                }
                catch(Exception e)
                {
                    failure = true;
                    
                }
                if (failure)
                {
                    await DisplayAlert("Error", "No available volunteers, please try again later.", "OK");
                }
        }