public void Post_Returns_IEntryResponse() { //Arrange var controller = new ParkingRateController(); var entryRequest = new EntryRequest { EntryTime = DateTime.Now.AddHours(1), ExitTime = DateTime.Now.AddHours(1.1), RegistrationNo = "Test" }; //Act var actionResult = controller.Post(entryRequest); //Assert Assert.IsInstanceOf <OkObjectResult>(actionResult.Result); var result = (EntryResponse)((OkObjectResult)actionResult.Result).Value; Assert.IsInstanceOf <EntryResponse>(result); Assert.AreEqual(200, ((OkObjectResult)actionResult.Result).StatusCode); Assert.AreEqual(entryRequest.EntryTime, result.EntryTime); Assert.AreEqual(entryRequest.ExitTime, result.ExitTime); Assert.AreEqual(entryRequest.RegistrationNo, result.RegistrationNo); Assert.IsTrue(result.Amount > 0); }
public static IEnumerable<AssociatedSchool> GetAssociatedSchoolsWithClaim(UserInformation userInfo, string claimType, EntryRequest request) { if (!request.LocalEducationAgencyId.HasValue) { return (from school in userInfo.AssociatedSchools where school.ClaimTypes.Any(ct => ct == claimType) select new AssociatedSchool { LocalEducationAgencyId = school.LocalEducationAgencyId, SchoolId = school.SchoolId, SchoolName = school.Name }); } return (from school in userInfo.AssociatedSchools where school.ClaimTypes.Any(ct => ct == claimType) && school.LocalEducationAgencyId == request.LocalEducationAgencyId select new AssociatedSchool { LocalEducationAgencyId = school.LocalEducationAgencyId, SchoolId = school.SchoolId, SchoolName = school.Name }); }
public bool Run(string hash) { Request = new EntryRequest(); Request.param.hash = hash; return(Run(Request)); }
public async Task <ActionResult <Entry> > PostEntry(EntryRequest request) { if (!HasPermission(request.AuthorId)) { return(StatusCode(StatusCodes.Status403Forbidden)); } if (request.Text is null) { return(BadRequest()); } request.Text = request.Text.Trim(); if (request.Text == string.Empty) { return(BadRequest()); } request.Text = Util.Truncate(request.Text, MaxLength.Entry); Entry entry = new() { AuthorId = request.AuthorId, Text = request.Text, Timestamp = DateTime.UtcNow }; context.Entries.Add(entry); await context.SaveChangesAsync(); return(Ok(entry.Id)); }
public IActionResult Index(string id, string phone, EntryRequest request, string zip) { Entry entry = null; try { if (String.IsNullOrWhiteSpace(zip)) { zip = "00000"; } if (String.IsNullOrWhiteSpace(id) || id.Equals("000000000000000000000000")) { entry = new Entry() { timestamp = DateTime.Now, phone = phone, zip = zip, request = request }; entry.Validate(); _save.Add(entry); } else { entry = _save.Find(new ObjectId(id)); if (entry == null) { entry = new Entry(); entry.id = new ObjectId(id); } entry.phone = phone; entry.zip = zip; entry.request = request; entry.Validate(); _save.Replace(entry); } return(View(_save.GetNoZip())); } catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.Append("Fehler: "); if (entry != null) { } DataContractJsonSerializer dcjs = new DataContractJsonSerializer(entry.GetType()); using (MemoryStream ms = new MemoryStream()) { dcjs.WriteObject(ms, entry); sb.AppendLine(Encoding.Default.GetString(ms.ToArray())); }; sb.AppendLine(e.ToString()); Console.WriteLine(sb.ToString()); return(BadRequest(e.Message)); } }
private async Task <HttpResponseMessage> AddComment(int id, EntryRequest data) { var request = new HttpRequestMessage(HttpMethod.Post, $"api/entries/{id}/comments") { Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json") }; var response = await client.SendAsync(request); return(response); }
public IActionResult Send(string id, string phone, EntryRequest request, string zip, string captchasecret, string captchaid) { Entry entry = null; try { if (String.IsNullOrWhiteSpace(zip)) { zip = "00000"; } if (String.IsNullOrWhiteSpace(id) || id.Equals("000000000000000000000000")) { entry = new Entry() { timestamp = DateTime.Now, phone = phone, zip = zip, request = request }; if (capatchaFactory.VerifyAndDelete(captchaid, captchasecret.ToUpper())) { entry.Validate(); _save.Add(entry); } else { return(AddFrame(entry, "Captcha nicht gelöst")); } } else { throw new NotSupportedException("Bearbeiten nicht erlaubt"); } return(View(entry)); }catch (Exception e) { StringBuilder sb = new StringBuilder(); sb.Append("Fehler: "); if (entry != null) { } DataContractJsonSerializer dcjs = new DataContractJsonSerializer(entry.GetType()); using (MemoryStream ms = new MemoryStream()) { dcjs.WriteObject(ms, entry); sb.AppendLine(Encoding.Default.GetString(ms.ToArray())); }; sb.AppendLine(e.ToString()); Console.WriteLine(sb.ToString()); return(BadRequest(e.Message)); } }
public async Task <Entry> CreateEntryAsync(EntryRequest request) { var entries = await context.Entries.Find(i => i.Article == request.Article).FirstOrDefaultAsync(); if (entries != null) { throw new RequestedResourceHasConflictException(nameof(request.Article)); } var entry = mapper.Map <EntryRequest, Entry>(request); await context.Entries.InsertOneAsync(entry); return(entry); }
public async Task <ActionResult> AddEntry([FromBody] EntryRequest createRequest) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var entry = await service.CreateEntryAsync(createRequest); var location = string.Format("/api/entries/{0}", entry.Id); return(Created(location, entry)); }
public bool Run(EntryRequest requestData) { var reply = Client.MakeRequest <EntryRequest>(requestData); JsonReply = reply.Content; if (reply.StatusCode == System.Net.HttpStatusCode.OK) { Result = JsonConvert.DeserializeObject <EntryResult>(reply.Content); return(true); } return(false); }
public IActionResult Post(EntryRequest model) { Response response = new Response(); using (JobsPhonesCTX db = new JobsPhonesCTX()) { using (var dbContextTransaction = db.Database.BeginTransaction()) { try { Entrada entrada = new Entrada(); entrada.IdUsuarioAdmin = model.IdUsuarioAdmin; entrada.IdProveedorEntrada = model.IdProveedorEntrada; entrada.FechaEntrada = DateTime.Now; entrada.IdEstadoEntrada = 1; db.Entrada.Add(entrada); db.SaveChanges(); foreach (var detalle in model.Detalles) { DetalleEntrada de = new DetalleEntrada(); de.IdEntrada = entrada.Id; de.IdProductoEntrada = detalle.IdProductoEntrada; de.CostoProducto = detalle.CostoProducto; de.CantidadEntrada = detalle.CantidadEntrada; db.DetalleEntrada.Add(de); var pd = db.Producto.Find(de.IdProductoEntrada); pd.ExistenciaProducto += de.CantidadEntrada; if (pd.IdEstadoProducto != 1) { pd.IdEstadoProducto = 1; } } db.SaveChanges(); dbContextTransaction.Commit(); response.Exito = 1; response.Message = "¡Se guardo correctamente los datos!"; } catch (Exception e) { dbContextTransaction.Rollback(); response.Message = e.Message; } } } return(Ok(response)); }
public static int? GetAssociatedLocalEducationAgencyWithClaim(UserInformation userInfo, string claimType, EntryRequest request) { if (!request.LocalEducationAgencyId.HasValue) { return (from lea in userInfo.AssociatedLocalEducationAgencies where lea.ClaimTypes.Any(ct => ct == claimType) select (int?)lea.LocalEducationAgencyId) .FirstOrDefault(); } return (from lea in userInfo.AssociatedLocalEducationAgencies where lea.ClaimTypes.Any(ct => ct == claimType) && lea.LocalEducationAgencyId == request.LocalEducationAgencyId select (int?)lea.LocalEducationAgencyId) .FirstOrDefault(); }
public async Task <IActionResult> PostComment(int id, EntryRequest request) { if (!HasPermission(request.AuthorId)) { return(StatusCode(StatusCodes.Status403Forbidden)); } Entry entry = await context.Entries.FindAsync(id); if (entry is null) { return(NotFound()); } if (request.Text is null) { return(BadRequest()); } request.Text = request.Text.Trim(); if (request.Text == string.Empty) { return(BadRequest()); } request.Text = Util.Truncate(request.Text, MaxLength.Comment); Comment comment = new() { AuthorId = request.AuthorId, ParentId = id, Text = request.Text, Timestamp = DateTime.UtcNow }; context.Comments.Add(comment); entry.CommentCount++; context.Entry(entry).State = EntityState.Modified; await context.SaveChangesAsync(); return(Ok(comment.Id)); }
public void PastDateAttribute_Returns_True_When_Date_Is_In_Past() { //Arrange var entryRequest = new EntryRequest { EntryTime = DateTime.Now.AddHours(-1), ExitTime = DateTime.Now, RegistrationNo = "Test" }; var pastDateAttribute = new PastDateAttribute(); // Act var result = pastDateAttribute.IsValid(entryRequest.EntryTime); //Assert Assert.IsTrue(result); }
public async Task <IActionResult> EditEntry(int id, [FromBody] EntryRequest request) { Entry entry = await context.Entries.FindAsync(id); if (entry is null) { return(NotFound()); } if (!HasPermission(entry.AuthorId)) { return(StatusCode(StatusCodes.Status403Forbidden)); } if (request.Text is null) { return(BadRequest()); } request.Text = request.Text.Trim(); if (request.Text == string.Empty) { return(BadRequest()); } request.Text = Util.Truncate(request.Text, MaxLength.Entry); entry.Text = request.Text; context.Entry(entry).State = EntityState.Modified; try { await context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { return(StatusCode(StatusCodes.Status500InternalServerError)); } return(Ok()); }
public void ExitTimeValidateAttribute_Returns_ValidationError_When_ExitTime_Not_GreaterThan_EntryTime() { //Arrange var entryRequest = new EntryRequest { EntryTime = DateTime.Now.AddHours(1), ExitTime = DateTime.Now.AddHours(0.9), RegistrationNo = "Test" }; var validationContext = new ValidationContext(entryRequest); var exitTimeValidateAttribute = new ExitTimeValidateAttribute("EntryTime"); // Act var result = exitTimeValidateAttribute.GetValidationResult(entryRequest.ExitTime, validationContext); //Assert Assert.NotNull(result); Assert.AreEqual("EntryTime cannot be greater than exit time", result.ErrorMessage); }
public void ExitTimeValidateAttribute_Returns_Success_When_ExitTime_GreaterThan_EntryTime() { //Arrange var entryRequest = new EntryRequest { EntryTime = DateTime.Now.AddHours(1), ExitTime = DateTime.Now.AddHours(1.1), RegistrationNo = "Test" }; var validationContext = new ValidationContext(entryRequest); var exitTimeValidateAttribute = new ExitTimeValidateAttribute("EntryTime"); var expectedResult = ValidationResult.Success; // Act var result = exitTimeValidateAttribute.GetValidationResult(entryRequest.ExitTime, validationContext); //Assert Assert.AreEqual(expectedResult, result); }
public ActionResult Get(EntryRequest request) { // Check to see if the incoming user's claims match the targeted local education agency if (!UserInformation.Current.IsAffiliatedWithLocalEducationAgency(request.LocalEducationAgencyId)) throw new UserAccessDeniedException( string.Format("User is not affiliated with the local education agency at '{0}'.", ControllerContext.HttpContext.Request.Url)); // Extract parameterized rule from user's claims string landingPageUrl = entryService.Get(request); // Store their "home" page for later sessionStateProvider[EdFiApp.Session.LandingPageUrl] = landingPageUrl; // this allows this page to handle this processing when the web app's session has expired // but the authentication did not expire. it then returns the user to the page they requested. var returnUrl = Request["returnUrl"]; if (!String.IsNullOrEmpty(returnUrl)) { return new RedirectResult(returnUrl); } return new RedirectResult(landingPageUrl); }
public ActionResult <IEntryResponse> Post(EntryRequest request) { var entryResponse = ParkingRateService.CalculateParkingFee(request); return(Ok(entryResponse)); }
private async Task <AuthenticationResponse[]> CreateUsers() { RegisterRequest registerData = new() { Name = "User4", Username = "******", Email = "*****@*****.**", Password = "******" }; var auth1 = await CreateUser(registerData); Assert.True(auth1.Token != null); registerData = new() { Name = "User5", Username = "******", Password = "******" }; var auth2 = await CreateUser(registerData); Assert.True(auth2.Token != null); return(new AuthenticationResponse[] { auth1, auth2 }); } private async Task PostEntries(AuthenticationResponse auth1, AuthenticationResponse auth2) { //Ensure entry creation SetUser(auth1); EntryRequest entryData = new() { AuthorId = auth1.Id, Text = "text" }; var response = await CreateEntry(entryData); response.EnsureSuccessStatusCode(); //Ensure invalid data handling response = await CreateEntry(new { AuthorId = "not a number", Text = "text" }); Assert.True(response.StatusCode == HttpStatusCode.BadRequest); //Ensure empty data handling entryData = new EntryRequest { AuthorId = auth1.Id, Text = " " }; response = await CreateEntry(entryData); Assert.True(response.StatusCode == HttpStatusCode.BadRequest); //Ensure that users cannot post for other users entryData = new EntryRequest { AuthorId = auth2.Id, Text = "text" }; response = await CreateEntry(entryData); Assert.True(response.StatusCode == HttpStatusCode.Forbidden); //Ensure text truncation in case of exceeding 256 symbol limit entryData = new EntryRequest { AuthorId = auth1.Id, Text = new string('*', (int)MaxLength.Entry + 10) }; response = await CreateEntry(entryData); //Get entry and check text length int entryId = await GetEntryId(response); Entry entry = await GetEntry(entryId); Assert.True(entry.Text.Length <= (int)MaxLength.Entry); } private async Task EditEntries(AuthenticationResponse auth1, AuthenticationResponse auth2) { //Add a test entry and get its id SetUser(auth1); EntryRequest entryData = new() { AuthorId = auth1.Id, Text = "text" }; var response = await CreateEntry(entryData); int entryId = await GetEntryId(response); //Ensure entry editing and data handling EntryRequest editEntryData = new() { AuthorId = auth1.Id, Text = " text edited " }; response = await EditEntry(entryId, editEntryData); response.EnsureSuccessStatusCode(); //Get entry and check its correctness Entry entry = await GetEntry(entryId); Assert.True(entry.Text == "text edited"); //Ensure that authorized users cannot edit other users' entries SetUser(auth2); editEntryData = new EntryRequest { AuthorId = auth1.Id, Text = "new text" }; response = await EditEntry(entryId, editEntryData); Assert.True(response.StatusCode == HttpStatusCode.Forbidden); } private async Task DeleteEntries(AuthenticationResponse auth1, AuthenticationResponse auth2) { //Add a test entry to delete it later SetUser(auth1); EntryRequest entryData = new() { AuthorId = auth1.Id, Text = "delete" }; var response = await CreateEntry(entryData); int entryId = await GetEntryId(response); //Ensure that authorized users cannot delete other users' entries SetUser(auth2); response = await DeleteEntry(entryId); Assert.True(response.StatusCode == HttpStatusCode.Forbidden); //Ensure entry deletion SetUser(auth1); response = await DeleteEntry(entryId); response.EnsureSuccessStatusCode(); //Ensure that the entry has been deleted response = await client.GetAsync($"api/entries/{entryId}"); Assert.True(response.StatusCode == HttpStatusCode.NotFound); //Ensure that it's impossible to delete a non-existent entry response = await DeleteEntry(42); Assert.True(response.StatusCode == HttpStatusCode.NotFound); } private async Task LikeEntries(AuthenticationResponse auth1, AuthenticationResponse auth2) { //Create an entry and get its id SetUser(auth1); EntryRequest entryData = new() { AuthorId = auth1.Id, Text = "text" }; var response = await CreateEntry(entryData); int entryId = await GetEntryId(response); //Like the entry as the first user response = await AddLike(entryId); response.EnsureSuccessStatusCode(); //Ensure that users cannot like the same entry more than once response = await AddLike(entryId); Assert.True(response.StatusCode == HttpStatusCode.BadRequest); //Ensure that users cannot like a non-existent tweet response = await AddLike(42); Assert.True(response.StatusCode == HttpStatusCode.BadRequest); //Like the entry as the second user SetUser(auth2); response = await AddLike(entryId); response.EnsureSuccessStatusCode(); //Ensure that all likes have been recorded Entry entry = await GetEntry(entryId); Assert.True(entry.LikeCount == 2); //Ensure that users cannot remove likes from non-existent tweets response = await RemoveLike(42); Assert.True(response.StatusCode == HttpStatusCode.BadRequest); //Remove like as the second user response = await RemoveLike(entryId); response.EnsureSuccessStatusCode(); //Ensure that like has been removed entry = await GetEntry(entryId); Assert.True(entry.LikeCount == 1); } private async Task RetweetEntries(AuthenticationResponse auth1, AuthenticationResponse auth2) { //Create an entry and get its id SetUser(auth1); EntryRequest entryData = new() { AuthorId = auth1.Id, Text = "text to retweet" }; var response = await CreateEntry(entryData); int entryId = await GetEntryId(response); //Retweet the entry as the second user SetUser(auth2); response = await client.PostAsync($"api/entries/{entryId}/retweet", null); response.EnsureSuccessStatusCode(); //Ensure that users cannot retweet more than once response = await client.PostAsync($"api/entries/{entryId}/retweet", null); Assert.True(response.StatusCode == HttpStatusCode.BadRequest); //Ensure that users cannot retweet non-existent tweets response = await client.PostAsync($"api/entries/{42}/retweet", null); Assert.True(response.StatusCode == HttpStatusCode.BadRequest); //Ensure that the retweet has been recorded var entries = await GetUserRetweets(auth2.Id); Assert.Contains(entries, x => x.Id == entryId); Entry entry = await GetEntry(entryId); Assert.True(entry.RetweetCount == 1); //Ensure that users cannot delete non-existent retweets response = await client.DeleteAsync($"api/entries/{42}/remove-retweet"); Assert.True(response.StatusCode == HttpStatusCode.BadRequest); //Ensure retweet deletion response = await client.DeleteAsync($"api/entries/{entryId}/remove-retweet"); response.EnsureSuccessStatusCode(); //Check that the retweet has been deleted entries = await GetUserRetweets(auth2.Id); Assert.DoesNotContain(entries, x => x.Id == entryId); entry = await GetEntry(entryId); Assert.True(entry.RetweetCount == 0); } private async Task CommentEntries(AuthenticationResponse auth1, AuthenticationResponse auth2) { //Create an entry and get its id SetUser(auth1); EntryRequest entryData = new() { AuthorId = auth1.Id, Text = "text to comment" }; var response = await CreateEntry(entryData); int entryId = await GetEntryId(response); //Ensure comment creation and get its id EntryRequest commentData = new() { AuthorId = auth1.Id, Text = "comment1" }; response = await AddComment(entryId, commentData); response.EnsureSuccessStatusCode(); int commentId = await GetEntryId(response); //Ensure that users cannot add comments to non-existent entries response = await AddComment(42, commentData); Assert.True(response.StatusCode == HttpStatusCode.NotFound); //Ensure that users cannot add comments using other user's id commentData = new() { AuthorId = auth2.Id, Text = "comment1" }; response = await AddComment(entryId, commentData); Assert.True(response.StatusCode == HttpStatusCode.Forbidden); //Add comment as the second user SetUser(auth2); commentData = new() { AuthorId = auth2.Id, Text = "comment2" }; response = await AddComment(entryId, commentData); response.EnsureSuccessStatusCode(); //Ensure that all comments have been recorded List <Comment> comments = await GetComments(entryId); Assert.True(comments.Count == 2); //Ensure that users cannot delete other users' comments response = await client.DeleteAsync($"api/entries/{entryId}/comments/{commentId}"); Assert.True(response.StatusCode == HttpStatusCode.Forbidden); //Ensure that users cannot delete comments of non-existent entries SetUser(auth1); response = await client.DeleteAsync($"api/entries/{42}/comments/{commentId}"); Assert.True(response.StatusCode == HttpStatusCode.NotFound); //Ensure that users cannot delete non-existent comments response = await client.DeleteAsync($"api/entries/{entryId}/comments/{42}"); Assert.True(response.StatusCode == HttpStatusCode.NotFound); //Ensure comment deletion response = await client.DeleteAsync($"api/entries/{entryId}/comments/{commentId}"); response.EnsureSuccessStatusCode(); //Ensure that comment deletion has been recorded comments = await GetComments(entryId); Assert.True(comments.Count == 1); } private void SetUser(AuthenticationResponse auth) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", auth.Token); } private async Task <AuthenticationResponse> CreateUser(RegisterRequest data) { var request = new HttpRequestMessage(HttpMethod.Post, "api/authentication/register") { Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json") }; var response = await client.SendAsync(request); string result = await response.Content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <AuthenticationResponse>(result)); } private async Task <HttpResponseMessage> CreateEntry(object data) { var request = new HttpRequestMessage(HttpMethod.Post, "api/entries") { Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json") }; var response = await client.SendAsync(request); return(response); } private async Task <HttpResponseMessage> EditEntry(int id, EntryRequest data) { var request = new HttpRequestMessage(HttpMethod.Patch, $"api/entries/{id}") { Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json") }; var response = await client.SendAsync(request); return(response); } private async Task <HttpResponseMessage> DeleteEntry(int id) { return(await client.SendAsync(new HttpRequestMessage(HttpMethod.Delete, $"api/entries/{id}"))); }
/// <summary> /// Throws an exception describing the unhandled request for a user entry provider. /// </summary> /// <param name="request">The entry request request providing the domain-specific context for the entry point.</param> /// <returns>The URL for the application-specific location for the entry point.</returns> public string GetUserEntry(EntryRequest request) { throw new DashboardsAuthenticationException("No dashboard home page could be determined based on your permissions. Please contact your administrator."); }