private static List<LocationDO> GetAllLocation()
 {
     Repository<vStore_Location> rep = new Repository<vStore_Location>(CheckoutDataContextProvider.Instance);
     List<vStore_Location> list = rep.GetAll().ToList();
     list.ForEach(x => x.Code = x.Code.Trim());
     return Mapper.Map<List<vStore_Location>, List<LocationDO>>(list);
 }
Example #2
0
        public void CanStageANewFileInAPersistentManner()
        {
            TemporaryCloneOfTestRepo path = BuildTemporaryCloneOfTestRepo(StandardTestRepoPath);
            using (var repo = new Repository(path.RepositoryPath))
            {
                const string filename = "unit_test.txt";
                Assert.Equal(FileStatus.Nonexistent, repo.Index.RetrieveStatus(filename));
                Assert.Null(repo.Index[filename]);

                File.WriteAllText(Path.Combine(repo.Info.WorkingDirectory, filename), "some contents");
                Assert.Equal(FileStatus.Untracked, repo.Index.RetrieveStatus(filename));
                Assert.Null(repo.Index[filename]);

                repo.Index.Stage(filename);
                Assert.NotNull(repo.Index[filename]);
                Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus(filename));
            }

            using (var repo = new Repository(path.RepositoryPath))
            {
                const string filename = "unit_test.txt";
                Assert.NotNull(repo.Index[filename]);
                Assert.Equal(FileStatus.Added, repo.Index.RetrieveStatus(filename));
            }
        }
Example #3
0
        public void CanListRemoteReferencesFromUrl(string url)
        {
            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                IList<DirectReference> references = repo.Network.ListReferences(url).ToList();

                foreach (var directReference in references)
                {
                    // None of those references point to an existing
                    // object in this brand new repository
                    Assert.Null(directReference.Target);
                }

                List<Tuple<string, string>> actualRefs = references.
                    Select(directRef => new Tuple<string, string>(directRef.CanonicalName, directRef.TargetIdentifier)).ToList();

                Assert.Equal(ExpectedRemoteRefs.Count, actualRefs.Count);
                for (int i = 0; i < ExpectedRemoteRefs.Count; i++)
                {
                    Assert.Equal(ExpectedRemoteRefs[i].Item2, actualRefs[i].Item2);
                    Assert.Equal(ExpectedRemoteRefs[i].Item1, actualRefs[i].Item1);
                }
            }
        }
Example #4
0
        public PackageManager(Repository repo, IAbsoluteDirectoryPath workDir, bool createWhenNotExisting = false,
            string remote = null) {
            Contract.Requires<ArgumentNullException>(repo != null);
            Contract.Requires<ArgumentNullException>(workDir != null);
            WorkDir = workDir;
            Repo = repo;
            StatusRepo = new StatusRepo();
            Settings = new PackageManagerSettings();

            Repository.Factory.HandlePathRequirements(WorkDir, Repo);

            if (!WorkDir.Exists) {
                if (!createWhenNotExisting)
                    throw new Exception("Workdir doesnt exist");
                WorkDir.MakeSurePathExists();
            }

            if (!string.IsNullOrWhiteSpace(remote)) {
                var config =
                    Repository.DeserializeJson<RepositoryConfigDto>(
                        FetchString(Tools.Transfer.JoinUri(new Uri(remote), "config.json")));
                if (config.Uuid == Guid.Empty)
                    throw new Exception("Invalid remote, does not contain an UUID");
                Repo.AddRemote(config.Uuid, remote);
                Repo.Save();
            }

            Repository.Log("Opening repository at: {0}. Working directory at: {1}", Repo.RootPath, WorkDir);
            _remote = remote;
        }
Example #5
0
 public void CannotReadReflogOnUnknownReference()
 {
     using (var repo = new Repository(StandardTestRepoWorkingDirPath))
     {
         Assert.Throws<InvalidSpecificationException>(() => repo.Refs.Log("toto").Count());
     }
 }
Example #6
0
        public void CanListRemoteReferences(string url)
        {
            string remoteName = "testRemote";

            string repoPath = InitNewRepository();

            using (var repo = new Repository(repoPath))
            {
                Remote remote = repo.Network.Remotes.Add(remoteName, url);
                IList<Reference> references = repo.Network.ListReferences(remote).ToList();

                foreach (var reference in references)
                {
                    // None of those references point to an existing
                    // object in this brand new repository
                    Assert.Null(reference.ResolveToDirectReference().Target);
                }

                List<Tuple<string, string>> actualRefs = references.
                    Select(directRef => new Tuple<string, string>(directRef.CanonicalName, directRef.ResolveToDirectReference()
                        .TargetIdentifier)).ToList();

                Assert.Equal(TestRemoteRefs.ExpectedRemoteRefs.Count, actualRefs.Count);
                Assert.True(references.Single(reference => reference.CanonicalName == "HEAD") is SymbolicReference);
                for (int i = 0; i < TestRemoteRefs.ExpectedRemoteRefs.Count; i++)
                {
                    Assert.Equal(TestRemoteRefs.ExpectedRemoteRefs[i].Item2, actualRefs[i].Item2);
                    Assert.Equal(TestRemoteRefs.ExpectedRemoteRefs[i].Item1, actualRefs[i].Item1);
                }
            }
        }
        public void CanCompareACommitTreeAgainstItsParent()
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                Tree commitTree = repo.Head.Tip.Tree;
                Tree parentCommitTree = repo.Head.Tip.Parents.Single().Tree;

                using (var changes = repo.Diff.Compare<TreeChanges>(parentCommitTree, commitTree))
                {
                    Assert.Equal(1, changes.Count());
                    Assert.Equal(1, changes.Added.Count());

                    TreeEntryChanges treeEntryChanges = changes.Single(c => c.Path == "1.txt");

                    Assert.Equal("1.txt", treeEntryChanges.Path);
                    Assert.Equal(ChangeKind.Added, treeEntryChanges.Status);

                    Assert.Equal(treeEntryChanges.Path, changes.Added.Single().Path);

                    Assert.Equal(Mode.Nonexistent, treeEntryChanges.OldMode);
                }

                using (var patch = repo.Diff.Compare<Patch>(parentCommitTree, commitTree))
                {
                    Assert.False(patch["1.txt"].IsBinaryComparison);
                }
            }
        }
Example #8
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            RegisterRoutes(RouteTable.Routes);

            var bus = new FakeBus();

            var storage = new EventStore(bus);
            var rep = new Repository<InventoryItem>(storage);
            var commands = new InventoryCommandHandlers(rep);
            bus.RegisterHandler<CheckInItemsToInventory>(commands.Handle);
            bus.RegisterHandler<CreateInventoryItem>(commands.Handle);
            bus.RegisterHandler<DeactivateInventoryItem>(commands.Handle);
            bus.RegisterHandler<RemoveItemsFromInventory>(commands.Handle);
            bus.RegisterHandler<RenameInventoryItem>(commands.Handle);
            var detail = new InvenotryItemDetailView();
            bus.RegisterHandler<InventoryItemCreated>(detail.Handle);
            bus.RegisterHandler<InventoryItemDeactivated>(detail.Handle);
            bus.RegisterHandler<InventoryItemRenamed>(detail.Handle);
            bus.RegisterHandler<ItemsCheckedInToInventory>(detail.Handle);
            bus.RegisterHandler<ItemsRemovedFromInventory>(detail.Handle);
            var list = new InventoryListView();
            bus.RegisterHandler<InventoryItemCreated>(list.Handle);
            bus.RegisterHandler<InventoryItemRenamed>(list.Handle);
            bus.RegisterHandler<InventoryItemDeactivated>(list.Handle);
            ServiceLocator.Bus = bus;
        }
Example #9
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 Init()
        {
            _users = new List<UserEntity>();
            for (var ndx = 0; ndx < 10; ++ndx)
            {
                var postfix = ndx.ToString();
                var user = new UserEntity
                {
                    UserEntityId = ndx + 1,
                    DateRegistered = ServerTime.Now,
                    UserName = "User" + postfix,
                    Email = String.Format("user.{0}@test.com", ndx)
                };

                _users.Add(user);
            }

            Mapper.CreateMap<UserEntity, User>()
                .ForMember(p => p.Id, opt => opt.MapFrom(src => src.UserEntityId))
                .IgnoreAllNonExisting();

            var builder = new ContainerBuilder();

            builder.RegisterType<QueryBuilder>().As<IQueryBuilder>();
            var entitiesRepo = new Repository<UserEntity>(_users);
            var usersRepo = new Repository<User>(_users.Select(p
                => p.MapTo<User>()));

            builder.RegisterInstance(entitiesRepo).As<IRepository<UserEntity>>().SingleInstance();
            builder.RegisterInstance(usersRepo).As<IRepository<User>>().SingleInstance();

            var container = builder.Build();
            var resolver = new AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(resolver);
        }
Example #11
0
        public override List<EpisodeParseResult> PerformSearch(Repository.Series series, dynamic options, Model.Notification.ProgressNotification notification)
        {
            if (options.Episode == null)
                throw new ArgumentException("Episode is invalid");

            notification.CurrentMessage = "Looking for " + options.Episode;

            var reports = new List<EpisodeParseResult>();
            var title = GetSearchTitle(series);

            var seasonNumber = options.Episode.SeasonNumber;
            var episodeNumber = options.Episode.EpisodeNumber;

            Parallel.ForEach(_indexerProvider.GetEnabledIndexers(), indexer =>
            {
                try
                {
                    reports.AddRange(indexer.FetchEpisode(title, seasonNumber, episodeNumber));
                }

                catch (Exception e)
                {
                    logger.ErrorException(String.Format("An error has occurred while searching for {0}-S{1:00}E{2:00} from: {3}",
                                                         series.Title, options.SeasonNumber, options.EpisodeNumber, indexer.Name), e);
                }
            });

            return reports;
        }
 public RendezVousController()
 {
     SlotRepository = new TimeSlotRepository();
     ContactRepository = new Repository<Contact>();
     DateRepository = new DateRepository();
     HolidayRepository = new HolidayRepository();
 }
        public ArticleRevisionDiffApiModel(
            ArticleSlug articleSlug,
            ArticleRevisionDate oldRevisionDate,
            ArticleRevisionDate newRevisionDate,
            Repository repository)
        {
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }

            var oldRevision = repository.GetArticleRevision(articleSlug, oldRevisionDate);
            if (oldRevision == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            var newRevision = repository.GetArticleRevision(articleSlug, newRevisionDate);
            if (newRevision == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            var oldRevisionContent = MarkdownTextService.MakeText(oldRevision.MarkdownContent).ToHtmlLinebreaks();

            var newRevisionContent = MarkdownTextService.MakeText(newRevision.MarkdownContent).ToHtmlLinebreaks();

            var diff = new Helpers.HtmlDiff(oldRevisionContent ?? string.Empty, newRevisionContent ?? string.Empty);

            this.HtmlDiff = diff.Build();

            this.OldCreatedAt = oldRevision.CreatedAt.ToString(ArticleRevisionDate.FormattedDateTimeFormat);
            this.NewCreatedAt = newRevision.CreatedAt.ToString(ArticleRevisionDate.FormattedDateTimeFormat);
        }
Example #14
0
        /// <summary>Create <see cref="CleanDialog"/>.</summary>
        /// <param name="repository">Related <see cref="Repository"/>.</param>
        public CleanDialog(Repository repository)
        {
            Verify.Argument.IsNotNull(repository, "repository");

            _repository = repository;

            InitializeComponent();

            Localize();

            for(int i = 0; i < _lstFilesToClear.Columns.Count; ++i)
            {
                var col = _lstFilesToClear.Columns[i];
                col.IsVisible = col.Id == (int)ColumnId.Name;
            }

            _lstFilesToClear.Style = GitterApplication.DefaultStyle;
            _lstFilesToClear.Columns[0].SizeMode = Framework.Controls.ColumnSizeMode.Auto;
            _lstFilesToClear.ShowTreeLines = false;

            if(!GitFeatures.CleanExcludeOption.IsAvailableFor(repository))
            {
                _lblExcludePattern.Enabled = false;
                _txtExclude.Enabled = false;
                _txtExclude.Text = Resources.StrlRequiredVersionIs.UseAsFormat(
                    GitFeatures.CleanExcludeOption.RequiredVersion);
            }

            GitterApplication.FontManager.InputFont.Apply(_txtPattern, _txtExclude);

            LoadConfig();
        }
 public TransportadorasController()
 {
     context = new Context();
     var dataBaseInitializer = new DataBaseInitializer();
     dataBaseInitializer.InitializeDatabase(context);
     repositorioTransportadora = new Repository<Transportadora>(context);
 }
Example #16
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);
        }
Example #17
0
        public void CanListRemoteReferenceObjects()
        {
            const string url = "http://github.com/libgit2/TestGitRepository";
            const string remoteName = "origin";

            var scd = BuildSelfCleaningDirectory();

            string clonedRepoPath = Repository.Clone(url, scd.DirectoryPath);

            using (var repo = new Repository(clonedRepoPath))
            {
                Remote remote = repo.Network.Remotes[remoteName];
                IEnumerable<Reference> references = repo.Network.ListReferences(remote).ToList();

                var actualRefs = new List<Tuple<string,string>>();

                foreach(Reference reference in references)
                {
                    Assert.NotNull(reference.CanonicalName);

                    var directReference = reference.ResolveToDirectReference();

                    Assert.NotNull(directReference.Target);
                    actualRefs.Add(new Tuple<string, string>(reference.CanonicalName, directReference.Target.Id.Sha));
                }

                Assert.Equal(TestRemoteRefs.ExpectedRemoteRefs.Count, actualRefs.Count);
                Assert.True(references.Single(reference => reference.CanonicalName == "HEAD") is SymbolicReference);
                for (int i = 0; i < TestRemoteRefs.ExpectedRemoteRefs.Count; i++)
                {
                    Assert.Equal(TestRemoteRefs.ExpectedRemoteRefs[i].Item1, actualRefs[i].Item1);
                    Assert.Equal(TestRemoteRefs.ExpectedRemoteRefs[i].Item2, actualRefs[i].Item2);
                }
            }
        }
Example #18
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);
        }
        public void CanCompareACommitTreeAgainstATreeWithNoCommonAncestor()
        {
            var path = SandboxStandardTestRepoGitDir();
            using (var repo = new Repository(path))
            {
                Tree commitTree = repo.Head.Tip.Tree;
                Tree commitTreeWithDifferentAncestor = repo.Branches["refs/remotes/origin/test"].Tip.Tree;

                using (var changes = repo.Diff.Compare<TreeChanges>(commitTreeWithDifferentAncestor, commitTree))
                {
                    Assert.Equal(10, changes.Count());
                    Assert.Equal(9, changes.Added.Count());
                    Assert.Equal(1, changes.Deleted.Count());

                    Assert.Equal("readme.txt", changes.Deleted.Single().Path);
                    Assert.Equal(new[] { "1.txt", subBranchFilePath, "README", "branch_file.txt", "deleted_staged_file.txt", "deleted_unstaged_file.txt", "modified_staged_file.txt", "modified_unstaged_file.txt", "new.txt" },
                                 changes.Added.Select(x => x.Path).OrderBy(p => p, StringComparer.Ordinal).ToArray());
                }

                using (var patch = repo.Diff.Compare<Patch>(commitTreeWithDifferentAncestor, commitTree))
                {
                    Assert.Equal(9, patch.LinesAdded);
                    Assert.Equal(2, patch.LinesDeleted);
                    Assert.Equal(2, patch["readme.txt"].LinesDeleted);
                }
            }
        }
Example #20
0
        public void Write_Year(Repository repository, int year, int samplingPeriodInSeconds)
        {
            var random = new Random();
            var since = new DateTime(year, 1, 1);
            var watch = Stopwatch.StartNew();
            int batchSize = 10000;

            int samples = (365 * 24 * 60 * 60) / samplingPeriodInSeconds;
            batchSize = int.MaxValue;
            var batch = new List<Event>();

            repository.HintSamplingPeriod( samples);
            for (int i = 1; i < samples + 1; i++)
            {
                batch.Add(new Event(since.AddSeconds(samplingPeriodInSeconds), random.NextDouble(), (i / batchSize) + 1));

                if (i % batchSize == 0 && i != 1)
                {
                    repository.AppendValues(batch.ToArray()).Wait();
                    batch.Clear();

                    var remaining = TimeSpan.FromTicks((watch.Elapsed.Ticks / i) * (samples - i));
                    //Console.WriteLine("{0} / {1},  {2:0} %    remaining : {3}", i, samples, ((double)i / samples) * 100, remaining);
                }
            }
            repository.AppendValues(batch.ToArray()).Wait();

            watch.Stop();

            //Console.WriteLine("Written {2} : Elapses {0}, append/s {1}", watch.Elapsed, 525600 / watch.Elapsed.TotalSeconds, year);
        }
        public virtual void Initializer()
        {
            //Add a client to be removed by our test.

            //Instantiate a new context.
            using (var context = new MainContext())
            {
                //Create a repository based on the context.
                var myRepo = new Repository<Address>(context);

                //Have to provide valid info.
                MyNewAddress = new Address
                {
                    AddressLine1 = "Barão de Mesquita Street",
                    AddressLine2 = "Tijuca",
                    Country = MyCountryTest,
                    State = "RJ",
                    Zip = "20540-156"
                };

                myRepo.Add(MyNewAddress);

                myRepo.Save();
            }
        }
Example #22
0
 public HomeRepository()
 {
     Adapter = new DbContextAdapter(ContextFactory.GetContext(ContextFactory.DBKey.SALES));
     Unit_OfWork = new UnitOfWork(Adapter);
     ProductRepo = new Repository<Product>(Adapter);
     CatRepo = new Repository<ProductCategory>(Adapter);
 }
Example #23
0
 public static async Task<PackageManager> Create(Repository repo, IAbsoluteDirectoryPath workDir,
     bool createWhenNotExisting = false,
     string remote = null) {
     var pm = new PackageManager(repo, workDir, createWhenNotExisting, remote);
     await repo.RefreshRemotes().ConfigureAwait(false);
     return pm;
 }
Example #24
0
        protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
        {
            if (FormsAuthentication.CookiesSupported != true) return;
            if (Request.Cookies[FormsAuthentication.FormsCookieName] == null) return;

            //let us take out the username now
            var formsAuthenticationTicket = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
            if (formsAuthenticationTicket == null) return;

            var username = formsAuthenticationTicket.Name;
            var roles = String.Empty;

            using (IDataContextAsync context = new OIDataContext())
            using (IUnitOfWorkAsync unitOfWork = new UnitOfWork(context))
            {
                IRepositoryAsync<Account> accountRepository = new Repository<Account>(context, unitOfWork);
                var user =
                    accountRepository.Query(u => u.Username == username).Include(r => r.Role).Select().SingleOrDefault();

                if (user != null) roles = user.Role.RoleType;
            }

            //Let us set the Pricipal with our user specific details
            HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
                new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
        }
Example #25
0
        public void CommitOnDetachedHeadShouldInsertReflogEntry()
        {
            string repoPath = CloneStandardTestRepo();

            using (var repo = new Repository(repoPath))
            {
                Assert.False(repo.Info.IsHeadDetached);

                var parentCommit = repo.Head.Tip.Parents.First();
                repo.Checkout(parentCommit.Sha);
                Assert.True(repo.Info.IsHeadDetached);

                const string relativeFilepath = "new.txt";
                string filePath = Path.Combine(repo.Info.WorkingDirectory, relativeFilepath);

                File.WriteAllText(filePath, "content\n");
                repo.Index.Stage(relativeFilepath);

                var author = DummySignature;
                const string commitMessage = "Commit on detached head";
                var commit = repo.Commit(commitMessage, author, author);

                // Assert a reflog entry is created on HEAD
                var reflogEntry = repo.Refs.Log("HEAD").First();
                Assert.Equal(author, reflogEntry.Commiter);
                Assert.Equal(commit.Id, reflogEntry.To);
                Assert.Equal(string.Format("commit: {0}", commitMessage), repo.Refs.Log("HEAD").First().Message);
            }
        }
Example #26
0
 public void BlindlyMovingABranchOverAnExistingOneThrows()
 {
     using (var repo = new Repository(BareTestRepoPath))
     {
         Assert.Throws<LibGit2Exception>(() => repo.Branches.Move("br2", "test"));
     }
 }
Example #27
0
 public ActionResult Create(Fund fund)
 {
     try
     {
         if (ModelState.IsValid)
         {
             //fundRepository.InsertFund(fund);
             NHibernateHelper helper = new NHibernateHelper("thangma");
             // Notice the unit of work we are using is to commit
             //    one truck's data at a time.
             UnitOfWork unitOfWork = new UnitOfWork(helper.SessionFactory);
             Repository<Fund> repository = new Repository<Fund>(unitOfWork.Session);
             //Truck truck = CreateFund();
             repository.Add(fund);
             unitOfWork.Commit();
             return RedirectToAction("Index");
         }
     }
     catch (DataException)
     {
         //Log the error (add a variable name after DataException)
         ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
     }
     return View(fund);
 }
        public void CanCreateStandardRepo()
        {
            string repoPath = InitNewRepository();

            Assert.True(Repository.IsValid(repoPath));

            using (var repo = new Repository(repoPath))
            {
                Assert.True(Repository.IsValid(repo.Info.WorkingDirectory));
                Assert.True(Repository.IsValid(repo.Info.Path));

                string dir = repo.Info.Path;
                Assert.True(Path.IsPathRooted(dir));
                Assert.True(Directory.Exists(dir));
                CheckGitConfigFile(dir);

                Assert.NotNull(repo.Info.WorkingDirectory);
                Assert.Equal(repoPath, repo.Info.Path);
                Assert.False(repo.Info.IsBare);

                AssertIsHidden(repo.Info.Path);

                AssertInitializedRepository(repo, "refs/heads/master");

                repo.Refs.Add("HEAD", "refs/heads/orphan", true);
                AssertInitializedRepository(repo, "refs/heads/orphan");
            }
        }
        static void InitData(Repository repository)
        {
            LibraryDepartment abonement = new LibraryDepartment("Абонемент", true);
            LibraryDepartment readingRoom = new LibraryDepartment("Читальный зал", false);
            repository.LibraryDepartmentRepository.Save(abonement);
            repository.LibraryDepartmentRepository.Save(readingRoom);

            repository.LibrarianRepository.Save(new Librarian("Мария Иванова", abonement));
            repository.LibrarianRepository.Save(new Librarian("Татьяна Петрова", readingRoom));

            repository.ReaderRepository.Save(new Reader("Иван Иванов", "Брест"));
            repository.ReaderRepository.Save(new Reader("Петр Петров", "Брест"));
            repository.ReaderRepository.Save(new Reader("Сидор Сидоров", "Брест"));

            repository.BookRepository.Save(new Book("Бен Ватсон", "С# 4.0 на примерах", 2000, abonement));
            repository.BookRepository.Save(new Book("Кристиан Нейгел", "C# 4.0 и платформа .NET 4", 2001, abonement));
            repository.BookRepository.Save(new Book("Михаил Фленов", "Библия C#", 2002, abonement));
            repository.BookRepository.Save(new Book("Чарльз Петцольд", "Программирование в тональности C#", 2003, abonement));
            repository.BookRepository.Save(new Book("Герберт Шилдт", "C# 4.0 полное руководство", 2004, abonement));
            repository.BookRepository.Save(new Book("Трей Нэш", "C# 2010. Ускоренный курс ", 2005, readingRoom));
            repository.BookRepository.Save(new Book("Мэтью Мак-Дональд", "Microsoft ASP.NET 3.5 с примерами", 2006, readingRoom));
            repository.BookRepository.Save(new Book("Чарльз Петцольд", "Программирование с использованием Windows Forms", 2007, readingRoom));
            repository.BookRepository.Save(new Book("Фаронов В.В.", "Программирование на языке С#", 2008, readingRoom));
            repository.BookRepository.Save(new Book("Либерти Дж.", "Программирование на C#", 2009, readingRoom));
        }
Example #30
0
        public void MyCouponJsonSerializeAndDeserialize_Test()
        {
            IRepository repo = new Repository();

            var coupons = repo.Query<CouponView>(x => x.UserID == 443);

            if (coupons != null && coupons.Count > 0)
            {
                var couponDtos = coupons.MapToList<CouponView, CouponDto>().ToList();

                var jsonSerializer = new JavaScriptSerializer();

                var json = jsonSerializer.Serialize(couponDtos);

                if (!string.IsNullOrEmpty(json))
                {
                    couponDtos = jsonSerializer.Deserialize<List<CouponDto>>(json);

                    Assert.IsInstanceOfType(couponDtos[0], typeof(CouponDto));
                }

                var myCouponDto = new MyCouponDto
                {
                    Coupons = couponDtos
                };

                json = jsonSerializer.Serialize(myCouponDto);

                Assert.IsTrue(!string.IsNullOrEmpty(json));
            }
        }