public void CreateRepository()
 {
     _repo = new UserRepository();
     _user1 = new User("admin","test");
     _repo.Save(_user1);
     _user2 = new User("razvan","1234");
     _repo.Save(_user2);
 }
 public void CreateRepository()
 {
     _repo = new ExpenseRepository();
     _exp1 = new Expense(TypeExpense.Car, 34, "euro");
     _exp2 = new Expense(TypeExpense.Eat, 45, "euro");
     _repo.Save(_exp1);
     _repo.Save(_exp2);
 }
        public when_implementing_base_repository() 
        {
            RefreshDb();

            _repository = new DataProviderRepository(Session);
            var dataProvider = ReadDataProviderMother.Ivid;
            _repository.Save(dataProvider);
            _repository.Save(ReadDataProviderMother.Rgt);

            Session.Flush();

            _id = GetFromDb(dataProvider).Id;
        }
        public void Common_CanDelete(IRepository<Product> db)
        {
            db.Save(new Product { ProductName = "Optimus", Category = "Autobots", MinimumPrice = 7 });

            var px = new Product { ProductName = "Bumble Bee", Category = "Autobots", MinimumPrice = 8 };
            db.Save(px);

            db.Save(new Product { ProductName = "Megatron", Category = "Decepticon", MinimumPrice = 9 });

            db.Delete(px.ProductId, px.RowVersion);

            Assert.AreEqual(7 + 9, db.All.Sum(x => x.MinimumPrice));
            Assert.AreEqual(null, db.Get(px.ProductId));
            Assert.AreEqual(2, db.All.Count());
        }
        static void Main(string[] args)
        {
            IoC.Register();
            _repo = IoC.Resolve<IRepository>();

            var geos = _repo.Find<City>().ToList();
            Console.WriteLine(string.Format("{0} total cities...", geos.Count()));

            int i =0;
            foreach (var geo in geos)
            {
                if (geo.Geography.GetType() == typeof(NetTopologySuite.Geometries.MultiPoint))
                {
                    Console.WriteLine(string.Format("{0} is a MultiPoint...", geo.Name));
                    var point = new NetTopologySuite.Geometries.Point(geo.Geography.Coordinates.First());
                    geo.Geography = point;
                    _repo.Save<City>(geo);
                    _repo.SubmitChanges();
                    Console.WriteLine(string.Format("{0} updated to Point...", geo.Name));
                    i++;
                }
            }
            Console.WriteLine(string.Format("{0} total Cities updated...", i));
            Console.Read();
        }
        // Update course 
        public static CourseUpdate.Response Handle(IRepository repository, CourseUpdate.Request request)
        {
            var container = CourseFactory.CreatePartial(request.CommandModel.CourseID).Modify(request.CommandModel);
            var validationDetails = repository.Save(container);

            return new CourseUpdate.Response(validationDetails);
        }
Beispiel #7
0
 private static Setting InitializeSetting(string settingName, IRepository repository)
 {
     var setting = new Setting { Name = settingName.Encrypt() };
     repository.Add<Setting>(setting);
     repository.Save();
     return setting;
 }
 public override void Handle(IRepository _repository)
 {
     var command = this;
     var order = _repository.GetOrder(command.OrderId);
     var products = order.Products.Add(_repository.GetProduct(command.ProductId));
     _repository.Save(order.With(products:products));
 }
        // Modify student
        public static StudentModify.Response Handle(IRepository repository, StudentModify.Request request)
        {
            var commandModel = request.CommandModel;
            var container = StudentFactory.CreatePartial(commandModel.ID).Modify(commandModel);
            var validationDetails = repository.Save(container);

            return new StudentModify.Response(validationDetails);
        }
        // Delete course 
        public static CourseDelete.Response Handle(IRepository repository, CourseDelete.Request request)
        {
            var course = CourseFactory.CreatePartial(request.CommandModel.CourseId);
            var container = course.Delete();
            repository.Save(container);

            return new CourseDelete.Response();
        }
Beispiel #11
0
        /// <summary>Setups the basic settings.</summary>
        /// <param name="settingsRepository">The settings repository.</param>
        private static void SetupSettings(IRepository<Settings> settingsRepository)
        {
            var userRegistrationPrice = new Settings
            {
                _Key = USER_REGISTRATION_PRICE_KEY,
                Value = "50"
            };

            var vendorRegistrationPrice = new Settings
            {
                _Key = VENDOR_REGISTRATION_PRICE_KEY,
                Value = "100"
            };

            settingsRepository.Save(userRegistrationPrice);
            settingsRepository.Save(vendorRegistrationPrice);
        }
Beispiel #12
0
        private static void SampleMethod(IRepository<Product,int?> productRepository)
        {
            SessionProvider.RebuildSchema();

            //Create a Product
            var pNew = new Product { ProductName = "Canned Salmon" };
            productRepository.Save(pNew);

            //Get a Product
            var pGet = productRepository.GetById(pNew.ProductId);

            //Update a Product
            pGet.ProductName = "Canned Tuna";
            productRepository.Save(pGet);

            //Delete a Product
            productRepository.Delete(pNew);
        }
        // Delete studen
        public static StudentDelete.Response Handle(IRepository repository, StudentDelete.Request request)
        {
            var container = StudentFactory
                .CreatePartial(request.CommandModel.StudentId)
                .Delete();

            var validationDetails = repository.Save(container);

            return new StudentDelete.Response(validationDetails);
        }
        public void SetUp()
        {
            _repository = new MockRepository();

            _developer = new Developer() { Username = "******" };

            _calculators = new[] { new DefaultAchievementCalculator(_repository) };

            _repository.Save(_developer);
        }
Beispiel #15
0
        public virtual void setup()
        {
            var mongoRepository = new MongoRepository("blogspecs");
            mongoRepository.DeleteCollection<BlogSettings>();
            mongoRepository.DeleteCollection<Post>();

            _repository = mongoRepository;

            _blog = new BlogSettings
            {
                VirtualMediaPath = ""
            };
            _repository.Save(_blog);

            _fakePost = Post.CreatePost("Hello world", "", "BjartN", null);

            _repository.Save(_fakePost);

            _api = new  Infrastructure.MetaWeblogApi.MetaWeblog(_repository, new FakeUrlContext(),new FakeAuthenticationService());
        }
        public static CountryCreate.Response Handle(IRepository repository, CountryCreate.Request request)
        {
            var validationDetails = Validator.ValidateRequest(request);
            if (validationDetails.HasValidationIssues)
                return new CountryCreate.Response(validationDetails: validationDetails);

            var country = new Country(request.CommandModel.Name, request.CommandModel.Population);
            repository.Add(country);
            repository.Save();

            return new CountryCreate.Response(country.Id);
        }
Beispiel #17
0
        public static void InitializeTestClass(TestContext testContext)
        {
            if (Directory.Exists(Configuration.PERSITS_VIRTUAL_FILE_PATH))
            {
                Directory.Delete(Configuration.PERSITS_VIRTUAL_FILE_PATH, true);
            }

            Application.Current.SetApplicationAssembly(Assembly.GetExecutingAssembly());
            repository = new DefaultRepository(fileStoreService, cacheStoreService);

            repository.Save(RepositoryTests.GetContentTypeCollection());
        }
        // Create student
        public static StudentCreate.Response Handle(IRepository repository, StudentCreate.Request request)
        {
            var container = new EntityStateWrapperContainer();
            container.AddEntity(StudentFactory.Create(request.CommandModel));
            var validationDetails = repository.Save(container);

            var studentId = default(int?);
            if (!validationDetails.HasValidationIssues)
                studentId = container.FindEntity<Student>().ID;

            return new StudentCreate.Response(validationDetails, studentId);
        }
        // Create Department
        public static DepartmentCreate.Response Handle(IRepository repository, DepartmentCreate.Request request)
        {
            // Validation now performed in the dispacther decorators (See AutoValidate<T> in the DomainBootstrapper class)

            var container = DepartmentFactory.Create(request.CommandModel);
            var validationDetails = repository.Save(container);

            var deptId = default(int?);
            if (!validationDetails.HasValidationIssues)
                deptId = container.FindEntity<Department>().DepartmentID;

            return new DepartmentCreate.Response(validationDetails, deptId);
        }
        // Create course
        public static CourseCreate.Response Handle(IRepository repository, CourseCreate.Request request)
        {
            // Validation now performed in the dispacther decorators (See AutoValidate<T> in the DomainBootstrapper class)

            var container = new EntityStateWrapperContainer();
            container.AddEntity(CourseFactory.Create(request.CommandModel));
            var validationDetails = repository.Save(container);

            var courseId = default(int?);
            if (!validationDetails.HasValidationIssues)
                courseId = container.FindEntity<Course>().CourseID;

            return new CourseCreate.Response(validationDetails, courseId);
        }
        // Modify instructor with course 
        public static InstructorModifyAndCourses.Response Handle(IRepository repository, InstructorModifyAndCourses.Request request)
        {
            var commandModel = request.CommandModel;
            var instructor = repository.GetEntity<Instructor>(
                p => p.ID == commandModel.InstructorId,
                new EagerLoadingQueryStrategy<Instructor>(
                    p => p.Courses,
                    p => p.OfficeAssignment));

            var container = instructor.Modify(repository, request.CommandModel);
            var validationDetails = repository.Save(container);

            return new InstructorModifyAndCourses.Response(validationDetails);
        }
        public void GetContact_ContactExists_ContactReturned(
            TestIndexUtils contactIndex,
            IRepository<ElasticContact> repo,
            ElasticContact contact,
            ISystemContext ctx)
        {
            using (contactIndex)
            {
                repo.Save(contact, ctx);

                var res = repo.Get(contact.Id, ctx);
                res.Should().NotBeNull();
                res.Id.Should().Be(contact.Id);
            }
        }
        public void GetContact_ContactDoesntExist_ContactNotReturned(
            TestIndexUtils contactIndex,
            IRepository<ElasticContact> repo,
            ElasticContact contact,
            ISystemContext ctx)
        {
            using (contactIndex)
            {
                // a little hacky - this is an easy way of ensuring the test index exists first.
                repo.Save(contact, ctx);

                var res = repo.Get(new Guid(), ctx);
                res.Should().BeNull();
            }
        }
Beispiel #24
0
        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();

            builder.RegisterType<Customer>().As<ICustomer>();
            builder.RegisterType<LineItem>().As<ILineItem>();
            builder.RegisterType<Order>().As<IOrder>();
            builder.RegisterType<Product>().As<IProduct>();

            Container = builder.Build();

            _customerRepo = new Repository<Customer>();
            _customerRepo.Add(new Customer { FirstName = "Chris", LastName = "Cais" });
            _customerRepo.Add(new Customer { FirstName = "James", LastName = "Harden" });
            _customerRepo.Save();
        }
Beispiel #25
0
        public virtual void setup()
        {
            _savedPosts = new List<Post>();

            var mongoRepository = new MongoRepository("blogspecs");
            mongoRepository.DeleteCollection<BlogSettings>();
            mongoRepository.DeleteCollection<Post>();

            _repository = mongoRepository;

            for (var i = 0; i < 10; i++)
            {
                var post = Post.CreatePost("Title" + i, "Body" + i, "BjartN", new List<Tag> {new Tag("tag"  + i), new Tag("tag" + (i+1))});
                _repository.Save(post);
                _savedPosts.Add(post);
            }
        }
        // Delete instructor
        public static InstructorDelete.Response Handle(IRepository repository, InstructorDelete.Request request)
        {
            var container = new EntityStateWrapperContainer();
            var depts = repository.GetEntities<Department>(p => p.InstructorID == request.CommandModel.InstructorId);
            foreach (var dept in depts)
                container.Add(dept.SetInstructorId(null));

            var deletedInstructor = repository.GetEntity<Instructor>(
                p => p.ID == request.CommandModel.InstructorId,
                new EagerLoadingQueryStrategy<Instructor>(
                    p => p.OfficeAssignment));

            container.Add(deletedInstructor.Delete());
            var validationDetails = repository.Save(container);

            return new InstructorDelete.Response(validationDetails);
        }
        // Update department
        #region Update department
        public static DepartmentUpdate.Response Handle(IRepository repository, DepartmentUpdate.Request request)
        {
            var validationDetails = Validator.ValidateRequest(request, repository);
            if (validationDetails.HasValidationIssues)
                return new DepartmentUpdate.Response(validationDetails);

            var commandModel = request.CommandModel;
            var currentDept = repository.GetEntity<Department>(
                p => p.DepartmentID == commandModel.DepartmentID,
                new AsNoTrackingQueryStrategy());

            var rowVersion = default(byte[]);
            var container = currentDept.Modify(request.CommandModel);
            validationDetails = repository.Save(container, dbUpdateEx => OnUpdateFailedFunc(repository, dbUpdateEx, commandModel, ref rowVersion));

            return new DepartmentUpdate.Response(validationDetails, rowVersion);
        }
        // Delete Department
        public static DepartmentDelete.Response Handle(IRepository repository, DepartmentDelete.Request request)
        {
            var validationDetails = Validator.ValidateRequest(request, repository);
            if (validationDetails.HasValidationIssues)
                return new DepartmentDelete.Response(validationDetails);

            var department = repository.GetEntity<Department>(
                p => p.DepartmentID == request.CommandModel.DepartmentID,
                new EagerLoadingQueryStrategy<Department>(
                    p => p.Administrator));

            var hasConcurrencyError = false;
            var container = department.Delete();
            validationDetails = repository.Save(container, dbUpdateConcurrencyExceptionFunc: dbUpdateEx =>
            {
                hasConcurrencyError = true;
                return new ValidationMessageCollection(new ValidationMessage(string.Empty, dbUpdateEx.ToString()));
            });

            return new DepartmentDelete.Response(validationDetails, hasConcurrencyError);
        }
        public JsonResult Create(BonusDto bonusDto)
        {
            BonusAggregate bonus;

            if (bonusDto.Amount <= 0)
                throw new ArgumentOutOfRangeException("Amount should be more than 0");

            if (bonusDto.EmployeeId <= 0)
                throw new ArgumentNullException("You should specify an existing employee");

            using (var dbContext = new DatabaseContext())
            {
                BonusesRepository = new BonusesRepository(dbContext);
                var employeeRepository = new EmployeesRepository(dbContext);
                bonus = new BonusFactory(employeeRepository).Create(bonusDto);

                BonusesRepository.Save(bonus);
            }

            return Json(bonus);
        }
Beispiel #30
0
        /// <summary>
        /// Deletes the page.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="principal">The principal.</param>
        /// <param name="messages">The messages.</param>
        /// <returns>
        /// Delete result
        /// </returns>
        /// <exception cref="ConcurrentDataException"></exception>
        /// <exception cref="System.ComponentModel.DataAnnotations.ValidationException">
        /// </exception>
        public bool DeletePage(DeletePageViewModel model, IPrincipal principal, IMessagesIndicator messages = null)
        {
            var languagesFuture = repository.AsQueryable <Language>().ToFuture();

            var page =
                repository.AsQueryable <PageProperties>(p => p.Id == model.PageId)
                .FetchMany(p => p.PageContents)
                .ThenFetch(pc => pc.Content)
                .ToFuture()
                .ToList()
                .FirstOne();

            // Unidentified problem where in some cases proxy is returned.
            if (page is INHibernateProxy)
            {
                page = repository.UnProxy(page);
            }

            if (model.Version > 0 && page.Version != model.Version)
            {
                throw new ConcurrentDataException(page);
            }

            if (page.IsMasterPage && repository.AsQueryable <MasterPage>(mp => mp.Master == page).Any())
            {
                var message    = PagesGlobalization.DeletePageCommand_MasterPageHasChildren_Message;
                var logMessage = string.Format("Failed to delete page. Page is selected as master page. Id: {0} Url: {1}", page.Id, page.PageUrl);
                throw new ValidationException(() => message, logMessage);
            }

            var isRedirectInternal = false;

            if (!string.IsNullOrWhiteSpace(model.RedirectUrl))
            {
                isRedirectInternal = urlService.ValidateInternalUrl(model.RedirectUrl);
                if (!isRedirectInternal && urlService.ValidateInternalUrl(urlService.FixUrl(model.RedirectUrl)))
                {
                    isRedirectInternal = true;
                }
                if (isRedirectInternal)
                {
                    model.RedirectUrl = urlService.FixUrl(model.RedirectUrl);
                }
            }

            if (model.UpdateSitemap)
            {
                accessControlService.DemandAccess(principal, RootModuleConstants.UserRoles.EditContent);
            }

            var sitemaps     = new Dictionary <Sitemap, bool>();
            var sitemapNodes = sitemapService.GetNodesByPage(page);

            if (model.UpdateSitemap)
            {
                sitemapNodes.Select(node => node.Sitemap)
                .Distinct()
                .ToList()
                .ForEach(
                    sitemap =>
                    sitemaps.Add(
                        sitemap,
                        !cmsConfiguration.Security.AccessControlEnabled || accessControlService.GetAccessLevel(sitemap, principal) == AccessLevel.ReadWrite));

                foreach (var node in sitemapNodes)
                {
                    if (sitemaps[node.Sitemap] && node.ChildNodes.Count > 0)
                    {
                        var logMessage = string.Format("In {0} sitemap node {1} has {2} child nodes.", node.Sitemap.Id, node.Id, node.ChildNodes.Count);
                        throw new ValidationException(() => PagesGlobalization.DeletePageCommand_SitemapNodeHasChildNodes_Message, logMessage);
                    }
                }
            }

            unitOfWork.BeginTransaction();

            // Update sitemap nodes
            IList <SitemapNode> updatedNodes = new List <SitemapNode>();
            IList <SitemapNode> deletedNodes = new List <SitemapNode>();

            UpdateSitemapNodes(model, page, sitemapNodes, sitemaps, languagesFuture.ToList(), updatedNodes, deletedNodes);

            Redirect redirect;

            if (!string.IsNullOrWhiteSpace(model.RedirectUrl))
            {
                if (string.Equals(page.PageUrl, model.RedirectUrl, StringComparison.OrdinalIgnoreCase))
                {
                    var logMessage = string.Format("Circular redirect loop from url {0} to url {0}.", model.RedirectUrl);
                    throw new ValidationException(() => PagesGlobalization.ValidatePageUrlCommand_SameUrlPath_Message, logMessage);
                }

                // Validate url
                if (!urlService.ValidateExternalUrl(model.RedirectUrl))
                {
                    var logMessage = string.Format("Invalid redirect url {0}.", model.RedirectUrl);
                    throw new ValidationException(() => PagesGlobalization.ValidatePageUrlCommand_InvalidUrlPath_Message, logMessage);
                }

                string patternsValidationMessage;
                if (isRedirectInternal &&
                    !urlService.ValidateUrlPatterns(model.RedirectUrl, out patternsValidationMessage, PagesGlobalization.DeletePage_RedirectUrl_Name))
                {
                    var logMessage = string.Format("{0}. URL: {1}.", patternsValidationMessage, model.RedirectUrl);
                    throw new ValidationException(() => patternsValidationMessage, logMessage);
                }

                redirect = redirectService.GetPageRedirect(page.PageUrl);
                if (redirect != null)
                {
                    redirect.RedirectUrl = model.RedirectUrl;
                }
                else
                {
                    redirect = redirectService.CreateRedirectEntity(page.PageUrl, model.RedirectUrl);
                }

                if (redirect != null)
                {
                    repository.Save(redirect);
                }
            }
            else
            {
                redirect = null;
            }

            // Delete child entities.
            if (page.PageTags != null)
            {
                foreach (var pageTag in page.PageTags)
                {
                    repository.Delete(pageTag);
                }
            }

            var deletedPageContents  = new List <PageContent>();
            var htmlContentsToDelete = new List <HtmlContent>();

            if (page.PageContents != null)
            {
                foreach (var pageContent in page.PageContents)
                {
                    // If content is HTML content, delete HTML content
                    var htmlContent = pageContent.Content as HtmlContent;
                    if (htmlContent != null)
                    {
                        var draft = pageContent.Content.History != null?pageContent.Content.History.FirstOrDefault(c => c.Status == ContentStatus.Draft) : null;

                        if (draft != null)
                        {
                            repository.Delete(draft);
                        }

                        repository.Delete(htmlContent);
                        htmlContentsToDelete.Add(htmlContent);
                    }

                    repository.Delete(pageContent);
                    deletedPageContents.Add(pageContent);
                }
            }

            if (page.Options != null)
            {
                foreach (var option in page.Options)
                {
                    repository.Delete(option);
                }
            }

            if (page.AccessRules != null)
            {
                var rules = page.AccessRules.ToList();
                rules.ForEach(page.RemoveRule);
            }

            if (page.MasterPages != null)
            {
                foreach (var master in page.MasterPages)
                {
                    repository.Delete(master);
                }
            }

            // Delete page
            repository.Delete <Root.Models.Page>(page);

            // Commit
            unitOfWork.Commit();

            var updatedSitemaps = new List <Sitemap>();

            foreach (var node in updatedNodes)
            {
                Events.SitemapEvents.Instance.OnSitemapNodeUpdated(node);
                if (!updatedSitemaps.Contains(node.Sitemap))
                {
                    updatedSitemaps.Add(node.Sitemap);
                }
            }

            foreach (var node in deletedNodes)
            {
                Events.SitemapEvents.Instance.OnSitemapNodeDeleted(node);
                if (!updatedSitemaps.Contains(node.Sitemap))
                {
                    updatedSitemaps.Add(node.Sitemap);
                }
            }

            foreach (var updatedSitemap in updatedSitemaps)
            {
                Events.SitemapEvents.Instance.OnSitemapUpdated(updatedSitemap);
            }

            // Notifying about redirect created
            if (redirect != null)
            {
                Events.PageEvents.Instance.OnRedirectCreated(redirect);
            }

            // Notify about deleted page contents
            foreach (var deletedPageContent in deletedPageContents)
            {
                Events.PageEvents.Instance.OnPageContentDeleted(deletedPageContent);
            }

            // Notify about deleted html contents
            foreach (var htmlContent in htmlContentsToDelete)
            {
                Events.PageEvents.Instance.OnHtmlContentDeleted(htmlContent);
            }

            // Notifying, that page is deleted.
            Events.PageEvents.Instance.OnPageDeleted(page);

            if (sitemaps.Any(tuple => !tuple.Value) && messages != null)
            {
                // Some sitemaps where skipped, because user has no permission to edit.
                messages.AddSuccess(PagesGlobalization.DeletePage_SitemapSkipped_Message);
            }

            return(true);
        }
Beispiel #31
0
        /// <summary>
        /// Saves the blog post.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="childContentOptionValues">The child content option values.</param>
        /// <param name="principal">The principal.</param>
        /// <param name="errorMessages">The error messages.</param>
        /// <param name="updateActivationIfNotChanged">if set to <c>true</c> update activation time even if it was not changed.</param>
        /// <returns>
        /// Saved blog post entity
        /// </returns>
        /// <exception cref="System.ComponentModel.DataAnnotations.ValidationException"></exception>
        /// <exception cref="SecurityException">Forbidden: Access is denied.</exception>
        public BlogPost SaveBlogPost(BlogPostViewModel request, IList <ContentOptionValuesViewModel> childContentOptionValues, IPrincipal principal, out string[] errorMessages, bool updateActivationIfNotChanged = true)
        {
            errorMessages = new string[0];
            string[] roles;
            if (request.DesirableStatus == ContentStatus.Published)
            {
                accessControlService.DemandAccess(principal, RootModuleConstants.UserRoles.PublishContent);
                roles = new[] { RootModuleConstants.UserRoles.PublishContent };
            }
            else
            {
                accessControlService.DemandAccess(principal, RootModuleConstants.UserRoles.EditContent);
                roles = new[] { RootModuleConstants.UserRoles.EditContent };
            }

            var isNew       = request.Id.HasDefaultValue();
            var userCanEdit = securityService.IsAuthorized(RootModuleConstants.UserRoles.EditContent);

            ValidateData(isNew, request);

            BlogPost        blogPost;
            BlogPostContent content;
            PageContent     pageContent;

            GetBlogPostAndContentEntities(request, principal, roles, ref isNew, out content, out pageContent, out blogPost);
            var beforeChange = new UpdatingBlogModel(blogPost);

            // Master page / layout
            Layout layout;
            Page   masterPage;
            Region region;

            LoadDefaultLayoutAndRegion(out layout, out masterPage, out region);

            if (masterPage != null)
            {
                var level = accessControlService.GetAccessLevel(masterPage, principal);
                if (level < AccessLevel.Read)
                {
                    var          message    = BlogGlobalization.SaveBlogPost_FailedToSave_InaccessibleMasterPage;
                    const string logMessage = "Failed to save blog post. Selected master page for page layout is inaccessible.";
                    throw new ValidationException(() => message, logMessage);
                }
            }

            if (pageContent.Region == null)
            {
                pageContent.Region = region;
            }

            // Load master pages for updating page's master path and page's children master path
            IList <Guid>       newMasterIds;
            IList <Guid>       oldMasterIds;
            IList <Guid>       childrenPageIds;
            IList <MasterPage> existingChildrenMasterPages;

            PrepareForUpdateChildrenMasterPages(isNew, blogPost, request, out newMasterIds, out oldMasterIds, out childrenPageIds, out existingChildrenMasterPages);

            // TODO: TEST AND TRY TO FIX IT: TRANSACTION HERE IS REQUIRED!
            // UnitOfWork.BeginTransaction(); // NOTE: this causes concurrent data exception.

            Redirect redirectCreated = null;

            if (!isNew && userCanEdit && !string.Equals(blogPost.PageUrl, request.BlogUrl) && !string.IsNullOrWhiteSpace(request.BlogUrl))
            {
                request.BlogUrl = urlService.FixUrl(request.BlogUrl);
                pageService.ValidatePageUrl(request.BlogUrl, request.Id);
                if (request.RedirectFromOldUrl)
                {
                    var redirect = redirectService.CreateRedirectEntity(blogPost.PageUrl, request.BlogUrl);
                    if (redirect != null)
                    {
                        repository.Save(redirect);
                        redirectCreated = redirect;
                    }
                }

                blogPost.PageUrl = urlService.FixUrl(request.BlogUrl);
            }

            // Push to change modified data each time.
            blogPost.ModifiedOn = DateTime.Now;

            if (userCanEdit)
            {
                blogPost.Title       = request.Title;
                blogPost.Description = request.IntroText;
                blogPost.Author      = request.AuthorId.HasValue ? repository.AsProxy <Author>(request.AuthorId.Value) : null;

                categoryService.CombineEntityCategories <BlogPost, PageCategory>(blogPost, request.Categories);

                blogPost.Image = (request.Image != null && request.Image.ImageId.HasValue) ? repository.AsProxy <MediaImage>(request.Image.ImageId.Value) : null;
                if (isNew || request.DesirableStatus == ContentStatus.Published)
                {
                    if (updateActivationIfNotChanged)
                    {
                        blogPost.ActivationDate = request.LiveFromDate;
                        blogPost.ExpirationDate = TimeHelper.FormatEndDate(request.LiveToDate);
                    }
                    else
                    {
                        blogPost.ActivationDate = TimeHelper.GetFirstIfTheSameDay(blogPost.ActivationDate, request.LiveFromDate);
                        blogPost.ExpirationDate = TimeHelper.GetFirstIfTheSameDay(blogPost.ExpirationDate, TimeHelper.FormatEndDate(request.LiveToDate));
                    }
                }
            }

            if (isNew)
            {
                if (!string.IsNullOrWhiteSpace(request.BlogUrl))
                {
                    blogPost.PageUrl = urlService.FixUrl(request.BlogUrl);
                    pageService.ValidatePageUrl(blogPost.PageUrl);
                }
                else
                {
                    blogPost.PageUrl = CreateBlogPermalink(request.Title, null, blogPost.Categories != null ? blogPost.Categories.Select(x => x.Id) : null);
                }

                blogPost.MetaTitle = request.MetaTitle ?? request.Title;
                if (masterPage != null)
                {
                    blogPost.MasterPage = masterPage;
                    masterPageService.SetPageMasterPages(blogPost, masterPage.Id);
                }
                else
                {
                    blogPost.Layout = layout;
                }
                UpdateStatus(blogPost, request.DesirableStatus);
                AddDefaultAccessRules(blogPost, principal, masterPage);
            }
            else if (request.DesirableStatus == ContentStatus.Published ||
                     blogPost.Status == PageStatus.Preview)
            {
                // Update only if publishing or current status is preview.
                // Else do not change, because it may change from published to draft status
                UpdateStatus(blogPost, request.DesirableStatus);
            }

            // Create content.
            var newContent = new BlogPostContent
            {
                Id               = content != null ? content.Id : Guid.Empty,
                Name             = request.Title,
                Html             = request.Content ?? string.Empty,
                EditInSourceMode = request.EditInSourceMode,
                ActivationDate   = request.LiveFromDate,
                ExpirationDate   = TimeHelper.FormatEndDate(request.LiveToDate)
            };

            if (!updateActivationIfNotChanged && content != null)
            {
                newContent.ActivationDate = TimeHelper.GetFirstIfTheSameDay(content.ActivationDate, newContent.ActivationDate);
                newContent.ExpirationDate = TimeHelper.GetFirstIfTheSameDay(content.ExpirationDate, newContent.ExpirationDate);
            }

            // Preserve content if user is not authorized to change it.
            if (!userCanEdit)
            {
                if (content == null)
                {
                    throw new SecurityException("Forbidden: Access is denied."); // User has no rights to create new content.
                }

                var contentToPublish = (BlogPostContent)(content.History != null
                    ? content.History.FirstOrDefault(c => c.Status == ContentStatus.Draft) ?? content
                    : content);

                newContent.Name = contentToPublish.Name;
                newContent.Html = contentToPublish.Html;
            }

            content             = SaveContentWithStatusUpdate(isNew, newContent, request, principal);
            pageContent.Content = content;
            optionService.SaveChildContentOptions(content, childContentOptionValues, request.DesirableStatus);

            blogPost.PageUrlHash     = blogPost.PageUrl.UrlHash();
            blogPost.UseCanonicalUrl = request.UseCanonicalUrl;

            MapExtraProperties(isNew, blogPost, content, pageContent, request, principal);

            // Notify about page properties changing.
            var cancelEventArgs = Events.BlogEvents.Instance.OnBlogChanging(beforeChange, new UpdatingBlogModel(blogPost));

            if (cancelEventArgs.Cancel)
            {
                errorMessages = cancelEventArgs.CancellationErrorMessages.ToArray();
                return(null);
            }

            repository.Save(blogPost);
            repository.Save(content);
            repository.Save(pageContent);

            masterPageService.UpdateChildrenMasterPages(existingChildrenMasterPages, oldMasterIds, newMasterIds, childrenPageIds);

            pageContent.Content   = content;
            blogPost.PageContents = new [] { pageContent };



            IList <Tag> newTags = null;

            if (userCanEdit)
            {
                newTags = SaveTags(blogPost, request);
            }

            // Commit
            unitOfWork.Commit();

            // Notify about new created tags.
            Events.RootEvents.Instance.OnTagCreated(newTags);

            // Notify about new or updated blog post.
            if (isNew)
            {
                Events.BlogEvents.Instance.OnBlogCreated(blogPost);
            }
            else
            {
                Events.BlogEvents.Instance.OnBlogUpdated(blogPost);
            }

            // Notify about redirect creation.
            if (redirectCreated != null)
            {
                Events.PageEvents.Instance.OnRedirectCreated(redirectCreated);
            }

            return(blogPost);
        }
Beispiel #32
0
        public void Migrate()
        {
            try
            {
                var consumersFromSugar     = _sugarDataContext.Query <WWhatsInTheBag>().OrderByDescending(x => x.DateModified).ToList();
                var whatsInTheBagSugar     = _sugarDataContext.Query <WWhatsInTheBagCstm>().ToList();
                var whatsInToConsumerSugar = _sugarDataContext.Query <WWhatsInTheBagCConsumersC>();
                var countFromSugar         = consumersFromSugar.Count;

                var loopCount = countFromSugar / _splitCount;

                if (loopCount > 0)
                {
                    loopCount = countFromSugar;
                }

                _logger.LogInformation("#################Starting Migration of Whats in the bag");
                _logger.LogInformation($"Found {countFromSugar} to migrate");

                for (var x = 0; x < loopCount; x++)
                {
                    var skip = x * _splitCount;
                    if (skip > countFromSugar)
                    {
                        break;
                    }
                    _logger.LogInformation($"Starting segment starting at {skip}");

                    _repository.ReloadContext();
                    _repository.GetDatabase().ChangeTracker.AutoDetectChangesEnabled = false;
                    var sugarItems = consumersFromSugar.Skip(x * _splitCount).Take(_splitCount).ToList();

                    foreach (var sItem in sugarItems)
                    {
                        var bagItem        = whatsInTheBagSugar.FirstOrDefault(y => y.IdC == sItem.Id);
                        var itemToConsumer = whatsInToConsumerSugar.FirstOrDefault(y => y.WWhatsInTheBagCConsumerswWhatsInTheBagIdb == sItem.Id);
                        var consumerOld    = _sugarDataContext.Query <CConsumers>().FirstOrDefault(y => y.Id == itemToConsumer.WWhatsInTheBagCConsumerscConsumersIda);

                        if (consumerOld == null)
                        {
                            continue;
                        }

                        var consumer = _repository.Query <ConsumerData.Models.Consumer>()
                                       .Include(y => y.GolferProfile)
                                       .FirstOrDefault(y => y.PrimaryEmail.ToLower() == consumerOld.Email.ToLower());
                        if (consumer == null)
                        {
                            continue;
                        }
                        if (consumer.GolferProfile == null)
                        {
                            consumer.GolferProfile = new ConsumerData.Models.GolferProfile
                            {
                                Created    = DateTime.UtcNow,
                                ConsumerId = consumer.Id.Value
                            };
                            _repository.SaveQueue(consumer);
                        }

                        var cdmItem = new ConsumerData.Models.WhatsInTheBag
                        {
                            ClubShaftFlexId      = _staticTableHelper.GetFlexId(bagItem.FlexC),
                            ClubLoftId           = _staticTableHelper.GetLoftId(bagItem.LoftC),
                            FaceLieAdjustmentId  = _staticTableHelper.GetLieId(bagItem.FaceLieAdjustmentC),
                            FaceLoftAdjustmentId = _staticTableHelper.GetLoftId(bagItem.FaceLoftAdjustmentC),
                            Created            = DateTime.UtcNow,
                            ClubCategoryId     = _staticTableHelper.GetCategoryId(sItem.Category),
                            BrandId            = _staticTableHelper.GetBrandId(sItem.Vendor),
                            ClubCategoryTypeId = _staticTableHelper.GetClubCategoryTypeId(bagItem.HeadLoftC),
                            ModelId            = _staticTableHelper.GetModelId(sItem.Model),
                            PlanToPurchase     = !string.IsNullOrWhiteSpace(sItem.PlanningToPurchase),
                            ClubShaftLengthId  = _staticTableHelper.GetChaftLengthId(bagItem.ShaftLengthC),
                            Sku             = bagItem.SkuC,
                            GolferProfileId = consumer.GolferProfile.Id
                        };

                        try
                        {
                            _repository.SaveQueue(cdmItem);
                        }
                        catch (Exception e)
                        {
                            _logger.LogError(e.Message);
                        }
                    }

                    _logger.LogInformation($"Saving Whats in the bag " + DateTime.UtcNow.ToLongDateString());
                    try
                    {
                        _repository.Save();
                    }
                    catch (Exception e)
                    {
                        _logger.LogError(e.Message);
                    }
                    _logger.LogInformation($"Saving Whats in the bag" + DateTime.UtcNow.ToLongDateString());
                }
            }
            catch (Exception e)
            {
                _logger.LogError("Migrate [WhatsInTheBag] failed", e);
            }
        }
        private List <BlogPostImportResult> ImportBlogPosts(IPrincipal principal, IDictionary <string, Guid> authors, IDictionary <string, Guid> categories,
                                                            List <BlogMLPost> blogs, List <BlogPostImportResult> modifications, bool createRedirects = false)
        {
            var createdBlogPosts = new List <BlogPostImportResult>();

            if (blogs != null)
            {
                foreach (var blogML in blogs)
                {
                    BlogPostViewModel blogPostModel = null;

                    try
                    {
                        blogPostModel = MapViewModel(blogML, modifications.First(m => m.Id == blogML.ID));

                        BlogPostImportResult blogPostResult = null;
                        if (!ValidateModel(blogPostModel, blogML, out blogPostResult))
                        {
                            createdBlogPosts.Add(blogPostResult);
                            continue;
                        }

                        if (blogML.Authors != null && blogML.Authors.Count > 0)
                        {
                            blogPostModel.AuthorId = authors[blogML.Authors[0].Ref];
                        }
                        if (blogML.Categories != null && blogML.Categories.Count > 0 && categories != null && categories.Count > 0)
                        {
                            for (var i = 0; i < blogML.Categories.Count; i++)
                            {
                                var category = blogML.Categories[i];

                                if (blogPostModel.Categories == null)
                                {
                                    blogPostModel.Categories = new List <LookupKeyValue>();
                                }

                                blogPostModel.Categories.Add(new LookupKeyValue()
                                {
                                    Key = categories[category.Ref].ToLowerInvariantString()
                                });
                            }
                        }

                        string[] error;
                        var      blogPost = blogService.SaveBlogPost(blogPostModel, null, principal, out error);
                        if (blogPost == null)
                        {
                            blogPostResult = new BlogPostImportResult
                            {
                                Title        = blogML.PostName ?? blogML.Title,
                                Success      = false,
                                ErrorMessage = error.Length > 0 ? error[0] : string.Empty
                            };
                            createdBlogPosts.Add(blogPostResult);

                            continue;
                        }

                        blogPostResult = new BlogPostImportResult
                        {
                            Title   = blogML.PostName ?? blogML.Title,
                            PageUrl = blogPost.PageUrl,
                            Id      = blogPost.Id.ToString(),
                            Success = true
                        };
                        createdBlogPosts.Add(blogPostResult);

                        if (createRedirects)
                        {
                            var oldUrl = TryValidateOldUrl(blogML.PostUrl);
                            if (oldUrl != null && oldUrl != blogPostModel.BlogUrl)
                            {
                                var redirect = redirectService.GetPageRedirect(oldUrl);
                                if (redirect == null)
                                {
                                    redirect = redirectService.CreateRedirectEntity(oldUrl, blogPostModel.BlogUrl);
                                    repository.Save(redirect);
                                    unitOfWork.Commit();
                                    Events.PageEvents.Instance.OnRedirectCreated(redirect);
                                }
                                else
                                {
                                    blogPostResult.WarnMessage = string.Format(BlogGlobalization.ImportBlogPosts_RedirectWasAlreadyCreatedFor_Message, blogML.PostUrl);
                                }
                            }
                            else if (oldUrl == null)
                            {
                                blogPostResult.WarnMessage = string.Format(BlogGlobalization.ImportBlogPosts_FailedToCreateRedirectFor_Message, blogML.PostUrl);
                            }
                        }
                    }
                    catch (Exception exc)
                    {
                        var failedBlogPost = new BlogPostImportResult
                        {
                            Title        = blogML.PostName ?? blogML.Title,
                            PageUrl      = blogPostModel != null && blogPostModel.BlogUrl != null ? blogPostModel.BlogUrl : blogML.PostUrl,
                            Success      = false,
                            ErrorMessage = exc.Message,
                            Id           = blogML.ID
                        };
                        createdBlogPosts.Add(failedBlogPost);

                        Log.Error("Failed to import blog post.", exc);
                    }
                }
            }

            return(createdBlogPosts);
        }
 private void SaveToDb(User user)
 {
     _userRepository.Save(user);
     _userRepository.Commit();
 }
 public override void HandleMessage(Yupi.Model.Domain.Habbo session, Yupi.Protocol.Buffers.ClientMessage message,
                                    Yupi.Protocol.IRouter router)
 {
     session.Info.Preferences.PreferOldChat = message.GetBool();
     UserRepository.Save(session.Info);
 }
Beispiel #36
0
 public void UpdateSensor(SensorsFromUser editedSensor)
 {
     sensorRepo.Update(editedSensor);
     sensorRepo.Save();
 }
Beispiel #37
0
        /// <summary>
        /// Puts the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <returns><c>PutPageResponse</c> with created or updated item id.</returns>
        public PutPagePropertiesResponse Put(PutPagePropertiesRequest request)
        {
            if (request.Data.IsMasterPage)
            {
                accessControlService.DemandAccess(securityService.GetCurrentPrincipal(), RootModuleConstants.UserRoles.Administration);
            }
            else
            {
                accessControlService.DemandAccess(securityService.GetCurrentPrincipal(), RootModuleConstants.UserRoles.EditContent);
            }

            PageProperties pageProperties = null;

            var isNew = !request.Id.HasValue || request.Id.Value.HasDefaultValue();

            if (!isNew)
            {
                pageProperties =
                    repository.AsQueryable <PageProperties>(e => e.Id == request.Id.GetValueOrDefault())
                    .FetchMany(p => p.Options)
                    .Fetch(p => p.Layout)
                    .ThenFetchMany(l => l.LayoutOptions)
                    .FetchMany(p => p.MasterPages)
                    .FetchMany(f => f.AccessRules)
                    .ToList()
                    .FirstOrDefault();

                isNew = pageProperties == null;
            }
            UpdatingPagePropertiesModel beforeChange = null;

            if (isNew)
            {
                pageProperties = new PageProperties
                {
                    Id          = request.Id.GetValueOrDefault(),
                    Status      = PageStatus.Unpublished,
                    AccessRules = new List <AccessRule>()
                };
            }
            else if (request.Data.Version > 0)
            {
                pageProperties.Version = request.Data.Version;
            }

            if (!isNew)
            {
                beforeChange = new UpdatingPagePropertiesModel(pageProperties);
            }

            if (!isNew && pageProperties.IsMasterPage != request.Data.IsMasterPage)
            {
                const string message    = "IsMasterPage cannot be changed for updating page. It can be modified only when creating a page.";
                var          logMessage = string.Format("{0} PageId: {1}", message, request.Id);
                throw new ValidationException(() => message, logMessage);
            }

            // Load master pages for updating page's master path and page's children master path
            IList <Guid>       newMasterIds;
            IList <Guid>       oldMasterIds;
            IList <Guid>       childrenPageIds;
            IList <MasterPage> existingChildrenMasterPages;

            masterPageService.PrepareForUpdateChildrenMasterPages(pageProperties, request.Data.MasterPageId, out newMasterIds, out oldMasterIds, out childrenPageIds, out existingChildrenMasterPages);

            unitOfWork.BeginTransaction();

            if (!string.IsNullOrEmpty(request.Data.PageUrl) || string.IsNullOrEmpty(pageProperties.PageUrl))
            {
                var pageUrl = request.Data.PageUrl;
                if (string.IsNullOrEmpty(pageUrl) && !string.IsNullOrWhiteSpace(request.Data.Title))
                {
                    pageUrl = pageService.CreatePagePermalink(request.Data.Title, null, null, request.Data.LanguageId, request.Data.Categories);
                }
                else
                {
                    pageUrl = urlService.FixUrl(pageUrl);
                    pageService.ValidatePageUrl(pageUrl, request.Id);
                }

                pageProperties.PageUrl     = pageUrl;
                pageProperties.PageUrlHash = pageUrl.UrlHash();
            }

            pageProperties.Title       = request.Data.Title;
            pageProperties.Description = request.Data.Description;

            var newStatus = request.Data.IsMasterPage || request.Data.IsPublished ? PageStatus.Published : PageStatus.Unpublished;

            if (!request.Data.IsMasterPage && pageProperties.Status != newStatus)
            {
                accessControlService.DemandAccess(securityService.GetCurrentPrincipal(), RootModuleConstants.UserRoles.PublishContent);
            }

            pageProperties.Status      = newStatus;
            pageProperties.PublishedOn = request.Data.IsPublished && !request.Data.PublishedOn.HasValue ? DateTime.Now : request.Data.PublishedOn;

            masterPageService.SetMasterOrLayout(pageProperties, request.Data.MasterPageId, request.Data.LayoutId);

            categoryService.CombineEntityCategories <PageProperties, PageCategory>(pageProperties, request.Data.Categories);

            pageProperties.IsArchived              = request.Data.IsArchived;
            pageProperties.IsMasterPage            = request.Data.IsMasterPage;
            pageProperties.LanguageGroupIdentifier = request.Data.LanguageGroupIdentifier;
            pageProperties.ForceAccessProtocol     = (Core.DataContracts.Enums.ForceProtocolType)(int) request.Data.ForceAccessProtocol;
            pageProperties.Language = request.Data.LanguageId.HasValue && !request.Data.LanguageId.Value.HasDefaultValue()
                                    ? repository.AsProxy <Language>(request.Data.LanguageId.Value)
                                    : null;

            pageProperties.Image = request.Data.MainImageId.HasValue
                                    ? repository.AsProxy <MediaImage>(request.Data.MainImageId.Value)
                                    : null;
            pageProperties.FeaturedImage = request.Data.FeaturedImageId.HasValue
                                    ? repository.AsProxy <MediaImage>(request.Data.FeaturedImageId.Value)
                                    : null;
            pageProperties.SecondaryImage = request.Data.SecondaryImageId.HasValue
                                    ? repository.AsProxy <MediaImage>(request.Data.SecondaryImageId.Value)
                                    : null;

            pageProperties.CustomCss       = request.Data.CustomCss;
            pageProperties.CustomJS        = request.Data.CustomJavaScript;
            pageProperties.UseCanonicalUrl = request.Data.UseCanonicalUrl;
            pageProperties.UseNoFollow     = request.Data.UseNoFollow;
            pageProperties.UseNoIndex      = request.Data.UseNoIndex;

            if (request.Data.MetaData != null)
            {
                pageProperties.MetaTitle       = request.Data.MetaData.MetaTitle;
                pageProperties.MetaDescription = request.Data.MetaData.MetaDescription;
                pageProperties.MetaKeywords    = request.Data.MetaData.MetaKeywords;
            }

            IList <Tag> newTags = null;

            if (request.Data.Tags != null)
            {
                tagService.SavePageTags(pageProperties, request.Data.Tags, out newTags);
            }

            if (request.Data.AccessRules != null)
            {
                pageProperties.AccessRules.RemoveDuplicateEntities();
                var accessRules =
                    request.Data.AccessRules.Select(
                        r => (IAccessRule) new AccessRule {
                    AccessLevel = (Core.Security.AccessLevel)(int) r.AccessLevel, Identity = r.Identity, IsForRole = r.IsForRole
                })
                    .ToList();
                accessControlService.UpdateAccessControl(pageProperties, accessRules);
            }

            if (request.Data.PageOptions != null)
            {
                var options = request.Data.PageOptions.ToServiceModel();

                var pageOptions = pageProperties.Options != null?pageProperties.Options.Distinct() : null;

                pageProperties.Options = optionService.SaveOptionValues(options, pageOptions, () => new PageOption {
                    Page = pageProperties
                });
            }

            if (!isNew)
            {
                // Notify about page properties changing.
                var cancelEventArgs = Events.PageEvents.Instance.OnPagePropertiesChanging(beforeChange, new UpdatingPagePropertiesModel(pageProperties));
                if (cancelEventArgs.Cancel)
                {
                    throw new CmsApiValidationException(
                              cancelEventArgs.CancellationErrorMessages != null && cancelEventArgs.CancellationErrorMessages.Count > 0
                            ? string.Join(",", cancelEventArgs.CancellationErrorMessages)
                            : "Page properties saving was canceled.");
                }
            }

            repository.Save(pageProperties);

            //
            // If creating new page, page id is unknown when children pages are loaded, so Guid may be empty
            // Updating id to saved page's Id manually
            //
            if (isNew && childrenPageIds != null && childrenPageIds.Count == 1 && childrenPageIds[0].HasDefaultValue())
            {
                childrenPageIds[0] = pageProperties.Id;
            }

            masterPageService.UpdateChildrenMasterPages(existingChildrenMasterPages, oldMasterIds, newMasterIds, childrenPageIds);

            unitOfWork.Commit();

            // Fire events.
            Events.RootEvents.Instance.OnTagCreated(newTags);
            if (isNew)
            {
                Events.PageEvents.Instance.OnPageCreated(pageProperties);
            }
            else
            {
                Events.PageEvents.Instance.OnPagePropertiesChanged(pageProperties);
            }

            return(new PutPagePropertiesResponse {
                Data = pageProperties.Id
            });
        }
Beispiel #38
0
 public void AltaHistorialCompraVentaLibro(HistorialCompraVentaLibro historialCompraVentaLibro)
 {
     _historialCompraVentaLibroRepository.Save(historialCompraVentaLibro);
 }
 public bool Save()
 {
     return(_db.Save());
 }
Beispiel #40
0
 private void Save()
 {
     db.Save();
 }
 public void Post([FromBody] Client client)
 {
     repository.Create(client);
     repository.Save();
 }
 public void Create(EWeeklyReportDto eWeeklyReporttDto)
 {
     _repositoryEWeeklyReport.Create(Mapper.Map <EWeeklyReport>(eWeeklyReporttDto));
     _repositoryEWeeklyReport.Save();
 }
Beispiel #43
0
        public void Handle(CreateToDoListCommand command)
        {
            ToDoList todoList = new ToDoList(command.Id, command.Title, command.Description);

            _repo.Save(todoList, Guid.NewGuid());
        }
        /// <summary>
        /// Saves changes for this table
        /// and re caches the table data.
        /// </summary>
        public async Task Save()
        {
            await _repository.Save();

            await CacheTable();
        }
 public IActionResult Post(TodoItem item)
 {
     return(Ok(_repository.Save(item)));
 }
 public Task Save <T>(T aggregate, int?expectedVersion = null, CancellationToken cancellationToken = default(CancellationToken)) where T : AggregateRoot
 {
     return(Task.WhenAll(TryMakeSnapshot(aggregate), _repository.Save(aggregate, expectedVersion, cancellationToken)));
 }
Beispiel #47
0
        /// <summary>
        /// Uploads the image.
        /// </summary>
        /// <param name="rootFolderId">The root folder id.</param>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="fileLength">Length of the file.</param>
        /// <param name="fileStream">The file stream.</param>
        /// <param name="reuploadMediaId">The reupload media identifier.</param>
        /// <param name="overrideUrl">if set to <c>true</c> override URL.</param>
        /// <returns>
        /// Image entity.
        /// </returns>
        public MediaImage UploadImage(Guid rootFolderId, string fileName, long fileLength, Stream fileStream, Guid reuploadMediaId, bool overrideUrl = true)
        {
            overrideUrl = false; // TODO: temporary disabling feature #1055.

            var folderName     = mediaFileService.CreateRandomFolderName();
            var publicFileName = MediaHelper.RemoveInvalidPathSymbols(MediaImageHelper.CreatePublicFileName(fileName, Path.GetExtension(fileName)));
            var fileExtension  = Path.GetExtension(fileName);
            var imageType      = ImageHelper.GetImageType(fileExtension);

            MediaImage   uploadImage         = null;
            MemoryStream thumbnailFileStream = new MemoryStream();
            Size         size;
            Size         thumbnailSize = ThumbnailSize;
            long         thumbnailImageLength;

            /* Upload standard raster type images */
            if (imageType == ImageType.Raster)
            {
                fileStream = RotateImage(fileStream);
                size       = GetSize(fileStream);

                CreatePngThumbnail(fileStream, thumbnailFileStream, ThumbnailSize);
                thumbnailImageLength = thumbnailFileStream.Length;
            }
            /* Upload vector graphics images */
            else
            {
                size = Size.Empty;
                ReadParametersFormVectorImage(fileStream, ref size);
                thumbnailImageLength = fileStream.Length;
                CreateSvgThumbnail(fileStream, thumbnailFileStream, ThumbnailSize);
            }

            try
            {
                if (!reuploadMediaId.HasDefaultValue())
                {
                    // Re-uploading image: Get original image, folder name, file extension, file name
                    uploadImage             = (MediaImage)repository.First <MediaImage>(image => image.Id == reuploadMediaId).Clone();
                    uploadImage.IsTemporary = true;

                    // Create new original image and upload file stream to the storage
                    uploadImage = CreateImage(rootFolderId, fileName, fileExtension, Path.GetFileName(fileName), size, fileLength);
                }
                else
                {
                    // Uploading new image
                    // Create new original image and upload file stream to the storage
                    uploadImage = CreateImage(
                        rootFolderId,
                        fileName,
                        fileExtension,
                        Path.GetFileName(fileName),
                        size,
                        fileLength);
                }
                SetThumbnailParameters(uploadImage, thumbnailSize, thumbnailImageLength);
                mediaImageVersionPathService.SetPathForNewOriginal(uploadImage, folderName, publicFileName, imageType);

                unitOfWork.BeginTransaction();
                repository.Save(uploadImage);
                unitOfWork.Commit();

                StartTasksForImage(uploadImage, fileStream, thumbnailFileStream, false);
            }
            finally
            {
                if (thumbnailFileStream != null)
                {
                    thumbnailFileStream.Dispose();
                }
            }

            return(uploadImage);
        }
 public void AddMessage(Message message)
 {
     _messageRepository.Add(message);
     _messageRepository.Save();
 }
Beispiel #49
0
 public bool Save()
 {
     return(_repository.Save());
 }
Beispiel #50
0
        public void Handle(AddNewToDoItemCommand command)
        {
            ToDoItem item = new ToDoItem(command.TodoListId, command.Id, command.CreationDate, command.Description, command.DueDate, command.Importance);

            _repo.Save(item, Guid.NewGuid());
        }
 public void Save(TeamMember member)
 {
     _repository.Save(member);
 }
 public void SaveBook(Book book)
 {
     _repository.Save(book);
 }
Beispiel #53
0
 public void Save()
 {
     employeeRepository.Save();
 }
 public Team AddTeam(Team newTeam)
 {
     newTeam.ID = GetNewId();
     return(repository.Save(newTeam));
 }
Beispiel #55
0
 public void RemoveVendedor(Vendedor vendedor)
 {
     vendedorRP.Delete(vendedor);
     vendedorRP.Save();
 }
Beispiel #56
0
 public EmployeeServiceTest()
 {
     _employeeRepository = new MemoryRepository <Employee>();
     _allEmployees       = SetupEmployees();
     _allEmployees.ForEach(empl => _employeeRepository.Save(empl.Id, empl));
 }
Beispiel #57
0
 public virtual void Save()
 {
     BaseRepository.Save();
 }
        private PageProperties ClonePage(System.Guid pageId, string pageTitle, string pageUrl,
                                         IEnumerable <IAccessRule> userAccessList, bool cloneAsMasterPage, System.Guid?languageId, System.Guid?languageGroupIdentifier)
        {
            var principal = securityService.GetCurrentPrincipal();

            if (cloneAsMasterPage)
            {
                accessControlService.DemandAccess(principal, RootModuleConstants.UserRoles.Administration);
            }
            else
            {
                accessControlService.DemandAccess(principal, RootModuleConstants.UserRoles.EditContent);
            }

            // Create / fix page url
            if (pageUrl == null && !string.IsNullOrWhiteSpace(pageTitle))
            {
                pageUrl = pageService.CreatePagePermalink(pageTitle, null);
            }
            else
            {
                pageUrl = urlService.FixUrl(pageUrl);
                pageService.ValidatePageUrl(pageUrl);
            }

            var page = repository
                       .AsQueryable <PageProperties>()
                       .Where(f => f.Id == pageId)
                       .FetchMany(f => f.Options)
                       .FetchMany(f => f.PageContents).ThenFetch(f => f.Region)
                       .FetchMany(f => f.PageContents).ThenFetch(f => f.Content)
                       .FetchMany(f => f.PageContents).ThenFetchMany(f => f.Options)
                       .FetchMany(f => f.PageTags).ThenFetch(f => f.Tag)
                       .FetchMany(f => f.MasterPages).ThenFetch(f => f.Master)
                       .ToList().FirstOne();

            ValidateCloningPage(page, languageId, languageGroupIdentifier);

            unitOfWork.BeginTransaction();

            // Detach page to avoid duplicate saving.
            repository.Detach(page);
            page.PageContents.ForEach(repository.Detach);
            page.PageTags.ForEach(repository.Detach);
            page.Options.ForEach(repository.Detach);
            page.SaveUnsecured = true;

            var pageContents = page.PageContents.Distinct().ToList();
            var pageTags     = page.PageTags.Distinct().ToList();
            var pageOptions  = page.Options.Distinct().ToList();

            var masterPages = page.MasterPages != null?page.MasterPages.Distinct().ToList() : new List <MasterPage>();

            // Clone page with security
            var newPage = ClonePageOnly(page, userAccessList, pageTitle, pageUrl, cloneAsMasterPage);

            if (languageId.HasValue)
            {
                if (languageId.Value.HasDefaultValue())
                {
                    newPage.Language = null;
                }
                else
                {
                    newPage.Language = repository.AsProxy <Language>(languageId.Value);
                }
            }
            if (languageGroupIdentifier.HasValue)
            {
                newPage.LanguageGroupIdentifier = languageGroupIdentifier.Value;
            }
            else
            {
                newPage.LanguageGroupIdentifier = null;
            }
            repository.Save(newPage);

            // Clone contents.
            pageContents.ForEach(pageContent => ClonePageContent(pageContent, newPage));

            // Clone tags.
            pageTags.ForEach(pageTag => ClonePageTags(pageTag, newPage));

            // Clone options.
            pageOptions.ForEach(pageOption => ClonePageOption(pageOption, newPage));

            // Clone master pages
            masterPages.ForEach(masterPage => CloneMasterPages(masterPage, newPage));

            // Set language identifier for parent page, if it hasn't and child is cloned from the parent.
            if (languageGroupIdentifier.HasValue && !page.LanguageGroupIdentifier.HasValue)
            {
                page.LanguageGroupIdentifier = languageGroupIdentifier.Value;
                repository.Save(page);
            }

            unitOfWork.Commit();

            Events.PageEvents.Instance.OnPageCloned(newPage);

            return(newPage);
        }
Beispiel #59
0
 public void TestInit()
 {
     repository = new DefaultRepository(fileStoreService, cacheStoreService);
     repository.Save(RepositoryTests.GetContentTypeCollection());
 }
Beispiel #60
0
 public Customer SaveCustomer(Customer customer)
 {
     return(_repository.Save(customer));
 }