/// <summary> /// Return the ID assigned by dynamics, or NULL if none. /// </summary> /// <param name="dsr"></param> /// <returns></returns> public static Guid?GetAssignedId(this DataServiceResponse dsr) { Guid?result = null; if (dsr != null) { var ienum = dsr.GetEnumerator(); while (ienum.MoveNext()) { ChangeOperationResponse cor = (ChangeOperationResponse)ienum.Current; if (cor.Descriptor is EntityDescriptor) { EntityDescriptor ed = (EntityDescriptor)cor.Descriptor; string identity = ed.Identity.ToString(); // convert the identity to a guid. int endpos = identity.LastIndexOf(")"); int startpos = identity.LastIndexOf("(") + 1; string guid = identity.Substring(startpos, endpos - startpos); result = Guid.ParseExact(guid, "D"); return(result); } } } return(result); }
/// <summary> /// Verifies the data service response. /// </summary> /// <param name="responseData">The expected data for the response.</param> /// <param name="response">The response to verify.</param> /// <param name="cachedOperationsFromResponse">The individual operation responses, pre-enumerated and cached</param> /// <exception cref="TaupoNotSupportedException"> /// When exception is expected in the response data /// </exception> public void VerifyDataServiceResponse(DataServiceResponseData responseData, DataServiceResponse response, IList <OperationResponse> cachedOperationsFromResponse) { ExceptionUtilities.CheckArgumentNotNull(responseData, "responseData"); ExceptionUtilities.CheckArgumentNotNull(response, "response"); ExceptionUtilities.CheckArgumentNotNull(cachedOperationsFromResponse, "cachedOperationsFromResponse"); ExceptionUtilities.CheckAllRequiredDependencies(this); this.Assert.AreEqual(responseData.IsBatchResponse, response.IsBatchResponse, "Verifying if it's a batch response."); this.Assert.AreEqual(responseData.BatchStatusCode, response.BatchStatusCode, "Verifying batch status code."); //// No batch headers verification //// Note: verifying order of operation responses as well as the content. this.Assert.AreEqual(responseData.Count, cachedOperationsFromResponse.Count, "Unexpected number of operation responses in data service response"); for (int responseOrder = 0; responseOrder < responseData.Count; responseOrder++) { var operationResponseData = responseData[responseOrder]; var currentResponse = cachedOperationsFromResponse[responseOrder]; ChangeOperationResponseData changeResponseData = operationResponseData as ChangeOperationResponseData; if (changeResponseData != null) { ChangeOperationResponse changeResponse = currentResponse as ChangeOperationResponse; this.Assert.IsNotNull(changeResponse, GetVerificationFailureMessage(responseOrder, "Unexpected type of the operation response.\r\nExpected: {0}\r\nActual: {1}", typeof(ChangeOperationResponse).FullName, currentResponse)); this.VerifyChangeOperationResponse(changeResponseData, changeResponse, responseOrder); } else { throw new TaupoNotSupportedException( GetVerificationFailureMessage(responseOrder, "Verification for the operation response data of type '{0}' is not supported by this verifier.", operationResponseData.GetType().FullName)); } } }
public Item AddItem(string prefix = "TEST") { Item item = CreateItem(GetNextValueItemCode(prefix), prefix); try { serviceContainer.AddToItems(item); DataServiceResponse response = serviceContainer.SaveChanges(); if (response != null) { ChangeOperationResponse opRes = (ChangeOperationResponse)response.SingleOrDefault(); object retItem = ((System.Data.Services.Client.EntityDescriptor)(opRes.Descriptor)).Entity; if (retItem != null) { return((Item)retItem); } } } catch (Exception ex) { serviceContainer.Detach(item); throw ex; } return(null); }
private Document AddNewOSaleOrder(Document order) { Document newOrderDoc = null; try { serviceContainer.AddToOrders(order); DataServiceResponse response = serviceContainer.SaveChanges(); if (response != null) { ChangeOperationResponse opRes = (ChangeOperationResponse)response.SingleOrDefault(); object retDoc = ((System.Data.Services.Client.EntityDescriptor)(opRes.Descriptor)).Entity; if (retDoc != null) { newOrderDoc = (Document)retDoc; } } } catch (Exception ex) { //Discard the order from beting tracking serviceContainer.Detach(order); throw ex; } return(newOrderDoc); }
public void ItSavesNewCar() { // Arrange var newCar = new Car { Name = "Hakosuka", Make = "Nissan", Model = "Skyline GTR", Year = 1996 }; var service = new Mock <ICarService>(); service.Setup(m => m.Create(It.IsAny <Data.Models.Car>())) .ReturnsAsync(TestHelpers.Fixture.Create <Data.Models.Car>()); // Bind our mock with Ninject var kernel = new StandardKernel(); kernel.Bind <ICarService>().ToConstant(service.Object); var container = new ExampleContainer(new Uri(BaseAddress)); using (WebApp.Start(BaseAddress, app => TestHelpers.ConfigureWebApi(app, kernel))) { // Act container.AddToCars(newCar); ChangeOperationResponse response = container.SaveChanges().Cast <ChangeOperationResponse>().First(); var entityDescriptor = (EntityDescriptor)response.Descriptor; var actual = (Car)entityDescriptor.Entity; // Assert Assert.AreEqual((int)HttpStatusCode.Created, response.StatusCode); service.Verify(m => m.Create(It.IsAny <Data.Models.Car>()), Times.Once); Assert.IsNotNull(actual); } }
public Item UpdateItem(string itemCode, string textToAdd) { Item item = GetItem(itemCode); if (item == null) { throw new Exception($"Item: {itemCode} Not Found!"); } item.ItemName = $"{item.ItemName} UPD. {textToAdd}"; serviceContainer.UpdateObject(item); DataServiceResponse response = serviceContainer.SaveChanges(SaveChangesOptions.PatchOnUpdate); if (response != null) { ChangeOperationResponse opRes = (ChangeOperationResponse)response.SingleOrDefault(); object retItem = ((System.Data.Services.Client.EntityDescriptor)(opRes.Descriptor)).Entity; if (retItem != null) { Console.WriteLine($"Artículo {((Item)retItem).ItemCode} modificado. ItemName: {((Item)retItem).ItemName} "); return((Item)retItem); } } return(null); }
public void ItUpdatesTheCar() { // Arrange var storedCar = TestHelpers.Fixture.Create <Car>(); var service = new Mock <ICarService>(); service.Setup(m => m.Find(It.IsAny <int>())).ReturnsAsync(storedCar); service.Setup(m => m.Update(It.IsAny <Car>())).ReturnsAsync(storedCar); // Bind our mock with Ninject var kernel = new StandardKernel(); kernel.Bind <ICarService>().ToConstant(service.Object); var container = new ExampleContainer(new Uri(BaseAddress)); using (WebApp.Start(BaseAddress, app => TestHelpers.ConfigureWebApi(app, kernel))) { // Act Client.Example.Data.Models.Car target = container.Cars.ByKey(storedCar.Id).GetValue(); target.Name = TestHelpers.Fixture.Create <string>(); container.UpdateObject(target); ChangeOperationResponse response = container.SaveChanges(SaveChangesOptions.ReplaceOnUpdate) .Cast <ChangeOperationResponse>() .First(); var entityDescriptor = (EntityDescriptor)response.Descriptor; var actual = (Client.Example.Data.Models.Car)entityDescriptor.Entity; // Assert Assert.AreEqual((int)HttpStatusCode.NoContent, response.StatusCode); Assert.IsNotNull(actual); Assert.AreEqual(storedCar.Make, actual.Make); Assert.AreEqual(storedCar.Model, actual.Model); Assert.AreEqual(storedCar.Year, actual.Year); } }
private void savePhotoDetails_Click(object sender, RoutedEventArgs e) { EntityDescriptor entity = null; try { if (photoEntity.FileName == string.Empty || photoEntity.FileName == null) { MessageBox.Show("You must first select an image file to upload."); return; } // Send the update (POST or MERGE) request to the data service and // capture the added or updated entity in the response. ChangeOperationResponse response = context.SaveChanges().FirstOrDefault() as ChangeOperationResponse; // When we issue a POST request, the photo ID and edit-media link are not updated // on the client (a bug), so we need to get the server values. if (photoEntity.PhotoId == 0) { if (response != null) { entity = response.Descriptor as EntityDescriptor; } // Verify that the entity was created correctly. if (entity != null && entity.EditLink != null) { // Cache the current merge option (we reset to the cached // value in the finally block). cachedMergeOption = context.MergeOption; // Set the merge option so that server changes win. context.MergeOption = MergeOption.OverwriteChanges; // Get the updated entity from the service. // Note: we need Count() just to execute the query. context.Execute <PhotoInfo>(entity.EditLink).Count(); } } this.DialogResult = true; this.Close(); } catch (DataServiceRequestException ex) { // Get the change operation result. ChangeOperationResponse response = ex.Response.FirstOrDefault() as ChangeOperationResponse; string errorMessage = string.Empty; // Check for a resource not found error. if (response != null && response.StatusCode == 404) { // Tell the user to refresh the photos from the data service. errorMessage = "The selected image may have been removed from the data service.\n" + "Click the Refresh Photos button to refresh photos from the service."; } else { // Just provide the general error message. errorMessage = string.Format("The photo data could not be updated or saved. {0}", ex.Message); } // Show the messsage box. MessageBox.Show(errorMessage, "Operation Failed"); // Return false since we could not add or update the photo. this.DialogResult = false; return; } finally { // Reset to the cached merge option. context.MergeOption = cachedMergeOption; } }
private void VerifyChangeOperationResponse(ChangeOperationResponseData expected, ChangeOperationResponse actual, int responseOrder) { this.Assert.IsNotNull(actual.Descriptor, GetVerificationFailureMessage(responseOrder, "Change operation response descriptor should not be null!")); this.VerifyDescriptor(expected.DescriptorData, actual.Descriptor, responseOrder); this.Assert.AreEqual( expected.StatusCode, actual.StatusCode, GetVerificationFailureMessage(responseOrder, "Status code verification failed for the change operation response data: {0}.", expected)); // No headers verification // Verify exceptions if (!string.IsNullOrEmpty(expected.ExceptionId)) { throw new TaupoNotSupportedException( string.Format( CultureInfo.InvariantCulture, "Change operation response data with order {0} has non-null exception id '{1}'. This verifier does not support exception verification.", responseOrder, expected.ExceptionId)); } this.Assert.IsNull(actual.Error, GetVerificationFailureMessage(responseOrder, "Unexpected exception thrown:\r\n{0}", actual.Error)); this.Assert.AreEqual( expected.DescriptorData.State.ToProductEnum(), actual.Descriptor.State, GetVerificationFailureMessage(responseOrder, "Descriptor State verification failed for the change operation response data: {0}.", expected)); }
public ChangesetResponseWrapper(ChangeOperationResponse cr) : base(cr) { this._ChangesetResponse = cr; }