Inheritance: IBoatInspectorRepository
示例#1
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));
            }
        }
        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));
        }
示例#3
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);
 }
 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);
 }
示例#5
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);
                }
            }
        }
示例#6
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);
            }
        }
示例#7
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));
            }
        }
示例#8
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;
 }
示例#9
0
 public void CannotReadReflogOnUnknownReference()
 {
     using (var repo = new Repository(StandardTestRepoWorkingDirPath))
     {
         Assert.Throws<InvalidSpecificationException>(() => repo.Refs.Log("toto").Count());
     }
 }
        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();
            }
        }
示例#11
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;
        }
        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);
                }
            }
        }
        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);
                }
            }
        }
示例#14
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);
                }
            }
        }
示例#15
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);
                }
            }
        }
示例#16
0
        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");
            }
        }
 public TransportadorasController()
 {
     context = new Context();
     var dataBaseInitializer = new DataBaseInitializer();
     dataBaseInitializer.InitializeDatabase(context);
     repositorioTransportadora = new Repository<Transportadora>(context);
 }
示例#18
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(';'));
        }
示例#19
0
 public void BlindlyMovingABranchOverAnExistingOneThrows()
 {
     using (var repo = new Repository(BareTestRepoPath))
     {
         Assert.Throws<LibGit2Exception>(() => repo.Branches.Move("br2", "test"));
     }
 }
示例#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);
        }
示例#21
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);
 }
示例#22
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);
        }
示例#23
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;
        }
        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 = "******" + 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);
        }
示例#25
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 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);
        }
示例#27
0
 public RendezVousController()
 {
     SlotRepository = new TimeSlotRepository();
     ContactRepository = new Repository<Contact>();
     DateRepository = new DateRepository();
     HolidayRepository = new HolidayRepository();
 }
示例#28
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();
        }
示例#29
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();
        }
示例#30
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);
        }
示例#31
0
        /// <summary>
        ///  The Main method is the starting point for a .net application.
        /// </summary>
        static void Main(string[] args)
        {
            // We must create an instance of the Repository class in order to use it's methods to
            //  interact with the database.
            Repository repository = new Repository();

            List <Department> departments = repository.GetAllDepartments();

            // PrintDepartmentReport should print a department report to the console, but does it?
            //  Take a look at how it's defined below...
            PrintDepartmentReport("All Departments", departments);

            // What is this? Scroll to the bottom of the file and find out for yourself.
            Pause();


            // Create an new instance of a Department, so we can save our new department to the database.
            Department accounting = new Department {
                DeptName = "Accounting"
            };

            // Pass the accounting object as an argument to the repository's AddDepartment() method.
            repository.AddDepartment(accounting);

            departments = repository.GetAllDepartments();
            PrintDepartmentReport("All Departments after adding Accounting department", departments);

            Pause();


            // Pull the object that represents the Accounting department from the list of departments that
            //  we got from the database.
            // First() is a handy LINQ method that gives us the first element in a list that matches the condition.
            Department accountingDepartmentFromDB = departments.First(d => d.DeptName == "Accounting");

            // How are the "accounting" and "accountingDepartmentFromDB" objects different?
            //  Why are they different?
            Console.WriteLine($"                accounting --> {accounting.Id}: {accounting.DeptName}");
            Console.WriteLine($"accountingDepartmentFromDB --> {accountingDepartmentFromDB.Id}: {accountingDepartmentFromDB.DeptName}");

            Pause();

            // Change the name of the Accounting department and save the change to the database.
            accountingDepartmentFromDB.DeptName = "Creative Accounting";
            repository.UpdateDepartment(accountingDepartmentFromDB.Id, accountingDepartmentFromDB);

            departments = repository.GetAllDepartments();
            PrintDepartmentReport("All Departments after updating Accounting department", departments);

            Pause();


            // Maybe we don't need an Accounting department after all...
            repository.DeleteDepartment(accountingDepartmentFromDB.Id);

            departments = repository.GetAllDepartments();
            PrintDepartmentReport("All Departments after deleting Accounting department", departments);

            Pause();

            // Create a new variable to contain a list of Employees and get that list from the database
            List <Employee> employees = repository.GetAllEmployees();

            // Does this method do what it claims to do, or does it need some work?
            PrintEmployeeReport("All Employees", employees);

            Pause();


            employees = repository.GetAllEmployeesWithDepartment();
            PrintEmployeeReport("All Employees with departments", employees);

            Pause();


            // Here we get the first department by index.
            //  We could use First() here without passing it a condition, but using the index is easy enough.
            Department firstDepartment = departments[0];

            employees = repository.GetAllEmployeesWithDepartmentByDepartmentId(firstDepartment.Id);
            PrintEmployeeReport($"Employees in {firstDepartment.DeptName}", employees);

            Pause();


            // Instantiate a new employee object.
            //  Note we are making the employee's DepartmentId refer to an existing department.
            //  This is important because if we use an invalid department id, we won't be able to save
            //  the new employee record to the database because of a foreign key constraint violation.
            Employee jane = new Employee()
            {
                FirstName    = "Jane",
                LastName     = "Lucas",
                DepartmentId = firstDepartment.Id
            };

            repository.AddEmployee(jane);

            employees = repository.GetAllEmployeesWithDepartment();
            PrintEmployeeReport("All Employees after adding Jane", employees);

            Pause();


            // Once again, we see First() in action.
            Employee dbJane = employees.First(e => e.FirstName == "Jane");

            // Get the second department by index.
            Department secondDepartment = departments[1];

            dbJane.DepartmentId = secondDepartment.Id;
            repository.UpdateEmployee(dbJane.Id, dbJane);

            employees = repository.GetAllEmployeesWithDepartment();
            PrintEmployeeReport("All Employees after updating Jane", employees);

            Pause();


            repository.DeleteEmployee(dbJane.Id);
            employees = repository.GetAllEmployeesWithDepartment();

            PrintEmployeeReport("All Employees after updating Jane", employees);

            Pause();
        }
 /// <summary>
 /// Has sent email
 /// </summary>
 /// <param name="familyMemberId">Family member identifier</param>
 /// <param name="emailType">Email template type</param>
 /// <returns>Result</returns>
 public bool HasSent(int familyMemberId, EmailType emailType)
 {
     return(Repository.Table <EmailHistory>().Any(m => m.FamilyMemberID == familyMemberId && m.EmailType == emailType));
 }
示例#33
0
        public void OnClone(string url, Repository repository)
        {
            var gitExt = ServiceProvider.GetService <IGitRepositoriesExt>();

            gitExt.Clone(url, repository.Path, CloneOptions.RecurseSubmodule);
        }
示例#34
0
 public Enumerable(Repository<T> repository) =>
     this.repository = repository;
 protected override async Task <Role> GetEntityByIdAsync(int id)
 {
     return(await Repository.GetAllIncluding(x => x.Permissions).FirstOrDefaultAsync(x => x.Id == id));
 }
 protected override IQueryable <User> CreateFilteredQuery(PagedAndSortedResultRequestDto input)
 {
     return(Repository.GetAllIncluding(x => x.Roles));
 }
示例#37
0
 protected override IQueryable <Tenant> CreateFilteredQuery(PagedTenantResultRequestDto input)
 {
     return(Repository.GetAll()
            .WhereIf(!input.Keyword.IsNullOrWhiteSpace(), x => x.TenancyName.Contains(input.Keyword) || x.Name.Contains(input.Keyword))
            .WhereIf(input.IsActive.HasValue, x => x.IsActive == input.IsActive));
 }
示例#38
0
        public void CadastrarPedidoNoProcesso(Guid processoId, Guid tipoPedidoId, Guid riscoId, decimal valorPedido, decimal valorProvisao)
        {
            var pedido = new Pedido(processoId, tipoPedidoId, riscoId, valorPedido, valorProvisao);

            Repository.Adicionar(pedido);
        }
示例#39
0
 public void Export(Repository repository, IEnumerable<MediaFolder> models, System.IO.Stream outputStream)
 {
     throw new NotImplementedException();
 }
 public ItemProdutoService()
 {
     context         = new DNAMaisSiteContext();
     repoItemProduto = new Repository <ItemProduto>(context);
 }
示例#41
0
 private static IEnumerable<MediaFolder> ToMediaFolders(Repository repository, Dictionary<string, MediaFolder> folders)
 {
     return folders.Select(it => ToMediaFolder(repository, it.Key, it.Value)).ToArray();
 }
示例#42
0
 public frmCariEdit()
 {
     InitializeComponent();
     _repository = new Repository();
 }
示例#43
0
 /// <summary>
 /// Create a new basic collator, using the supplied repository registry
 /// </summary>
 /// <param name="repository">Repository registry the collator uses to find a repository</param>
 public BasicCollator(Repository repository)
 {
     this.Repository = repository;
 }
示例#44
0
 public IQueryable<MediaFolder> All(Repository repository)
 {
     return MediaFolders.RootFolders(repository).AsQueryable();
 }
示例#45
0
 /// <inheritdoc/>
 public override bool Set(Address a, object data, Dictionary <string, object> setOptions)
 {
     return(Repository.Set(new List <object> {
         data
     }, setOptions)[0]);
 }
示例#46
0
        protected override async Task <User> GetEntityByIdAsync(long id)
        {
            var user = Repository.GetAllIncluding(x => x.Roles).FirstOrDefault(x => x.Id == id);

            return(await Task.FromResult(user));
        }
 private static bool RepoIsModifiable(Repository repo)
 {
     return
         (!repo.Archived &&
          repo.Permissions.Pull);
 }
示例#48
0
 /// <inheritdoc/>
 public override void Delete(Address a, object data, bool bypassChecks)
 {
     Repository.Delete(data, bypassChecks);
 }
示例#49
0
 public GitManager(string repoPath)
 {
     _repository = new Repository(repoPath);
 }
示例#50
0
 public List<Position_Dto> GetPositionByDepartmentId(Guid departmentId)
 {
     return Repository.Where(x => x.DepartmentId == departmentId).Select(MapToGetListOutputDto).ToList();
 }
示例#51
0
        public override void Execute()
        {
            var form = Repository.Load <BestStartGrant>(FormId);

            form.AddEvidenceFile(Filename, Content);
        }
示例#52
0
 void OnDestroy() => Repository.Unregister(References.Stats);
示例#53
0
 public void TestInitialize()
 {
     repository = new Repository(TestConfiguration.ConnectionString, MeetingInfoDatabase.DAO.DatabaseType.Ado);
 }
 public new async Task <IEnumerable <PostgresDatabase> > GetAsync()
 {
     return(await Repository.All().Include(d => d.Schemas).ToListAsync());
 }
示例#55
0
        /// <summary>
        /// Normalization of a git directory turns all remote branches into local branches, turns pull request refs into a real branch and a few other things. This is designed to be run *only on the build server* which checks out repositories in different ways.
        /// It is not recommended to run normalization against a local repository
        /// </summary>
        public static void NormalizeGitDirectory(ILog log, IEnvironment environment, string gitDirectory, AuthenticationInfo authentication,
                                                 bool noFetch, string currentBranch, bool isDynamicRepository)
        {
            using var repo = new Repository(gitDirectory);
            // Need to ensure the HEAD does not move, this is essentially a BugCheck
            var expectedSha        = repo.Head.Tip.Sha;
            var expectedBranchName = repo.Head.CanonicalName;

            try
            {
                var remote = EnsureOnlyOneRemoteIsDefined(log, repo);

                AddMissingRefSpecs(log, repo, remote);

                //If noFetch is enabled, then GitVersion will assume that the git repository is normalized before execution, so that fetching from remotes is not required.
                if (noFetch)
                {
                    log.Info("Skipping fetching, if GitVersion does not calculate your version as expected you might need to allow fetching or use dynamic repositories");
                }
                else
                {
                    Fetch(log, authentication, remote, repo);
                }

                EnsureLocalBranchExistsForCurrentBranch(log, repo, remote, currentBranch);
                CreateOrUpdateLocalBranchesFromRemoteTrackingOnes(log, repo, remote.Name);

                // Bug fix for https://github.com/GitTools/GitVersion/issues/1754, head maybe have been changed
                // if this is a dynamic repository. But only allow this in case the branches are different (branch switch)
                if (expectedSha != repo.Head.Tip.Sha &&
                    (isDynamicRepository || !expectedBranchName.IsBranch(currentBranch)))
                {
                    var newExpectedSha        = repo.Head.Tip.Sha;
                    var newExpectedBranchName = repo.Head.CanonicalName;

                    log.Info($"Head has moved from '{expectedBranchName} | {expectedSha}' => '{newExpectedBranchName} | {newExpectedSha}', allowed since this is a dynamic repository");

                    expectedSha = newExpectedSha;
                }

                var headSha = repo.Refs.Head.TargetIdentifier;

                if (!repo.Info.IsHeadDetached)
                {
                    log.Info($"HEAD points at branch '{headSha}'.");
                    return;
                }

                log.Info($"HEAD is detached and points at commit '{headSha}'.");
                log.Info($"Local Refs:{System.Environment.NewLine}" + string.Join(System.Environment.NewLine, repo.Refs.FromGlob("*").Select(r => $"{r.CanonicalName} ({r.TargetIdentifier})")));

                // In order to decide whether a fake branch is required or not, first check to see if any local branches have the same commit SHA of the head SHA.
                // If they do, go ahead and checkout that branch
                // If no, go ahead and check out a new branch, using the known commit SHA as the pointer
                var localBranchesWhereCommitShaIsHead = repo.Branches.Where(b => !b.IsRemote && b.Tip.Sha == headSha).ToList();

                var matchingCurrentBranch = !string.IsNullOrEmpty(currentBranch)
                    ? localBranchesWhereCommitShaIsHead.SingleOrDefault(b => b.CanonicalName.Replace("/heads/", "/") == currentBranch.Replace("/heads/", "/"))
                    : null;
                if (matchingCurrentBranch != null)
                {
                    log.Info($"Checking out local branch '{currentBranch}'.");
                    Commands.Checkout(repo, matchingCurrentBranch);
                }
                else if (localBranchesWhereCommitShaIsHead.Count > 1)
                {
                    var          branchNames   = localBranchesWhereCommitShaIsHead.Select(r => r.CanonicalName);
                    var          csvNames      = string.Join(", ", branchNames);
                    const string moveBranchMsg = "Move one of the branches along a commit to remove warning";

                    log.Warning($"Found more than one local branch pointing at the commit '{headSha}' ({csvNames}).");
                    var master = localBranchesWhereCommitShaIsHead.SingleOrDefault(n => n.FriendlyName == "master");
                    if (master != null)
                    {
                        log.Warning("Because one of the branches is 'master', will build master." + moveBranchMsg);
                        Commands.Checkout(repo, master);
                    }
                    else
                    {
                        var branchesWithoutSeparators = localBranchesWhereCommitShaIsHead.Where(b => !b.FriendlyName.Contains('/') && !b.FriendlyName.Contains('-')).ToList();
                        if (branchesWithoutSeparators.Count == 1)
                        {
                            var branchWithoutSeparator = branchesWithoutSeparators[0];
                            log.Warning($"Choosing {branchWithoutSeparator.CanonicalName} as it is the only branch without / or - in it. " + moveBranchMsg);
                            Commands.Checkout(repo, branchWithoutSeparator);
                        }
                        else
                        {
                            throw new WarningException("Failed to try and guess branch to use. " + moveBranchMsg);
                        }
                    }
                }
                else if (localBranchesWhereCommitShaIsHead.Count == 0)
                {
                    log.Info($"No local branch pointing at the commit '{headSha}'. Fake branch needs to be created.");
                    CreateFakeBranchPointingAtThePullRequestTip(log, repo, authentication);
                }
                else
                {
                    log.Info($"Checking out local branch 'refs/heads/{localBranchesWhereCommitShaIsHead[0].FriendlyName}'.");
                    Commands.Checkout(repo, repo.Branches[localBranchesWhereCommitShaIsHead[0].FriendlyName]);
                }
            }
            finally
            {
                if (repo.Head.Tip.Sha != expectedSha)
                {
                    if (environment.GetEnvironmentVariable("IGNORE_NORMALISATION_GIT_HEAD_MOVE") != "1")
                    {
                        // Whoa, HEAD has moved, it shouldn't have. We need to blow up because there is a bug in normalisation
                        throw new BugException($@"GitVersion has a bug, your HEAD has moved after repo normalisation.

To disable this error set an environmental variable called IGNORE_NORMALISATION_GIT_HEAD_MOVE to 1

Please run `git {CreateGitLogArgs(100)}` and submit it along with your build log (with personal info removed) in a new issue at https://github.com/GitTools/GitVersion");
                    }
                }
            }
        }
示例#56
0
 public override void refreshSQLObject()
 {
     this.ActivityNodeEAElement = Repository.GetElementByID(ActivityNodeEAElement.ElementID);
 }
示例#57
0
        public IServiceQueryResultList <DocumentData> SearchByUser(object userId)
        {
            IEnumerable <DocumentData> result = Repository.SearchByUser(userId);

            return(ServiceResultFactory.BuildServiceQueryResult <DocumentData>(result));
        }
示例#58
0
 protected override async Task <User> GetEntityByIdAsync(long id)
 {
     return(await Repository.GetAllIncluding(x => x.Roles).FirstOrDefaultAsync(x => x.Id == id));
 }
示例#59
0
        /// <summary>
        /// 修改验证
        /// </summary>
        /// <param name="info"></param>
        protected override bool ValidateModify(AccountEntity info)
        {
            var dataEntity = Repository.Get <AccountEntity>(info.Id);

            return(ValidateModifyName(info, dataEntity) && ValidateAccountBalance(info, dataEntity));
        }
示例#60
0
 private static void Fetch(ILog log, AuthenticationInfo authentication, Remote remote, Repository repo)
 {
     log.Info($"Fetching from remote '{remote.Name}' using the following refspecs: {string.Join(", ", remote.FetchRefSpecs.Select(r => r.Specification))}.");
     Commands.Fetch(repo, remote.Name, new string[0], authentication.ToFetchOptions(), null);
 }