public void TestPost() { var controller = new RequestController() { UserAgent = "salient.ReliableHttpClient" }; var gate = new AutoResetEvent(false); Exception exception = null; string responseText = null; var headers = new Dictionary<string, object> { { "TEST_HEADER", "VALUE" } }; // http://www.henrycipolla.com/blog/2010/10/let-me-dump-your-post-free-http-post-test-server controller.BeginRequest(new Uri("http://posttestserver.com/post.php?dump"), RequestMethod.POST, "foo=bar", headers, ContentType.FORM, ContentType.TEXT, TimeSpan.Zero, 3000, "target", "uriTemplate", 0, null, ar => { try { controller.EndRequest(ar); responseText = ar.ResponseText; Console.WriteLine(responseText); } catch (Exception ex) { exception = ex; } gate.Set(); }, null); if (!gate.WaitOne(10000)) { throw new Exception("timed out"); } if (exception != null) { Assert.Fail(exception.Message); } }
private Client BuildClientAndSetupResponse(string expectedJson) { TestRequestFactory factory = new TestRequestFactory(); var requestController = new RequestController(TimeSpan.FromSeconds(0), 2, factory, new DummyJsonExceptionFactory(), new ThrottledRequestQueue(TimeSpan.FromSeconds(5), 30, 10, "default")); var ctx = new Client(new Uri("http://foo.bar"), requestController); factory.CreateTestRequest(expectedJson); return ctx; }
public async Task Create_SendsEventSummaryQuery_WithCorrectEventId() { const int id = 1; var mediator = new Mock <IMediator>(); mediator.Setup(mock => mock.SendAsync(It.IsAny <EventSummaryQuery>())).ReturnsAsync(null).Verifiable(); var sut = new RequestController(mediator.Object); await sut.Create(id); mediator.Verify(x => x.SendAsync(It.Is <EventSummaryQuery>(a => a.EventId == id)), Times.Once); }
private void overtimeRequestButton_Click(object sender, EventArgs e) { var overtime = workingHour.Text.Split(':'); TimeSpan time = new TimeSpan(0); try { if (overtime.Length >= 1) { time = new TimeSpan(Convert.ToInt32(overtime[0]), 0, 0); } else if (overtime.Length >= 2) { time = new TimeSpan(Convert.ToInt32(overtime[0]), Convert.ToInt32(overtime[1]), 0); } } catch (FormatException ex) { showErrorMessage("Invalid working hour value"); return; } if (time <= new TimeSpan(0)) { showErrorMessage("Invalid working hour value"); return; } if (overtimeRequestDescription.Text.Trim().Equals("")) { showErrorMessage("Description must not be empty."); return; } EmployeeControllerInterface employeeController = new EmployeeController(); Employee employee = employeeController.fetchEmployeeByUsername(user.username); Request request = new Request(); request.employee = employee; request.name = "OVERTIME"; request.requestedDate = Convert.ToDateTime(dateOfRequest.Text); request.status = RequestStatus.Pending; request.description = overtimeRequestDescription.Text; DateTime date = DateTime.Now; request.dateFiled = new DateTime(date.Year, date.Month, date.Day, time.Hours, time.Minutes, 0);// Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyyy ")); RequestControllerInterface requestController = new RequestController(); request = requestController.createRequest(request); if (request != null) { loadPendingRequest(); homeTabs.SelectedTab = pendingRequestTab; } }
public ActionResult ScheduleRecurringJob(NewRecurringJobBE recurringJobConfig) { string recurringJobId = recurringJobConfig.JobId.ToLower();; // 1st remove the Job if it exists RecurringJob.RemoveIfExists(recurringJobId); TimeZoneInfo timeZoneInfo = TimeZoneInfo.Local; switch (recurringJobConfig.ScheduleTimeZone.ToUpper()) { case "EST": timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); break; default: timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"); break; } // run the background job immediately //_backgroundJobClient.Enqueue(() => Console.WriteLine("Hello Hangfire job!")); // setup a recurring job #region Using Expression //var manager = new RecurringJobManager(); //manager.AddOrUpdate(recurringJobId, Job.FromExpression(() => Console.WriteLine("Hello Hangfire job!")), @"0-59 * * * MON,TUE,WED,THU,FRI", timeZoneInfo); #endregion #region Using Reflection //RecurringJob.AddOrUpdate(recurringJobId, () => RequestController.EnqueueRequest(@"EventTypeA", // @"FIS.Paymetric.POC.EventTypeA.Plugin.EventTypeAPublisher", // @"FIS.Paymetric.POC.EventTypeA.Plugin", // @"Execute", // @"xtobr"), // @"0-59 * * * MON,TUE,WED,THU,FRI", // timeZoneInfo); #endregion //RecurringJob.AddOrUpdate(recurringJobId, () => RequestController.EnqueueRequest(@"EventTypeA"), // @"0-59 * * * MON,TUE,WED,THU,FRI", // timeZoneInfo); RecurringJob.AddOrUpdate(recurringJobId, () => RequestController.EnqueueRequest(recurringJobConfig.JobId, recurringJobConfig.JobPlugInType), recurringJobConfig.CronSchedule, timeZoneInfo); return(Ok($"Recurring job: [{recurringJobId}] created.")); }
public void ReproAbortedRequest() { TestRequestFactory factory = new TestRequestFactory(); var requestController = new RequestController(TimeSpan.FromSeconds(0), 2, factory, new ErrorResponseDTOJsonExceptionFactory(), new ThrottedRequestQueue(TimeSpan.FromSeconds(5), 30, 10, "data"), new ThrottedRequestQueue(TimeSpan.FromSeconds(3), 1, 3, "trading")); var ctx = new CIAPI.Rpc.Client(new Uri(TestConfig.RpcUrl), requestController); ctx.UserName = TestConfig.ApiUsername; ctx.Session = TestConfig.ApiTestSessionId; factory.CreateTestRequest("{}", TimeSpan.FromMinutes(1)); ctx.Market.GetMarketInformation("FOO"); }
protected override DataTable getVariableImpl(VariableDefinition def, CallerController <CallerData> caller, RequestController <RequestData> request) { try { IncomingAggreGateCommand ans = sendGetVariable(def.getName()); return(decodeRemoteDataTable(def.getFormat(), ans.getEncodedDataTableFromReply())); } catch (Exception ex) { Log.CONTEXT_VARIABLES.debug("Error getting variable '" + def.getName() + "' from context '" + this.getPath() + "'", ex); throw new ContextException(ex.Message, ex); } }
protected override Boolean setVariableImpl(VariableDefinition def, CallerController <CallerData> caller, RequestController <RequestData> request, DataTable value) { try { controller.sendCommandAndCheckReplyCode(ClientCommandUtils.setVariableOperation(this.getPath(), def.getName(), value.encode(controller.createClassicEncodingSettings(true)))); return(true); } catch (Exception ex) { Log.CONTEXT_VARIABLES.debug("Error setting veriable '" + def.getName() + "' of context '" + this.getPath() + "'", ex); throw new ContextException(ex.Message, ex); } }
public RequestControllerTest() { _mockRequestManager = new Mock <IRequestManager>(); var _mockContextProvider = new Mock <IContextProvider>(); var _mockFileOperationManager = new Mock <IFileOperationsManager>(); _mockRequestManager.Setup(x => x.GetLearnerRequests()).ReturnsAsync(mockRequestModelList); _mockRequestManager.Setup(x => x.ListAllRequests(It.IsAny <RequestSearchFilter>())).ReturnsAsync(mockRequestListResponse); _mockRequestManager.Setup(x => x.DownloadAssignment(It.IsAny <IEnumerable <Guid> >())).ReturnsAsync(mockFileDownloadResponse); _mockRequestManager.Setup(x => x.UpdateAssignmentDueDate(mockrequestId, mocknewAssignmentDueDate)).ReturnsAsync(mockresponse); requestController = new RequestController(_mockContextProvider.Object, _mockRequestManager.Object, _mockFileOperationManager.Object); }
public async Task EditGet_ReturnsHttpUnauthorizedResult_WhenUserIsNotOrgAdmin() { var mediator = new Mock <IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny <EditRequestQuery>())).ReturnsAsync(new EditRequestViewModel()); var sut = new RequestController(mediator.Object); sut.MakeUserNotAnOrgAdmin(); var result = await sut.Edit(Guid.NewGuid()); Assert.IsType <UnauthorizedResult>(result); }
public async Task EditPost_ReturnsHttpUnauthorizedResult_WhenUserIsNotOrgAdmin() { var mediator = new Mock <IMediator>(); mediator.Setup(mock => mock.SendAsync(It.IsAny <EventSummaryQuery>())).ReturnsAsync(new EventSummaryViewModel()); var sut = new RequestController(mediator.Object); sut.MakeUserNotAnOrgAdmin(); var result = await sut.Edit(new EditRequestViewModel { EventId = 1 }); Assert.IsType <UnauthorizedResult>(result); }
//private ILogWriter _logger; /// <summary> /// The controller module uses the prototype design pattern /// to be able to create new controller objects for requests /// if the stack is empty. /// </summary> /// <param name="prototype">A prototype which will be cloned for each request</param> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="InvalidProgramException">If a controller with that name have been added already.</exception> public void Add(RequestController prototype) { Check.Require(prototype, "prototype"); lock (_controllers) { if (_controllers.ContainsKey(prototype.ControllerName)) { throw new InvalidOperationException("Controller with name '" + prototype.ControllerName + "' already exists."); } _controllers.Add(prototype.ControllerName, new ControllerContext(prototype)); } }
public async Task Create_ReturnsBadRequest_WhenEventSummaryQueryReturnsNull() { var mockMediator = new Mock <IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventSummaryQuery>())).ReturnsAsync(null).Verifiable(); var sut = new RequestController(mockMediator.Object); var result = await sut.Create(1); var objResult = Assert.IsType <BadRequestObjectResult>(result); objResult.StatusCode.ShouldNotBeNull(); objResult.StatusCode.Value.ShouldBe(StatusCodes.Status400BadRequest); }
public void ReviewControllerDetailsReturnsView_ExpectedSuccess() { var _mock = new Mock <IRequestLogic>(); _mock.Setup(x => x.GetSingleRequest(It.IsAny <Int32>())).ReturnsAsync(GetRequest()); var controllerUnderTest = new RequestController(_context, _mock.Object); // Act var result = controllerUnderTest.Details(1); // Assert Assert.NotNull(result); var viewResult = Assert.IsType <Task <IActionResult> >(result); }
public void ConfirmUpdate_Success() { var contextMock = new Mock <IDbContext>(); var hostingEnv = new Mock <IHostingEnvironment>(); var controller = new RequestController(contextMock.Object, hostingEnv.Object); var modelMock = MockCreateRequestViewModel(); var response = controller.ConfirmUpdate(modelMock); var result = response as ViewResult; Assert.IsType <ViewResult>(response); CheckModelValues(modelMock, (result.ViewData.Values.ElementAt(0) as CreateRequestViewModel)); }
public async Task EditPost_ReturnsForbidResult_WhenUserIsNotAuthorized() { var mediator = new Mock <IMediator>(); mediator.Setup(mock => mock.SendAsync(It.IsAny <EventSummaryQuery>())).ReturnsAsync(new EventSummaryViewModel()); mediator.Setup(x => x.SendAsync(It.IsAny <AuthorizableEventQuery>())).ReturnsAsync(new FakeAuthorizableEvent(false, false, false, false)); mediator.Setup(x => x.SendAsync(It.IsAny <AuthorizableRequestQuery>())).ReturnsAsync(new FakeAuthorizableRequest(false, false, false, false)); var sut = new RequestController(mediator.Object); var result = await sut.Edit(new EditRequestViewModel { EventId = 1 }); Assert.IsType <ForbidResult>(result); }
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { RequestController requestController = new RequestController(); //this.RelayState.Value = relayStateToBepersistedAcross; this.SAMLRequest.Value = requestController.MontaRequestXML(); //this.form1.Action = appSettings.Get("formActionAuthnDestination"); this.form1.Action = ConfigurationManager.AppSettings["AMA_formActionAuthnDestination"]; } }
// Start is called before the first frame update IEnumerator LoginEnumerator(string username, string password) { var login = new LoginForm(username, password); var f = JsonUtility.ToJson(login); var bytes = System.Text.Encoding.UTF8.GetBytes(f); Debug.Log(f); //74 65 73 74 33 e2 80 8b //74 65 73 74 33 yield return(RequestController.PostRequestWorkaround("authentication/login", bytes, "")); string jsonCode = RequestController.GetResponseData(); try { code = JsonUtility.FromJson <Code>(jsonCode).code; } catch { Debug.LogWarning("Failed to login"); yield break; } //WWWForm tokenForm = new WWWForm(); // tokenForm.AddField("grantType", "authorization_code"); //tokenForm.AddField("code", code); TokenForm t = new TokenForm("authorization_code", code); var tok = JsonUtility.ToJson(t); var tokenBytes = System.Text.Encoding.UTF8.GetBytes(tok); yield return(RequestController.PostRequestWorkaround("token", tokenBytes, "")); string jsonToken = RequestController.GetResponseData(); accessToken = JsonUtility.FromJson <Token>(jsonToken).accessToken; todoList.SetActive(true); mainMenu.SetActive(false); SessionController.SetAccessToken(accessToken); yield return(sessionController.GetLists()); UISystem.instance.GenerateTaskLists(); yield return(sessionController.GetAllTasks()); UISystem.instance.MapTasksToLists(); }
public static void saveFcmID(string fcmId) { var client = new RestClient(); client.BaseUrl = new Uri(Constants.RestBaseUri); client.Authenticator = new NtlmAuthenticator(); var request = new RestRequest("/login", Method.POST); request.AddParameter("loginid", Data.DataHandler.getLoginData().loginid); request.AddParameter("fcmid", fcmId); IRestResponse response = new RequestController(request).send(); }
public void RequestControllerCreateReturnsView_ExpectedSuccess() { // Arrange var requests = GetRequests(); var _mock = new Mock <IRequestLogic>(); _mock.Setup(x => x.GetPassengerRequests(It.IsAny <Int32>())).ReturnsAsync(requests); var controllerUnderTest = new RequestController(_context, _mock.Object); // Act var result = controllerUnderTest.Create(GetRequest(), "*****@*****.**"); // Assert var viewResult = Assert.IsType <Task <IActionResult> >(result); }
private async void XtraMainForm_KeyPress(object sender, KeyPressEventArgs e) { if (!checkBoxKeyboardHelper.Checked) { return; } try { await RequestController.AppPostExecution(comboBoxSelectHostname.Text, APIController.SendText, e.KeyChar.ToString()); } catch (Exception ex) { MessageBox.Show(ex.ToString(), "Exception Error", MessageBoxButtons.OK, MessageBoxIcon.Question); } }
// Here we test if the requests are ordered // correctly by score. public void TestIndexScore() { //Arrange var mockUnitOfWork = new MockUnitOfWork(); mockUnitOfWork.MediaRepository.Insert(new Movie { ID = 1, Title = "Test", CategoryID = 1, ReleaseYear = 1998, }); var movie = new Movie { ID = 1, Title = "Test", CategoryID = 1, ReleaseYear = 1998, }; for (int i = 1; i < 8; i++) { mockUnitOfWork.RequestRepository.Insert(new Request { ID = i, MediaID = 1, LanguageID = i, Score = i, Media = movie, }); } var controller = new RequestController(mockUnitOfWork); //Act var result = controller.Index("Score"); //Assert var viewresult = (ViewResult)result; List <RequestVoteViewModel> model = viewresult.Model as List <RequestVoteViewModel>; Assert.IsTrue(model.Count() == 7); for (int i = 0; i < model.Count() - 1; i++) { Assert.IsTrue(model[i].Request.Score <= model[i + 1].Request.Score); } }
private void btnComplete_Click(object sender, EventArgs e) { currentServiceRequest.Status = "Resolved"; RequestController rqCtr = new RequestController(); rqCtr.Update(currentServiceRequest); if (sdLogic.GetQueueDuration(tech) == 0) { tech.EmploymentStatus = "Open"; TechnicianController techCtr = new TechnicianController(); techCtr.Update(tech); } LoadData(); }
public void UpdatePickupAddress_Success_Address_Found() { var contextMock = new Mock <IDbContext>(); var hostingEnv = new Mock <IHostingEnvironment>(); var controller = new RequestController(contextMock.Object, hostingEnv.Object); var requestMock = MockRequestModel(); var modelMock = MockCreateRequestViewModel(); contextMock.Setup(x => x.IfExistingAddress(It.IsAny <Address>())).Returns(true); contextMock.Setup(x => x.GetAddressId(It.IsAny <Address>())).Returns(1); controller.UpdatePickupAddress(modelMock, requestMock); contextMock.Verify(x => x.GetAddressId(It.IsAny <Address>()), Times.Once()); Assert.Equal(1, requestMock.PickupAddressId); }
private void button2_Click(object sender, EventArgs e) { RegisterBindingModel registerData = new RegisterBindingModel() { FirstName = nameText.Text, LastName = secondText.Text, SecondName = lastText.Text, DateOfBith = new DateTime(Convert.ToInt32(Year.SelectedItem), Mounth.SelectedIndex + 1, Convert.ToInt32(Day.SelectedItem)), Photo = imageToByteArray(pictureBox1.Image), Email = emailText.Text, Password = textBox1.Text, ConfirmPassword = textBox2.Text }; RequestController.HttpPOST(_registrationUrl, JsonConvert.SerializeObject(registerData), "application/json"); }
public async Task EditGet_ReturnsViewResult_WhenRequestIsFoundAndUserIsAuthorized() { var mediator = new Mock <IMediator>(); mediator.Setup(x => x.SendAsync(It.IsAny <EditRequestQuery>())).ReturnsAsync(new EditRequestViewModel { Name = "test" }); mediator.Setup(x => x.SendAsync(It.IsAny <AuthorizableRequestQuery>())).ReturnsAsync(new FakeAuthorizableRequest(true, false, false, false)); var sut = new RequestController(mediator.Object); var result = await sut.Edit(Guid.NewGuid()) as ViewResult; result.ViewName.ShouldBe("Edit"); result.ViewData["Title"].ShouldBe("Edit test"); }
public void CreateNewNewContractRequest(ServiceContract serviceContract, Client client) { endCall(); NewContractRequestController newContractRequestController = new NewContractRequestController(); RequestController requestController = new RequestController(); NewContractRequest newContractRequest = new NewContractRequest( DateTime.Now, null, callLog ); newContractRequestController.Create(newContractRequest); newContractRequestController.Set(serviceContract, newContractRequest); requestController.Set(client, newContractRequest); }
public async Task Create_ReturnsHttpUnauthorizedResult_WhenUserIsNotOrgAdmin() { var mockMediator = new Mock <IMediator>(); mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventSummaryQuery>())).ReturnsAsync(new EventSummaryViewModel()); var sut = new RequestController(mockMediator.Object); sut.MakeUserNotAnOrgAdmin(); var result = await sut.Create(1); var objResult = Assert.IsType <UnauthorizedResult>(result); objResult.StatusCode.ShouldBe(StatusCodes.Status401Unauthorized); }
public void RequestControllerDriverIndexReturnsView_ExpectedSuccess() { // Arrange var requests = GetRequests(); var _mock = new Mock <IRequestLogic>(); _mock.Setup(x => x.GetDriverRequests(It.IsAny <Int32>())).ReturnsAsync(requests); var controllerUnderTest = new RequestController(_context, _mock.Object); // Act var result = controllerUnderTest.DriverIndex(1); // Assert Assert.NotNull(result); Assert.Equal(typeof(Task <IActionResult>), result.GetType()); }
/// <summary> /// Method that process the incoming request. /// </summary> /// <param name="request">Information sent by the browser about the request</param> /// <param name="response">Information that is being sent back to the client.</param> /// <param name="session">Session used to </param> public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session) { if (request.UriParts.Length == 0) { return(false); } ControllerContext context; lock (_controllers) { if (_controllers.ContainsKey(request.UriParts[0])) { context = _controllers[request.UriParts[0]]; } else { return(false); } } if (!context.Prototype.CanHandle(request)) { return(false); } RequestController controller = null; try { lock (context) controller = context.Pop(); controller.Process(request, response, session); } finally { if (controller != null) { lock (context) context.Push(controller); } } return(true); }
public async Task EditGet_ReturnsNotFound_WhenEditRequestQueryReturnsNull() { var eventId = Guid.NewGuid(); EditRequestQuery eventSummaryQuery = null; // will be assigned from the Moq callback var mockMediator = new Mock <IMediator>(); mockMediator.Setup(x => x.SendAsync(It.IsAny <EditRequestQuery>())).ReturnsAsync(null).Callback <EditRequestQuery>(cmd => eventSummaryQuery = cmd).Verifiable(); var sut = new RequestController(mockMediator.Object); var result = await sut.Edit(eventId); var objResult = Assert.IsType <NotFoundResult>(result); objResult.StatusCode.ShouldBe(StatusCodes.Status404NotFound); }
public async Task EditGet_SendsEditRequestQueryQuery_WithCorrectArguments() { var eventId = Guid.NewGuid(); EditRequestQuery eventSummaryQuery = null; // will be assigned from the Moq callback var mockMediator = new Mock <IMediator>(); mockMediator.Setup(x => x.SendAsync(It.IsAny <EditRequestQuery>())).ReturnsAsync(null).Callback <EditRequestQuery>(cmd => eventSummaryQuery = cmd).Verifiable(); var sut = new RequestController(mockMediator.Object); await sut.Edit(eventId); mockMediator.Verify(x => x.SendAsync(It.IsAny <EditRequestQuery>()), Times.Once); eventSummaryQuery.Id.ShouldBe(eventId); }
public static MockClient AuthenticatedClient() { _requestFactory = new TestRequestFactory(); var requestController = new RequestController(TimeSpan.FromSeconds(0), 0, _requestFactory, new ErrorResponseDTOJsonExceptionFactory(), new ThrottedRequestQueue(TimeSpan.FromSeconds(5), 30, 10, "data"), new ThrottedRequestQueue(TimeSpan.FromSeconds(3), 1, 3, "trading")); var authenticatedClient = new MockClient { _client = new Client(new Uri("https://mock.server.com/TradingAPI"), requestController) { UserName = "******", Session = "MOCKSESSION" } }; return authenticatedClient; }
public void PostCaseValidRequest() { var requestDTO = new RequestDTO(oneRequest); var requestLogicMock = new Mock <IRequestLogic>(MockBehavior.Strict); requestLogicMock.Setup(m => m.Create(It.IsAny <Request>())).Returns(oneRequest.RequestNumber); var reauestController = new RequestController(requestLogicMock.Object); var result = reauestController.Post(requestDTO); var okResult = result as OkObjectResult; var value = okResult.Value; requestLogicMock.VerifyAll(); Assert.AreEqual(oneRequest.RequestNumber, value); }
public void TestGet() { var logger = LogManager.GetLogger(typeof(RequestController)); var controller = new RequestController(new Serializer()); var gate = new AutoResetEvent(false); Exception exception = null; string responseText = null; controller.BeginRequest(new Uri("http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo"), RequestMethod.GET, null, null, ContentType.TEXT, ContentType.TEXT, TimeSpan.FromSeconds(1), 3000, "http://api.geonames.org", "citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo", 0, new Dictionary<string, object>(), ar => { try { controller.EndRequest(ar); responseText = ar.ResponseText; Console.WriteLine(responseText); } catch (Exception ex) { exception = ex; } gate.Set(); }, null); if (!gate.WaitOne(10000)) { throw new Exception("timed out"); } // verify cache has purged gate.WaitOne(3000); if (exception != null) { Assert.Fail(exception.Message); } var output = GetLogOutput(); }
public void RequestControllerDidReceiveResponse(RequestController p0) { _Activity.DismissDialog(DIALOG_PROGRESS); _Activity.dialogSuccessMsg = _Activity.GetString(Resource.String.profile_success); _Activity.ShowDialog(DIALOG_SUCCESS); }
public void RequestControllerDidFail(RequestController controller, Java.Lang.Exception exception) { _Activity.DismissDialog(DIALOG_PROGRESS); // Error handling has to account for many different types of // failures... if(exception is RequestControllerException) { RequestControllerException ctrlException = (RequestControllerException) exception; if(ctrlException.HasDetail(RequestControllerException.DetailUserUpdateRequestEmailTaken)) { // this case is not quite a fatal error. if the email address is already // taken, an email will be sent to it to allow the user to link this device // with his account. // that's why we'll show a success dialog in this case. _Activity.dialogSuccessMsg = _Activity.GetString(Resource.String.profile_success_email_taken); _Activity.ShowDialog(DIALOG_SUCCESS); } else { // in any of these cases it's an error: _Activity.dialogErrorMsg = ""; // email may be invalid if(ctrlException.HasDetail(RequestControllerException.DetailUserUpdateRequestInvalidEmail)) { _Activity.dialogErrorMsg += _Activity.GetString(Resource.String.profile_error_email_invalid); } // username may be invalid, taken or too short if(ctrlException.HasDetail(RequestControllerException.DetailUserUpdateRequestUsernameTaken)) { _Activity.dialogErrorMsg += _Activity.GetString(Resource.String.profile_error_username_taken); } else if (ctrlException.HasDetail(RequestControllerException.DetailUserUpdateRequestUsernameTooShort)) { _Activity.dialogErrorMsg += _Activity.GetString(Resource.String.profile_error_username_too_short); } else if (ctrlException.HasDetail(RequestControllerException.DetailUserUpdateRequestInvalidUsername)) { _Activity.dialogErrorMsg += _Activity.GetString(Resource.String.profile_error_username_invalid); } _Activity.ShowDialog(DIALOG_ERROR); } } else { // generic Exception _Activity.dialogErrorMsg = exception.LocalizedMessage; _Activity.ShowDialog(DIALOG_ERROR); } // update displayed values User user = ((UserController)controller).User; _Activity.usernameText.Text = user.Login; _Activity.emailText.Text = user.EmailAddress; }
private CIAPI.Rpc.Client BuildClientAndSetupResponse(string expectedJson) { TestRequestFactory factory = new TestRequestFactory(); var requestController = new RequestController(TimeSpan.FromSeconds(0), 2, factory, new ErrorResponseDTOJsonExceptionFactory(), new ThrottedRequestQueue(TimeSpan.FromSeconds(5), 30, 10, "data"), new ThrottedRequestQueue(TimeSpan.FromSeconds(3), 1, 3, "trading")); var ctx = new CIAPI.Rpc.Client(new Uri(TestConfig.RpcUrl), requestController); factory.CreateTestRequest(expectedJson); return ctx; }
public void RequestControllerDidReceiveResponse(RequestController requestController) { // get the scores from our controller ScoresController scoresController = (ScoresController) requestController; var scores = scoresController.Scores; // set up the leaderboard as string array var scoreList = new List<String>(); int i = 0; foreach ( Score score in scores) { scoreList.Add(++i + ". " + score.User.DisplayName + " - " + ScoreFormatter.Format(score)); } // find the list ListView list = _Activity.FindViewById<ListView>(Resource.Id.leaderboard_list); // set up an adapter for our list view var adapter = new ArrayAdapter<String>(_Activity, Android.Resource.Layout.SimpleListItem1, scoreList); // put the adapter into the list list.Adapter = adapter; // we're done! _Activity.DismissDialog(DIALOG_PROGRESS); }
public void RequestControllerDidFail(RequestController controller, Java.Lang.Exception exception) { _Activity.DismissDialog(DIALOG_PROGRESS); _Activity.ShowDialog(DIALOG_ERROR); }
public void RequestControllerDidFail(RequestController p0, Java.Lang.Exception p1) { // something went wrong... possibly no internet connection _Activity.DismissDialog(DIALOG_PROGRESS); _Activity.ShowDialog(DIALOG_FAILED); }
public void RequestControllerDidReceiveResponse(RequestController p0) { // reset the text field to 0 _Activity.scoreField.Text = "0"; // remove the progress dialog _Activity.DismissDialog(DIALOG_PROGRESS); // show the success dialog _Activity.ShowDialog(DIALOG_SUBMITTED); // alternatively, you may want to return to the main screen // or start another round of the game at this point }