Ejemplo n.º 1
0
 private static string PageUrl(this UrlHelper urlHelper, PageReference pageLink, object routeValues, IContentRepository contentRepository)
 {
     if (contentRepository == null)
         contentRepository = ServiceLocator.Current.GetInstance<IContentRepository>();
     if (PageReference.IsNullOrEmpty(pageLink))
         return string.Empty;
     PageData page = contentRepository.Get<PageData>((ContentReference)pageLink);
     return UrlExtensions.PageUrl(urlHelper, page, routeValues);
 }
Ejemplo n.º 2
0
        protected PageData FindParentByPageType(PageData pd, Type pagetype, IContentRepository contentLocator)
        {
            if (pd is BlogStartPage)
            {
                return pd;
            }
            return FindParentByPageType(contentLocator.Get<PageData>(pd.ParentLink), pagetype, contentLocator);

        }
Ejemplo n.º 3
0
        private static List<ContentFolder> GetFolders(IContentRepository contentRepository)
        {
            var folders = new List<ContentFolder>();
            folders.Add(contentRepository.Get<ContentFolder>(SiteDefinition.Current.GlobalAssetsRoot));

            if (ImageOptimizationSettings.Instance.IncludeContentAssets)
            {
                folders.Add(contentRepository.Get<ContentFolder>(SiteDefinition.Current.ContentAssetsRoot));
            }
            return folders;
        }
        private static void DeleteBlobs(IEnumerable<ContentReference> contentReferences, IContentRepository repo, StringBuilder sb,
            BlobFactory blobFactory)
        {
            foreach (ContentReference reference in contentReferences)
            {
                ImageFile file = null;
                try
                {
                    file = repo.Get<ImageFile>(reference);
                }
                catch
                {
                }
                if (file != null)
                {

                    IContentVersionRepository versionRepo = ServiceLocator.Current.GetInstance<IContentVersionRepository>();
                    IEnumerable<ContentVersion> versions = versionRepo.List(file.ContentLink);
                    foreach (ContentVersion version in versions)
                    {
                        var versionOfFile = repo.Get<ImageFile>(version.ContentLink);
                        if (versionOfFile != null)
                        {
                            DeleteBlobInstances(sb, blobFactory, versionOfFile);
                        }
                    }

                    sb.AppendFormat("{0}<br>", file.Name);

                    // Delete old versions
                    DeleteOldVersions(file, sb);
                }
            }
        }
        protected void GetEntry_Click(object sender, EventArgs e)
        {
            try
            {
                this.ResetPanels();

                _repo = ServiceLocator.Current.GetInstance<IContentRepository>();
                _referenceConverter = ServiceLocator.Current.GetInstance<ReferenceConverter>();

                var content = _repo.Get<CatalogContentBase>(_referenceConverter.GetContentLink(Code.Value));

                ErrorMessage.Text = (content is PackageContent).ToString();

                string code = Code.Value;
                var entry = CatalogContext.Current.GetCatalogEntry(
                    code, new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.Children));

                if (entry == null)
                    throw new Exception(string.Format("No style or variant found with code {0}", code));

                DisplayVariant(entry);

            }
            catch (Exception ex)
            {
                ErrorMessage.Text = ex.Message;
                ErrorPanel.Visible = true;
            }
        }
Ejemplo n.º 6
0
 public Content Get(int id)
 {
     return(_contentRepository.Get(id));
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Method used to pull serachable content from ContentAreas and lists of ContentReferences
        /// </summary>
        /// <param name="contentData"></param>
        public List <CrawlerContent> ProcessContentReferences(ContentData contentData)
        {
            var list = new List <CrawlerContent>();

            if (contentData == null)
            {
                return(list);
            }

            var pageProps = contentData.GetType().GetProperties();


            foreach (var pageProp in pageProps)
            {
                try {
                    if (pageProp.Name == "ContentLink")
                    {
                        continue;
                    }

                    if (pageProp.Name == "Item")
                    {
                        continue;
                    }

                    //_logger.Debug(string.Format("Processing {0}", pageProp.Name));

                    var propValue = pageProp.GetValue(contentData);

                    if (propValue == null)
                    {
                        continue;
                    }

                    switch (pageProp.PropertyType.Name)
                    {
                    case "ContentArea":

                        var refContentArea = propValue as ContentArea;

                        if (refContentArea == null)
                        {
                            continue;
                        }

                        foreach (var contentRef in refContentArea.Items)
                        {
                            var blockData = Repository.Get <IContent>(contentRef.ContentLink) as BlockData;

                            if (blockData != null)
                            {
                                var fields = ParseBlockData(blockData);

                                if (fields.Any())
                                {
                                    list.AddRange(fields);
                                }
                            }
                        }

                        break;


                    case "IList`1":

                        var refList = propValue as IList <ContentReference>;

                        if (refList == null)
                        {
                            continue;
                        }

                        foreach (var contentRef in refList)
                        {
                            var blockData = Repository.Get <IContent>(contentRef) as BlockData;

                            if (blockData != null)
                            {
                                var fields = ParseBlockData(blockData);

                                if (fields.Any())
                                {
                                    list.AddRange(fields);
                                }
                            }
                        }

                        break;

                    case "ContentReference":

                        var blockRef = propValue as ContentReference;

                        var blockData1 = Repository.Get <IContent>(blockRef) as BlockData;

                        if (blockData1 != null)
                        {
                            var fields = ParseBlockData(blockData1);

                            if (fields.Any())
                            {
                                list.AddRange(fields);
                            }
                        }

                        break;


                    default:

                        var blockData2 = propValue as BlockData;

                        if (blockData2 != null)
                        {
                            var blockFields = ParseBlockData(blockData2);

                            if (blockFields.Any())
                            {
                                list.AddRange(blockFields);
                            }
                        }


                        break;
                    }
                }
                catch (Exception ex)
                {
                    _logger.Error(string.Format("{0} \"{1}\" {2}", ex.Message, pageProp.Name, ex.StackTrace));
                }
            }


            return(list);
        }
        public ActionResult Index(CheckoutPage currentPage, CheckoutViewModel model, PaymentInfo paymentInfo, int[] SelectedCategories)
        {
            model.PaymentInfo         = paymentInfo;
            model.AvailableCategories = GetAvailableCategories();
            model.SelectedCategories  = SelectedCategories;

            bool requireSSN = paymentInfo.SelectedPayment == new Guid("8dca4a96-a5bb-4e85-82a4-2754f04c2117") ||
                              paymentInfo.SelectedPayment == new Guid("c2ea88f8-c702-4331-819e-0e77e7ac5450");

            // validate input!
            ValidateFields(model, requireSSN);

            CartHelper ch = new CartHelper(Cart.DefaultName);

            // Verify that we actually have the items we're about to sell
            ConfirmStocks(ch.LineItems);

            if (ModelState.IsValid)
            {
                var    billingAddress  = model.BillingAddress.ToOrderAddress(Constants.Order.BillingAddressName);
                var    shippingAddress = model.ShippingAddress.ToOrderAddress(Constants.Order.ShippingAddressName);
                string username        = model.Email.Trim();
                billingAddress.Email = username;
                billingAddress.DaytimePhoneNumber = model.Phone;

                HandleUserCreation(model, billingAddress, shippingAddress, username);

                if (ModelState.IsValid)
                {
                    // Checkout:

                    ch.Cart.OrderAddresses.Add(billingAddress);
                    ch.Cart.OrderAddresses.Add(shippingAddress);

                    AddShipping(ch.Cart, shippingAddress);

                    ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.CustomerClub] = model.MemberClub;
                    if (model.SelectedCategories != null)
                    {
                        ch.Cart.OrderForms[0][Constants.Metadata.OrderForm.SelectedCategories] = string.Join(",", model.SelectedCategories);
                    }
                    OrderGroupWorkflowManager.RunWorkflow(ch.Cart, OrderGroupWorkflowManager.CartPrepareWorkflowName);

                    AddPayment(ch.Cart, paymentInfo.SelectedPayment.ToString(), billingAddress);

                    ch.Cart.AcceptChanges();

                    BasePaymentPage page      = null;
                    var             startPage = _contentRepository.Get <HomePage>(ContentReference.StartPage);
                    foreach (var p in _contentRepository.GetChildren <BasePaymentPage>(startPage.Settings.PaymentContainerPage))
                    {
                        if (p.PaymentMethod.Equals(model.PaymentInfo.SelectedPayment.ToString()))
                        {
                            page = p;
                            break;
                        }
                    }

                    var resolver = ServiceLocator.Current.GetInstance <UrlResolver>();

                    if (page != null)
                    {
                        var url = resolver.GetUrl(page.ContentLink);
                        return(Redirect(url));
                    }
                }
            }

            Guid?selectedPayment = model.PaymentInfo.SelectedPayment;

            model.PaymentInfo = GetPaymentInfo();
            if (selectedPayment.HasValue)
            {
                model.PaymentInfo.SelectedPayment = selectedPayment.Value;
            }
            model.TermsArticle = currentPage.TermsArticle;

            return(View(model));
        }
Ejemplo n.º 9
0
        public ActionResult Preview(long id)
        {
            var content = _contentRepository.Get(id);

            return(Json(content.ContentHtml, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 10
0
        public void Initialize(InitializationEngine context)
        {
            // this returns empty if one of your sites does not have a * wildcard hostname
            ContentReference startReference = ContentReference.StartPage;

            // we can use the site definition repo to get the first site's start page instead
            if (ContentReference.IsNullOrEmpty(startReference))
            {
                var siteRepo  = context.Locate.Advanced.GetInstance <ISiteDefinitionRepository>();
                var firstSite = siteRepo.List().FirstOrDefault();
                if (firstSite == null)
                {
                    return;                    // if no sites, give up running this module
                }
                startReference = firstSite.StartPage;
            }

            string enabledString = ConfigurationManager.AppSettings["alloy:CreatePages"];
            bool   enabled;

            if (bool.TryParse(enabledString, out enabled))
            {
                if (enabled)
                {
                    IContentRepository repo = context.Locate.Advanced.GetInstance <IContentRepository>();

                    // create About Us page
                    StandardPage aboutUs;

                    IContent content = repo.GetBySegment(
                        startReference, "about-us",
                        CultureInfo.GetCultureInfo("en"));

                    if (content == null)
                    {
                        aboutUs = repo.GetDefault <StandardPage>(startReference);

                        aboutUs.Name            = "About us";
                        aboutUs.MetaTitle       = "About us title";
                        aboutUs.MetaDescription = "Alloy improves the effectiveness of project teams by putting the proper tools in your hands. Communication is made easy and inexpensive, no matter where team members are located.";
                        aboutUs.MainBody        = new XhtmlString(aboutUs.MetaDescription);
                        aboutUs.SortIndex       = 400;

                        repo.Save(aboutUs, SaveAction.Publish, AccessLevel.NoAccess);
                    }

                    // get the \For All Sites\Products\ folder
                    ContentFolder productsFolder = repo.GetBySegment(
                        ContentReference.GlobalBlockFolder, "Products",
                        CultureInfo.GetCultureInfo("en")) as ContentFolder;

                    // create Alloy Meet page
                    ProductPage alloyMeet;

                    content = repo.GetBySegment(
                        startReference, "alloy-meet",
                        CultureInfo.GetCultureInfo("en"));

                    if (content == null)
                    {
                        alloyMeet = repo.GetDefault <ProductPage>(startReference);

                        alloyMeet.Name                = "Alloy Meet";
                        alloyMeet.MetaDescription     = "You've never had a meeting like this before!";
                        alloyMeet.MainBody            = new XhtmlString("Participants from remote locations appear in your meeting room, around your table, or stand presenting at your white board.");
                        alloyMeet.Theme               = "theme1";
                        alloyMeet.UniqueSellingPoints = new[]
                        {
                            "Project tracking",
                            "White board sketch",
                            "Built-in reminders",
                            "Share meeting results",
                            "Email interface to request meetings"
                        };
                        alloyMeet.SortIndex = 100;
                        alloyMeet.PageImage = repo.GetBySegment(
                            productsFolder.ContentLink, "AlloyMeet.png",
                            CultureInfo.GetCultureInfo("en")).ContentLink;

                        repo.Save(alloyMeet, SaveAction.Publish, AccessLevel.NoAccess);
                    }

                    // create Alloy Plan page
                    ProductPage alloyPlan;

                    content = repo.GetBySegment(
                        startReference, "alloy-plan",
                        CultureInfo.GetCultureInfo("en"));

                    if (content == null)
                    {
                        alloyPlan = repo.GetDefault <ProductPage>(startReference);

                        alloyPlan.Name                = "Alloy Plan";
                        alloyPlan.MetaDescription     = "Project management has never been easier!";
                        alloyPlan.MainBody            = new XhtmlString("Planning is crucial to the success of any project. Alloy Plan takes into consideration all aspects of project planning; from well-defined objectives to staffing, capital investments and management support. Nothing is left to chance.");
                        alloyPlan.Theme               = "theme2";
                        alloyPlan.UniqueSellingPoints = new[]
                        {
                            "Project planning",
                            "Reporting and statistics",
                            "Email handling of tasks",
                            "Risk calculations",
                            "Direct communication to members"
                        };
                        alloyPlan.SortIndex = 200;
                        alloyPlan.PageImage = repo.GetBySegment(
                            productsFolder.ContentLink, "AlloyPlan.png",
                            CultureInfo.GetCultureInfo("en")).ContentLink;

                        repo.Save(alloyPlan, SaveAction.Publish, AccessLevel.NoAccess);
                    }

                    // create Alloy Track page
                    ProductPage alloyTrack;

                    content = repo.GetBySegment(
                        startReference, "alloy-track",
                        CultureInfo.GetCultureInfo("en"));

                    if (content == null)
                    {
                        alloyTrack = repo.GetDefault <ProductPage>(startReference);

                        alloyTrack.Name                = "Alloy Track";
                        alloyTrack.MetaDescription     = "Projects have a natural lifecycle with well-defined stages.";
                        alloyTrack.MainBody            = new XhtmlString("From start-up meetings to final sign-off, we have the solutions for today’s market-driven needs. Leverage your assets to the fullest through the combination of Alloy Plan, Alloy Meet and Alloy Track.");
                        alloyTrack.Theme               = "theme3";
                        alloyTrack.UniqueSellingPoints = new[]
                        {
                            "Shared timeline",
                            "Project emails",
                            "To-do lists",
                            "Workflows",
                            "Status reports"
                        };
                        alloyTrack.SortIndex = 300;
                        alloyTrack.PageImage = repo.GetBySegment(
                            productsFolder.ContentLink, "AlloyTrack.png",
                            CultureInfo.GetCultureInfo("en")).ContentLink;

                        repo.Save(alloyTrack, SaveAction.Publish, AccessLevel.NoAccess);
                    }

                    // change Start page sort order for children
                    if (repo.Get <StartPage>(startReference)
                        .CreateWritableClone() is StartPage startPage)
                    {
                        startPage.ChildSortOrder = FilterSortOrder.Index;
                        repo.Save(startPage, SaveAction.Publish, AccessLevel.NoAccess);
                    }
                }
            }
        }
        public ContentReference CreateVersions(string defaultName)
        {
            var editorialBlock1 = CreateEditorialBlock(1, ContentReference.GlobalBlockFolder);
            var editorialBlock2 = CreateEditorialBlock(1, ContentReference.GlobalBlockFolder);
            var editorialBlock3 = CreateEditorialBlock(1, ContentReference.GlobalBlockFolder);
            // create standard page
            var standardPage = _contentRepository.GetDefault <StandardPage>(ContentReference.StartPage);

            standardPage.Name            = defaultName;
            standardPage.MetaDescription = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut rhoncus turpis laoreet nisl pulvinar, vitae ultricies ligula dictum. Quisque feugiat viverra ipsum quis convallis.";
            standardPage.MainBody        = new XhtmlString("Etiam convallis in arcu eu tincidunt. Ut laoreet eu ante at laoreet. Cras auctor metus sed nunc rutrum tincidunt ut vel erat. Suspendisse in finibus augue.");
            standardPage.MainContentArea = new ContentArea()
            {
                Items =
                {
                    new ContentAreaItem
                    {
                        ContentLink = ((IContent)editorialBlock1).ContentLink
                    },
                    new ContentAreaItem
                    {
                        ContentLink = ((IContent)editorialBlock2).ContentLink
                    },
                    new ContentAreaItem
                    {
                        ContentLink = ((IContent)editorialBlock3).ContentLink
                    }
                }
            };
            SaveAction saveAction2      = (SaveAction.SkipValidation | SaveAction.Publish) & SaveAction.ActionMask;
            var        contentReference = _contentRepository.Save(standardPage, saveAction2, AccessLevel.NoAccess);

            var assetsFolderContentLink = _contentChangeManager.GetOrCreateContentAssetsFolder(contentReference);

            MoveEditorialBlock(editorialBlock1, assetsFolderContentLink);
            MoveEditorialBlock(editorialBlock2, assetsFolderContentLink);
            MoveEditorialBlock(editorialBlock3, assetsFolderContentLink);

            ContextCache.Current["CurrentITransferContext"] = (object)this;
            ContextCache.Current["PageSaveDB:PageSaved"]    = (object)true;


            // create versions for contnts
            var currentDate = DateTime.Now;

            for (var i = 1; i < 30; i++)
            {
                UpdateEditorialBlock(editorialBlock1, currentDate.AddMonths(-i));
                if (i % 2 != 0)
                {
                    UpdateEditorialBlock(editorialBlock2, currentDate.AddMonths(-i).AddDays(-i % 5 + 1));
                }
                if (i % 3 != 0)
                {
                    UpdateEditorialBlock(editorialBlock3, currentDate.AddMonths(-i).AddDays(-i % 3 + 1));
                }
            }

            standardPage = _contentRepository.Get <StandardPage>(contentReference);
            // create versions for standard page
            for (var i = 1; i < 15; i++)
            {
                var clone   = (StandardPage)standardPage.CreateWritableClone();
                var newDate = currentDate.AddMonths(-i * 2).AddDays(-1);
                clone.Name = clone.Name + " " + newDate.ToString("yyyy-MM-dd");

                var changeTrackable = clone as IChangeTrackable;
                changeTrackable.Saved               = newDate;
                changeTrackable.Changed             = newDate;
                changeTrackable.Created             = newDate;
                changeTrackable.SetChangedOnPublish = true;

                IContent contentData = (IContent)clone;
                contentData.ContentLink = contentData.ContentLink.ToReferenceWithoutVersion();
                contentData.ContentGuid = Guid.Empty;

                (clone as IVersionable).StartPublish = newDate;

                _contentRepository.Save(contentData, saveAction2, AccessLevel.NoAccess);
            }

            return(contentReference);
        }
Ejemplo n.º 12
0
        public override ActionResult Index(MyPageBlock currentBlock)
        {
            var model = new MyPageBlockViewModel <MyPageBlock>(currentBlock);

            string email       = Request.QueryString["email"];
            string code        = Request.QueryString["code"];
            string cancelEvent = Request.QueryString["cancelEvent"];
            string editEvent   = Request.QueryString["editEvent"];

            if (email.IsNullOrEmpty() || code.IsNullOrEmpty())
            {
                return(View("~/Modules/BVNetwork.Attend/Views/Blocks/MyPageBlock/EmptyView.cshtml", model));  //No results found, code not matching email.
            }
            var currentParticipant = BVNetwork.Attend.Business.API.AttendRegistrationEngine.GetParticipant(email, code);

            if (currentParticipant == null)
            {
                return(View("~/Modules/BVNetwork.Attend/Views/Blocks/MyPageBlock/EmptyView.cshtml", model));
            }


            ////Set name
            if (currentParticipant != null)
            {
                model.ParticipantName = currentParticipant.Username;
            }


            //Cancel event?
            if (cancelEvent == "true" && currentParticipant != null)
            {
                var entry = (currentParticipant as BlockData).CreateWritableClone() as ParticipantBlock;
                if (entry.AttendStatus != AttendStatus.Cancelled.ToString())
                {
                    entry.AttendStatus = AttendStatus.Cancelled.ToString();
                    ParticipantLog.AddLogText("Status change", "Status changed to ", entry);
                    _contentRepository.Save(entry as IContent, SaveAction.Publish, AccessLevel.NoAccess);
                    AttendRegistrationEngine.SendStatusMail(entry);
                    return(View("~/Modules/BVNetwork.Attend/Views/Blocks/MyPageBlock/Cancelled.cshtml", model));
                }
            }

            model.RegistrationCode = code;
            model.Email            = email;
            model.CurrentBlock     = currentBlock;

            //Edit event?
            if (editEvent == "true" && currentParticipant != null)
            {
                model.CurrentEvent     = _contentRepository.Get <EventPageBase>(currentParticipant.EventPage);
                model.PredefinedValues = currentParticipant.XForm;
                return(View("~/Modules/BVNetwork.Attend/Views/Blocks/MyPageBlock/EditEvent.cshtml", model));  //Edit event
            }


            var entries = BVNetwork.Attend.Business.API.AttendRegistrationEngine.GetParticipantByEmail(email);

            model.AllEntries      = new List <ParticipantBlock>();
            model.UpcomingEntries = new List <ParticipantBlock>();
            model.PastEntries     = new List <ParticipantBlock>();

            foreach (var entry in entries)
            {
                if (entry.EventPage == null || entry.EventPage == PageReference.EmptyReference)
                {
                    continue;
                }
                model.AllEntries.Add(entry as ParticipantBlock);

                var eventPage = BVNetwork.Attend.Business.API.AttendRegistrationEngine.GetEventPageBase(entry);
                if ((eventPage).EventDetails.EventEnd > DateTime.Now) //&& (entry.AttendStatus.Contains(AttendStatus.Confirmed.ToString()) || entry.AttendStatus == AttendStatus.Submitted.ToString() || entry.AttendStatus == AttendStatus.Standby.ToString()))
                {
                    model.UpcomingEntries.Add(entry as ParticipantBlock);
                }
                else
                {
                    model.PastEntries.Add(entry as ParticipantBlock);
                }
            }
            model.UpcomingEntries = model.UpcomingEntries.OrderBy(x => x.EventPageData().EventDetails.EventEnd).ToList();

            if (model.UpcomingEntries.Count == 0)
            {
                return(View("~/Modules/BVNetwork.Attend/Views/Blocks/MyPageBlock/EmptyView.cshtml", model));  //No results found, code not matching email.
            }

            var pageRouteHelper = EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance <EPiServer.Web.Routing.PageRouteHelper>();

            model.CurrentPage = pageRouteHelper.Page;

            return(View("~/Modules/BVNetwork.Attend/Views/Blocks/MyPageBlock/Index.cshtml", model));  //No results found, code not matching email.
        }
        private MediaData CreateNewFile(InRiverImportResource inriverResource)
        {
            ResourceMetaField resourceFileId = inriverResource.MetaFields.FirstOrDefault(m => m.Id == "ResourceFileId");

            if (String.IsNullOrEmpty(resourceFileId?.Values.FirstOrDefault()?.Data))
            {
                _logger.Debug("ResourceFileId is null, won't do stuff.");
                return(null);
            }

            _logger.Debug($"Attempting to create and import file from path: {inriverResource.Path}");

            var fileInfo = new FileInfo(inriverResource.Path);

            IEnumerable <Type> mediaTypes = _contentMediaResolver.ListAllMatching(fileInfo.Extension).ToList();

            _logger.Debug($"Found {mediaTypes.Count()} matching media types for extension {fileInfo.Extension}.");

            Type contentTypeType = mediaTypes.FirstOrDefault(x => x.GetInterfaces().Contains(typeof(IInRiverResource))) ??
                                   _contentMediaResolver.GetFirstMatching(fileInfo.Extension);

            if (contentTypeType == null)
            {
                _logger.Warning($"Can't find suitable content type when trying to import {inriverResource.Path}");
            }

            else
            {
                _logger.Debug($"Chosen content type-type is {contentTypeType.Name}.");
            }

            ContentType contentType = _contentTypeRepository.Load(contentTypeType);

            var newFile = _contentRepository.GetDefault <MediaData>(GetFolder(fileInfo, contentType), contentType.ID);

            newFile.Name        = fileInfo.Name;
            newFile.ContentGuid = EpiserverEntryIdentifier.EntityIdToGuid(inriverResource.ResourceId);

            // ReSharper disable once SuspiciousTypeConversion.Global
            if (newFile is IInRiverResource resource)
            {
                resource.ResourceFileId = Int32.Parse(resourceFileId.Values.First().Data);
                resource.EntityId       = inriverResource.ResourceId;

                try
                {
                    resource.HandleMetaData(inriverResource.MetaFields);
                }
                catch (Exception exception)
                {
                    _logger.Error($"Error when running HandleMetaData for resource {inriverResource.ResourceId} with contentType {contentType.Name}: {exception.Message}");
                }
            }

            Blob blob = _blobFactory.CreateBlob(newFile.BinaryDataContainer, fileInfo.Extension);

            using (Stream stream = blob.OpenWrite())
            {
                FileStream fileStream = File.OpenRead(fileInfo.FullName);
                fileStream.CopyTo(stream);
                fileStream.Dispose();
            }

            newFile.BinaryData = blob;

            _logger.Debug($"New mediadata is ready to be saved: {newFile.Name}, from path {inriverResource.Path}");

            ContentReference contentReference = _contentRepository.Save(newFile, SaveAction.Publish, AccessLevel.NoAccess);
            var mediaData = _contentRepository.Get <MediaData>(contentReference);

            _logger.Debug($"Saved file {fileInfo.Name} with Content ID {contentReference?.ID}.");

            return(mediaData);
        }
        public async Task <ActionResult> Index(
            ContentApprovalsManagerPage currentPage,
            string task, int?stepIndex, string user, string decision)
        {
            var viewmodel = new ContentApprovalsManagerViewModel(currentPage);

            if (!string.IsNullOrWhiteSpace(task))
            {
                switch (task)
                {
                case "createDefinition":

                    var all     = new[] { CultureInfo.InvariantCulture };
                    var english = new[] { CultureInfo.GetCultureInfo("en") };
                    var swedish = new[] { CultureInfo.GetCultureInfo("sv") };

                    var def = new ContentApprovalDefinition
                    {
                        ContentLink = ContentReference.StartPage,
                        Steps       = new List <ApprovalDefinitionStep>
                        {
                            new ApprovalDefinitionStep(
                                "Alice reviews English, Bob reviews Swedish", new[]
                            {
                                new ApprovalDefinitionReviewer(userName1, english),
                                new ApprovalDefinitionReviewer(userName2, swedish),
                            }),
                            new ApprovalDefinitionStep(
                                "Editors (Eve or Bob) reviews all languages", new[]
                            {
                                new ApprovalDefinitionReviewer(editors, all, ApprovalDefinitionReviewerType.Role)
                            })
                        },
                        RequireCommentOnReject = true
                    };

                    await repoDefinitions.SaveAsync(def);

                    break;

                case "modifyStart":

                    var approvalToDelete = await repoApprovals.GetAsync(ContentReference.StartPage);

                    if (approvalToDelete != null)
                    {
                        await repoApprovals.DeleteAsync(approvalToDelete.ID);
                    }

                    var start = repoContent.Get <StartPage>(ContentReference.StartPage)
                                .CreateWritableClone() as StartPage;

                    start.Name += "X";

                    repoContent.Save(content: start,
                                     action: SaveAction.RequestApproval,
                                     access: AccessLevel.NoAccess);

                    break;

                case "processStep":

                    var approval = await repoApprovals.GetAsync(ContentReference.StartPage);

                    if (decision == "Approve")
                    {
                        await engine.ApproveStepAsync(
                            id : approval.ID,
                            username : user,
                            stepIndex : stepIndex.Value,
                            comment : "I approve: the page looks great!");
                    }
                    else
                    {
                        await engine.RejectStepAsync(
                            id : approval.ID,
                            username : user,
                            stepIndex : stepIndex.Value,
                            comment : "I decline: the page looks horrible!");
                    }
                    break;

                case "deleteApprovals":

                    var list = await repoApprovals.ListAsync(new ApprovalQuery());

                    foreach (var item in list)
                    {
                        await repoApprovals.DeleteAsync(item.ID);
                    }

                    break;
                }
            }

            // GetAsync(ContentReference) extension methods need
            // using EPiServer.Approvals.ContentApprovals
            viewmodel.ApprovalDefinition = await repoDefinitions.GetAsync(ContentReference.StartPage);

            viewmodel.Approval = await repoApprovals.GetAsync(ContentReference.StartPage);

            return(View("~/Features/ContentApprovals/ContentApprovalsManager.cshtml", viewmodel));
        }
        protected void WalkCategoryTree(NodeContent node, 
            IContentRepository repository, 
            CatalogContentLoader contentLoader, 
            ICatalogSystem catalog,
            ReferenceConverter referenceConverter)
        {
            // ReSharper disable PossibleMultipleEnumeration
            // Get all products
            Stopwatch tmr = Stopwatch.StartNew();
            IEnumerable<EntryContentBase> entries = repository.GetChildren<EPiServer.Commerce.Catalog.ContentTypes.EntryContentBase>(node.ContentLink);
            _log.Debug("Loaded {0} entries in category {1} using IContentRepository in {2}ms",
                            entries.Count(),
                            node.Name,
                            tmr.ElapsedMilliseconds);

            // Load and cache Entry objects. Still a lot of code that uses this
            tmr = Stopwatch.StartNew();
            foreach (EntryContentBase entryAsContent in entries)
            {
                // Load full entry
                int entryId = referenceConverter.GetObjectId(entryAsContent.ContentLink);
                // Catalog Gadget uses info
                //catalog.GetCatalogEntry(entryId,
                //	new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryInfo));
                catalog.GetCatalogEntry(entryId,
                    new CatalogEntryResponseGroup(CatalogEntryResponseGroup.ResponseGroup.CatalogEntryFull));
            }

            // Prime the catalog gadget
            // IEnumerable<IContent> children = repository.GetChildren<IContent>(node.ContentLink, new LanguageSelector("en"), 0, int.MaxValue);
            // _log.Debug("Loaded {0} children", children.Count());

            // .GetDescendents(node.ContentLink);

            tmr.Stop();
            _log.Debug("Loaded {0} entries in category {1} using ICatalogSystem in {2}ms",
                            entries.Count(),
                            node.Name,
                            tmr.ElapsedMilliseconds);

            // Get all products the way it is done in edit mode, but this does not seem to
            // use the cache.
            //int loadedEntries;
            //contentLoader.GetCatalogEntries(node.ContentLink, 0, int.MaxValue, out loadedEntries);
            //_log.Debug("Loaded {0} entries in category {1} using CatalogContentLoader", loadedEntries, node.Name);

            // Get child nodes the same way done by the UI
            IList<GetChildrenReferenceResult> catalogNodes = contentLoader.GetCatalogNodes(node.ContentLink);
            _log.Debug("Loaded {0} categories in category {1} using CatalogContentLoader", catalogNodes.Count, node.Name);
            foreach (GetChildrenReferenceResult catalogNode in catalogNodes)
            {
                NodeContent childNode = repository.Get<NodeContent>(catalogNode.ContentLink);
                WalkCategoryTree(childNode, repository, contentLoader, catalog, referenceConverter);
            }
            // ReSharper restore PossibleMultipleEnumeration
        }