GetById() public method

Retrieve an entity
public GetById ( Guid id ) : T
id Guid
return T
Example #1
0
        static void Main()
        {
            //Create all the repos I need
            var repo = new Repository();

            //Get some entities
            var person = repo.GetById<Person>(1);
            var company = repo.GetById<Company>(2);
            var order = repo.GetById<Order>(3);

            //Chagne and save entities
            person.FirstName = "Bob";
            company.CompanyName = "Bob's House of Propane and Day Old Sushi";
            order.OrderTotal = 1000000;

            var personId = repo.Save(person);
            var companyId = repo.Save(company);
            var orderId = repo.Save(order);

            Console.WriteLine("Saved person, Id is {0}", personId);
            Console.WriteLine("Saved company, Id is {0}", companyId);
            Console.WriteLine("Saved order, Id is {0}", orderId);

            Console.ReadKey();
        }
        public void Should_update_entity_using_single_context()
        {
            Order toUpdate = null;

            try
            {
                // Get original  -- Arrange
                using (var context = new RepositoryTest())
                {
                    var repo = new Repository<Order>(context);

                    toUpdate = repo.GetById(10337);

                    // alter property and then update -- Act
                    toUpdate.ShipName = "abc";

                    repo.Update(toUpdate);
                }

                // Requery db to Assert that data updated
                using (var context = new RepositoryTest())
                {
                    var repo = new Repository<Order>(context);

                    var original = repo.GetById(10337);

                    Assert.AreEqual("abc", original.ShipName);
                }
            }
            finally
            {
                // Clean up the data so that its in the correct state
                TestScriptHelper.ResetShipName();
            }
        }
        public void CategoriesShouldBeReturnedNested()
        {
            using (new TransactionScope())
            {
                var connectionStringProvider = new ConnectionStringProvider("<my connection string>");
                var dataContextProvider = new DataContextProvider(connectionStringProvider);

                // first insert a new graph into the database
                var categoryRepository = new Repository<Category>(dataContextProvider);

                // use the object graph created by the mock category repository
                var root = MockRepositoryBuilder.CreateCategoryRepository().GetRootCategory();

                // add the root into the real database
                categoryRepository.InsertOnSubmit(root);

                categoryRepository.SubmitChanges();

                // try to get the root again (note we need the actual id because we don't want the real root,
                // which will have a different graph of categories, from the database)
                var rootFromDb = categoryRepository.GetById(root.CategoryId);

                MockRepositoryBuilder.AssertCategoryGraphIsCorrect(rootFromDb);
            }
        }
Example #4
0
        public void TestChangeCity()
        {
            Guid id = Guid.NewGuid();
            Guid companyId = Guid.NewGuid();
            Guid countryId = Guid.NewGuid();
            Guid cityId = Guid.NewGuid();

            Repository<Address> repository = new Repository<Address>(ObjectFactory.Create<IEventStore>());

            Address address = repository.GetById(id);

            address.Create(id, Owner.Company, companyId);
            address.ChangeCountry(countryId);
            address.ChangeCity(cityId);

            Assert.AreEqual(Owner.Company, address.State.Owner);
            Assert.AreEqual(countryId, address.State.CountryId);
            Assert.AreEqual(cityId, address.State.CityId);
            Assert.AreEqual(3, address.GetUncommittedChanges().Count);

            address.Commit();
            Assert.AreEqual(0, address.GetUncommittedChanges().Count);

            address.LoadFromHistory(new List<Event> {new AddressEvents.NoteChanged(id, "this note should be applied to aggregate")});
            Assert.AreEqual("this note should be applied to aggregate", address.State.Note);
        }
 //public static void PrintUsage(IEnumerable<ICommandFactory> availableCommands)
 //    {
 //        Console.WriteLine("List of Commands:");
 //        foreach(var command in availableCommands)
 //            Console.WriteLine("{0}", command.CommandDescription);
 //    }
 public static IRavenEntity fetch(IRavenEntity entity)
 {
     Repository repo = new Repository();
     var entityToReturn = repo.GetById(entity);
     if (entityToReturn != null) { return entityToReturn; }
     else { return null; }
 }
        public void AddNewsWhenNewsIsAddedToDbShouldReturnNews()
        {
            //Arange -> prepare the objects
            var repo = new Repository<Models.News>(new NewsContext());
            var news = new Models.News()
            {
                Id = 1,
                Title = "title 1",
                Content = "content 1",
                PublishedData = DateTime.Now
            };

            //Act -> perform some logic
            repo.Add(news);
            repo.SaveChanges();

            //Assert -> validate the results
            var newsFromDb = repo.GetById(news.Id);

            Assert.IsNotNull(newsFromDb);
            Assert.AreEqual(news.Title, newsFromDb.Title);
            Assert.AreEqual(news.Content, newsFromDb.Content);
            Assert.AreEqual(news.PublishedData, newsFromDb.PublishedData);
            Assert.IsTrue(newsFromDb.Id != 0);
        }
        public DetailBookController(Views.Book.BookDetailsView view, ReadOnlyContext context, int bookID, int userID)
        {
            this.userID = userID;
            this.bookID = bookID;
            _context = context;
            _detailBookView = view;

            _booksRepository = context.GetRepository<DataInterface.Entities.Copy>();
            _leasesRepository = context.GetRepository<DataInterface.Entities.Lease>();
            _usersRepository = context.GetRepository<DataInterface.Entities.User>();
            _reservationsRepository = context.GetRepository<DataInterface.Entities.Reservation>();
            selectedBook = _booksRepository.GetById(bookID);

            var userBorrowedBooks = _leasesRepository.GetByQuery(x => x.Copy.Book.Id == bookID);
            var userBookingBooks = _reservationsRepository.GetByQuery(x => x.ReservedCopy.Book.Id == bookID);
            Views.Book.BookDetailsView example = new Views.Book.BookDetailsView(selectedBook, userBorrowedBooks, userBookingBooks);

            if (_context.CurrentUser.Role == DataInterface.Enums.Role.Reader)
            {
                Return.Visible = false;
                Title.Enabled = false;
                Author.Enabled = false;
                ISBN.Enabled = false;
                PublishingYear.Enabled = false;
                Publisher.Enabled = false;
                Format.Enabled = false;
            }

            _detailBookView = example;

            Return.Click += ReturnBook_Click;
            Borrow.Click += Borrow_Click;

            _detailBookView.Show();
        }
Example #8
0
        public void TestAddressHandler()
        {
            Guid id = Guid.NewGuid();
            Guid companyId = Guid.NewGuid();
            Guid countryId = Guid.NewGuid();
            Guid cityId = Guid.NewGuid();

            IMessageBus messageBus = ServiceMediator.Bus;
            messageBus.Send(new AddressCommands.Create(id, Owner.Company, companyId));
            messageBus.Send(new AddressCommands.ChangeCountry(id, countryId));
            messageBus.Send(new AddressCommands.ChangeCity(id, cityId));

            Repository<Address> repository = new Repository<Address>(ObjectFactory.Create<IEventStore>());
            Address address = repository.GetById(id);

            Assert.AreEqual(Owner.Company, address.State.Owner);
            Assert.AreEqual(countryId, address.State.CountryId);
            Assert.AreEqual(cityId, address.State.CityId);

            AddressFacade facade = new AddressFacade(ObjectFactory.Create<IReadModelStore>());
            GetAddressResponse response = facade.GetAddress(new GetAddressRequest {AddressId = id});
            Assert.IsNotNull(response);
            Assert.IsNotNull(response.Address);
            Assert.AreEqual(id, response.Address.AddressId);

            GetAddressListResponse searchResponse = facade.GetAddressList(new GetAddressListRequest {Filter = "qwerty"});
            Assert.IsNotNull(searchResponse);
            Assert.IsTrue(searchResponse.AddressList == null || searchResponse.AddressList.Count == 0);

            searchResponse = facade.GetAddressList(new GetAddressListRequest { Filter = "auna" });
            Assert.IsNotNull(searchResponse);
            Assert.IsTrue(searchResponse.AddressList != null && searchResponse.AddressList.Count == 1);
        }
Example #9
0
        public void CanStoreAProduct()
        {
            //Database.SetInitializer(new DropCreateDatabaseAlways<CoffeeShopContext>());
            long id;
            using (var session = m_sessionFactory.OpenSession())
            using (var tx = session.BeginTransaction())
            {
                var repository = new Repository<Product>(session);
                var product = new Product
                {
                    Name = "Coffee 1",
                    Price = 10.4m
                };

                repository.MakePersistent(product);
                id = product.Id;
                tx.Commit();
            }

            using (var session = m_sessionFactory.OpenSession())
            using (session.BeginTransaction())
            {
                var repository = new Repository<Product>(session);
                Product product = repository.GetById(id);

                product.Satisfy(p => p.Name == "Coffee 1" && p.Price == 10.4m);
            }
        }
        public void NothingShouldGoBang()
        {
            var factStore = new MemoryFactStore();
            var aggregateRebuilder = new AggregateRebuilder(factStore);
            var snapshot = new QueryModel<Student>(aggregateRebuilder);
            var eventBroker = Substitute.For<IDomainEventBroker>();

            Guid studentId;

            using (var unitOfWork = new UnitOfWork(factStore, eventBroker, new SystemClock()))
            {
                var repository = new Repository<Student>(snapshot, unitOfWork);

                var student = Student.Create("Fred", "Flintstone");
                studentId = student.Id;
                repository.Add(student);

                unitOfWork.Complete();
            }

            using (var unitOfWork = new UnitOfWork(factStore, eventBroker, new SystemClock()))
            {
                var repository = new Repository<Student>(snapshot, unitOfWork);
                var student = repository.GetById(studentId);

                student.FirstName.ShouldBe("Fred");
                student.LastName.ShouldBe("Flintstone");
            }
        }
        public void Should_throw_InvalidOperationException_if_invalid_id_provided()
        {
            using (var context = new RepositoryTestDataContext())
            {
                var repo = new Repository<Order>(context);

                Assert.Throws<InvalidOperationException>(() => repo.GetById(1));
            }
        }
Example #12
0
        public ActionResult Here(int locationId)
        {
            // Get the data
            IRepository repository = new Repository(new CheckInDatabaseContext());

            var location = repository.GetById<Location>(locationId);
            if (location == null)
            {
                return new HttpNotFoundResult();
            }

            var username = HttpContext.User.Identity.Name;

            var user = repository.Query<ApplicationUser>().SingleOrDefault(u => u.UserName == username);
            if (user == null)
            {
                return new HttpNotFoundResult();
            }

            // make a new check in
            var checkIn = new CheckIn();
            checkIn.User = user;
            checkIn.Location = location;
            checkIn.Time = DateTime.Now;
            repository.Insert(checkIn);

            // check to see if this user meets any achievements
            var allCheckins = repository.Query<CheckIn>().Where(c => c.User.Id == user.Id);
            var allAchievements = repository.Query<Achievement>();
            var allLocationIds = repository.Query<Location>().Select(l => l.Id);

            // two in one day?
            if (!allAchievements.Any(a => a.Type == AchievementType.TwoInOneDay) && allCheckins.Count(c => EntityFunctions.TruncateTime(c.Time) == DateTime.Today) > 2)
            {
                var twoInOneDay = new Achievement { Type = AchievementType.TwoInOneDay, User = user, TimeAwarded = DateTime.Now };
                repository.Insert(twoInOneDay);
            }

            // all locations?
            var hasAll = false;
            foreach (var testLocationId in allLocationIds)
            {
                hasAll = hasAll || allCheckins.Any(c => c.Location.Id == testLocationId);
            }

            if (!allAchievements.Any(a => a.Type == AchievementType.AllLocations) && hasAll)
            {
                var allLocations = new Achievement { Type = AchievementType.AllLocations, User = user, TimeAwarded = DateTime.Now };
                repository.Insert(allLocations);
            }

            // some day we'll have hundreds of achievements!

            repository.SaveChanges();

            return RedirectToAction("Index");
        }
Example #13
0
 public void GetById_ProductWithId1IsRequestedWithNoProductsInDb_NoProductIsReturnedFromDb()
 {
     using (var context = new CashRegisterContext())
     {
         var uut = new Repository<Product>(context);
         var result = uut.GetById((long)1);
         Assert.That(result, Is.EqualTo(null));
     }
 }
        public void Should_return_an_object_for_id_provided()
        {
            using (var context = new RepositoryTestDataContext())
            {
                var repo = new Repository<Order>(context);

                Assert.IsNotNull(repo.GetById(10248));
            }
        }
 public virtual void A_SetUpCountryRepo()
 {
     using (var context = new MainContext())
     {
         //Get the country.
         var myCountryRepo = new Repository<Country>(context);
         MyCountryTest = myCountryRepo.GetById(1);
     }
 }
 public void Should_throw_ArgumentNullException_if_null_id_provided()
 {
     using (var context = new RepositoryTestDataContext())
     {
         using (var repo = new Repository<Order>(context))
         {
             Assert.Throws<ArgumentNullException>(() => repo.GetById(null));
         }
     }
 }
Example #17
0
        public void TestGetByIdThrowsNotFoundException()
        {
            using (new SessionScope(FlushAction.Never))
            {
                var fooRepository = new Repository<Foo>();

                Guid id = Guid.NewGuid();

                Assert.Throws<NotFoundException>(() => fooRepository.GetById(id));
            }
        }
Example #18
0
        public void get_by_id_should_retrieve_object_from_container()
        {
            using (var container = GetContainer())
            {
                var repository = new Repository<Foo>(container);

                var foo = repository.GetById(1);

                foo.ShouldNotBeNull();
            }
        }
        public void Changing_An_Entity_Retrieved_By_The_Repository_Should_Not_Change_The_Stored_List()
        {
            var repository = new Repository<Author>();
            var author = repository.Insert(new Author()
            {
                FirstName = "Bruce",
                LastName = "Wayne"
            });

            var authorId = author.Id;

            author = repository.GetById(authorId);

            author.FirstName = "Dick";
            author.LastName = "Grayson";

            var authorStored = repository.GetById(authorId);
            Assert.AreEqual(authorId, authorStored.Id);
            Assert.AreEqual("Bruce", authorStored.FirstName);
            Assert.AreEqual("Wayne", authorStored.LastName);
        }
Example #20
0
		public void add_user_returns_valid_user_with_id ()
		{
			var dbName = "quad";
			var connectionString = "mongodb://localhost";
			var server = MongoDB.Driver.MongoServer.Create (connectionString);
			var dStore = new Repository (new RepositoryConfiguration () {DBName = dbName,
								ConnectionString=connectionString,Server = server});
			var user = dStore.Add(new User () { Email="*****@*****.**" });
			Assert.IsNotNull (user.Id);
			
			var newUser = dStore.GetById<User>(user.Id);
			
			Assert.IsNotNull (user);
			
			Assert.AreEqual (user.Email, newUser.Email);
			Assert.AreEqual (user.Id, newUser.Id);
			
			dStore.Delete<User>(user.Id);
			
			Assert.IsNull (dStore.GetById<User>(user.Id));
		}
Example #21
0
        public void GetUserById()
        {
            //Arrange
            var databaseFactory = new DatabaseFactory();
            var userRepository = new Repository<User>(databaseFactory);

            //Act
            var user = userRepository.GetById(1);

            //Asset
            Assert.NotNull(user);
        }
Example #22
0
        public void Loads_aggregate_from_session_if_tracked()
        {
            var trackedAggregate = new SomeDomainEntity();

            var session = new Session(this, this);
            session.Track(trackedAggregate);

            var repository = new Repository<SomeDomainEntity>(this, session);

            var loadedAggregate = repository.GetById(trackedAggregate.Id);

            loadedAggregate.ShouldBeSameAs(trackedAggregate);
        }
        public void Should_return_correct_object_for_id()
        {
            using (var context = new RepositoryTestDataContext())
            {
                var repo = new Repository<Order>(context);

                var actual = repo.GetById(10248);

                actual.Satisfies(o => o.OrderID == 10248
                                      && o.ShipVia == 3
                                      && o.ShipName == "Vins et alcools Chevalier");
            }
        }
Example #24
0
        public void Loads_aggregate_From_eventstore_if_not_tracked()
        {
            var untrackedAggregate = new SomeDomainEntity();
            var session = new Session(this, this);
            _aggregateToLoad = untrackedAggregate;

            var repository = new Repository<SomeDomainEntity>(this, session);

            var loadedAggregate = repository.GetById(untrackedAggregate.Id);

            loadedAggregate.ShouldBeSameAs(_aggregateToLoad);
            session.GetAggregateIfTracked<SomeDomainEntity>(untrackedAggregate.Id).ShouldNotBeNull("Aggregate should have been added to session");
        }
        public void Should_Delete_An_Entity()
        {
            var repository = new Repository<Author>();
            var author = repository.Insert(new Author()
            {
                FirstName = "Bruce",
                LastName = "Wayne"
            });

            repository.Delete(author.Id);
            author = repository.GetById(author.Id);
            Assert.IsNull(author);
        }
        public void Should_delete_the_record_when_given_a_valid_entity_on_the_same_data_context()
        {
            using (var context = new RepositoryTestDataContext())
            {
                var repo = new Repository<Order>(context);
                var original = repo.GetById(10287);

                repo.Delete(original);
            }

            Assert.IsTrue(CheckRecordDeleted());

            TestScriptHelper.InsertDeletedRecord();
        }
        public void GetAnAggregateWithSomeEventsReturnsEvents()
        {
            var aggregateId = Guid.NewGuid();
            var @event = new Event();
            var storageMock = new EventStoreMock().SeedEvents(aggregateId, @event);
            var repository = new Repository<AggregateRootMock>(storageMock);

            var rootMock = new AggregateRootMock(aggregateId);
            rootMock.SomeEvent(@event);

            repository.Save(rootMock, 0);
            var actualRoot = repository.GetById(aggregateId);
            
            Assert.Equal(@event, actualRoot.MyEvent);
        }
Example #28
0
        public void TestGetByIdReturnsSavedEntity()
        {
            using (new SessionScope(FlushAction.Never))
            {
                IRepository<Foo> fooRepository = new Repository<Foo>();

                var entity = new Foo();

                ActiveRecordMediator.SaveAndFlush(entity);

                var foo = fooRepository.GetById(entity.Id);

                Assert.AreEqual(entity, foo);
            }
        }
        public void Update()
        {
            const string newName = "Rafael Fernandes";

            using (var context = new MainContext())
            {
                var myRepo = new Repository<Core.Customer>(context);

                var firstClientInTheDb = myRepo.GetAll().FirstOrDefault();
                if (firstClientInTheDb != null)
                {
                    //Find an entity to be updated.
                    var myClient = myRepo.GetById(firstClientInTheDb.Id);

                    myClient.Name = newName;

                    myRepo.Update(myClient);
                    myRepo.Save();

                    //Compare if the name changed in the database
                    Assert.AreEqual(myRepo.GetById(firstClientInTheDb.Id).Name, newName);
                }
            }
        }
        private bool CheckRecordDeleted()
        {
            using (var context = new RepositoryTestDataContext())
            {
                var repo = new Repository<Order>(context);
                try
                {
                    repo.GetById(10287);
                }
                catch (InvalidOperationException ioe)
                {
                    return true;
                }

                return false;
            }
        }
Example #31
0
        public override async Task <Command> Add(Command command)
        {
            Command cmd = new Command(command);

            try
            {
                var dto = await SerializerAsync.DeserializeJson <CompraManualDto>(command.Json);

                var compras = await MyRepository.Get(t => t.Codigo.Equals(dto.Codigo));

                if (compras != null && !compras.Any())
                {
                    var unidadeMedidaRep = new Repository <UnidadeMedida>(Context);
                    var servicoRep       = new Repository <Servico>(Context);

                    var tipoEntradaRep = new Repository <TipoEntrada>(Context);
                    var tipoEntrada    = await tipoEntradaRep.GetById(dto.TipoEntradaId);

                    var fornecedorRep = new Repository <Fornecedor>(Context);
                    var fornecedor    = await fornecedorRep.GetById(dto.FornecedorId);

                    var entity = new CompraManual();
                    entity.UpdateEntity(dto);

                    if (tipoEntrada != null)
                    {
                        entity.TipoEntrada = tipoEntrada;
                    }

                    if (fornecedor != null)
                    {
                        entity.Fornecedor = fornecedor;
                    }

                    if (entity.DataEmissao == DateTime.MinValue)
                    {
                        entity.DataEmissao = DateTime.Now;
                    }

                    if (String.IsNullOrEmpty(entity.Codigo))
                    {
                        if (!string.IsNullOrEmpty(entity.Fornecedor.NomeFantasia))
                        {
                            entity.Codigo = entity.Fornecedor.NomeFantasia + DateTime.Now.ToString();
                        }
                    }

                    if (entity.Itens != null && entity.Itens.Count > 0)
                    {
                        entity.ValorTotal = 0;
                        foreach (var item in entity.Itens)
                        {
                            var unidadeMedida = await unidadeMedidaRep.GetById(item.UnidadeId);

                            var servico = await servicoRep.GetById(item.ServicoId);

                            if (unidadeMedida != null)
                            {
                                item.Unidade = unidadeMedida;
                            }

                            if (servico != null)
                            {
                                item.Servico = servico;
                                item.Codigo  = servico.Codigo + DateTime.Now.ToString();
                            }

                            entity.ValorTotal += item.ValorTotal;
                        }
                    }

                    var insertEntity = await MyRepository.Insert(entity);

                    if (insertEntity != null)
                    {
                        cmd.Cmd  = ServerCommands.LogResultOk;
                        cmd.Json = await SerializerAsync.SerializeJson(true);

                        await MyRepository.Save();

                        cmd.EntityId = entity.Id;
                    }
                    else
                    {
                        cmd.Cmd = ServerCommands.RepeatedHumanCode;
                        ConsoleEx.WriteLine(ServerCommands.RepeatedHumanCode);
                    }
                }
                else
                {
                    cmd.Cmd = ServerCommands.LogResultDeny;
                }
            }
            catch (Exception e)
            {
                ConsoleEx.WriteError(e);
            }

            return(cmd);
        }
Example #32
0
 void dataItemskryptonDataGridView_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
 {
     if (m_editMode == EditMode.View)
     {
         return;
     }
     itemsDataGrid.Rows[e.RowIndex].ErrorText = "";
     if (!itemsDataGrid[e.ColumnIndex, e.RowIndex].IsInEditMode)
     {
         return;
     }
     if (e.ColumnIndex == scanColumn.Index)
     {
         if (!((DataGridViewTextBoxCell)itemsDataGrid[scanColumn.Index, e.RowIndex]).IsInEditMode)
         {
             return;
         }
         if (e.FormattedValue.ToString() == "")
         {
             return;
         }
         IList result = r_part.SearchActivePart(e.FormattedValue.ToString(), true);
         if (result.Count == 1)
         {
             Part p = (Part)result[0];
             for (int i = 0; i < itemsDataGrid.Rows.Count; i++)
             {
                 if (i == e.RowIndex)
                 {
                     continue;
                 }
                 Part pi = (Part)itemsDataGrid[codeColumn.Index, i].Tag;
                 if (pi == null)
                 {
                     continue;
                 }
                 if (pi.ID == p.ID)
                 {
                     itemsDataGrid.Rows[e.RowIndex].ErrorText = "Part : " + p.NAME + " already add.";
                     e.Cancel = true;
                     return;
                 }
             }
             itemsDataGrid[codeColumn.Index, e.RowIndex].Tag   = p;
             itemsDataGrid[scanColumn.Index, e.RowIndex].Value = p.BARCODE;
             itemsDataGrid[codeColumn.Index, e.RowIndex].Value = p.CODE;
             itemsDataGrid[nameColumn.Index, e.RowIndex].Value = p.NAME;
             //dataItemskryptonDataGridView[QtyColumn.Index, e.RowIndex].Value = 0;
             //unitColumn.Items.Clear();
             // IList units = r_part.GetAllUnit(p.ID, p.UNIT.ID);
             //Utils.GetListCode(unitColumn.Items, units);
             p.UNIT = (Unit)r_unit.GetById(p.UNIT);
             itemsDataGrid[unitColumn.Index, e.RowIndex].Value  = p.UNIT.ToString();
             itemsDataGrid[priceColumn.Index, e.RowIndex].Value = r_po.GetTheLatestPOPrice(((Supplier)supplierkryptonComboBox.SelectedItem).ID, p.ID, p.UNIT.ID);
             //dataItemskryptonDataGridView[totalAmountColumn.Index, e.RowIndex].Value = 0;
             itemsDataGrid[warehouseColumn.Index, e.RowIndex].Value = m_warehouses[0].ToString();
         }
         if ((result.Count == 0) || (result.Count > 1))
         {
             using (SearchPartForm fr = new SearchPartForm(e.FormattedValue.ToString(), result))
             {
                 fr.ShowDialog();
                 Part p = fr.PART;
                 if (p == null)
                 {
                     p = (Part)itemsDataGrid[codeColumn.Index, e.RowIndex].Tag;
                     if (p == null)
                     {
                         e.Cancel = true;
                         return;
                     }
                 }
                 else
                 {
                     for (int i = 0; i < itemsDataGrid.Rows.Count; i++)
                     {
                         if (i == e.RowIndex)
                         {
                             continue;
                         }
                         Part pi = (Part)itemsDataGrid[codeColumn.Index, i].Tag;
                         if (pi == null)
                         {
                             continue;
                         }
                         if (pi.ID == p.ID)
                         {
                             itemsDataGrid.Rows[e.RowIndex].ErrorText = "Part : " + p.NAME + " already add.";
                             e.Cancel = true;
                             return;
                         }
                     }
                     itemsDataGrid[codeColumn.Index, e.RowIndex].Tag   = p;
                     itemsDataGrid[scanColumn.Index, e.RowIndex].Value = p.BARCODE;
                     itemsDataGrid[codeColumn.Index, e.RowIndex].Value = p.CODE;
                     itemsDataGrid[nameColumn.Index, e.RowIndex].Value = p.NAME;
                     //dataItemskryptonDataGridView[QtyColumn.Index, e.RowIndex].Value = 0;
                     //unitColumn.Items.Clear();
                     //IList units = r_part.GetAllUnit(p.ID, p.UNIT.ID);
                     //Utils.GetListCode(unitColumn.Items, units);
                     p.UNIT = (Unit)r_unit.GetById(p.UNIT);
                     itemsDataGrid[unitColumn.Index, e.RowIndex].Value  = p.UNIT.ToString();
                     itemsDataGrid[priceColumn.Index, e.RowIndex].Value = r_po.GetTheLatestPOPrice(((Supplier)supplierkryptonComboBox.SelectedItem).ID, p.ID, p.UNIT.ID);
                     // dataItemskryptonDataGridView[totalAmountColumn.Index, e.RowIndex].Value = 0;
                     itemsDataGrid[warehouseColumn.Index, e.RowIndex].Value = m_warehouses[0].ToString();
                 }
             }
         }
     }
     if (e.ColumnIndex == discabcColumn.Index)
     {
         if (e.FormattedValue.ToString() == "")
         {
             return;
         }
         else
         {
             try
             {
                 splitDiscString(e.FormattedValue.ToString(), 0);
                 splitDiscString(e.FormattedValue.ToString(), 1);
                 splitDiscString(e.FormattedValue.ToString(), 2);
             }
             catch (Exception x)
             {
                 itemsDataGrid.Rows[e.RowIndex].ErrorText = x.Message;
                 e.Cancel = true;
                 return;
             }
         }
     }
 }
        /// <summary>
        /// 删除不正常的流程实例(流程在取消状态,才可以进行删除!)
        /// </summary>
        /// <param name="processInstanceID">流程实例ID</param>
        /// <param name="isForced">不取消,直接删除</param>
        /// <returns>是否删除标识</returns>
        internal bool Delete(int processInstanceID, bool isForced = false)
        {
            bool       isDeleted = false;
            IDbSession session   = SessionFactory.CreateSession();

            try
            {
                session.BeginTrans();
                var entity = Repository.GetById <ProcessInstanceEntity>(processInstanceID);

                if (entity.ProcessState == (int)ProcessStateEnum.Canceled ||
                    isForced == true)
                {
                    //delete tasks
                    var sqlTasks = @"DELETE 
                                    FROM WfTasks 
                                    WHERE ProcessInstanceID=@processInstanceID";
                    Repository.Execute(session.Connection, sqlTasks,
                                       new { processInstanceID = processInstanceID },
                                       session.Transaction);

                    //delete transitioninstance
                    var sqlTransitionInstance = @"DELETE 
                                                FROM WfTransitionInstance 
                                                WHERE ProcessInstanceID=@processInstanceID";
                    Repository.Execute(session.Connection, sqlTransitionInstance,
                                       new { processInstanceID = processInstanceID },
                                       session.Transaction);

                    //delete activityinstance
                    var sqlActivityInstance = @"DELETE 
                                                FROM WfActivityInstance 
                                                WHERE ProcessInstanceID=@processInstanceID";
                    Repository.Execute(session.Connection, sqlActivityInstance,
                                       new { processInstanceID = processInstanceID },
                                       session.Transaction);

                    //delete process variable
                    var sqlProcessVariable = @"DELETE
                                               FROM WfProcessVariable
                                               WHERE ProcessInstanceID=@processInstanceID";
                    Repository.Execute(session.Connection, sqlProcessVariable,
                                       new { processInstanceID = processInstanceID },
                                       session.Transaction);

                    //delete processinstance
                    Repository.Delete <ProcessInstanceEntity>(session.Connection, processInstanceID, session.Transaction);

                    session.Commit();
                    isDeleted = true;
                }
                else
                {
                    throw new ProcessInstanceException(LocalizeHelper.GetEngineMessage("processinstancemanager.delete.error"));
                }
            }
            catch (System.Exception)
            {
                session.Rollback();
                throw;
            }
            finally
            {
                session.Dispose();
            }

            return(isDeleted);
        }
Example #34
0
        public UserDetailsVM GetById(int id)
        {
            var gelen = _udRepo.GetById(5);

            return(ConvertEntityToVM(gelen));
        }
Example #35
0
 public async Task <ClubLevel> GetById(int _id)
 {
     return(await clubLevelProviderRepository.GetById(_id));
 }
 public async Task <Challenge> GetById(int _id)
 {
     return(await challengeRepository.GetById(_id));
 }
Example #37
0
        public new TEntityDTO GetById(ZOperationResult operationResult, object[] ids)
        {
            TEntityDTO result = null;

            try
            {
                if (IsRead(operationResult) || IsUpdate(operationResult) || IsDelete(operationResult))
                {
                    result = (TEntityDTO)Activator.CreateInstance(typeof(TEntityDTO), Repository.GetById(ids));
                }
            }
            catch (Exception exception)
            {
                operationResult.ParseException(exception);
            }

            return(result);
        }
Example #38
0
 protected override Demographic GetById(int id)
 {
     return(Repository.GetById(id));
 }
Example #39
0
 public async Task <PersonTaxDao> GetById(int _id)
 {
     return(await PersonTaxDaoDaoRepository.GetById(_id));
 }
Example #40
0
        public void Execute(UndoCommand command)
        {
            Repository = Container.Resolve <IRepository>();
            var undoGroup = Repository.All <UndoItem>().GroupBy(p => p.Group).LastOrDefault();

            if (undoGroup == null)
            {
                return;
            }
            IsUndoRedo = true;
            try
            {
                foreach (var undoItem in undoGroup)
                {
                    // Create redo item
                    var redoItem = new RedoItem();
                    redoItem.Data         = undoItem.Data;
                    redoItem.Group        = undoItem.Group;
                    redoItem.DataRecordId = undoItem.DataRecordId;
                    redoItem.Name         = undoItem.Name;
                    redoItem.Time         = undoItem.Time;
                    redoItem.Type         = undoItem.Type;
                    redoItem.RecordType   = undoItem.RecordType;
                    redoItem.UndoData     = InvertJsonExtensions.SerializeObject(undoItem).ToString();

                    if (undoItem.Type == UndoType.Inserted)
                    {
                        var record = Repository.GetById <IDataRecord>(undoItem.DataRecordId);
                        redoItem.Data = InvertJsonExtensions.SerializeObject(record).ToString();
                        Repository.Remove(record);
                        redoItem.Type = UndoType.Removed;
                    }
                    else if (undoItem.Type == UndoType.Removed)
                    {
                        var obj =
                            InvertJsonExtensions.DeserializeObject(Type.GetType(undoItem.RecordType),
                                                                   JSON.Parse(undoItem.Data).AsObject) as IDataRecord;
                        Repository.Add(obj);
                        redoItem.Type = UndoType.Inserted;
                        redoItem.Data = InvertJsonExtensions.SerializeObject(obj).ToString();
                    }
                    else
                    {
                        var record = Repository.GetById <IDataRecord>(undoItem.DataRecordId);
                        // We don't want to signal any events on deserialization
                        record.Repository = null;
                        redoItem.Data     = InvertJsonExtensions.SerializeObject(record).ToString();
                        InvertJsonExtensions.DeserializeExistingObject(record, JSON.Parse(undoItem.Data).AsObject);
                        record.Changed    = true;
                        record.Repository = Repository;
                    }
                    Repository.Remove(undoItem);
                    Repository.Add(redoItem);
                }
            }
            catch (Exception ex)
            {
                // If we don't catch the exception IsUndoRedo won't be set back to fals causing cascading issues
            }
            IsUndoRedo = false;
            Repository.Commit();
        }
Example #41
0
 /// <summary>
 /// Search TEntity with specified id in repository
 /// </summary>
 /// <param name="id">Id to search</param>
 /// <returns>Entity if found, else null</returns>
 public TIEntity GetById(long id)
 {
     return(Repository.GetById(id));
 }
Example #42
0
 // GET api/values/5
 public virtual Band Get(Guid id)
 {
     return(Repository.GetById <Band>(id));
 }
Example #43
0
 public bool IsEntityExist(int id)
 {
     return(_repository.GetById(id) != null);
 }
Example #44
0
 /// <summary>
 /// 获取任务
 /// </summary>
 /// <param name="taskID">任务ID</param>
 /// <returns>任务实体</returns>
 public TaskEntity GetTask(int taskID)
 {
     return(Repository.GetById <TaskEntity>(taskID));
 }
 public async Task <PurchaseReceivedChallanHeader> GetById(int _id)
 {
     return(await PurchaseReceivedChallanHeaderDaoRepository.GetById(_id));
 }
 /// <summary>
 /// 根据ID获取流程实例数据
 /// </summary>
 /// <param name="conn">连接</param>
 /// <param name="processInstanceID">流程实例ID</param>
 /// <param name="trans">事务</param>
 /// <returns>流程实例实体</returns>
 internal ProcessInstanceEntity GetById(IDbConnection conn, int processInstanceID, IDbTransaction trans)
 {
     return(Repository.GetById <ProcessInstanceEntity>(conn, processInstanceID, trans));
 }
Example #47
0
 public CU_Page GetCU_PageById(int Id)
 {
     return(_CU_PageServiceRepository.GetById(Id));
 }
Example #48
0
 public async Task <SalesOrderDetail> GetById(int _id)
 {
     return(await SalesOrderDetailDaoRepository.GetById(_id));
 }
 /// <summary>
 /// 根据GUID获取流程实例数据
 /// </summary>
 /// <param name="processInstanceID"></param>
 /// <returns>流程实例实体</returns>
 internal ProcessInstanceEntity GetById(int processInstanceID)
 {
     return(Repository.GetById <ProcessInstanceEntity>(processInstanceID));
 }
Example #50
0
 /*
  * Return a particular staff
  */
 public Staff GetStaffById(int staffId)
 {
     return(_staffRepository.GetById(staffId));
 }
 protected override IEntity ExecuteResult()
 {
     return(Repository.GetById <IEntity>(Id));
 }
Example #52
0
        public Doaa GetByID(int id)
        {
            var Doaa = _DoaaRepository.GetById(id);

            return(Doaa);
        }
Example #53
0
 public Refer GetReferDoctorById(int Id)
 {
     return(_ReferRepository.GetById(Id));
 }
Example #54
0
 public CU_Role_Page GetRolePageById(int RolePageId)
 {
     return(_CU_Role_PageServiceRepository.GetById(RolePageId));
 }
 public async Task <WorkOrderReceivedChallanTax> GetById(int _id)
 {
     return(await WorkOrderReceivedChallanTaxDaoRepository.GetById(_id));
 }
 /// <summary>
 /// 根据ID获取实例数据
 /// </summary>
 /// <param name="transitionInstanceID">转移ID</param>
 /// <returns>转移实例</returns>
 internal TransitionInstanceEntity GetById(int transitionInstanceID)
 {
     return(Repository.GetById <TransitionInstanceEntity>(transitionInstanceID));
 }
        private void runReporttoolStripButton_Click(object sender, EventArgs e)
        {
            Supplier s         = (Supplier)supplierkryptonComboBox.SelectedItem;
            bool     allStatus = statuskryptonComboBox2.Text == "ALL";
            bool     status    = true;

            if (!allStatus)
            {
                status = Boolean.Parse(statuskryptonComboBox2.Text);
            }
            string type = trtypekryptonComboBox1.Text;

            IList trs = r_sup.GetAllTransactions(s.ID, startdateKryptonDateTimePicker.Value, enDatekryptonDateTimePicker1.Value,
                                                 allStatus, status);

            transactionkryptonDataGridView.Rows.Clear();
            if (trs.Count > 0)
            {
                foreach (object ev in trs)
                {
                    if (ev is Event)
                    {
                        Event t = (Event)ev;
                        if (type != "ALL")
                        {
                            if (t.STOCK_CARD_ENTRY_TYPE.ToString() != type)
                            {
                                continue;
                            }
                        }
                        int r = transactionkryptonDataGridView.Rows.Add();
                        transactionkryptonDataGridView[datetrColumn.Index, r].Value = t.TRANSACTION_DATE;
                        transactionkryptonDataGridView[typeTrColumn.Index, r].Value = t.STOCK_CARD_ENTRY_TYPE.ToString();
                        transactionkryptonDataGridView[codeTrColumn.Index, r].Value = t.CODE;
                        transactionkryptonDataGridView[postedColumn.Index, r].Value = t.POSTED.ToString();
                        Supplier sup = (Supplier)r_sup.GetById((Supplier)t.VENDOR);
                        Employee emp = (Employee)r_emp.GetById(t.EMPLOYEE);
                        transactionkryptonDataGridView[supplierColumn.Index, r].Value   = sup.NAME;
                        transactionkryptonDataGridView[supCodeColumn.Index, r].Value    = sup.CODE;
                        transactionkryptonDataGridView[supAddressColumn.Index, r].Value = sup.ADDRESS;
                        transactionkryptonDataGridView[employeeColumn.Index, r].Value   = emp.CODE;
                        if (t is PurchaseOrder)
                        {
                            PurchaseOrder p = (PurchaseOrder)t;
                            p.TOP      = (TermOfPayment)r_top.GetById(p.TOP);
                            p.CURRENCY = (Currency)r_ccy.GetById(p.CURRENCY);
                            transactionkryptonDataGridView[topColumn.Index, r].Value    = p.TOP.CODE;
                            transactionkryptonDataGridView[amountColumn.Index, r].Value = p.NET_TOTAL;
                            transactionkryptonDataGridView[ccyColumn.Index, r].Value    = p.CURRENCY.CODE;
                        }
                        if (t is SupplierInvoice)
                        {
                            SupplierInvoice p = (SupplierInvoice)t;
                            p.TOP      = (TermOfPayment)r_top.GetById(p.TOP);
                            p.CURRENCY = (Currency)r_ccy.GetById(p.CURRENCY);
                            transactionkryptonDataGridView[topColumn.Index, r].Value    = p.TOP.CODE;
                            transactionkryptonDataGridView[amountColumn.Index, r].Value = p.NET_TOTAL;
                            transactionkryptonDataGridView[ccyColumn.Index, r].Value    = p.CURRENCY.CODE;
                        }
                    }
                    if (ev is EventJournal)
                    {
                        EventJournal t = (EventJournal)ev;
                        if (type != "ALL")
                        {
                            if (t.VENDOR_BALANCE_ENTRY_TYPE.ToString() != type)
                            {
                                continue;
                            }
                        }
                        int r = transactionkryptonDataGridView.Rows.Add();
                        transactionkryptonDataGridView[datetrColumn.Index, r].Value = t.TRANSACTION_DATE;
                        transactionkryptonDataGridView[typeTrColumn.Index, r].Value = t.VENDOR_BALANCE_ENTRY_TYPE.ToString();
                        transactionkryptonDataGridView[codeTrColumn.Index, r].Value = t.CODE;
                        transactionkryptonDataGridView[postedColumn.Index, r].Value = t.POSTED.ToString();
                        Supplier sup = (Supplier)r_sup.GetById((Supplier)t.VENDOR);
                        Employee emp = (Employee)r_emp.GetById(t.EMPLOYEE);
                        transactionkryptonDataGridView[supplierColumn.Index, r].Value   = sup.NAME;
                        transactionkryptonDataGridView[supCodeColumn.Index, r].Value    = sup.CODE;
                        transactionkryptonDataGridView[supAddressColumn.Index, r].Value = sup.ADDRESS;
                        transactionkryptonDataGridView[employeeColumn.Index, r].Value   = emp.CODE;
                        if (t is Payment)
                        {
                            Payment p = (Payment)t;
                            p.CURRENCY = (Currency)r_ccy.GetById(p.CURRENCY);
                            transactionkryptonDataGridView[amountColumn.Index, r].Value = p.NET_AMOUNT;
                            transactionkryptonDataGridView[ccyColumn.Index, r].Value    = p.CURRENCY.CODE;
                        }
                        if (t is SupplierOutStandingInvoice)
                        {
                            SupplierOutStandingInvoice p = (SupplierOutStandingInvoice)t;
                            p.CURRENCY = (Currency)r_ccy.GetById(p.CURRENCY);
                            transactionkryptonDataGridView[amountColumn.Index, r].Value = p.NET_AMOUNT;
                            transactionkryptonDataGridView[ccyColumn.Index, r].Value    = p.CURRENCY.CODE;
                        }
                        if (t is APDebitNote)
                        {
                            APDebitNote p = (APDebitNote)t;
                            p.CURRENCY = (Currency)r_ccy.GetById(p.CURRENCY);
                            transactionkryptonDataGridView[amountColumn.Index, r].Value = p.NET_AMOUNT;
                            transactionkryptonDataGridView[ccyColumn.Index, r].Value    = p.CURRENCY.CODE;
                        }
                    }
                }
            }
        }
Example #58
0
 /// <summary>
 /// 获取任务
 /// </summary>
 /// <param name="conn">数据库链接</param>
 /// <param name="taskID">任务ID</param>
 /// <param name="trans">事务</param>
 /// <returns>任务实体</returns>
 public TaskEntity GetTask(IDbConnection conn, int taskID, IDbTransaction trans)
 {
     return(Repository.GetById <TaskEntity>(conn, taskID, trans));
 }
Example #59
0
 public ContratoEmpresaPrecificacaoProduto ConsultarPorId(int id)
 {
     return(repoContratoEmpresaPrecificacaoProduto.GetById(id));
 }
Example #60
0
 public UsuarioBackOffice ConsultarPorId(int id)
 {
     return(repoUsuarioBackOffice.GetById(id));
 }