コード例 #1
0
        public static async Task <GetRecordVoteCountResponse> GetRecordVoteCountAsync(GetRecordVoteCountRequest model)
        {
            int IterationsToRetry             = 5;
            int TimeToSleepForRetry           = 3000;
            GetRecordVoteCountResponse result = new GetRecordVoteCountResponse();

            if (Helpers.ConnectivyHelper.CheckConnectivity() != Enums.ConnectivtyResultEnum.HasConnectivity)
            {
                result.Status  = Enums.ResponseStatus.CommunicationError;
                result.Message = "El dispositivo no pudo comunicarse con el servidor, comprueba que tengas conexión a internet";
                return(result);
            }

            model.token = GetToken();

            for (int i = 0; i <= IterationsToRetry; i++)
            {
                try
                {
                    using (var client = new HttpClient())
                    {
                        var service = $"{Settings.FunctionURL}/api/GetRecordVoteCount/";

                        byte[] byteData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model));
                        using (var content = new ByteArrayContent(byteData))
                        {
                            content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                            var httpResponse = await client.PostAsync(service, content);

                            result = JsonConvert.DeserializeObject <GetRecordVoteCountResponse>(await httpResponse.Content.ReadAsStringAsync());

                            if (httpResponse.StatusCode == HttpStatusCode.OK)
                            {
                                result.Status = Enums.ResponseStatus.Ok;
                            }
                            else
                            {
                                result.Status = Enums.ResponseStatus.Error;
                                Thread.Sleep(TimeToSleepForRetry);
                            }
                            return(result);
                        }
                    }
                }
                catch (Exception)
                {
                    result.Status  = Enums.ResponseStatus.CommunicationError;
                    result.Message = "Ocurrió un error durante el proceso, por favor intenta de nuevo o espera unos minutos antes de vovler a intentar";
                    Thread.Sleep(TimeToSleepForRetry);
                    continue;
                }
            }
            return(result);
        }
コード例 #2
0
        public async Task <GetRecordVoteCountResponse> GetCountersAsync(Dictionary <ParameterTypeEnum, object> parameters)
        {
            telemetryClient.TrackTrace("Starting helper");

            GetRecordVoteCountResponse result = new GetRecordVoteCountResponse
            {
                IsSucceded = true,
                ResultId   = (int)GetRecordVoteCountResultEnum.Success
            };

            try
            {
                telemetryClient.TrackTrace("Getting parameters");

                parameters.TryGetValue(ParameterTypeEnum.Hash, out global::System.Object ohash);
                string hash = ohash.ToString().ToLower();

                //database helpers
                DBRecordVoteHelper dbRecordVoteHelper = new DBRecordVoteHelper(DBCONNECTION_INFO);

                telemetryClient.TrackTrace("Getting record votes");

                //get votes
                var votes = await dbRecordVoteHelper.GetRecordVoteList(hash);

                telemetryClient.TrackTrace("Counting votes");

                result.Approvals    = votes.FindAll(x => x.isApproval == true).Count;
                result.Disapprovals = votes.FindAll(x => x.isApproval == false).Count;
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)GetRecordVoteCountResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)GetRecordVoteCountResultEnum.Failed;
            }

            telemetryClient.TrackTrace("Finishing helper");
            return(result);
        }
コード例 #3
0
        public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, TraceWriter log, ExecutionContext context)
        {
            TelemetryClient telemetryClient = new TelemetryClient
            {
                InstrumentationKey = Settings.APPINSIGHTS_INSTRUMENTATIONKEY
            };

            telemetryClient.TrackTrace("Starting function: GetRecordVoteCount");

            GetRecordVoteCountResponse result = new GetRecordVoteCountResponse
            {
                IsSucceded = true,
                ResultId   = (int)GetRecordVoteCountResultEnum.Success
            };

            try
            {
                string  requestBody = new StreamReader(req.Body).ReadToEnd();
                dynamic data        = JsonConvert.DeserializeObject(requestBody);
                string  token       = data?.token;
                string  hash        = data?.hash;

                Dictionary <ParameterTypeEnum, object> parameters = new Dictionary <ParameterTypeEnum, object>
                {
                    { ParameterTypeEnum.Hash, hash }
                };

                telemetryClient.TrackTrace("Validating token");

                //validate token
                if (!string.IsNullOrEmpty(token))
                {
                    var      decrypted_token = SecurityHelper.Decrypt(token, Settings.SECURITY_SEED);
                    byte[]   token_bytes     = Convert.FromBase64String(decrypted_token);
                    DateTime when            = DateTime.FromBinary(BitConverter.ToInt64(token_bytes, 0));

                    if (when < DateTime.UtcNow.AddMinutes(-5))
                    {
                        result.IsSucceded = false;
                        result.ResultId   = (int)GetRecordVoteCountResultEnum.InvalidToken;
                    }
                    else
                    {
                        telemetryClient.TrackTrace("Calling helper");
                        GetRecordVoteCountHelper helper = new GetRecordVoteCountHelper(telemetryClient, Settings.STORAGE_ACCOUNT, Settings.RPC_CLIENT, Configurations.GetMongoDbConnectionInfo());
                        result = await helper.GetCountersAsync(parameters);
                    }
                }
                else
                {
                    result.IsSucceded = false;
                    result.ResultId   = (int)GetRecordVoteCountResultEnum.MissingToken;
                }
            }
            catch (AggregateException ex)
            {
                foreach (var innerException in ex.Flatten().InnerExceptions)
                {
                    telemetryClient.TrackException(innerException);
                }
                result.IsSucceded = false;
                result.ResultId   = (int)GetRecordVoteCountResultEnum.Failed;
            }
            catch (Exception ex)
            {
                telemetryClient.TrackException(ex);
                result.IsSucceded = false;
                result.ResultId   = (int)GetRecordVoteCountResultEnum.Failed;
            }

            //get message for result id
            string message = EnumDescription.GetEnumDescription((GetRecordVoteCountResultEnum)result.ResultId);

            //build json result object
            dynamic jsonresult = new JObject();

            jsonresult.message      = message;
            jsonresult.approvals    = result.Approvals;
            jsonresult.disapprovals = result.Disapprovals;

            telemetryClient.TrackTrace("Finishing function: GetRecordVoteCount");

            //send ok result or bad request
            return((result.IsSucceded) ? (ActionResult) new OkObjectResult(jsonresult) : (ActionResult) new BadRequestObjectResult(jsonresult));
        }