/// <summary>
        /// Creates a product in all the regional providers based on the
        /// product in the master catalog as defined by the master id and
        /// master type parameters.
        /// </summary>
        /// <param name="masterId">
        /// Id of the product in the master catalog that is to be replicated.
        /// </param>
        /// <param name="masterType">
        /// The type of the product in the master catalog that is to be replicated.
        /// </param>
        private void CreateProductAccrossRegions(Guid masterId, Type masterType)
        {
            var transactionName   = "CreateProductsRegional";
            var regionalProviders = this.GetRegionalCatalogProviders();
            var masterProduct     = this.GetMasterProduct(masterId, masterType);

            foreach (var regionalProvider in regionalProviders)
            {
                var manager = CatalogManager.GetManager(regionalProvider, transactionName);

                // make sure the master item wasn't already synced for some reason
                if (manager.GetProducts(masterType.FullName).Any(p => p.GetValue <string>("MasterId") == masterId.ToString()))
                {
                    continue;
                }

                var regionalItem = manager.CreateItem(masterType) as Product;
                // associate the product in the regional catalog with the one
                // in the master catalog
                regionalItem.SetValue("MasterId", masterId.ToString());

                // copy logic; incomplete, modify as necessary
                regionalItem.Title   = masterProduct.Title;
                regionalItem.Price   = masterProduct.Price;
                regionalItem.Weight  = masterProduct.Weight;
                regionalItem.UrlName = masterProduct.UrlName;

                // ensure the URLs of the new product are correctly set up
                manager.Provider.RecompileItemUrls(regionalItem);
            }

            TransactionManager.CommitTransaction(transactionName);
        }
Esempio n. 2
0
        private void CreateUser(string username, string firstname, string lastname, string email)
        {
            string transaction    = "FacebookLoginCreateUserTransaction" + Guid.NewGuid().ToString();
            var    userManager    = UserManager.GetManager(string.Empty, transaction);
            var    profileManager = UserProfileManager.GetManager(string.Empty, transaction);
            var    roleManager    = RoleManager.GetManager("AppRoles", transaction);

            var currentUser = userManager.CreateUser(username);

            var adminRole = roleManager.GetRoles().Where(role => role.Name == "Users").FirstOrDefault();

            currentUser.IsBackendUser = false;

            roleManager.AddUserToRole(currentUser, adminRole);

            TransactionManager.CommitTransaction(transaction);

            var profile = profileManager.CreateProfile(currentUser, "Telerik.Sitefinity.Security.Model.SitefinityProfile") as SitefinityProfile;

            if (!String.IsNullOrEmpty(firstname) && !string.IsNullOrEmpty(lastname) && !string.IsNullOrEmpty(username))
            {
                profile.FirstName = firstname;
                profile.LastName  = lastname;
                profile.Nickname  = username;
                profileManager.RecompileItemUrls <SitefinityProfile>(profile);

                TransactionManager.CommitTransaction(transaction);
            }
        }
Esempio n. 3
0
        // Creates a new bug item
        private void CreateBugItem(DynamicModuleManager dynamicModuleManager, Type bugType, string transactionName)
        {
            DynamicContent bugItem = dynamicModuleManager.CreateDataItem(bugType);

            // This is how values for the properties are set
            bugItem.SetValue("Title", "Some Title");
            bugItem.SetValue("Description", "Some Description");
            // Set the selected value
            bugItem.SetValue("Priority", "Option2");


            bugItem.SetString("UrlName", "SomeUrlName");
            bugItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
            bugItem.SetValue("PublicationDate", DateTime.UtcNow);



            bugItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft");

            // Create a version and commit the transaction in order changes to be persisted to data store
            var versionManager = VersionManager.GetManager(null, transactionName);

            versionManager.CreateVersion(bugItem, false);
            TransactionManager.CommitTransaction(transactionName);
        }
        public async Task <Unit> Handle(TransactionalCommand request,
                                        CancellationToken cancellationToken)
        {
            try
            {
                _transactionManager.BeginTransaction();
                foreach (var command in request.commands.Where(x => x != null))
                {
                    await _mediator.Send(command, cancellationToken);
                }

                _transactionManager.CommitTransaction();
            }
            catch (Exception e)
            {
                _transactionManager.RollbackTransaction();
                throw e;
            }
            finally
            {
                _transactionManager.Dispose();
            }

            return(Unit.Value);
        }
Esempio n. 5
0
        private void MigrateData(string transactionName)
        {
            this.SetMigartionProperies();

            var migrationType = this.ddlMigrationType.SelectedValue;

            switch (migrationType)
            {
            case "GuidArray":
                this.MigrateGuidArray(transactionName);
                break;

            case "Guid":
                this.MigrateGuid(transactionName);
                break;

            case "Media":
                this.MigrateMedia(transactionName);
                break;
            }

            this.Log(transactionCommitMessage);
            TransactionManager.CommitTransaction(transactionName);
            this.Log(migrationCompleteMessage);
        }
Esempio n. 6
0
        private void CreateUser(string dataProviderName, string externalProviderName, string email, string externalId, string firstName, string lastName)
        {
            // Start transaction
            Guid   guid            = Guid.NewGuid();
            string transactionName = string.Concat("ExternalLoginCreateUserTransaction", guid.ToString());

            UserManager        userManager    = UserManager.GetManager(dataProviderName, transactionName);
            UserProfileManager profileManager = UserProfileManager.GetManager(string.Empty, transactionName);

            // Create new user
            User newUser = userManager.CreateUser(null);

            newUser.IsBackendUser        = false;
            newUser.IsApproved           = true;
            newUser.Email                = email;
            newUser.ExternalProviderName = externalProviderName;
            newUser.ExternalId           = externalId;
            newUser.SetUserName(email);

            // Update user roles
            List <string> autoAssignedRoles = (
                from s in Config.Get <AuthenticationConfig>().SecurityTokenService
                .AuthenticationProviders[externalProviderName].AutoAssignedRoles
                .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                select s.Trim()).ToList();

            RoleManager roleManager = RoleManager.GetManager(string.Empty, transactionName);
            List <Role> roles       = roleManager.GetRoles().ToList();

            foreach (string newRole in autoAssignedRoles.Distinct())
            {
                Role role = (
                    from r in roles
                    where r.Name == newRole
                    select r).FirstOrDefault();

                if (role == null)
                {
                    continue;
                }

                roleManager.AddUserToRole(newUser, role);
            }

            // Update user profile
            SitefinityProfile newProfile =
                profileManager.CreateProfile(newUser, Guid.NewGuid(), typeof(SitefinityProfile)) as SitefinityProfile;

            if (newProfile != null)
            {
                newProfile.FirstName = firstName;
                newProfile.LastName  = lastName;
            }

            // Commit transaction
            TransactionManager.FlushTransaction(transactionName);
            profileManager.RecompileItemUrls(newProfile);
            TransactionManager.CommitTransaction(transactionName);
        }
Esempio n. 7
0
 public void CommitTransaction(IDbTransaction trans)
 {
     try {
         TransactionManager.CommitTransaction(trans);
     } catch (InvalidCommitOrRollbackTransactionException e) {
         throw new InvalidCommitOrRollbackException(e.Message);
     }
 }
Esempio n. 8
0
        public string CreateOffice()
        {
            string result = "Office created successfully";

            try
            {
                // Set a transaction name and get the version manager
                var transactionName = "someTransactionName";
                var versionManager  = VersionManager.GetManager(null, transactionName);

                // Set the culture name for the multilingual fields
                var cultureName = "en";
                Thread.CurrentThread.CurrentUICulture = new CultureInfo(cultureName);

                DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(this.ProviderName, transactionName);

                DynamicContent officeItem = dynamicModuleManager.CreateDataItem(this.OfficeType);

                // This is how values for the properties are set
                officeItem.SetString("Title", "New York", cultureName);
                officeItem.SetString("Info", LOREM_IPSUM, cultureName);
                Address        address        = new Address();
                CountryElement addressCountry = Telerik.Sitefinity.Configuration.Config.Get <LocationsConfig>().Countries.Values.First(x => x.Name == "United States");
                address.CountryCode = addressCountry.IsoCode;
                address.StateCode   = addressCountry.StatesProvinces.Values.First().Abbreviation;
                address.City        = "New York City";
                address.Street      = "Baker Street";
                address.Zip         = "12345";
                officeItem.SetValue("Address", address);


                // Get related item manager
                LibrariesManager pictureManager = LibrariesManager.GetManager("OpenAccessDataProvider");
                var pictureItem = pictureManager.GetImages().FirstOrDefault(i => i.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Master && i.Title.Contains("New York"));
                if (pictureItem != null)
                {
                    // This is how we relate an item
                    officeItem.CreateRelation(pictureItem, "Picture");
                }

                officeItem.SetString("UrlName", "new-york", cultureName);
                officeItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
                officeItem.SetValue("PublicationDate", DateTime.UtcNow);


                officeItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft", new CultureInfo(cultureName));

                // Create a version and commit the transaction in order changes to be persisted to data store
                versionManager.CreateVersion(officeItem, false);
                TransactionManager.CommitTransaction(transactionName);
            }
            catch (Exception ex)
            {
                return(ex.Message.ToString());
            }

            return(result);
        }
        private void CreateNews(string[] values)
        {
            NewsManager man = NewsManager.GetManager("", "123");

            man.Provider.SuppressSecurityChecks = true;
            TaxonomyManager tMan = TaxonomyManager.GetManager("", "456");

            tMan.Provider.SuppressSecurityChecks = true;
            string title   = values[0],
                   tags    = values[1],
                   content = values[2];
            var newsItem   = man.GetNewsItems().FirstOrDefault(i => i.Title == title);

            if (newsItem != null)
            {
                return;
            }
            newsItem = man.CreateNewsItem();
            var newsId = newsItem.Id;

            newsItem.Title   = title;
            newsItem.Content = content;
            var tag  = tMan.GetTaxa <FlatTaxon>().FirstOrDefault(i => i.Title == tags);
            var taxa = tMan.GetTaxonomy <FlatTaxonomy>(TaxonomyManager.TagsTaxonomyId);

            if (tag == null)
            {
                tag             = tMan.CreateTaxon <FlatTaxon>(Guid.NewGuid());
                tag.Title       = tags;
                tag.Name        = tags;
                tag.Description = "This tag categorizes the Breakfast";
                tag.UrlName     = new Lstring(Regex.Replace(tags, @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-").ToLower());
                taxa.Taxa.Add(tag);
            }

            newsItem.Organizer.AddTaxa("Tags", tag.Id);

            newsItem.DateCreated     = DateTime.UtcNow;
            newsItem.PublicationDate = DateTime.UtcNow;
            newsItem.LastModified    = DateTime.UtcNow;
            newsItem.UrlName         = Regex.Replace(title.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");

            //Recompiles and validates the url of the news item.
            man.RecompileAndValidateUrls(newsItem);

            //Save the changes.
            TransactionManager.CommitTransaction("123");

            //Publish the news item. The published version acquires new ID.
            var bag = new Dictionary <string, string>();

            bag.Add("ContentType", typeof(NewsItem).FullName);
            WorkflowManager.MessageWorkflow(newsId, typeof(NewsItem), null, "Publish", false, bag);
            man.Lifecycle.Publish(newsItem);
            man.SaveChanges();
        }
Esempio n. 10
0
        private bool ProcessImagesInternal(string providerName)
        {
            string           transactionName  = string.Format("imageoptimization_{0}", providerName);
            LibrariesManager librariesManager = LibrariesManager.GetManager(providerName, transactionName);
            bool             itemsProcessed   = false;
            int processedImages = 0;

            IEnumerable <Image> images = librariesManager.GetImages().Where(i => i.Status == ContentLifecycleStatus.Master && ((i.GetValue <object>(ImageOptimizationConstants.IsOptimizedFieldName) == null) || !i.GetValue <bool>(ImageOptimizationConstants.IsOptimizedFieldName))).Take(this.batchSize);

            foreach (var image in images)
            {
                try
                {
                    this.BuildTrace(string.Format("{0} - Attempting to optimize image {1} ({2})", DateTime.UtcNow.ToString("yyyy-MM-dd-T-HH:mm:ss"), image.Title, image.Id));

                    Image master = image;
                    Image temp   = librariesManager.Lifecycle.CheckOut(image) as Image;

                    Stream sourceImageStream = librariesManager.Download(image.Id);
                    librariesManager.Upload(temp, sourceImageStream, image.Extension, true);

                    temp.SetValue(ImageOptimizationConstants.IsOptimizedFieldName, true);

                    master = librariesManager.Lifecycle.CheckIn(temp) as Image;

                    ProcessReplacedImageTranslations(librariesManager, master);

                    if (master.ApprovalWorkflowState == "Published")
                    {
                        librariesManager.Lifecycle.Publish(master);
                    }

                    this.BuildTrace(string.Format("{0} - Image {1} ({2}) has been optimized", DateTime.UtcNow.ToString("yyyy-MM-dd-T-HH:mm:ss"), image.Title, image.Id));

                    if (processedImages % 5 == 0)
                    {
                        TransactionManager.CommitTransaction(transactionName);
                    }

                    processedImages += 1;
                }
                catch (Exception ex)
                {
                    this.BuildTrace(string.Format("Optimization of image {0} ({1}) failed with exception {2}", image.Title, image.Id, ex.Message), true);
                }

                this.WriteTraceLog();

                itemsProcessed = true;
            }

            TransactionManager.CommitTransaction(transactionName);

            return(itemsProcessed);
        }
Esempio n. 11
0
        /// <summary>
        /// Demonstrates how to update the database multiple times in the
        /// context of a transaction. All updates will succeed or all will be
        /// rolled back.
        /// </summary>
        private void transactionalUpdateButton_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;

            string   results = "";
            Products prod    = new Products();

            prod.DefaultCommandType = chkStoredProcedures.Checked ? System.Data.CommandType.StoredProcedure : System.Data.CommandType.Text;

            Employees emp = new Employees();

            emp.DefaultCommandType = chkStoredProcedures.Checked ? System.Data.CommandType.StoredProcedure : System.Data.CommandType.Text;

            // Update the requested product
            prod.LoadByPrimaryKey(4);
            prod.UnitsInStock += 1;

            // Update the requested employee
            emp.LoadByPrimaryKey(1);
            emp.s_Country = "CAN";

            // Retrieve the current transaction manager
            TransactionManager tx = TransactionManager.ThreadTransactionMgr();

            try
            {
                tx.BeginTransaction();

                // Save both objects within the same transaction
                emp.Save();
                prod.Save();

                // Deliberately throw an error, to cause the transaction to rollback
                throw new Exception("Deliberate exception, transaction rolled back.");

                tx.CommitTransaction();

                //this.DisplayResults(this.transactionalUpdateButton.Text, chkStoredProcedures.Checked ? "Stored Procedure" : emp.Query.LastQuery, results);
            }
            catch (Exception ex)
            {
                tx.RollbackTransaction();
                TransactionManager.ThreadTransactionMgrReset();
                this.DisplayResults(this.transactionalUpdateButton.Text, ex.Message);
            }

            Cursor = Cursors.Arrow;
        }
        public static void CreateStory(SuccessStoryWidgetViewModel successStoryWidgetViewModel)
        {
            var transactionName = "Submit";

            var providerName   = "OpenAccessDataProvider";
            var versionManager = VersionManager.GetManager(providerName, transactionName);

            var dynamicModuleProviderName             = "OpenAccessProvider";
            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(dynamicModuleProviderName, transactionName);

            using (new ElevatedModeRegion(dynamicModuleManager))  //ElevatedModeRegion is set to override access restrictions for given users
            {
                Type           successStoryType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.SuccessStories.SuccessStory");
                DynamicContent successStoryItem = dynamicModuleManager.CreateDataItem(successStoryType);

                successStoryItem.SetValue("Title", successStoryWidgetViewModel.Title);
                successStoryItem.SetValue("Description", successStoryWidgetViewModel.Description);
                successStoryItem.SetValue("SummaryDescription", successStoryWidgetViewModel.SummaryDescription);
                successStoryItem.SetValue("ProductsUsed", successStoryWidgetViewModel.ProductsUsed);
                successStoryItem.SetValue("Company", successStoryWidgetViewModel.Company);
                successStoryItem.SetValue("CompanyWebsite", successStoryWidgetViewModel.CompanyWebsite);
                successStoryItem.SetValue("Industry", successStoryWidgetViewModel.Industry);

                // Get related item manager
                LibrariesManager thumbnailManager = LibrariesManager.GetManager();

                var thumbnailItem = thumbnailManager.GetImages().FirstOrDefault(i => i.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Master);

                if (thumbnailItem != null)
                {
                    // This is how we relate an item
                    successStoryItem.CreateRelation(thumbnailItem, "Thumbnail");
                }

                //Trimming spaces from the Title, then setting it to Lowercase with the .ToLower() method, so it can be used as a unique URL for a newly submitted Success Story
                var urlName         = successStoryWidgetViewModel.Title;
                var urlNameNoSpaces = urlName.Replace(" ", "");

                successStoryItem.SetString("UrlName", urlNameNoSpaces.ToLower());
                successStoryItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
                successStoryItem.SetValue("PublicationDate", DateTime.UtcNow);

                successStoryItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft");

                versionManager.CreateVersion(successStoryItem, true);
                TransactionManager.CommitTransaction(transactionName);
            }
        }
Esempio n. 13
0
        protected void DeleteSearchIndex(string searchIndexName, Guid publishingPointId)
        {
            var transaction = Guid.NewGuid().ToString();
            var manager     = PublishingManager.GetManager(PublishingConfig.SearchProviderName, transaction);
            var pp          = manager.GetPublishingPoint(publishingPointId);

            foreach (var settings in pp.PipeSettings)
            {
                manager.DeletePipeSettings(settings);
            }
            manager.DeletePublishingPoint(pp);
            TransactionManager.CommitTransaction(transaction);

            var service = ServiceBus.ResolveService <ISearchService>();

            service.DeleteIndex(searchIndexName);
        }
        protected virtual object CloseUnitOfWork(MethodExecutionEventArgs eventArgs)
        {
            object transactionState = eventArgs.InstanceTag;

            if (eventArgs.Exception == null)
            {
                NHibernateSession.CurrentFor(FactoryKey).Flush();
                transactionState = TransactionManager.CommitTransaction(FactoryKey, transactionState);
            }
            else
            {
                transactionState = TransactionManager.RollbackTransaction(FactoryKey, transactionState);
            }
            transactionState = TransactionManager.PopTransaction(FactoryKey, transactionState);

            return(transactionState);
        }
Esempio n. 15
0
        public void AddTaxonomiesToListItem(Guid listItemId, IEnumerable <string> categories, IEnumerable <string> tags)
        {
            string       transactionName = "AddTaxonomiesToListItem";
            ListsManager listManager     = ListsManager.GetManager(string.Empty, transactionName);

            ListItem listItemMaster = listManager.GetListItems().Where(i => i.Id == listItemId).FirstOrDefault();

            if (listItemMaster == null)
            {
                throw new ItemNotFoundException(string.Format(CultureInfo.CurrentCulture, "List item with id {0} was not found.", listItemId));
            }

            ListItem listItemTemp = listManager.Lifecycle.CheckOut(listItemMaster) as ListItem;

            var taxonomyManager = TaxonomyManager.GetManager();

            if (categories != null)
            {
                if (categories.Count() > 0)
                {
                    HierarchicalTaxon category = null;
                    foreach (var c in categories)
                    {
                        category = taxonomyManager.GetTaxa <HierarchicalTaxon>().Single(t => t.Title == c);
                        listItemTemp.Organizer.AddTaxa("Category", category.Id);
                    }
                }
            }

            if (tags != null)
            {
                if (tags.Count() > 0)
                {
                    FlatTaxon tag = null;
                    foreach (var tg in tags)
                    {
                        tag = taxonomyManager.GetTaxa <FlatTaxon>().Single(t => t.Title == tg);
                        listItemTemp.Organizer.AddTaxa("Tags", tag.Id);
                    }
                }
            }

            listItemMaster = listManager.Lifecycle.CheckIn(listItemTemp) as ListItem;
            listManager.Lifecycle.Publish(listItemMaster);
            TransactionManager.CommitTransaction(transactionName);
        }
Esempio n. 16
0
        public void Update(DynamicContent entity, string changeComment)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            // Set a transaction name and get the version manager
            var transactionName = $"{entity.GetType().Name}-{DateTime.Now.Ticks}";

            applicationLogger.Info($"Updating entity with transaction name {transactionName} for {entity.UrlName}");
            var versionManager = VersionManager.GetManager(null, transactionName);

            CreateVersion(entity, changeComment, versionManager, WorkflowStatus.Draft);

            // Commit the transaction in order for the items to be actually persisted to data store
            TransactionManager.CommitTransaction(transactionName);
        }
Esempio n. 17
0
        /// <summary>
        /// Deletes all the products that correspond to the product in the master catalog
        /// as defined by the master id and master type.
        /// </summary>
        /// <param name="masterId">
        /// The id of the product in the master catalog that is being deleted.
        /// </param>
        /// <param name="masterType">
        /// The type of the product in the master catalog that is being deleted.
        /// </param>
        private void DeleteProductAccrossRegions(Guid masterId, Type masterType)
        {
            var transactionName   = "DeleteProductsRegional";
            var regionalProviders = this.GetRegionalCatalogProviders();

            foreach (var regionalProvider in regionalProviders)
            {
                var manager       = CatalogManager.GetManager(regionalProvider, transactionName);
                var regionalItems = manager.GetProducts(masterType.FullName)
                                    .Where(p => p.GetValue <string>("MasterId") == masterId.ToString());

                foreach (var regionalItem in regionalItems)
                {
                    manager.DeleteItem(regionalItem);
                }
            }

            TransactionManager.CommitTransaction(transactionName);
        }
        public async Task Handle(PersonDeletedEvent @event)
        {
            var person = @event.Person;
            var filter = CreateFilter(person);

            Transaction = TransactionManager.BeginTransaction();

            try
            {
                await HandleCategoryCounters(filter);
                await HandleCityCounters(person, filter);

                TransactionManager.CommitTransaction(Transaction);
            }
            catch (Exception e)
            {
                TransactionManager.RollBackTransaction(Transaction);
                throw e;
            }
        }
        public async Task Handle(PersonUpdatedEvent @event)
        {
            var oldPerson = @event.OldPersonData;
            var newPerson = @event.NewPersonData;
            var oldFilter = CreateFilter(oldPerson);
            var newFilter = CreateFilter(newPerson);

            Transaction = TransactionManager.BeginTransaction();

            try
            {
                await HandleCategoryCounters(oldFilter, newFilter);
                await HandleCityCounters(oldPerson.Address.City, newPerson.Address.City,
                                         oldFilter, newFilter);

                TransactionManager.CommitTransaction(Transaction);
            }
            catch (Exception e)
            {
                TransactionManager.RollBackTransaction(Transaction);
                throw e;
            }
        }
Esempio n. 20
0
        public void Publish(DynamicContent entity, string changeComment)
        {
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }

            //CodeReview: Consider audit / log transaction name as well, might be an useful instrument for prd troubleshooting.
            var transactionName = $"{entity.GetType().Name}-{DateTime.Now.Ticks}";

            applicationLogger.Info($"Publishing entity with transaction name {transactionName} for {entity.UrlName}");

            var versionManager = VersionManager.GetManager(null, transactionName);

            // You need to set appropriate workflow status
            // Now the item is published and can be seen in the page
            CreateVersion(entity, changeComment, versionManager, WorkflowStatus.Published);

            // We can now call the following to publish the item
            dynamicModuleManager.Lifecycle.Publish(entity);

            // Commit the transaction in order for the items to be actually persisted to data store
            TransactionManager.CommitTransaction(transactionName);
        }
Esempio n. 21
0
 /// <summary>
 ///     Applies the outstanding operations in the current transaction to the database.
 /// </summary>
 public virtual void CommitTransaction()
 => TransactionManager.CommitTransaction();
Esempio n. 22
0
        private void UpdateUser(string dataProviderName, string externalProviderName, string email, string externalId, string firstName, string lastName)
        {
            // Start transaction
            Guid   guid            = Guid.NewGuid();
            string transactionName = string.Concat("ExternalLoginUpdateUserTransaction", guid.ToString());

            UserManager userManager = UserManager.GetManager(dataProviderName, transactionName);
            var         user        = userManager.GetUser(email);

            if (user == null)
            {
                return;
            }
            bool updateIsRequired = false;

            if (user.ExternalProviderName != externalProviderName)
            {
                user.ExternalProviderName = externalProviderName;
                updateIsRequired          = true;
            }
            if (user.ExternalId != externalId)
            {
                user.ExternalId  = externalId;
                updateIsRequired = true;
            }

            // Update user roles
            List <string> autoAssignedRoles = (
                from s in Config.Get <AuthenticationConfig>().SecurityTokenService
                .AuthenticationProviders[externalProviderName].AutoAssignedRoles
                .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries)
                select s.Trim()).ToList();

            RoleManager roleManager = RoleManager.GetManager(string.Empty, transactionName);
            List <Role> roles       = roleManager.GetRoles().ToList();

            foreach (string newRole in autoAssignedRoles.Distinct())
            {
                Role role = (
                    from r in roles
                    where r.Name == newRole
                    select r).FirstOrDefault();

                if (role == null)
                {
                    continue;
                }
                roleManager.AddUserToRole(user, role);
                updateIsRequired = true;
            }

            // Update user profile
            UserProfileManager profileManager = UserProfileManager.GetManager(string.Empty, transactionName);
            SitefinityProfile  userProfile    = profileManager.GetUserProfile <SitefinityProfile>(user) ??
                                                profileManager.CreateProfile(user,
                                                                             "Telerik.Sitefinity.Security.Model.SitefinityProfile") as
                                                SitefinityProfile;

            if (userProfile != null)
            {
                userProfile.FirstName = firstName;
                userProfile.LastName  = lastName;
                updateIsRequired      = true;
            }

            // Commit transaction
            if (updateIsRequired)
            {
                profileManager.RecompileItemUrls(userProfile);
                TransactionManager.CommitTransaction(transactionName);
            }
        }
Esempio n. 23
0
        public void Upload(TorrentUploaderWidgetModel torrent)
        {
            string torrentExtention = Path.GetExtension(torrent.TorrentFile.FileName);
            string torrentTitle     = Path.GetFileNameWithoutExtension(torrent.TorrentFile.FileName);
            Guid   torrentFileId    = this._documentService.UploadTorrentFile(torrentTitle, torrent.TorrentFile.InputStream, torrent.TorrentFile.FileName, torrentExtention, TORRENT_FILE_LIBRARY);

            string imageExtention = Path.GetExtension(torrent.CoverImage.FileName);
            string imageTitle     = Path.GetFileNameWithoutExtension(torrent.CoverImage.FileName);
            Guid   torrentImageId = this._imageService.Upload(imageTitle, torrent.CoverImage.InputStream, torrent.CoverImage.FileName, imageExtention, TORRENT_COVER_IMAGE_ALBUM);

            // Set the provider name for the DynamicModuleManager here. All available providers are listed in
            // Administration -> Settings -> Advanced -> DynamicModules -> Providers
            var providerName = String.Empty;

            // Set a transaction name and get the version manager
            var transactionName = "someTransactionName";
            var versionManager  = VersionManager.GetManager(null, transactionName);

            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName, transactionName);
            Type           torrentType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Torrents.Torrent");
            DynamicContent torrentItem = dynamicModuleManager.CreateDataItem(torrentType);

            // This is how values for the properties are set
            torrentItem.SetValue("Title", torrent.Title);
            torrentItem.SetValue("Description", torrent.Description);

            LibrariesManager torrentFileManager = LibrariesManager.GetManager();
            var torrentFileItem = torrentFileManager.GetDocuments().FirstOrDefault(i => i.Id == torrentFileId && i.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Master);

            if (torrentFileItem != null)
            {
                torrentItem.CreateRelation(torrentFileItem, "TorrentFile");
            }

            LibrariesManager imageManager = LibrariesManager.GetManager();
            var imageItem = imageManager.GetImages().FirstOrDefault(i => i.Id == torrentImageId && i.Status == Telerik.Sitefinity.GenericContent.Model.ContentLifecycleStatus.Master);

            if (imageItem != null)
            {
                torrentItem.CreateRelation(imageItem, "Image");
            }

            torrentItem.SetString("UrlName", Guid.NewGuid().ToString());
            torrentItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
            torrentItem.SetValue("PublicationDate", DateTime.UtcNow);

            // Create a version and commit the transaction in order changes to be persisted to data store
            torrentItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft");

            // Create a version and commit the transaction in order changes to be persisted to data store
            versionManager.CreateVersion(torrentItem, false);

            // We can now call the following to publish the item
            ILifecycleDataItem publishedTorrentItem = dynamicModuleManager.Lifecycle.Publish(torrentItem);

            // You need to set appropriate workflow status
            torrentItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Published");

            // Create a version and commit the transaction in order changes to be persisted to data store
            versionManager.CreateVersion(torrentItem, true);



            TransactionManager.CommitTransaction(transactionName);
        }
Esempio n. 24
0
        public string CreateSuccessStory(SuccessStoryViewModel submittedStory, string domain)
        {
            var message = String.Empty;

            try
            {
                var providerName = String.Empty;

                var transactionName = $"storyTransaction_{DateTime.Now}";
                var versionManager  = VersionManager.GetManager(null, transactionName);

                DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName, transactionName);
                Type           successStoryType           = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.SuccessStories.SuccessStory");
                DynamicContent successStoryItem           = dynamicModuleManager.CreateDataItem(successStoryType);

                successStoryItem.SetValue("Title", submittedStory.Title);
                successStoryItem.SetValue("Description", submittedStory.Description);
                successStoryItem.SetValue("SummaryDescription", submittedStory.SummaryDescription);
                successStoryItem.SetValue("ProductsUsed", submittedStory.ProductsUsed);
                successStoryItem.SetValue("Company", submittedStory.Company);
                successStoryItem.SetValue("CompanyWebsite", submittedStory.CompanyWebsite);
                successStoryItem.SetValue("Industry", submittedStory.Industry);

                LibrariesManager thumbnailManager = LibrariesManager.GetManager();

                if (submittedStory.Thumbnail != null)
                {
                    var fileStream = submittedStory.Thumbnail.InputStream;
                    var imgId      = Guid.NewGuid();
                    CreateImageWithNativeAPI(imgId, submittedStory.Title, fileStream, submittedStory.Thumbnail.FileName, Path.GetExtension(submittedStory.Thumbnail.FileName));
                    var thumbnailItem = thumbnailManager.GetImage(imgId);
                    if (thumbnailItem != null)
                    {
                        successStoryItem.CreateRelation(thumbnailItem, "Thumbnail");
                    }
                }

                successStoryItem.SetString("UrlName", $"{submittedStory.Title}-{submittedStory.Company}");
                successStoryItem.SetValue("Owner", SecurityManager.GetCurrentUserId());
                successStoryItem.SetValue("PublicationDate", DateTime.UtcNow);

                successStoryItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft");

                versionManager.CreateVersion(successStoryItem, false);

                ILifecycleDataItem publishedCarItem = dynamicModuleManager.Lifecycle.Publish(successStoryItem);

                successStoryItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Published");

                versionManager.CreateVersion(successStoryItem, true);

                TransactionManager.CommitTransaction(transactionName);
                message = $"A new Success Story has been submitted. Take a look <a style=\"font-weight:bold;color:blue;\" href=\"{domain}/success-story-details{successStoryItem.ItemDefaultUrl.Value}\">here</a>";
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            }

            return(message);
        }
Esempio n. 25
0
        internal static void CreatePost(SocialPost item, Taxon taxa)
        {
            try
            {
                var providerName = DynamicModuleManager.GetDefaultProviderName("Telerik.Sitefinity.DynamicTypes.Model.UserGeneratedContent.SocialPost");

                // Set a transaction name and get the version manager
                var transactionName = new Guid().ToString();
                var versionManager  = VersionManager.GetManager(null, transactionName);

                DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName, transactionName);
                Type postType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.UserGeneratedContent.SocialPost");

                var itemFilter = String.Format("NetworkUrl = \"{0}\"", item.url);
                var checkItem  = dynamicModuleManager.GetDataItems(postType).Where(itemFilter);

                if (checkItem.Count() > 0 || item.image.IsNullOrWhitespace())
                {
                    return;
                }

                dynamicModuleManager.Provider.SuppressSecurityChecks = true;

                DynamicContent socialPostItem = dynamicModuleManager.CreateDataItem(postType);

                // This is how values for the properties are set
                //postItem.SetValue("Title", String.Format("{0}: {1}", item.User.Username, item.Id));
                socialPostItem.SetValue("Title", item.image);
                socialPostItem.SetValue("Text", item.text);
                socialPostItem.SetValue("Network", item.network);
                socialPostItem.SetValue("NetworkUrl", item.url);
                socialPostItem.Organizer.AddTaxa("searchhashtags", taxa.Id);
                socialPostItem.SetValue("SearchId", item.id);
                socialPostItem.SetValue("SocialUser", JsonConvert.SerializeObject(item.user, Formatting.Indented));
                socialPostItem.SetValue("ImageUrl", item.image);
                socialPostItem.SetValue("Highlight", false);
                socialPostItem.SetValue("Type", item.type);

                var posted = DateTime.UtcNow;
                DateTime.TryParseExact(item.posted.Replace("+00000", "").Trim(), "yyyy-MM-dd hh:mm:ss", CultureInfo.CurrentCulture, DateTimeStyles.None, out posted);
                //DateTime.TryParseExact(item.posted.Replace("+00000","").Trim(), "yyyy-MM-dd hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out posted);

                if (posted < DateTime.UtcNow.AddYears(-1))
                {
                    posted = DateTime.UtcNow;
                }

                socialPostItem.SetValue("Posted", posted);

                socialPostItem.SetString("UrlName", Guid.NewGuid().ToString());
                socialPostItem.SetValue("PublicationDate", DateTime.UtcNow);


                socialPostItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "AwaitingApproval");

                // Create a version and commit the transaction in order changes to be persisted to data store
                versionManager.CreateVersion(socialPostItem, false);
                TransactionManager.CommitTransaction(transactionName);

                dynamicModuleManager.Provider.SuppressSecurityChecks = false;
            }
            catch (Exception)
            {
                return;
            }
        }
Esempio n. 26
0
        public PagedResult <ExerciseDTO> GetExercises(ExerciseSearchCriteria searchCriteria, PartialRetrievingInfo retrievingInfo)
        {
            Log.WriteWarning("GetExercises:Username={0},Search-UserId:{1},SearchGroups:{2}", SecurityInfo.SessionData.Profile.UserName, searchCriteria.UserId, searchCriteria.SearchGroups.Count);
            var session = Session;

            //Profile _profile = null;
            Exercise _exercise = null;

            using (var transactionScope = new TransactionManager(true))
            {
                var myProfile = session.Load <Profile>(SecurityInfo.SessionData.Profile.GlobalId);
                if (searchCriteria.UserId.HasValue)
                {
                    myProfile = session.Load <Profile>(searchCriteria.UserId.Value);
                }

                var ids = myProfile.FavoriteExercises.Select(x => x.GlobalId).ToList();

                var queryExercises = session.QueryOver <Exercise>(() => _exercise).Where(x => !x.IsDeleted);

                if (searchCriteria.ExerciseTypes.Count > 0)
                {
                    var langOr = Restrictions.Disjunction();
                    foreach (var lang in searchCriteria.ExerciseTypes)
                    {
                        langOr.Add <Exercise>(x => x.ExerciseType == (ExerciseType)lang);
                    }
                    queryExercises = queryExercises.And(langOr);
                }

                if (!string.IsNullOrEmpty(searchCriteria.Name))
                {
                    queryExercises = queryExercises.Where(Restrictions.InsensitiveLike("Name", searchCriteria.Name + "%"));
                }


                if (searchCriteria.SearchGroups.Count > 0)
                {
                    Disjunction mainOr = Restrictions.Disjunction();
                    if (searchCriteria.SearchGroups.IndexOf(ExerciseSearchCriteriaGroup.Global) > -1)
                    {
                        Log.WriteVerbose("Search: global");
                        mainOr.Add <Exercise>(dto => dto.Profile == null);
                    }
                    if (searchCriteria.SearchGroups.IndexOf(ExerciseSearchCriteriaGroup.Mine) > -1)
                    {
                        Log.WriteVerbose("Search: mine");
                        mainOr.Add <Exercise>(dto => dto.Profile == myProfile);
                    }
                    if (searchCriteria.SearchGroups.IndexOf(ExerciseSearchCriteriaGroup.Other) > -1)
                    {
                        Log.WriteVerbose("Search: other");
                        mainOr.Add <Exercise>(dto => dto.Profile != null && dto.Profile != myProfile);
                    }
                    if (searchCriteria.SearchGroups.IndexOf(ExerciseSearchCriteriaGroup.Favorites) > -1)
                    {
                        if (ids.Count > 0)
                        {
                            mainOr.Add <BodyArchitect.Model.TrainingPlan>(x => x.GlobalId.IsIn((ICollection)ids));
                        }
                    }
                    queryExercises = queryExercises.Where(mainOr);
                }

                //if (searchCriteria.UserId.HasValue)
                //{
                //    queryExercises = queryExercises.Where(dto => dto.Profile == myProfile);
                //}
                queryExercises = queryExercises.ApplySorting(searchCriteria.SortOrder, searchCriteria.SortAscending);

                var res1 = (from rv in session.Query <RatingUserValue>()
                            from tp in session.Query <Exercise>()
                            where tp.GlobalId == rv.RatedObjectId &&
                            rv.ProfileId == SecurityInfo.SessionData.Profile.GlobalId
                            select rv).ToDictionary(t => t.RatedObjectId);

                var listPack = queryExercises.ToPagedResults <ExerciseDTO, Exercise>(retrievingInfo, null,
                                                                                     delegate(IEnumerable <Exercise> list)
                {
                    var output = new List <ExerciseDTO>();
                    foreach (var planDto in list)
                    {
                        var tmp = planDto.Map <ExerciseDTO>();
                        if (res1.ContainsKey(planDto.GlobalId))
                        {
                            tmp.UserRating       = res1[planDto.GlobalId].Rating;
                            tmp.UserShortComment = res1[planDto.GlobalId].ShortComment;
                        }
                        output.Add(tmp);
                    }
                    return(output.ToArray());
                });
                transactionScope.CommitTransaction();
                return(listPack);
            }
        }
Esempio n. 27
0
        public void CreateTorrentWithPublish(CreateTorrentDto createTorrentDto)
        {
            // Set the provider name for the DynamicModuleManager here. All available providers are listed in
            // Administration -> Settings -> Advanced -> DynamicModules -> Providers
            var providerName = "OpenAccessProvider";

            // Set a transaction name and get the version manager
            var transactionName = "someTransactionName";
            var versionManager  = VersionManager.GetManager(null, transactionName);

            DynamicModuleManager dynamicModuleManager = DynamicModuleManager.GetManager(providerName, transactionName);
            Type           torrentType = TypeResolutionService.ResolveType("Telerik.Sitefinity.DynamicTypes.Model.Torrents.Torrent");
            DynamicContent torrentItem = dynamicModuleManager.CreateDataItem(torrentType);

            // This is how values for the properties are set
            torrentItem.SetValue("AdditionalInfo", createTorrentDto.AdditionalInfo);
            torrentItem.SetValue("Description", createTorrentDto.Description);
            torrentItem.SetValue("Title", createTorrentDto.Title);
            torrentItem.SetValue("CreationDate", DateTime.Now);

            List <Guid> taxonIds = _taxonomyService.GetTaxonIdsByTaxonomy(createTorrentDto.Genres, Constants.GenresTaxonomyName);

            if (taxonIds.Any())
            {
                torrentItem.Organizer.AddTaxa(Constants.GenresTaxonomyName, taxonIds.ToArray());
            }

            Image imageFileItem = _imageService.CreateImageWithNativeAPI(createTorrentDto.ImageDto);

            if (imageFileItem != null)
            {
                // This is how we relate an item
                torrentItem.CreateRelation(imageFileItem, "ImageFile");
            }

            Document torrentFileItem = _documentService.CreateDocumentNativeAPI(createTorrentDto.DocumentDto);

            if (torrentFileItem != null)
            {
                // This is how we relate an item
                torrentItem.CreateRelation(torrentFileItem, "TorrentFile");
            }

            torrentItem.SetString("UrlName", $"{createTorrentDto.Title}{torrentItem.Id}");
            torrentItem.SetValue("Owner", ClaimsManager.GetCurrentIdentity().UserId);
            torrentItem.SetValue("PublicationDate", DateTime.UtcNow);

            torrentItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Draft");

            // Create a version and commit the transaction in order changes to be persisted to data store
            versionManager.CreateVersion(torrentItem, false);

            // We can now call the following to publish the item
            ILifecycleDataItem publishedTorrentItem = dynamicModuleManager.Lifecycle.Publish(torrentItem);

            // You need to set appropriate workflow status
            torrentItem.SetWorkflowStatus(dynamicModuleManager.Provider.ApplicationName, "Published");

            // Create a version and commit the transaction in order changes to be persisted to data store
            versionManager.CreateVersion(torrentItem, true);

            // Now the item is published and can be seen in the page

            // Commit the transaction in order for the items to be actually persisted to data store
            TransactionManager.CommitTransaction(transactionName);
        }