public void UpdateProductRecipe(ProductRecipe productRecipe) { var dAProductRecipe = ManualMapper.ManMap(productRecipe); _db.Update(dAProductRecipe); _db.SaveChanges(); }
public void UpdateStore(Store store) { var dAStore = ManualMapper.ManMap(store); _db.Update(dAStore); _db.SaveChanges(); }
public void UpdateOrderHeader(OrderHeader orderHeader) { var dAOrderHeader = ManualMapper.ManMap(orderHeader); _db.Update(dAOrderHeader); _db.SaveChanges(); }
public void UpdateProduct(Product product) { var dAProduct = ManualMapper.ManMap(product); _db.Update(dAProduct); _db.SaveChanges(); }
public void UpdateInventory(Inventory inventory) { var dAInventory = ManualMapper.ManMap(inventory); _db.Update(dAInventory); _db.SaveChanges(); }
public void UpdateOrderDetail(OrderDetail orderDetails) { var dAOrderDetails = ManualMapper.ManMap(orderDetails); _db.Update(dAOrderDetails); _db.SaveChanges(); }
public void UpdateCustomer(Customer customer) { var dACustomer = ManualMapper.ManMap(customer); _db.Update(dACustomer); _db.SaveChanges(); }
public void UpdateIngredient(Ingredient ingredient) { var dAIngredient = ManualMapper.ManMap(ingredient); _db.Update(dAIngredient); _db.SaveChanges(); }
public void InsertStore(Store store) { _db.Store.Include(s => s.Inventory); _db.Store.Include(s => s.OrderHeader); _db.Add(ManualMapper.ManMap(store)); _db.SaveChanges(); }
public void UpdateAddress(Address address) { var dAAddress = ManualMapper.ManMap(address); _db.Update(dAAddress); _db.SaveChanges(); }
public void InsertProduct(Product product) { _db.Product.Include(p => p.OrderDetail); _db.Product.Include(p => p.ProductRecipe); _db.Add(ManualMapper.ManMap(product)); _db.SaveChanges(); }
public void InsertIngredient(Ingredient ingredient) { _db.Ingredient.Include(i => i.Inventory); _db.Ingredient.Include(i => i.ProductRecipe); _db.Add(ManualMapper.ManMap(ingredient)); _db.SaveChanges(); }
public void InsertCustomer(Customer customer) { //_db.Customer.Include(c => c.OrderHeader); //_db.Customer.Include(c => c.Address); _db.Add(ManualMapper.ManMap(customer)); _db.SaveChanges(); }
public List <OrderDetail> GetOrderDetailByOrderHeaderID(int orderHeaderId) { OrderHeader orderHeader = GetOrderByOrderId(orderHeaderId); List <OrderDetail> orderDetails = ManualMapper.ManMap(_db.OrderDetail.Where(od => od.OrderId == orderHeaderId)).ToList(); return(orderDetails); }
/// <summary> /// Adds the roles to the specified user if permission allows it /// </summary> /// <param name="performingUserId">User performing the role addition</param> /// <param name="adjustedUserId">User having roles added</param> /// <param name="rolesToAdd">Roles to be added to the user</param> /// <returns></returns> public IEnumerable <IRoleDto> AddRolesToUser(int performingUserId, int adjustedUserId, IEnumerable <IRoleDto> rolesToAdd) { using (var context = new PrometheusContext()) { List <Role> newRoles = new List <Role>(); foreach (var role in rolesToAdd) { newRoles.Add((from r in context.Roles where r.Id == role.Id select r).First()); /* attach context objects */ } if (!context.Users.Any(x => x.Id == adjustedUserId)) { throw new EntityNotFoundException("Could not add Roles to User.", typeof(User), adjustedUserId); } var updatedUser = context.Users.Find(adjustedUserId); updatedUser.Roles = new List <Role>(); context.Users.Attach(updatedUser); foreach (var role in newRoles) { updatedUser.Roles.Add(role); } context.Entry(updatedUser).State = EntityState.Modified; context.SaveChanges(); foreach (var updatedUserRole in updatedUser.Roles) { yield return(ManualMapper.MapRoleToDto(updatedUserRole)); } } }
/// <summary> /// Finds text input with identifier provided and returns its DTO /// </summary> /// <param name="performingUserId"></param> /// <param name="textInput"></param> /// <returns></returns> public ISelectionInputDto GetSelectionInput(int performingUserId, int textInputId) { using (var context = new PrometheusContext()) { return(ManualMapper.MapSelectionInputToDto(context.SelectionInputs.Find(textInputId))); } }
public void From_TypedEntity_With_Relations_To_NodeVersion() { //Arrange var mapper = new ManualMapper(new FakeLookupHelper(), new FakeHiveProvider()); mapper.Configure(); var entityParent = HiveModelCreationHelper.MockTypedEntity(false); entityParent.Id = HiveId.ConvertIntToGuid(1); var entityChild = HiveModelCreationHelper.MockTypedEntity(false); entityChild.Id = HiveId.ConvertIntToGuid(2); entityParent.Relations.Add(FixedRelationTypes.ContentTreeRelationType, entityChild); //Act var resultParent = mapper.Map <TypedEntity, NodeVersion>(entityParent); //var resultChild = mapper.Map<TypedEntity, NodeVersion>(entityChild); //Assert Assert.AreEqual(entityParent.EntitySchema.Alias, resultParent.AttributeSchemaDefinition.Alias); Assert.AreEqual(entityParent.Attributes.Count, resultParent.Attributes.Count); Assert.AreEqual(entityParent.Relations.Count(), resultParent.Node.OutgoingRelations.Count); Assert.AreEqual(entityParent.Relations.Single().Source.Id, resultParent.Node.OutgoingRelations.First().StartNode.Id); Assert.AreEqual(entityParent.Relations.Single().Destination.Id, resultParent.Node.OutgoingRelations.First().EndNode.Id); //BUG: If you call entityChild.Relations.Count() an infinite loop occurs :( //Assert.AreEqual(entityChild.Relations.Count(), resultChild.Node.IncomingRelations.Count); }
public IEnumerable <OrderHeader> GetOrderHistory(int sortOrder) { if (sortOrder == 1) { IEnumerable <OrderHeader> orderHistory = ManualMapper.ManMap(_db.OrderHeader); return(orderHistory.OrderBy(o => o.OrderDate)); } else if (sortOrder == 2) { IEnumerable <OrderHeader> orderHistory = ManualMapper.ManMap(_db.OrderHeader); return(orderHistory.OrderByDescending(o => o.OrderDate)); } else if (sortOrder == 3) { IEnumerable <OrderHeader> orderHistory = ManualMapper.ManMap(_db.OrderHeader); return(orderHistory.OrderBy(o => o.TotalCost)); } else if (sortOrder == 4) { IEnumerable <OrderHeader> orderHistory = ManualMapper.ManMap(_db.OrderHeader); return(orderHistory.OrderByDescending(o => o.TotalCost)); } else { // this is the same code a sfor the case "earliest" // I am using it as a default, and I will check for valid inputs in the // ConsoleApp IEnumerable <OrderHeader> orderHistory = ManualMapper.ManMap(_db.OrderHeader); return(orderHistory.OrderBy(o => o.OrderDate)); }; }
/// <summary> /// Retrieves the service packages that the service option id exists in /// </summary> /// <param name="performingUserId"></param> /// <param name="serviceOptionId"></param> /// <returns></returns> public IEnumerable <IServiceRequestPackageDto> GetServiceRequestPackagesForServiceOption(int performingUserId, int serviceOptionId, ServiceRequestAction action) { using (var context = new PrometheusContext()) { var option = context.ServiceOptions.Find(serviceOptionId); if (option == null) { throw new InvalidOperationException(string.Format("Service Option with ID {0} does not exist. Cannot retrieve service package with option identifier {0}.", serviceOptionId)); } //All packages where the service option exists in the first category of the package // OR the service option exists in the first service of the package var packages = context.ServiceRequestPackages.Where( x => x.Action == action && (x.ServiceOptionCategoryTags.Any( y => y.Order == 1 && y.ServiceOptionCategory.ServiceOptions.Any( z => z.Id == serviceOptionId)) || x.ServiceTags.Any( y => y.Order == 1 && y.Service.ServiceOptionCategories.Any( z => z.Id == serviceOptionId)))); //Sweet baby jesus if (!packages.Any()) { throw new InvalidOperationException(string.Format("Service Request Package with Service Option ID {0} does not exist.", serviceOptionId)); } foreach (var package in packages) { yield return(ManualMapper.MapServiceRequestPackageToDto(package)); } } }
/// <summary> /// Finds service WorkUnit with identifier provided and returns its DTO /// </summary> /// <param name="performingUserId"></param> /// <param name="serviceWorkUnitId"></param> /// <returns></returns> public IServiceWorkUnitDto GetServiceWorkUnit(int performingUserId, int serviceWorkUnitId) { using (var context = new PrometheusContext()) { return(ManualMapper.MapServiceWorkUnitToDto(context.ServiceWorkUnits.Find(serviceWorkUnitId))); } }
/// <summary> /// Gets the required inputs for all supplied service options /// </summary> /// <param name="performingUserId"></param> /// <param name="serviceOptions">Service Options to get the inputs for</param> /// <returns></returns> public IInputGroupDto GetInputsForServiceOptions(int performingUserId, IEnumerable <IServiceOptionDto> serviceOptions) { if (serviceOptions == null) { base.ThrowArgumentNullError(nameof(serviceOptions)); } var inputGroup = new InputGroupDto(); //Initialize the lists for inputs List <IScriptedSelectionInputDto> scriptedInputs = new List <IScriptedSelectionInputDto>(); List <ISelectionInputDto> selectionInputs = new List <ISelectionInputDto>(); List <ITextInputDto> textInputs = new List <ITextInputDto>(); using (var context = new PrometheusContext()) { var options = serviceOptions.Select(x => context.ServiceOptions.Find(x.Id)); foreach (var option in options) { textInputs.AddRange(from t in option.TextInputs select ManualMapper.MapTextInputToDto(t)); scriptedInputs.AddRange(from t in option.ScriptedSelectionInputs select ManualMapper.MapScriptedSelectionInputToDto(t)); selectionInputs.AddRange(from t in option.SelectionInputs select ManualMapper.MapSelectionInputToDto(t)); } } inputGroup.TextInputs = textInputs; inputGroup.SelectionInputs = selectionInputs; inputGroup.ScriptedSelectionInputs = scriptedInputs; return(inputGroup); }
public ActionResult Index() { IEnumerable <Library.Address> addresses = Repo.GetAddresses(); var addressesModels = ManualMapper.ManMap2(addresses); return(View(addressesModels)); }
public ActionResult Create(Models.Customer newCustomer) { try { if (ModelState.IsValid) { Library.Customer newCustomerMapped = ManualMapper.ManMap2(newCustomer); //var newCustomerMapped2 = ManualMapper.ManMap(newCustomerMapped); Repo.InsertCustomer(newCustomerMapped); } else { return(View()); } return(RedirectToAction(nameof(Index))); } catch (ArgumentException ex) { ModelState.AddModelError("Id", ex.Message); return(View()); } catch { return(View()); } }
protected override IServiceRequestPackageDto Create(int performingUserId, IServiceRequestPackageDto entity) { using (var context = new PrometheusContext()) { var servicePackage = context.ServiceRequestPackages.Find(entity.Id); if (servicePackage != null) { throw new InvalidOperationException(string.Format("Service Request Package with ID {0} already exists.", entity.Id)); } var savedPackage = context.ServiceRequestPackages.Add(ManualMapper.MapDtoToServiceRequestPackage(entity)); //Set tags to match DTO tags var categoryTags = new List <ServiceOptionCategoryTag>(); foreach (var tag in entity.ServiceOptionCategoryTags) { categoryTags.Add(ManualMapper.MapDtoToServiceOptionCategoryTag(tag)); } savedPackage.ServiceOptionCategoryTags = categoryTags; var serviceTags = new List <ServiceTag>(); foreach (var tag in entity.ServiceTags) { serviceTags.Add((ManualMapper.MapDtoToServiceTag(tag))); } savedPackage.ServiceTags = serviceTags; context.SaveChanges(performingUserId); return(ManualMapper.MapServiceRequestPackageToDto(savedPackage)); } }
/// <summary> /// Finds service goal with identifier provided and returns its DTO /// </summary> /// <param name="performingUserId"></param> /// <param name="serviceGoalId"></param> /// <returns></returns> public IServiceGoalDto GetServiceGoal(int performingUserId, int serviceGoalId) { using (var context = new PrometheusContext()) { return(ManualMapper.MapServiceGoalToDto(context.ServiceGoals.Find(serviceGoalId))); } }
/// <summary> /// Finds SWOT activity with identifier provided and returns its DTO /// </summary> /// <param name="performingUserId"></param> /// <param name="swotActivityId"></param> /// <returns></returns> public ISwotActivityDto GetSwotActivity(int performingUserId, int swotActivityId) { using (var context = new PrometheusContext()) { return(ManualMapper.MapSwotActivityToDto(context.SwotActivities.Find(swotActivityId))); } }
protected override IUserDto Update(int performingUserId, IUserDto userDto) { if (userDto.Id == AdministratorId) { throw new InvalidOperationException("Administrator account cannot be updated."); } if (userDto.Id == GuestId) { throw new InvalidOperationException("Guest account cannot be updated."); } using (var context = new PrometheusContext()) { if (!context.Users.Any(x => x.Id == userDto.Id)) { throw new InvalidOperationException(string.Format("User with ID {0} cannot be updated since it does not exist.", userDto.Id)); } var updatedUser = ManualMapper.MapDtoToUser(userDto); context.Users.Attach(updatedUser); context.Entry(updatedUser).State = EntityState.Modified; context.SaveChanges(); return(ManualMapper.MapUserToDto(updatedUser)); } }
/// <summary> /// Creates the entity in the database /// </summary> /// <param name="performingUserId">User creating the entity</param> /// <param name="entity">Entity to be created</param> /// <returns>Created entity DTO</returns> protected override ILifecycleStatusDto Create(int performingUserId, ILifecycleStatusDto lifecycleStatus) { using (var context = new PrometheusContext()) { var existingStatus = context.LifecycleStatuses.Find(lifecycleStatus.Id); if (existingStatus == null) { //Insert at correct Position foreach (var status in context.LifecycleStatuses) { if (status.Position >= lifecycleStatus.Position) { status.Position++; context.LifecycleStatuses.Attach(status); context.Entry(status).State = EntityState.Modified; } } var savedStatus = context.LifecycleStatuses.Add(ManualMapper.MapDtoToLifecycleStatus(lifecycleStatus)); context.SaveChanges(performingUserId); return(ManualMapper.MapLifecycleStatusToDto(savedStatus)); } else { throw new InvalidOperationException(string.Format("Lifecycle Status with ID {0} already exists.", lifecycleStatus.Id)); } } }
/// <summary> /// Changes the state of a service request to Submitted if the action is possible. /// </summary> /// <param name="userId">ID of user Submitting the request</param> /// <param name="requestId">ID of Service Request to Submit</param> /// <returns>Service Request after Submition is attempted</returns> public IServiceRequestDto <IServiceRequestOptionDto, IServiceRequestUserInputDto> SubmitRequest(int userId, int requestId) { IServiceRequestDto <IServiceRequestOptionDto, IServiceRequestUserInputDto> request = RequestFromId(requestId); if (request.State != ServiceRequestState.Incomplete) { throw new ServiceRequestStateException( string.Format("Cannot change the state of a Service Request to \"{0}\". " + "Service Request is in the \"{1}\" state and must be in the " + "\"{2}\" state to perform this action.", ServiceRequestState.Submitted, request.State, ServiceRequestState.Incomplete)); } if (UserCanSubmitRequest(userId, requestId)) { using (var context = new PrometheusContext()) { var requestEntity = context.ServiceRequests.Find(requestId); //Change state of the entity requestEntity.State = ServiceRequestState.Submitted; requestEntity.SubmissionDate = DateTime.UtcNow; //Save context.Entry(requestEntity).State = EntityState.Modified; context.SaveChanges(userId); request = ManualMapper.MapServiceRequestToDto(requestEntity); } } return(request); }
/// <summary> /// Retrieve a single department /// </summary> /// <param name="performingUserId">user making the request</param> /// <param name="departmentId">department to retrieve</param> /// <returns></returns> public IDepartmentDto GetDepartment(int performingUserId, int departmentId) { using (var context = new PrometheusContext()) { return(ManualMapper.MapDepartmentToDto(context.Departments.FirstOrDefault(x => x.Id == departmentId))); } }
public void ManualMapperMapErrorTest() { var target = new ManualMapper<FromTestClass, ToTestClass>(); var source = new FromTestClass() { Id = 5, Description = "test" }; var targetObj = new ToTestClass(); target.AddMappingAction("Id", "Code", (f, t) => { throw new InvalidOperationException(); }); target.Map(source, targetObj); }
public void Map_InvalidMappingAction_WrapsAndThrows() { var sut = new ManualMapper<FromTestClass, ToTestClass>(); var source = new FromTestClass {Id = 5, Description = "test"}; var targetObj = new ToTestClass(); sut.AddMappingAction("Id", "Code", (f, t) => { throw new InvalidOperationException(); }); Should.Throw<MappingException>(() => sut.Map(source, targetObj)); }
private ManualMapper<FromTestClass, ToTestClass> SetupTest(FromTestClass source) { var sut = new ManualMapper<FromTestClass, ToTestClass>(); source.Id = 5; source.Description = "test"; source.SampleDate = DateTime.Now; sut.AddMappingAction("Id", "Code", (f, t) => t.Code = f.Id); sut.AddMappingAction("Description", "Name", (f, t) => t.Name = f.Description); sut.AddMappingAction("SampleDate", "SampleDateInStrFormat", (f, t) => t.SampleDateInStrFormat = f.SampleDate.ToShortDateString()); return sut; }
public void ManualMapperMapTest() { var target = new ManualMapper<FromTestClass, ToTestClass>(); FromTestClass source = new FromTestClass() { Id = 5, Description = "test" }; var targetObj = new ToTestClass(); target.AddMappingAction("Id", "Code", (f, t) => t.Code = f.Id); target.AddMappingAction("Description", "Name", (f, t) => t.Name = f.Description); target.AddMappingAction("SampleDate", "SampleDateInStrFormat", (f, t) => t.SampleDateInStrFormat = f.SampleDate.ToShortDateString()); target.Map(source, targetObj); Assert.AreEqual(source.Id, targetObj.Code); Assert.AreEqual(source.Description, targetObj.Name); Assert.AreEqual(source.SampleDate.ToShortDateString(), targetObj.SampleDateInStrFormat); }
public NHibernateInMemoryRepository(IFrameworkContext fakeFrameworkContext, ISessionFactory sessionFactory = null, ISession sessionForTest = null) { using (DisposableTimer.TraceDuration<NHibernateInMemoryRepository>("Start setup", "End setup")) { if (sessionFactory == null && sessionForTest == null) { var builder = new NHibernateConfigBuilder("data source=:memory:", "unit-tester", SupportedNHDrivers.SqlLite, "thread_static", false); var config = builder.BuildConfiguration(); _sessionFactory = config.BuildSessionFactory(); SessionForTest = _sessionFactory.OpenSession(); // See http://stackoverflow.com/questions/4325800/testing-nhibernate-with-sqlite-no-such-table-schema-is-generated // and also http://nhforge.org/doc/nh/en/index.html#architecture-current-session // regarding contextual sessions and GetCurrentSession() // We pass in our own TextWriter because a bug in VS's testing framework means directly passing in Console.Out causes an ObjectDisposedException new SchemaExport(config).Execute(false, true, false, SessionForTest.Connection, _schemaWriter); } else { _sessionFactory = sessionFactory; SessionForTest = sessionForTest; } _dataContextFactory = new DataContextFactory(fakeFrameworkContext, SessionForTest, true); // Create reader ReadOnlyUnitOfWorkFactory = new ReadOnlyUnitOfWorkFactory(); _hiveReadProvider = new HiveReadProvider(new HiveProviderSetup(fakeFrameworkContext, "r-unit-tester", new FakeHiveProviderBootstrapper(), ReadOnlyUnitOfWorkFactory, null, _dataContextFactory)); // Create writer ReadWriteUnitOfWorkFactory = new ReadWriteUnitOfWorkFactory(); _writeProvider = new HiveReadWriteProvider(new HiveProviderSetup(fakeFrameworkContext, "rw-unit-tester", new FakeHiveProviderBootstrapper(), ReadOnlyUnitOfWorkFactory, ReadWriteUnitOfWorkFactory, _dataContextFactory)); //setup nhibernate mappers var manualMapper = new ManualMapper(new NhLookupHelper(_dataContextFactory), _writeProvider); fakeFrameworkContext.TypeMappers.Add(new Lazy<AbstractTypeMapper, TypeMapperMetadata>(() => manualMapper, new TypeMapperMetadata(true))); // Create hive wrappers for the readers and writers var governorRUowFactory = new ReadOnlyUnitOfWorkFactoryWrapper(new[] { _hiveReadProvider }); var governorRWUowFactory = new ReadWriteUnitOfWorkFactoryWrapper(new[] { _writeProvider }); _hiveReadProviderViaGovernor = new Framework.Hive.PersistenceGovernor.HiveReadProvider(new HiveProviderSetup(fakeFrameworkContext, "r-unit-wrapper", new FakeHiveProviderBootstrapper(), governorRUowFactory, null, null), new[] { _hiveReadProvider }); _hiveReadWriteProviderViaGovernor = new Framework.Hive.PersistenceGovernor.HiveReadWriteProvider(new HiveProviderSetup(fakeFrameworkContext, "rw-unit-wrapper", new FakeHiveProviderBootstrapper(), governorRUowFactory, governorRWUowFactory, null), new[] { _writeProvider }); } }
// [Fact] public void Benchmark() { var manual = new ManualMapper<SimplePost>(r => { var dt = new SimplePost(34); dt.Id = (Guid)r["Id"]; dt.Name = r["Name"].ToString(); dt.SetNumber((int)r["Number"]); return dt; }); var data = Setup.FakeReader(r => { r.Clear(); r.Add("Id",Guid.NewGuid()); r.Add("Name", "bla"); r.Add("Number", 23); }); var sut = Setup.MapperFactory().CreateMapper<SimplePost>("1") as Mapper<SimplePost>; sut.Map(data); }