示例#1
0
        /// <summary>
        /// Gets a ClientTimings object from a <see cref="ResultRequest"/>.
        /// </summary>
        /// <param name="request">The request to convert.</param>
        /// <returns>A <see cref="ClientTimings"/> object.</returns>
        public static ClientTimings FromRequest(ResultRequest request)
        {
            var result = new ClientTimings()
            {
                RedirectCount = request.RedirectCount ?? 0,
                Timings       = new List <ClientTiming>(request.Performance?.Count + request.Probes?.Count ?? 0)
            };

            if (request.Performance?.Count > 0)
            {
                foreach (var t in request.Performance)
                {
                    if (t.Name?.EndsWith("End") == true)
                    {
                        continue;
                    }
                    result.Timings.Add(t);
                }
            }
            if (request.Probes?.Count > 0)
            {
                result.Timings.AddRange(request.Probes);
            }
            // Noise
            result.Timings.RemoveAll(t => t.Start < 0 || t.Duration < 0);
            // Sort for storage later
            result.Timings.Sort((a, b) => a.Start.CompareTo(b.Start));

            // TODO: Collapse client start/end timings? Probably...
            return(result);
        }
示例#2
0
        public ResultRequest <DtoTokenResponse> RefreshToken(
            [FromBody] InboundRequest <DtoRefreshToken> request)
        {
            try
            {
                var dto = request?.Data;
                if (dto == null)
                {
                    return(ResultRequest <DtoTokenResponse> .Error("Access Token request fail",
                                                                   "Invalid request data"));
                }

                var encryptedRefreshToken = dto.RefreshToken;
                if (string.IsNullOrEmpty(encryptedRefreshToken))
                {
                    throw new LogicException(
                              "Refresh Token is required for grantType RefreshToken");
                }

                var tokenFromRefreshToken = _service.GetNewTokenFromRefreshToken(encryptedRefreshToken);

                return(ResultRequest <DtoTokenResponse> .Ok(tokenFromRefreshToken));
            }
            catch (Exception e)
            {
                return(ResultRequest <DtoTokenResponse> .Error("Access Token request error",
                                                               e.Message));
            }
        }
示例#3
0
        public Task <ResultRequest> BlockUserToken([FromBody] InboundRequest <DtoUserToken> request)
        {
            try
            {
                var dto = request?.Data;
                if (dto == null || (string.IsNullOrEmpty(dto.UserId) && string.IsNullOrEmpty(dto.Token)))
                {
                    return(Task.FromResult(ResultRequest.Error("Access Token request fail", "Invalid request data")));
                }

                var allTokens = string.IsNullOrEmpty(dto.Token);
                if (allTokens)
                {
                    UserTokenMapping.Remove(dto.UserId, true);
                }
                else
                {
                    UserTokenMapping.Remove(dto.UserId, new UserToken
                    {
                        UserId = dto.UserId,
                        Token  = dto.Token
                    });
                }

                return(Task.FromResult(ResultRequest.Ok()));
            }
            catch (Exception e)
            {
                return(Task.FromResult(ResultRequest.Error("Access Token request error", e.Message)));
            }
        }
示例#4
0
        public ActionResult Store([FromBody] ResultRequest request)
        {
            var userId = Convert.ToInt32(User.Identity.Name);
            var result = _resultService.Store(userId, request);

            return(Ok(result));
        }
示例#5
0
        public Result Store(int userId, ResultRequest request)
        {
            var result = new Result()
            {
                UserId                  = (userId > 0) ? userId : null as int?,
                Wpm                     = request.wpm,
                TestId                  = request.test_id,
                GoodKeystrokes          = request.good_keystrokes,
                BadKeystrokes           = request.bad_keystrokes,
                TotalPossibleKeystrokes = request.total_possible_keystrokes,
                Errors                  = request.errors,
                Accuracy                = request.accuracy,
                CreatedAt               = DateTime.Now,
                UpdatedAt               = DateTime.Now
            };

            _context.Results.Add(result);

            _context.SaveChanges();

            //If a registered user did this, check for new achievements.
            if (userId > 0)
            {
                //todo: maybe abstract to achievement service
                var checker = new CheckForAchievements(_context, userId);
                checker.Check();
            }

            return(result);
        }
示例#6
0
        /// <summary>
        /// Issues a storage request for the next open instance.
        /// </summary>
        private void NextStorageRequest()
        {
            // Pop an instance.
            var currentInstance = this._currentEvaluationProgress.PopOpenInstance();

            // Try to look it up in storage.
            var resultRequest = new ResultRequest <TInstance>(this._currentGenome, currentInstance);

            this._resultStorageActor.Tell(resultRequest);
        }
        public async Task <IActionResult> GetHourly(string city = null, string id = null, string zip = null)
        {
            if (Int32.TryParse(city, out int ID))
            {
                city = null; id = ID.ToString();
            }
            OpenWeatherService weatherService = new OpenWeatherService();
            ResultRequest      result         = await weatherService.GetHourlyAsync(city, id, zip);

            ViewBag.Error = result.RequestStatus;
            return(View(result.Forecast));
        }
        public async Task <IActionResult> GetWeather(string city = null, string id = null, string zip = null, string language = null, string units = null)
        {
            if (Int32.TryParse(city, out int ID))
            {
                city = null;  id = ID.ToString();
            }
            OpenWeatherService weatherService = new OpenWeatherService();
            ResultRequest      result         = await weatherService.GetWeatherAsync(city, id, zip, language, units);

            ViewBag.Error = result.RequestStatus;
            return(View(result.Weather));
        }
        /// <summary>
        /// Handles a <see cref="ResultRequest{I}" /> sent by a certain actor.
        /// </summary>
        /// <param name="request">The <see cref="ResultRequest{I}" /> to handle.</param>
        /// <param name="sender">The request's sender.</param>
        private void HandleResultRequest(ResultRequest <TInstance> request, IActorRef sender)
        {
            // Check if result is in storage.
            TResult result = null;

            if (this.LookUpResult(request.Genome, request.Instance, out result))
            {
                var resultMessage = new ResultMessage <TInstance, TResult>(request.Genome, request.Instance, result);
                sender.Tell(resultMessage);
            }
            else
            {
                var storageMissMessage = new StorageMiss <TInstance>(request.Genome, request.Instance);
                sender.Tell(storageMissMessage);
            }
        }
        public async Task <ActionResult <ResultResponse> > Create([FromBody] ResultRequest resultRequest)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var userName = this.User.Identity.Name;
            var user     = this.userManager.Users.SingleOrDefault(u => u.UserName == userName);

            var quiz = this.quizzesService.GetById <QuizPlayResponse>(resultRequest.QuizId);

            var maxPoints = quiz.Questions.Sum(q => q.Points);

            var resultId = await this.resultService.CreateAync(resultRequest.Points, maxPoints, user.Id, resultRequest.QuizId, resultRequest.MyAnswers.ToList());

            return(new ResultResponse {
                Id = resultId
            });
        }
示例#11
0
        public IHttpActionResult Put([FromBody] ResultRequest request)
        {
            using (var db = new Adriana42Context())
            {
                var selectionsRepository = new Repository <Models.Selection>(db);
                var selection            = selectionsRepository.GetById(request.SelectionId);
                if (selection == null)
                {
                    return(NotFound());
                }
                selection.Result = request.Result;

                var repository = new Repository <Models.Bet>(db);
                var bets       = repository.Find(b => b.SelectionId == request.SelectionId).ToList();
                bets.ForEach(b => b.Result = request.Result);

                db.SaveChanges();

                return(Ok());
            }
        }
示例#12
0
        public async Task <ResultRequest> RemoveAsync(Guid userId)
        {
            ResultRequest resultRequest = new ResultRequest {
                Type = ResultRequestType.Success, Message = ""
            };

            try
            {
                using (IDBWorker worker = kernel.Get <IDBWorker>())
                {
                    var user = await worker.UserManager.FindByIdAsync(userId);

                    var profile = worker.UserProfileRepository.Remove(user.UserProfile);
                    var result  = await worker.UserManager.DeleteAsync(user);

                    await worker.SaveAsync();

                    if (!result.Succeeded)
                    {
                        resultRequest = new ResultRequest {
                            Type = ResultRequestType.Error, Message = string.Join(",", result.Errors)
                        };
                    }
                }
            }
            catch (InvalidOperationException ioex)
            {
                resultRequest = new ResultRequest {
                    Type = ResultRequestType.Error, Message = ioex.Message
                };
            }
            catch (Exception ex)
            {
                resultRequest = new ResultRequest {
                    Type = ResultRequestType.Error, Message = ex.Message
                };
            }

            return(resultRequest);
        }
示例#13
0
        public async Task <ResultRequest <DtoTokenResponse> > LoginWithApiKey(
            [FromBody] InboundRequest <DtoAuthApiKey> request)
        {
            try
            {
                var dto = request?.Data;
                if (dto == null)
                {
                    return(ResultRequest <DtoTokenResponse> .Error("Access Token request fail",
                                                                   "Invalid request data"));
                }

                var token = await _service.GenerateToken(dto.ApiKey);

                return(ResultRequest <DtoTokenResponse> .Ok(token));
            }
            catch (Exception e)
            {
                return(ResultRequest <DtoTokenResponse> .Error("Access Token request error",
                                                               e.Message));
            }
        }
示例#14
0
        public async Task <ResponseOutput> GetResult(ResultRequest resultRequest)
        {
            var result = await _testResultRepo.Entities.FirstOrDefaultAsync(_ => _.GuidId == resultRequest.GuidId);

            var test = await _repository.Entities.FirstOrDefaultAsync(_ => _.Id == result.TestId);


            if (test == null || result == null)
            {
                return(new ResponseOutput(false, "Cannot found result of test"));
            }

            var resultOutput = new TestResultsView
            {
                Id            = result.Id,
                ExamedAt      = result.ExamedAt,
                CorrectAnswer = result.CorrectAnswer,
                GuidId        = result.GuidId,
                TestId        = result.TestId,
                TestName      = test.Title,
                TotalQuestion = result.TotalQuestion,
                TotalTime     = result.TotalTime,
                UserId        = result.UserId,
                TypeTestId    = test.TypeId
            };

            if (resultRequest.UserId.HasValue && resultRequest.UserId == result.UserId)
            {
                return(new ResponseOutput(true, resultOutput));
            }

            if (!resultRequest.UserId.HasValue && result.ExamedAt.CompareTo(DateTime.Now.AddDays(-1)) == 1)
            {
                return(new ResponseOutput(true, resultOutput));
            }

            return(new ResponseOutput(false, "Cannot find result of test "));
        }
示例#15
0
        //submit the test
        public async Task SubmitTest(ResultRequest resultRequest)
        {
            var test = await _baseRepository.GetById(resultRequest.TestId);

            if (test == null)
            {
                throw new Exception("Can not find this test!");
            }


            var result = new Result
            {
                AccountId = resultRequest.AccountId,
                TestId    = resultRequest.TestId,
                Score     = resultRequest.Score,
                Date      = DateTime.Now
            };

            var resultNew = await _resultService.Add(result);

            var list = new List <ResultDetailRequest>();

            for (int i = 0; i < resultRequest.Answers.Count(); i++)
            {
                var detailResult = new ResultDetailRequest
                {
                    ResultId    = resultNew.ResultId,
                    SelectedAns = resultRequest.Answers[i].Answer,
                    QuestionId  = resultRequest.Answers[i].QuestionId,
                    Ok          = resultRequest.Answers[i].Ok
                };
                list.Add(detailResult);
            }

            await _resultDetailService.AddRange(list);
        }
示例#16
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResultRequestTest"/> class.
 /// </summary>
 public ResultRequestTest()
 {
     this._resultRequestMessage = new ResultRequest <TestInstance>(ResultRequestTest.genome, ResultRequestTest.testInstance);
 }
示例#17
0
        /// <summary>
        /// Returns either json or full page html of a previous <see cref="MiniProfiler"/> session,
        /// identified by its <c>"?id=GUID"</c> on the query.
        /// </summary>
        /// <param name="context">The context to get a profiler response for.</param>
        private string GetSingleProfilerResult(HttpContext context)
        {
            Guid          id;
            ResultRequest clientRequest = null;
            // When we're rendering as a button/popup in the corner, it's an AJAX/JSON request.
            // If that's absent, we're rendering results as a full page for sharing.
            var jsonRequest = context.Request.Headers["Accept"]?.Contains("application/json") == true;

            // Try to parse from the JSON payload first
            if (jsonRequest &&
                context.Request.ContentLength > 0 &&
                ResultRequest.TryParse(context.Request.InputStream, out clientRequest) &&
                clientRequest.Id.HasValue)
            {
                id = clientRequest.Id.Value;
            }
            else if (Guid.TryParse(context.Request["id"], out id))
            {
                // We got the guid from the querystring
            }
            else if (Options.StopwatchProvider != null)
            {
                // Fall back to the last result
                id = Options.Storage.List(1).FirstOrDefault();
            }

            if (id == default(Guid))
            {
                return(jsonRequest ? NotFound(context) : NotFound(context, "text/plain", "No Guid id specified on the query string"));
            }

            var    profiler = Options.Storage.Load(id);
            string user     = Options.UserIdProvider?.Invoke(context.Request);

            Options.Storage.SetViewed(user, id);

            if (profiler == null)
            {
                return(jsonRequest ? NotFound(context) : NotFound(context, "text/plain", "No MiniProfiler results found with Id=" + id.ToString()));
            }

            bool needsSave = false;

            if (profiler.ClientTimings == null && clientRequest?.TimingCount > 0)
            {
                profiler.ClientTimings = ClientTimings.FromRequest(clientRequest);
                needsSave = true;
            }

            if (!profiler.HasUserViewed)
            {
                profiler.HasUserViewed = true;
                needsSave = true;
            }

            if (needsSave)
            {
                Options.Storage.Save(profiler);
            }

            if (!AuthorizeRequest(context, isList: false, message: out string authorizeMessage))
            {
                context.Response.ContentType = "application/json";
                return(@"""hidden"""); // JSON
            }

            return(jsonRequest ? ResultsJson(context, profiler) : ResultsFullPage(context, profiler));
        }
示例#18
0
        /// <summary>
        /// Returns either JSON or full page HTML of a previous <c>MiniProfiler</c> session,
        /// identified by its <c>"?id=GUID"</c> on the query.
        /// </summary>
        /// <param name="context">The context to get a profiler response for.</param>
        private async Task <string> GetSingleProfilerResultAsync(HttpContext context)
        {
            Guid          id;
            ResultRequest clientRequest = null;
            // When we're rendering as a button/popup in the corner, it's an AJAX/JSON request.
            // If that's absent, we're rendering results as a full page for sharing.
            bool jsonRequest = context.Request.Headers["Accept"].FirstOrDefault()?.Contains("application/json") == true;

            // Try to parse from the JSON payload first
            if (jsonRequest &&
                context.Request.ContentLength > 0 &&
                ResultRequest.TryParse(context.Request.Body, out clientRequest) &&
                clientRequest.Id.HasValue)
            {
                id = clientRequest.Id.Value;
            }
            else if (Guid.TryParse(context.Request.Query["id"], out id))
            {
                // We got the guid from the querystring
            }
            else if (Options.StopwatchProvider != null)
            {
                // Fall back to the last result
                id = (await Options.Storage.ListAsync(1).ConfigureAwait(false)).FirstOrDefault();
            }

            if (id == default(Guid))
            {
                return(NotFound(context, jsonRequest ? null : "No GUID id specified on the query string"));
            }

            var profiler = await Options.Storage.LoadAsync(id).ConfigureAwait(false);

            string user = Options.UserIdProvider?.Invoke(context.Request);

            await Options.Storage.SetViewedAsync(user, id).ConfigureAwait(false);

            if (profiler == null)
            {
                return(NotFound(context, jsonRequest ? null : "No MiniProfiler results found with Id=" + id.ToString()));
            }

            bool needsSave = false;

            if (profiler.ClientTimings == null && clientRequest?.TimingCount > 0)
            {
                profiler.ClientTimings = ClientTimings.FromRequest(clientRequest);
                needsSave = true;
            }

            if (!profiler.HasUserViewed)
            {
                profiler.HasUserViewed = true;
                needsSave = true;
            }

            if (needsSave)
            {
                await Options.Storage.SaveAsync(profiler).ConfigureAwait(false);
            }

            if (!AuthorizeRequest(context, isList: false, message: out string authorizeMessage))
            {
                context.Response.ContentType = "application/json";
                return(@"""hidden"""); // JSON
            }

            if (jsonRequest)
            {
                context.Response.ContentType = "application/json";
                return(profiler.ToJson());
            }
            else
            {
                context.Response.ContentType = "text/html; charset=utf-8";
                return(Render.SingleResultHtml(profiler, context.Request.PathBase + Options.RouteBasePath.Value.EnsureTrailingSlash()));
            }
        }
示例#19
0
 public ClientConnectedToServerVmEventArgs(ResultRequest result, string reason)
 {
     Result = result;
     Reason = reason;
 }
        static void Main()
        {
            // Create a new TransferGuard Service Client.
            var client = new TransferServiceClient();

            // Add the client certificate (where the subject is equal to SiteId) from the current user's personal certificate store.  The client certificate must be manually imported into the certificate store.
            if (client.ClientCredentials != null)
                client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, SiteId);

            // Get the current version of the TransferGuard Service
            var version = client.GetVersion();
            Console.WriteLine("Using TransferGuard Service Version: {0}\n", version);

            // Create an order.
            Console.WriteLine("Preparing to place order...\n");
            var orderRequest = new OrderRequest
                                   {
                                       HL7Message = @"<ORM_O01><MSH><MSH.1>|</MSH.1><MSH.2>^~\&amp;</MSH.2><MSH.3><HD.1>SENDING_APPLICATION</HD.1></MSH.3><MSH.4><HD.1>SENDING_FACILITY</HD.1></MSH.4><MSH.5><HD.1>PAML</HD.1></MSH.5><MSH.6><HD.1>PAML</HD.1></MSH.6><MSH.7><TS.1>20121204105753.865-0800</TS.1></MSH.7><MSH.9><MSG.1>ORM</MSG.1><MSG.2>O01</MSG.2><MSG.3>ORM_O01</MSG.3></MSH.9><MSH.10>1</MSH.10><MSH.11><PT.1>T</PT.1></MSH.11><MSH.12><VID.1>2.5.1</VID.1></MSH.12></MSH></ORM_O01>",
                                       SiteID = SiteId
                                   };

            // Place an order.
            var orderResponse = client.PlaceOrder(orderRequest);

            // Get the order message ID for tracking purposes.
            Console.WriteLine("Order successfully placed. You can use Message ID {0} to track the message.\n", orderResponse.MessageID);

            // Check if there are any results waiting.
            Console.WriteLine("Checking for pending results...\n");
            var resultRequest = new ResultRequest
                                    {
                                        SiteID = SiteId
                                    };

            var resultCount = client.GetPendingResultCount(resultRequest);
            Console.WriteLine("There are {0} result(s) waiting to be retieved.\n", resultCount);

            // If there are pending results, retrieve them
            if (resultCount > 0)
            {
                // Retrieve results.
                Console.WriteLine("Retrieving results...\n");
                var results = client.GetResults(resultRequest);

                var xmlResults = new XmlDocument();
                var ns = new XmlNamespaceManager(xmlResults.NameTable);
                ns.AddNamespace("v2xml", "urn:hl7-org:v2xml");

                int index = 0;
                foreach (Result result in results.Results)
                {
                    xmlResults.LoadXml(result.HL7Message);
                    XmlNode node = xmlResults.SelectSingleNode("//v2xml:ORU_R01/v2xml:MSH/v2xml:MSH.8", ns);
                    Console.WriteLine("Result Message {0}   ID: {1}", index, node.InnerXml);
                    index++;
                }
            }

            Console.WriteLine("\nPress enter to continue...");
            Console.ReadLine();
        }
        public async Task <IActionResult> GetResult([FromBody] ResultRequest request, CancellationToken cancellationToken)
        {
            var response = await _demoService.GetResult(request, cancellationToken);

            return(Ok(response));
        }
示例#22
0
 public async Task <ResultResponse> GetResult(ResultRequest request, CancellationToken cancellationToken)
 {
     return(await _demoApp.GetResult(request, cancellationToken));
 }
示例#23
0
        public async Task <IActionResult> SubmitTest(ResultRequest submitResultTest)
        {
            await _testService.SubmitTest(submitResultTest);

            return(Content("Success"));
        }
示例#24
0
 public async Task <ResponseOutput> GetResult([FromBody] ResultRequest resultRequest)
 {
     return(await _service.GetResult(resultRequest));
 }
示例#25
0
 public ConnectionResponse(ResultRequest result, string reason)
 {
     Result = result;
     Reason = reason;
 }
示例#26
0
 public async Task <ResultResponse> GetResult(ResultRequest request, CancellationToken cancellationToken)
 {
     return(await _stateProvider.Get <ResultResponse>(request.Token, cancellationToken));
 }
示例#27
0
 public string AddResult(int quizId, [FromBody] ResultRequest value)
 {
     _resultService.UpdateResult(value.attempt, value.question, value.correct);
     return("OK");
 }