Exemplo n.º 1
0
        public ActionResult <PayloadResponse> EditTestAthlete([FromBody] TestAthleteListViewModel info)
        {
            PayloadResponse response = new PayloadResponse();

            response.RequestTime = DateTime.Now.ToString();

            TestAthlete athlete = _repo.TestAthleteRepository.GetAll().Where(x => x.ID == info.ID && !x.IsRemoved).FirstOrDefault();

            if (info == null && info.ID <= 0)
            {
                response.Message      = "Data did not send properly";
                response.Payload      = athlete;
                response.PayloadType  = "EditTestAthlete";
                response.ResponseTime = DateTime.Now.ToString();
                response.Success      = false;
                return(response);
            }
            athlete.TestValue       = info.Distance;
            athlete.UpdatedBy       = Convert.ToInt32(User.Identity.Name);
            athlete.UpdatedDate     = DateTime.Now;
            athlete.FitnessRatingID = _repo.TestCustomRepository.GetFitnessRatingID(info.Distance);
            _repo.TestAthleteRepository.Update(athlete);

            _repo.Save();

            response.Message      = "Athlete is successfully updated.";
            response.Payload      = null;
            response.PayloadType  = "EditTestAthlete";
            response.ResponseTime = DateTime.Now.ToString();
            response.Success      = true;
            return(response);
        }
Exemplo n.º 2
0
 public ActionResult CreateAthleteTest(TestAthleteViewModel model)
 {
     try
     {
         if (ModelState.IsValid)
         {
             PayloadResponse response = new PayloadResponse();
             using (var repository = new WebApiClientRepository <PayloadResponse>())
             {
                 response = repository.GlobalApiCallPost(model, "api/Test/CreateTestAthlete");
                 if (response != null)
                 {
                     if (response.Success)
                     {
                         TempData["message_data_success"] = response.Message;
                         return(RedirectToAction(nameof(Details), new { id = model.ID }));
                     }
                     else
                     {
                         TempData["message_data"] = response.Message;
                         return(RedirectToAction(nameof(Details), new { id = model.ID }));
                     }
                 }
             }
         }
         // TODO: Add insert logic here
         TempData["message_data"] = "Problem on Athlete adding";
         return(RedirectToAction(nameof(Details), new { id = model.ID }));
     }
     catch
     {
         return(View());
     }
 }
Exemplo n.º 3
0
        public ActionResult EditAthleteTest(TestAthleteData data)
        {
            try
            {
                PayloadResponse          response = new PayloadResponse();
                TestAthleteListViewModel model    = new TestAthleteListViewModel();
                model.ID       = Convert.ToInt64(data.TestAthleteID);
                model.Distance = Convert.ToInt32(data.Distance);

                if (ModelState.IsValid)
                {
                    using (var repository = new WebApiClientRepository <PayloadResponse>())
                    {
                        response = repository.GlobalApiCallPost(model, "api/Test/EditTestAthlete");
                        if (response != null)
                        {
                            TempData["message_data_success"] = response.Message;
                            return(Ok(new { msg = response.Message }));
                        }
                    }
                }
                // TODO: Add insert logic here
                return(View());
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 4
0
 /// <summary>
 /// Validates that a response is valid.  This method throws an exception if there
 /// was an error in the response payload.
 /// </summary>
 /// <typeparam name="T">
 /// The type name of the payload response.
 /// </typeparam>
 /// <param name="response">
 /// The response object.
 /// </param>
 public void ValidateResponse <T>(PayloadResponse <T> response)
 {
     response.ArgumentNotNull("response");
     if (response.ErrorDetails.IsNotNull())
     {
         throw new HttpLayerException(response.ErrorDetails.StatusCode, response.ErrorDetails.ErrorMessage);
     }
 }
Exemplo n.º 5
0
        public PayloadResponse Insert(string MethodUrl)
        {
            string BaseUrl = auth.GetBaseURL();

            string contantData = "";


            HttpContent content = new MultipartFormDataContent();

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            var uri = new Uri(BaseUrl + MethodUrl);
            //client.DefaultRequestHeaders.Accept.Clear();
            //client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string Token = auth.GetToken();

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Token);
            HttpResponseMessage result = new HttpResponseMessage();

            try
            {
                result = client.PostAsync(uri, content).Result;
            }
            catch (Exception)
            {
                result = null;
            }
            dynamic jsonString = "";

            try
            {
                jsonString = result.Content.ReadAsStringAsync();
                jsonString.Wait();
            }
            catch (Exception ex)
            {
                PayloadResponse response = new PayloadResponse();
                response.Success = false;
                return(response);
            }


            PayloadResponse ob;

            try
            {
                ob = JsonConvert.DeserializeObject <PayloadResponse>(jsonString.Result);
                return(ob);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
        public async Task <IActionResult> PosTransaction([FromRoute] Guid account_id, [FromBody] PostTransactionRequest request)
        {
            var response = await mediator.Send(new PublishTransaction(account_id, request.Value, request.Type));

            if (response.Invalid)
            {
                return(ValidationError(response));
            }

            return(Created("", PayloadResponse.Create()));
        }
        public async Task <IActionResult> Get(string identifier)
        {
            var response = await mediator.Send(new AccountByIdentifier(identifier));

            if (response.Invalid)
            {
                return(ValidationError(response));
            }

            return(Ok(PayloadResponse <GetAccountResponse> .Create(new GetAccountResponse(response.Result as AccountEntity))));
        }
        public async Task <IActionResult> Post(PostTransferFundsRequest request)
        {
            var response = await mediator.Send(new Transfer(request.From, request.To, request.Value));

            if (response.Invalid)
            {
                return(ValidationError(response));
            }

            return(Ok(PayloadResponse.Create(true)));
        }
Exemplo n.º 9
0
        public ActionResult <PayloadResponse> IsAlive()
        {
            PayloadResponse response = new PayloadResponse();

            response.Message      = "200";
            response.Payload      = null;
            response.PayloadType  = "CreateTest";
            response.ResponseTime = DateTime.Now.ToString();
            response.Success      = true;
            return(Ok(response));
        }
Exemplo n.º 10
0
        public async Task <IActionResult> GetBalance([FromRoute] Guid account_id)
        {
            var response = await mediator.Send(new TransactionsByAccount(account_id));

            if (response.Invalid)
            {
                return(ValidationError(response));
            }

            var transactions = response.Result as List <TransactionEntity>;

            return(Ok(PayloadResponse <decimal> .Create(transactions.Sum(x => x.Value))));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> GetTransactions([FromRoute] Guid account_id)
        {
            var response = await mediator.Send(new TransactionsByAccount(account_id));

            if (response.Invalid)
            {
                return(ValidationError(response));
            }

            var transactions = response.Result as List <TransactionEntity>;

            var result = transactions.Select(tr => new GetTransactionsResponse(tr)).ToList();

            return(Ok(PayloadResponse <List <GetTransactionsResponse> > .Create(result)));
        }
Exemplo n.º 12
0
 public ActionResult Create(TestViewModel model)
 {
     try
     {
         if (ModelState.IsValid)
         {
             PayloadResponse response = new PayloadResponse();
             using (var repository = new WebApiClientRepository <PayloadResponse>())
             {
                 using (var storage = new LocalStorage())
                 {
                     LoggedInUserInfo userInfo = JsonConvert.DeserializeObject <LoggedInUserInfo>(storage.Get("userInfo").ToString());
                     model.CoachID = userInfo.UserID;
                 }
                 response = repository.GlobalApiCallPost(model, "api/Test/CreateTest");
                 if (response != null)
                 {
                     if (response.Success)
                     {
                         TempData["message_data_success"] = response.Message;
                         return(RedirectToAction(nameof(Index)));
                     }
                     else
                     {
                         TempData["message_data"] = response.Message;
                         return(RedirectToAction(nameof(Index)));
                     }
                 }
                 else
                 {
                     TempData["message_data"] = "Problem on Test creation";
                     return(RedirectToAction(nameof(Index)));
                 }
             }
         }
         else
         {
             TempData["message_data"] = "Problem on Test creation";
             return(RedirectToAction(nameof(Index)));
         }
     }
     catch
     {
         TempData["message_data"] = "Problem on Test creation";
         return(RedirectToAction(nameof(Index)));
     }
 }
Exemplo n.º 13
0
        public ActionResult <PayloadResponse> CreateTest([FromBody] TestViewModel info)
        {
            PayloadResponse response = new PayloadResponse();


            Test test = new Test();

            if (info == null)
            {
                response.Message      = "Data did not send properly";
                response.Payload      = test;
                response.PayloadType  = "CreateTest";
                response.ResponseTime = DateTime.Now.ToString();
                response.Success      = false;
                return(response);
            }

            Test existingTest = _repo.TestCustomRepository.GetTestByCoachAndDate(info.CoachID, info.TestDate, info.TestTypeID);

            if (existingTest != null && existingTest.ID > 0)
            {
                response.Message      = string.Format("You already have a Test at same Date ({0}) ", info.TestDate);
                response.Payload      = test;
                response.PayloadType  = "CreateTest";
                response.ResponseTime = DateTime.Now.ToString();
                response.Success      = false;
                return(response);
            }

            test.CoachID     = info.CoachID;
            test.TestDate    = info.TestDate;
            test.TestTypeID  = info.TestTypeID;
            test.CreatedBy   = Convert.ToInt32(User.Identity.Name);
            test.CreatedDate = DateTime.Now;
            test.IsRemoved   = false;
            _repo.TestRepository.Add(test);
            _repo.Save();

            response.Message      = "Test is successfully created.";
            response.Payload      = null;
            response.PayloadType  = "CreateTest";
            response.ResponseTime = DateTime.Now.ToString();
            response.Success      = true;

            return(response);
        }
Exemplo n.º 14
0
        public ActionResult <PayloadResponse> CreateTestAthlete([FromBody] TestAthleteViewModel info)
        {
            PayloadResponse response    = new PayloadResponse();
            TestAthlete     testAthlete = new TestAthlete();

            if (info == null)
            {
                response.Message      = "Data did not send properly";
                response.Payload      = testAthlete;
                response.PayloadType  = "CreateTestAthlete";
                response.ResponseTime = DateTime.Now.ToString();
                response.Success      = false;
                return(response);
            }

            TestAthlete existingTest = _repo.TestCustomRepository.GetTestAthleteByTestAndAthlete(info.ID, info.AthleteID);

            if (existingTest != null && existingTest.ID > 0)
            {
                response.Message      = string.Format("The Athlete ({0} {1}) is already exist into the Test. ", existingTest.Athlete.FirstName, existingTest.Athlete.LastName);
                response.Payload      = testAthlete;
                response.PayloadType  = "CreateTestAthlete";
                response.ResponseTime = DateTime.Now.ToString();
                response.Success      = false;
                return(response);
            }

            testAthlete.AthleteID       = info.AthleteID;
            testAthlete.TestValue       = info.TestValue;
            testAthlete.TestID          = info.ID;
            testAthlete.CreatedBy       = Convert.ToInt32(User.Identity.Name);
            testAthlete.CreatedDate     = DateTime.Now;
            testAthlete.IsRemoved       = false;
            testAthlete.FitnessRatingID = _repo.TestCustomRepository.GetFitnessRatingID(testAthlete.TestValue);
            _repo.TestAthleteRepository.Add(testAthlete);
            _repo.Save();

            response.Message      = "Athlete is successfully added in Test.";
            response.Payload      = null;
            response.PayloadType  = "CreateTestAthlete";
            response.ResponseTime = DateTime.Now.ToString();
            response.Success      = true;
            return(response);
        }
Exemplo n.º 15
0
        private void GenerateToken()
        {
            var section = configuration.GetSection("ZoomMeeting");

            var API_KEY    = section.GetValue <string>("api_key");
            var API_SECRET = section.GetValue <string>("api_secret");

            JsonWebTokenBuilder builder = new JsonWebTokenBuilder();
            var header  = new Header();//instanciado com os valores padrão.
            var payload = new PayloadResponse()
            {
                api_key    = API_KEY,
                expireDate = Convert.ToInt32(DateTime.UtcNow.AddMinutes(30).Subtract(new DateTime(1970, 1, 1)).TotalSeconds),
            };

            builder.AddHeader("alg", header.alg);
            builder.AddHeader("typ", header.typ);

            builder.AddClaim("exp", payload.expireDate);
            builder.AddClaim("iss", payload.api_key);

            this.Token = builder.GetJWT(API_SECRET);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Handle incoming websocket messages that are added to the message queue
        /// </summary>
        public static void ProcessMessageQueue()
        {
            CancellationToken cancellationToken = s_ProcessCancellationSource.Token;

            while (!cancellationToken.IsCancellationRequested)
            {
                if (s_MessageQueue.Count == 0)
                {
                    Thread.Sleep(1);
                    continue;
                }

                if (s_MessageQueue.TryTake(out string item))
                {
                    Payload response = JsonConvert.DeserializeObject <Payload>(item);
                    OnPayload?.Invoke(response);

                    switch (response.type)
                    {
                    case "PONG":
                    {
                        s_PongReceived = true;
                        Task.Run(() => DelayedHeartbeat());
                    }
                    break;

                    case "RECONNECT":
                    {
                        OnServerRestart?.Invoke();
                    }
                    break;

                    case "RESPONSE":
                    {
                        PayloadResponse payloadResponse = JsonConvert.DeserializeObject <PayloadResponse>(item);
                        if (payloadResponse.nonce != s_ListenNonce)
                        {
                            throw new AccessViolationException($"The nonce received does not match {s_ListenNonce} Unknown: {payloadResponse.nonce}");
                        }
                        OnResponse?.Invoke(payloadResponse);
                    }
                    break;

                    case "MESSAGE":
                    {
                        PayloadMessage payloadMessage = JsonConvert.DeserializeObject <PayloadMessage>(item);

                        string topicKey = GetTopicKey(payloadMessage.data.topic);

                        if (topicKey == "whispers")
                        {
                            JObject jobj = JObject.Parse(payloadMessage.data.message);

                            JToken jtokenType       = jobj.GetValue("type");
                            JToken jtokenData       = jobj.GetValue("data");
                            JToken jtokenDataObject = jobj.GetValue("data_object");
                            string type             = jtokenType.ToString();

                            try
                            {
#pragma warning disable 0618
                                Whispers.Data data        = JsonConvert.DeserializeObject <Whispers.Data>(jtokenData.ToString());
                                Whispers.Data data_object = JsonConvert.DeserializeObject <Whispers.Data>(jtokenDataObject.ToString());
#pragma warning restore 0618
                                payloadMessage.data.message = JObject.FromObject(new { type, data, data_object }).ToString().Replace("\n", "").Replace("\r", "");

                                if (s_TopicEvents.TryGetValue(topicKey, out Action <IPayload> value))
                                {
                                    value?.Invoke(payloadMessage);
                                }
                            }
                            catch (Exception ex)
                            {
                                OnTaskException?.Invoke(new TaskExceptionArgs(ex, "ProcessMessageQueue Whisper"));
                            }
                        }
                        else
                        {
                            if (s_TopicEvents.TryGetValue(topicKey, out Action <IPayload> value))
                            {
                                value?.Invoke(payloadMessage);
                            }
                        }
                    }
                    break;

                    default:
                        break;
                    }
                }
            }
            _ = InvokeReconnectWithBackoff(ReconnectReason.DefaultBreak);
        }
Exemplo n.º 17
0
        public PayloadResponse GlobalApiCallFunction(dynamic model, string methodUrl)
        {
            string BaseUrl = auth.GetBaseURL();

            string contantData = "";

            if (model != null)
            {
                contantData = JsonConvert.SerializeObject(model);
            }

            HttpContent content = new StringContent(contantData, Encoding.UTF8, "application/json");

            var client = new HttpClient {
                BaseAddress = new Uri(BaseUrl)
            };

            var uri = new Uri(BaseUrl + methodUrl);

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string Token = string.Empty;

            using (var storage = new LocalStorage())
            {
                Token = storage.Get("jwtToken").ToString();
            }

            client.DefaultRequestHeaders.Add("Authorization", "Bearer " + Token);
            HttpResponseMessage result = new HttpResponseMessage();

            try
            {
                result = client.PostAsync(uri, content).Result;
            }
            catch (Exception ex)
            {
                result = null;
            }
            dynamic jsonString = "";

            try
            {
                jsonString = result.Content.ReadAsStringAsync();
                jsonString.Wait();
            }
            catch (Exception ex)
            {
                PayloadResponse response = new PayloadResponse();
                response.Success = false;
                return(response);
            }


            PayloadResponse ob;

            try
            {
                ob = JsonConvert.DeserializeObject <PayloadResponse>(jsonString.Result);
                return(ob);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Exemplo n.º 18
0
 /// <summary>
 /// Deserializes a Connectivity Response.
 /// </summary>
 /// <param name="payload">The payload.</param>
 /// <returns>
 /// A PayloadResponse object with the operation id for the data.
 /// </returns>
 public PayloadResponse<Guid> DeserializeConnectivityResponse(string payload)
 {
     XmlDocument doc = new XmlDocument();
     using (var stream = payload.ToUtf8Stream())
     using (var reader = XmlReader.Create(stream))
     {
         doc.Load(reader);
     }
     var manager = new DynaXmlNamespaceTable(doc);
     PayloadResponse<Guid> result = new PayloadResponse<Guid>();
     var node = doc.SelectSingleNode("/def:PassthroughResponse/def:Data", manager.NamespaceManager);
     if (node.IsNotNull() && node.InnerText.IsNotNullOrEmpty())
     {
         var text = node.InnerText;
         Guid guid;
         if (!Guid.TryParse(text, out guid))
         {
             throw new SerializationException("Unable to deserialize the server response.");
         }
         result.Data = guid;
     }
     node = doc.SelectSingleNode("/def:PassthroughResponse/def:Error", manager.NamespaceManager);
     result.ErrorDetails = this.GetErrorDetails(node, manager.NamespaceManager);
     return result;
 }
Exemplo n.º 19
0
        /// <inheritdoc />
        public PayloadResponse<UserChangeRequestStatus> DeserializeConnectivityStatus(string payload)
        {
            XmlDocument doc = new XmlDocument();
            using (var stream = payload.ToUtf8Stream())
            using (var reader = XmlReader.Create(stream))
            {
                doc.Load(reader);
            }
            var manager = new DynaXmlNamespaceTable(doc);
            PayloadResponse<UserChangeRequestStatus> result = new PayloadResponse<UserChangeRequestStatus>();
            var node = doc.SelectSingleNode("/def:PassthroughResponse/def:Data", manager.NamespaceManager);
            if (node.IsNotNull())
            {
                result.Data = new UserChangeRequestStatus();
                var data = node;
                node = data.SelectSingleNode("def:State", manager.NamespaceManager);
                UserChangeRequestOperationStatus status;
                if (node.IsNull() || !UserChangeRequestOperationStatus.TryParse(node.InnerText, out status))
                {
                    throw new SerializationException("Unable to deserialize the server response.");
                }
                result.Data.State = status;

                node = data.SelectSingleNode("def:UserType", manager.NamespaceManager);
                UserChangeRequestUserType userType;
                if (node.IsNull() || !UserChangeRequestUserType.TryParse(node.InnerText, out userType))
                {
                    throw new SerializationException("Unable to deserialize the server response.");
                }
                result.Data.UserType = userType;

                node = data.SelectSingleNode("def:OperationType", manager.NamespaceManager);
                UserChangeRequestOperationType operationType;
                if (node.IsNull() || !UserChangeRequestOperationType.TryParse(node.InnerText, out operationType))
                {
                    throw new SerializationException("Unable to deserialize the server response.");
                }
                result.Data.OperationType = operationType;

                node = data.SelectSingleNode("def:RequestIssueDate", manager.NamespaceManager);
                DateTime requestTime;
                if (node.IsNull() || !DateTime.TryParse(node.InnerText, out requestTime))
                {
                    throw new SerializationException("Unable to deserialize the server response.");
                }
                result.Data.RequestIssueDate = requestTime.ToUniversalTime();

                node = data.SelectSingleNode("def:Error", manager.NamespaceManager);
                result.Data.ErrorDetails = this.GetErrorDetails(node, manager.NamespaceManager);

            }
            node = doc.SelectSingleNode("/def:PassthroughResponse/def:Error", manager.NamespaceManager);
            result.ErrorDetails = this.GetErrorDetails(node, manager.NamespaceManager);

            return result;
        }
Exemplo n.º 20
0
 protected BadRequestObjectResult ValidationError(Response validation)
 {
     return(BadRequest(PayloadResponse <List <string> > .Create(validation.Notifications, false)));
 }
Exemplo n.º 21
0
        public IActionResult Index()
        {
            var token            = string.Empty;
            var loggedInUserInfo = new LoggedInUserInfo();

            using (var storage = new LocalStorage())
            {
                if (storage.Exists("userInfo"))
                {
                    loggedInUserInfo = JsonConvert.DeserializeObject <LoggedInUserInfo>(storage.Get("userInfo").ToString());
                    token            = storage.Get("jwtToken").ToString();
                }
            }

            if (string.IsNullOrEmpty(token))
            {
                using (var storage = new LocalStorage())
                {
                    storage.Clear();
                }
                return(View());
            }

            PayloadResponse response = new PayloadResponse();

            using (var repository = new WebApiClientRepository <PayloadResponse>())
            {
                try
                {
                    response = repository.GlobalApiCallPost(null, "api/Auth/KeepAlive");

                    if (response == null || !response.Success)
                    {
                        using (var storage = new LocalStorage())
                        {
                            storage.Clear();
                        }
                        return(View());
                    }
                }
                catch (Exception)
                {
                    return(View());
                }
            }

            if (loggedInUserInfo != null && loggedInUserInfo.UserID > 0)
            {
                switch (loggedInUserInfo.Role)
                {
                case "Coach": return(RedirectToAction(nameof(CoachController.Index), "Coach"));

                case "Athlete":
                    return(RedirectToAction(nameof(AthleteController.Index), "Athlete"));

                default:
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(View());
                }
            }
            else
            {
                return(View());
            }
        }