public async Task CreateWithRelationship_HasMany_IsCreated() { // Arrange var serializer = GetSerializer <TodoItemCollection>(e => new { }, e => new { e.TodoItems }); var todoItem = _todoItemFaker.Generate(); _dbContext.TodoItems.Add(todoItem); _dbContext.SaveChanges(); var todoCollection = new TodoItemCollection { TodoItems = new HashSet <TodoItem> { todoItem } }; // Act var(body, response) = await Post("/api/v1/todoCollections", serializer.Serialize(todoCollection)); // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); var responseItem = _deserializer.DeserializeSingle <TodoItemCollectionClient>(body).Data; var contextCollection = GetDbContext().TodoItemCollections.AsNoTracking() .Include(c => c.Owner) .Include(c => c.TodoItems) .SingleOrDefault(c => c.Id == responseItem.Id); Assert.NotEmpty(contextCollection.TodoItems); Assert.Equal(todoItem.Id, contextCollection.TodoItems.First().Id); }
public async Task CreateWithRelationship_HasManyAndInclude_IsCreatedAndIncludes() { // Arrange var serializer = GetSerializer <TodoItemCollection>(e => new { }, e => new { e.TodoItems, e.Owner }); var owner = new Person(); var todoItem = new TodoItem { Owner = owner, Description = "Description" }; _dbContext.People.Add(owner); _dbContext.TodoItems.Add(todoItem); _dbContext.SaveChanges(); var todoCollection = new TodoItemCollection { Owner = owner, TodoItems = new List <TodoItem> { todoItem } }; // Act var(body, response) = await Post("/api/v1/todoCollections?include=todoItems", serializer.Serialize(todoCollection)); // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); var responseItem = _deserializer.DeserializeSingle <TodoItemCollectionClient>(body).Data; Assert.NotNull(responseItem); Assert.NotEmpty(responseItem.TodoItems); Assert.Equal(todoItem.Description, responseItem.TodoItems.Single().Description); }
public async Task CreateWithRelationship_HasManyAndIncludeAndSparseFieldset_IsCreatedAndIncludes() { // Arrange var serializer = GetSerializer <TodoItemCollection>(e => new { e.Name }, e => new { e.TodoItems, e.Owner }); var owner = new Person(); var todoItem = new TodoItem { Owner = owner, Ordinal = 123, Description = "Description" }; _dbContext.People.Add(owner); _dbContext.TodoItems.Add(todoItem); _dbContext.SaveChanges(); var todoCollection = new TodoItemCollection { Owner = owner, Name = "Jack", TodoItems = new HashSet <TodoItem> { todoItem } }; // Act var(body, response) = await Post("/api/v1/todoCollections?include=todoItems&fields=name&fields[todoItems]=ordinal", serializer.Serialize(todoCollection)); // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); var responseItem = _deserializer.DeserializeSingle <TodoItemCollectionClient>(body).Data; Assert.NotNull(responseItem); Assert.Equal(todoCollection.Name, responseItem.Name); Assert.NotEmpty(responseItem.TodoItems); Assert.Equal(todoItem.Ordinal, responseItem.TodoItems.Single().Ordinal); Assert.Null(responseItem.TodoItems.Single().Description); }
/// <summary> /// Reload TodoItems in current year, month and day. /// Author: ChuyangLiu /// </summary> public void ReloadItems() { if (TodoItems == null) { TodoItems = new TodoItemCollection(); } TodoItems.ReloadItems(Year, Month, Day); }
public async Task CreateResource_GuidResource_IsCreated() { // Arrange var serializer = GetSerializer <TodoItemCollection>(e => new { }, e => new { e.Owner }); var owner = new Person(); _dbContext.People.Add(owner); _dbContext.SaveChanges(); var todoItemCollection = new TodoItemCollection { Owner = owner }; // Act var(_, response) = await Post("/api/v1/todoCollections", serializer.Serialize(todoItemCollection)); // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); }
public async Task ClientGeneratedId_GuidIdAndEnabled_IsCreated() { // Arrange var serializer = GetSerializer <TodoItemCollection>(e => new { }, e => new { e.Owner }); var owner = new Person(); _dbContext.People.Add(owner); await _dbContext.SaveChangesAsync(); var clientDefinedId = Guid.NewGuid(); var todoItemCollection = new TodoItemCollection { Owner = owner, OwnerId = owner.Id, Id = clientDefinedId }; // Act var(body, response) = await Post("/api/v1/todoCollections", serializer.Serialize(todoItemCollection)); // Assert AssertEqualStatusCode(HttpStatusCode.Created, response); var responseItem = _deserializer.DeserializeSingle <TodoItemCollectionClient>(body).Data; Assert.Equal(clientDefinedId, responseItem.Id); }
public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_With_Overlap() { // arrange var todoCollection = new TodoItemCollection(); todoCollection.TodoItems = new List <TodoItem>(); var person = _personFaker.Generate(); var todoItem1 = _todoItemFaker.Generate(); var todoItem2 = _todoItemFaker.Generate(); todoCollection.Owner = person; todoCollection.TodoItems.Add(todoItem1); todoCollection.TodoItems.Add(todoItem2); _context.TodoItemCollections.Add(todoCollection); _context.SaveChanges(); var builder = new WebHostBuilder() .UseStartup <Startup>(); var server = new TestServer(builder); var client = server.CreateClient(); var content = new { data = new { type = "todo-collections", id = todoCollection.Id, relationships = new Dictionary <string, object> { { "todo-items", new { data = new object[] { new { type = "todo-items", id = $"{todoItem1.Id}" }, new { type = "todo-items", id = $"{todoItem2.Id}" } } } }, } } }; var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/todo-collections/{todoCollection.Id}"; var request = new HttpRequestMessage(httpMethod, route); string serializedContent = JsonConvert.SerializeObject(content); request.Content = new StringContent(serializedContent); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act var response = await client.SendAsync(request); _context = _fixture.GetService <AppDbContext>(); var updatedTodoItems = _context.TodoItemCollections.AsNoTracking() .Where(tic => tic.Id == todoCollection.Id) .Include(tdc => tdc.TodoItems).SingleOrDefault().TodoItems; Assert.Equal(HttpStatusCode.OK, response.StatusCode); Assert.Equal(2, updatedTodoItems.Count); }
public async Task Can_Update_ToMany_Relationship_By_Patching_Resource_When_Targets_Already_Attached() { // It is possible that entities we're creating relationships to // have already been included in dbContext the application beyond control // of JANDC. For example: a user may have been loaded when checking permissions // in business logic in controllers. In this case, // this user may not be reattached to the db context in the repository. // arrange var todoCollection = new TodoItemCollection(); todoCollection.TodoItems = new List <TodoItem>(); var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); todoCollection.Owner = person; todoCollection.Name = "PRE-ATTACH-TEST"; todoCollection.TodoItems.Add(todoItem); _context.TodoItemCollections.Add(todoCollection); _context.SaveChanges(); var newTodoItem1 = _todoItemFaker.Generate(); var newTodoItem2 = _todoItemFaker.Generate(); _context.AddRange(new TodoItem[] { newTodoItem1, newTodoItem2 }); _context.SaveChanges(); var builder = new WebHostBuilder() .UseStartup <Startup>(); var server = new TestServer(builder); var client = server.CreateClient(); var content = new { data = new { type = "todo-collections", id = todoCollection.Id, attributes = new { name = todoCollection.Name }, relationships = new Dictionary <string, object> { { "todo-items", new { data = new object[] { new { type = "todo-items", id = $"{newTodoItem1.Id}" }, new { type = "todo-items", id = $"{newTodoItem2.Id}" } } } }, } } }; var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/todo-collections/{todoCollection.Id}"; var request = new HttpRequestMessage(httpMethod, route); string serializedContent = JsonConvert.SerializeObject(content); request.Content = new StringContent(serializedContent); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.api+json"); // Act var response = await client.SendAsync(request); _context = _fixture.GetService <AppDbContext>(); var updatedTodoItems = _context.TodoItemCollections.AsNoTracking() .Where(tic => tic.Id == todoCollection.Id) .Include(tdc => tdc.TodoItems).SingleOrDefault().TodoItems; Assert.Equal(HttpStatusCode.OK, response.StatusCode); /// we are expecting two, not three, because the request does /// a "complete replace". Assert.Equal(2, updatedTodoItems.Count); }
public async Task Can_Update_ToMany_Relationship_By_Patching_Resource() { // Arrange var todoCollection = new TodoItemCollection { TodoItems = new HashSet <TodoItem>() }; var person = _personFaker.Generate(); var todoItem = _todoItemFaker.Generate(); todoCollection.Owner = person; todoCollection.TodoItems.Add(todoItem); _context.TodoItemCollections.Add(todoCollection); await _context.SaveChangesAsync(); var newTodoItem1 = _todoItemFaker.Generate(); var newTodoItem2 = _todoItemFaker.Generate(); _context.AddRange(newTodoItem1, newTodoItem2); await _context.SaveChangesAsync(); var builder = WebHost.CreateDefaultBuilder() .UseStartup <TestStartup>(); var server = new TestServer(builder); var client = server.CreateClient(); var content = new { data = new { type = "todoCollections", id = todoCollection.Id, relationships = new Dictionary <string, object> { { "todoItems", new { data = new object[] { new { type = "todoItems", id = $"{newTodoItem1.Id}" }, new { type = "todoItems", id = $"{newTodoItem2.Id}" } } } } } } }; var httpMethod = new HttpMethod("PATCH"); var route = $"/api/v1/todoCollections/{todoCollection.Id}"; var request = new HttpRequestMessage(httpMethod, route); string serializedContent = JsonConvert.SerializeObject(content); request.Content = new StringContent(serializedContent); request.Content.Headers.ContentType = new MediaTypeHeaderValue(HeaderConstants.MediaType); // Act var response = await client.SendAsync(request); _context = _fixture.GetService <AppDbContext>(); var updatedTodoItems = _context.TodoItemCollections.AsNoTracking() .Where(tic => tic.Id == todoCollection.Id) .Include(tdc => tdc.TodoItems).SingleOrDefault().TodoItems; Assert.Equal(HttpStatusCode.OK, response.StatusCode); // we are expecting two, not three, because the request does // a "complete replace". Assert.Equal(2, updatedTodoItems.Count); }
public async Task Included_Resources_Are_Correct() { // Arrange var role = new PersonRole(); var assignee = new Person { Role = role }; var collectionOwner = new Person(); var someOtherOwner = new Person(); var collection = new TodoItemCollection { Owner = collectionOwner }; var todoItem1 = new TodoItem { Collection = collection, Assignee = assignee }; var todoItem2 = new TodoItem { Collection = collection, Assignee = assignee }; var todoItem3 = new TodoItem { Collection = collection, Owner = someOtherOwner }; var todoItem4 = new TodoItem { Collection = collection, Owner = assignee }; var context = _fixture.GetService <AppDbContext>(); ResetContext(context); context.TodoItems.Add(todoItem1); context.TodoItems.Add(todoItem2); context.TodoItems.Add(todoItem3); context.TodoItems.Add(todoItem4); context.PersonRoles.Add(role); context.People.Add(assignee); context.People.Add(collectionOwner); context.People.Add(someOtherOwner); context.TodoItemCollections.Add(collection); await context.SaveChangesAsync(); string route = "/api/v1/todoItems/" + todoItem1.Id + "?include=" + "collection.owner," + "assignee.role," + "assignee.assignedTodoItems"; // Act var response = await _fixture.Client.GetAsync(route); // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); var body = await response.Content.ReadAsStringAsync(); var documents = JsonConvert.DeserializeObject <Document>(body); var included = documents.Included; // 1 collection, 1 owner, // 1 assignee, 1 assignee role, // 2 assigned todo items (including the primary resource) Assert.Equal(6, included.Count); var collectionDocument = included.FindResource("todoCollections", collection.Id); var ownerDocument = included.FindResource("people", collectionOwner.Id); var assigneeDocument = included.FindResource("people", assignee.Id); var roleDocument = included.FindResource("personRoles", role.Id); var assignedTodo1 = included.FindResource("todoItems", todoItem1.Id); var assignedTodo2 = included.FindResource("todoItems", todoItem2.Id); Assert.NotNull(assignedTodo1); Assert.Equal(todoItem1.Id.ToString(), assignedTodo1.Id); Assert.NotNull(assignedTodo2); Assert.Equal(todoItem2.Id.ToString(), assignedTodo2.Id); Assert.NotNull(collectionDocument); Assert.Equal(collection.Id.ToString(), collectionDocument.Id); Assert.NotNull(ownerDocument); Assert.Equal(collectionOwner.Id.ToString(), ownerDocument.Id); Assert.NotNull(assigneeDocument); Assert.Equal(assignee.Id.ToString(), assigneeDocument.Id); Assert.NotNull(roleDocument); Assert.Equal(role.Id.ToString(), roleDocument.Id); }
/// <summary> /// Initialize fields. /// Author: ChuyangLiu /// </summary> public TodoListPageViewModel() { Year = Month = Day = -1; TodoItems = null; }
/// <param name='cancellationToken'> /// Cancellation token. /// </param> public async Task <HttpOperationResponse <IList <TodoItem> > > GetTodoItemsWithOperationResponseAsync(CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool shouldTrace = ServiceClientTracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); ServiceClientTracing.Enter(invocationId, this, "GetTodoItemsAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/api/TodoItems"; string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (shouldTrace) { ServiceClientTracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); HttpResponseMessage httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { ServiceClientTracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); if (statusCode != HttpStatusCode.OK) { HttpOperationException <object> ex = new HttpOperationException <object>(); ex.Request = httpRequest; ex.Response = httpResponse; ex.Body = null; if (shouldTrace) { ServiceClientTracing.Error(invocationId, ex); } throw ex; } // Create Result HttpOperationResponse <IList <TodoItem> > result = new HttpOperationResponse <IList <TodoItem> >(); result.Request = httpRequest; result.Response = httpResponse; // Deserialize Response if (statusCode == HttpStatusCode.OK) { IList <TodoItem> resultModel = new List <TodoItem>(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null) { resultModel = TodoItemCollection.DeserializeJson(responseDoc); } result.Body = resultModel; } if (shouldTrace) { ServiceClientTracing.Exit(invocationId, result); } return(result); }