Exemple #1
0
 public ActionResult Create(ContentViewModel contentViewModel)
 {
     if (ModelState.IsValid)
     {
         _contentService.CreateContent(contentViewModel);
     }
     return(View());
 }
Exemple #2
0
        /// <summary>
        /// Updates or adds the content item. If content item already exists, it updates it.
        /// If content item doesn't exists, it creates new content item (in that case contentItem.Id will be set to newly created id).
        /// NOTE: Set the ParentId property of this item.
        /// </summary>
        /// <param name="contentItem">Content item to update/add</param>
        /// <param name="userId">User used for add or updating the content</param>
        /// <param name="publish">If set to <c>true</c> it contentItem will be published as well.</param>
        public static void Save(DocumentTypeBase contentItem, int userId, bool publish)
        {
            if (contentItem.ParentId < 1)
            {
                throw new ArgumentException("Parent property cannot be null");
            }

            if (String.IsNullOrEmpty(contentItem.Name))
            {
                throw new Exception("Name property of this content item is not set");
            }

            IContentType contentType = DocumentTypeManager.GetDocumentType(contentItem.GetType());

            IContent content;

            if (contentItem.Id == 0) // content item is new so create Document
            {
                content = ContentService.CreateContent(contentItem.Name, contentItem.ParentId, contentType.Alias);
            }
            else // content item already exists, so load it
            {
                content = ContentService.GetById(contentItem.Id);
            }

            var documentTypeProperties = contentItem.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            SaveProperties(contentItem, contentType, content, documentTypeProperties);

            if (publish)
            {
                ContentService.SaveAndPublish(content, userId);
                contentItem.Id = content.Id;
            }
        }
Exemple #3
0
        public ActionResult Create(string Groups, int Type, string Name, string Description, IEnumerable <HttpPostedFileBase> Files, DateTime BeginDate, DateTime EndDate, bool IsBroadcast = false, HttpPostedFileBase imageFile = null)
        {
            try
            {
                var IdsGroup = GetIdsFromString(Groups);

                var            FilesDTO        = GetFiles(Files);
                HttpFileStream imageFileStream = null;
                if (imageFile != null)
                {
                    imageFileStream = new HttpFileStream()
                    {
                        InputStream = imageFile.InputStream,
                        Name        = imageFile.FileName
                    };
                }
                ContentService.CreateContent(IdsGroup, null, Type, Name, Description, FilesDTO, BeginDate, EndDate, IsBroadcast, imageFileStream);
                InternalNotification.Success("Material Created");
            }
            catch (Exception ex)
            {
                InternalNotification.Error(ex);
            }
            return(RedirectToAction("index"));
        }
Exemple #4
0
        private int CreateContent(string template, XElement webNode, int parentId)
        {
            string title = webNode.Element("Label").Value;
            string esdId = webNode.Element("Identifier").Value;

            var node = _contentService.CreateContent(title, parentId, template);

            if (node != null)
            {
                if (node.HasProperty("title"))
                {
                    node.SetValue("title", title);
                }

                if (node.HasProperty("esdServiceId"))
                {
                    node.SetValue("esdServiceId", esdId);
                }

                if (node.HasProperty("sectionName"))
                {
                    node.SetValue("sectionName", title);
                }

                _contentService.SaveAndPublishWithStatus(node, 0, false);
                _nodeCount++;
                return(node.Id);
            }
            _lastError = "Error Creating Content";
            return(-1);
        }
        public HttpResponseMessage Post([FromBody] SeasonPass Data)
        {
            JsonResponse Response = new JsonResponse(true, new SecureContext());

            Response.Create();

            if (Response.IsAuthentic == true)
            {
                IContentService Service = Services.ContentService;

                var Pass = Service.CreateContent(EncDecService.Hash(Data.ID), 1121, "seasonPass");
                Pass.SetValue("passID", EncDecService.Hash(Data.ID));
                Pass.SetValue("holderName", EncDecService.Encrypt(Data.Holder));
                Pass.SetValue("validFrom", Convert.ToDateTime(Data.ValidFrom));
                Pass.SetValue("validTo", Convert.ToDateTime(Data.ValidTo));
                Pass.SetValue("acquiredOn", Convert.ToDateTime(Data.AcquiredOn));

                string ResponseMessage;

                if (Service.SaveAndPublishWithStatus(Pass))
                {
                    ResponseMessage = "The content has been successfully saved.";
                }
                else
                {
                    ResponseMessage = "An error occured while saving the season pass.";
                }

                Response.Set(new StringContent(ResponseMessage, ApiContext.GetEncoding(), "text/plain"));
            }

            return(Response.Get());
        }
Exemple #6
0
        public bool CreateLog(Form formModel)
        {
            bool result = false;

            if (formModel.IsSaveLog)
            {
                var formContent   = contentService.GetById(formModel.Id);
                var logCollection = formContent.Children().Where(c => c.ContentType.Alias == NodeAlias.LogCollection).FirstOrDefault();
                var logName       = DateTime.Now.ToString("yyyy-MM-dd - hh:mm:ss tt");
                if (formModel.LogName != null)
                {
                    var logNameQuery = formModel.Fields.Where(f => f.Id == formModel.LogName.Id).FirstOrDefault();
                    if (logNameQuery != null)
                    {
                        if (!string.IsNullOrEmpty(logNameQuery.Value))
                        {
                            logName = string.Format("{0} [{1}]", logName, logNameQuery.Value);
                        }
                    }
                }
                if (logCollection != null)
                {
                    IContent logNode = contentService.CreateContent(logName, logCollection, NodeAlias.Log, 0);

                    if (logNode.HasProperty(PropertyAlias.LogDetail))
                    {
                        string logDetail = GetLogDetail(formModel);
                        logNode.SetValue(PropertyAlias.LogDetail, logDetail);
                    }
                    result = contentService.SaveAndPublishWithStatus(logNode);
                }
            }
            return(result);
        }
Exemple #7
0
        public void SyncDataVnexpress()
        {
            IContentService contentService = Services.ContentService;
            var             parent         = contentService.GetById(1166);
            var             news           = CrawlerHtml();

            var pageNewsInDb = Umbraco.Content(1166).Children.ToList();

            try
            {
                foreach (var item in news)
                {
                    var anyNew = pageNewsInDb.Where(x => x.GetProperty("title").Value().Equals(item.Title))?.ToList();
                    if (anyNew.Count <= 0)
                    {
                        var message = contentService.CreateContent($"{item.Title}-{DateTime.Now}", parent.GetUdi(), "new");

                        message.SetValue("title", item.Title);
                        message.SetValue("description", item.Description);
                        message.SetValue("content", item.Content);
                        message.SetValue("image", item.LinkImage);

                        Services.ContentService.SaveAndPublish(message);
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
Exemple #8
0
        public IHttpActionResult CommitVote([FromBody] Vote data)
        {
            try
            {
                //validate vote
                bool validates = ValidateVote(data.IMEI, data.MatchId, data.PlayerId);
                if (validates)
                {
                    string message = "m:" + data.MatchId.ToString() + ", p:" + data.PlayerId.ToString() + ", IMEI: " + data.IMEI.ToString();
                    //create vote object
                    var vote = cs.CreateContent(message, data.VoteBatchId, "vote");

                    //set vote properties
                    vote.Properties["IMEI"].Value     = data.IMEI;
                    vote.Properties["matchId"].Value  = data.MatchId;
                    vote.Properties["playerId"].Value = data.PlayerId;

                    cs.Publish(vote);
                    cs.Save(vote);
                    return(StatusCode(HttpStatusCode.Created));
                }
                if (!validates)
                {
                    return(StatusCode(HttpStatusCode.Conflict));
                }
            }
            catch (Exception e)
            {
                Console.Write(e.Message);
            }
            return(StatusCode(HttpStatusCode.BadRequest));
        }
Exemple #9
0
        private int?CreateContent(Item item, int parentId, int userId = 0)
        {
            var contentTypes = _contentTypeService.GetAllContentTypeAliases();
            var contentType  = contentTypes.FirstOrDefault(x => item.NodeType.Ref.Replace(" ", "").ToLower().Contains(x.ToLower()));
            var content      = _contentService.CreateContent(item.Name, parentId, contentType, userId);

            return(content.Id);
        }
Exemple #10
0
        /// <summary>
        /// Add a simple content tree to the install
        /// </summary>
        public static IContent Node(IContentService contentService, int parentId = -1, string typeAlias = "textpage")
        {
            IContent node = contentService.CreateContent(Utility.RandomString(), parentId, typeAlias);

            contentService.SaveAndPublishWithStatus(node);

            return(node);
        }
Exemple #11
0
        /// <summary>
        /// Get the correct parent node for a news item
        /// It will create if it needs to
        /// </summary>
        private int GetParentNodeForNewsItem(IContentService contentService, IContent blogPostsFolder, DateTime date)
        {
            int parentID;

            //Create year folder if not present
            if (blogPostsFolder.Children().Where(x => x.GetValue <int>("year") == date.Year).Count() != 1)
            {
                var yearFolder = contentService.CreateContent(date.Year.ToString(), blogPostsFolder.Id, "USNBlogYearFolder");
                yearFolder.SetValue("year", date.Year.ToString());
                contentService.SaveAndPublishWithStatus(yearFolder);

                //Create month folder if not present
                if (yearFolder.Children().Where(x => x.GetValue <int>("month") == date.Month).Count() != 1)
                {
                    var monthFolder = contentService.CreateContent(date.ToString("MMMM", CultureInfo.CreateSpecificCulture("en")), yearFolder.Id, "USNBlogMonthFolder");
                    monthFolder.SetValue("month", date.Month.ToString());
                    contentService.SaveAndPublishWithStatus(monthFolder);
                    parentID = monthFolder.Id;
                }
                else
                {
                    var monthFolder = yearFolder.Children().Where(x => x.GetValue <int>("month") == date.Month).First();
                    parentID = monthFolder.Id;
                }
            }
            else
            {
                var yearFolder = blogPostsFolder.Children().Where(x => x.GetValue <int>("year") == date.Year).First();

                if (yearFolder.Children().Where(x => x.GetValue <int>("month") == date.Month).Count() != 1)
                {
                    var monthFolder = contentService.CreateContent(date.ToString("MMMM", CultureInfo.CreateSpecificCulture("en")), yearFolder.Id, "USNBlogMonthFolder");
                    monthFolder.SetValue("disableDelete", 1);
                    monthFolder.SetValue("month", date.Month.ToString());
                    contentService.SaveAndPublishWithStatus(monthFolder);
                    parentID = monthFolder.Id;
                }
                else
                {
                    var monthFolder = yearFolder.Children().Where(x => x.GetValue <int>("month") == date.Month).First();
                    parentID = monthFolder.Id;
                }
            }

            return(parentID);
        }
Exemple #12
0
        internal static IContent GetOrCreateContent(IContentType contentType, string contentName, IContentTypeService contentTypeService, IContentService contentService, IContent parentContent, List <IContent> contentList)
        {
            var content = contentService.GetContentOfContentType(contentType.Id).FirstOrDefault(x => !x.Trashed);

            if (content == null)
            {
                if (parentContent == null)
                {
                    content = contentService.CreateContent(contentName, -1, contentType.Alias);
                }
                else
                {
                    content = contentService.CreateContent(contentName, parentContent, contentType.Alias);
                }
                contentList.Add(content);
            }
            return(content);
        }
        private IContent CreatePageComponentsFolder(IContent node, bool returnNode)
        {
            var  filter = _sqlContent.Query <IContent>().Where(x => x.Name == "Components");
            long totalChildren;
            var  pageComponentsNode = _contentService.GetPagedChildren(node.Id, 0, 1, out totalChildren, filter: filter).FirstOrDefault();

            if (pageComponentsNode == null)
            {
                var pageComponentsNodeNew = _contentService.CreateContent("Components", node.GetUdi(), USNConstants.PageComponentsFolderAlias);
                pageComponentsNodeNew.SetValue(USNConstants.GeneralDisableDeleteFieldAlias, true);

                return(pageComponentsNodeNew);
            }
            else
            {
                return(returnNode ? pageComponentsNode : null);
            }
        }
        private void CreateVideo(GuidUdi parentUdi, string title, string thumbnailUrl, string videoUrl)
        {
            var video = _contentService.CreateContent(title, parentUdi, "video");

            video.SetValue("title", title);
            video.SetValue("videoThumbnailImageURL", thumbnailUrl);
            video.SetValue("videoLinkURL", videoUrl);

            _contentService.SaveAndPublish(video);
        }
        private void CreatePage()
        {
            var groupsOverviewPage = _umbracoHelper.TypedContentSingleAtXPath(XPathHelper.GetXpath(DocumentTypeAliasConstants.HomePage, DocumentTypeAliasConstants.GroupsOverviewPage));

            var content = _contentService.CreateContent("My Groups", groupsOverviewPage.Id, DocumentTypeAliasConstants.GroupsMyGroupsOverviewPage);

            content.SetValue(NavigationPropertiesConstants.NavigationNamePropName, "My Groups");
            content.SetValue(NavigationPropertiesConstants.IsHideFromLeftNavigationPropName, false);
            content.SetValue(NavigationPropertiesConstants.IsHideFromSubNavigationPropName, false);

            _contentMigration.SetGridValueAndSaveAndPublishContent(content, "groupsMyGroupsOverviewPageGrid.json");
        }
        /// <summary>
        /// Method to create an IContent object based on the Udi of a parent
        /// </summary>
        /// <param name="contentService"></param>
        /// <param name="name"></param>
        /// <param name="parentId"></param>
        /// <param name="mediaTypeAlias"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static IContent CreateContent(this IContentService contentService, string name, Udi parentId, string mediaTypeAlias, int userId = 0)
        {
            var guidUdi = parentId as GuidUdi;

            if (guidUdi == null)
            {
                throw new InvalidOperationException("The UDI provided isn't of type " + typeof(GuidUdi) + " which is required by content");
            }
            var parent = contentService.GetById(guidUdi.Guid);

            return(contentService.CreateContent(name, parent, mediaTypeAlias, userId));
        }
        public PlayerViewModel AddNewPlayer(PlayerViewModel newPlayer)
        {
            int nodeID = 2077;

            //get node info to add in
            var     playersNodeName = Umbraco.Content(nodeID).Name;
            var     playersNodeGuid = Umbraco.Content(nodeID).Key;
            GuidUdi currentPageUdi  = new GuidUdi(playersNodeName, playersNodeGuid);

            //create content node
            var data = _contentService.CreateContent(playersNodeName, currentPageUdi, UmbracoAliasConfiguration.Player.Alias, 0);

            //define properties
            data.Name = newPlayer.Name;
            data.SetValue(UmbracoAliasConfiguration.Player.PlayerName, newPlayer.Name);
            data.SetValue(UmbracoAliasConfiguration.Player.PlayerAge, newPlayer.Age);

            _contentService.SaveAndPublish(data);

            return(newPlayer);
        }
Exemple #18
0
 public async Task <string> CreateContent([FromBody] ContentModel model)
 {
     try
     {
         return(await contentService.CreateContent(model));
     }
     catch (Exception ex)
     {
         logger.LogError(ex, "Cannot set content");
         throw;
     }
 }
Exemple #19
0
 public ActionResult Create(Content _content)
 {
     try
     {
         _ContentService.CreateContent(_content);
         return(RedirectToAction("Index2"));
     }
     catch
     {
         return(View("Index"));
     }
 }
        public int GetItemTypeFolderId(int libraryFolderId, string itemTypeFolderDoctypeAlias, string selectedTypeName)
        {
            var libraryFolder = _contentService.GetById(libraryFolderId);

            IContent itemTypeFolder = null;
            string   itemTypeFolderDoctypeName;

            if (selectedTypeName.Contains(' '))
            {
                var words = selectedTypeName.Split(' ');

                var pluralisedLastWord = _pluralizationServiceWrapper.Pluralize(_variationContextAccessor.VariationContext.Culture, words.Last());

                itemTypeFolderDoctypeName = $"{string.Join(" ", words.Take(words.Length - 1))} {pluralisedLastWord}";
            }
            else
            {
                itemTypeFolderDoctypeName = _pluralizationServiceWrapper.Pluralize(_variationContextAccessor.VariationContext.Culture, selectedTypeName);
            }

            var       pageIndex   = 0;
            const int pageSize    = 100;
            var       children    = _pagingHelper.GetPagedChildren(_contentService, libraryFolder.Id, pageIndex, pageSize, out var totalRecords);
            var       hasNextPage = _pagingHelper.HasNextPage(pageIndex, pageSize, totalRecords);

            while (hasNextPage)
            {
                itemTypeFolder = children.SingleOrDefault(x => x.Name == itemTypeFolderDoctypeName);
                if (itemTypeFolder != null)
                {
                    break;
                }

                pageIndex++;
                children    = _pagingHelper.GetPagedChildren(_contentService, libraryFolder.Id, pageIndex, pageSize, out totalRecords);
                hasNextPage = _pagingHelper.HasNextPage(pageIndex, pageSize, totalRecords);
            }

            if (itemTypeFolder == null)
            {
                itemTypeFolder = _contentService.CreateContent(itemTypeFolderDoctypeName, libraryFolder.GetUdi(), itemTypeFolderDoctypeAlias);

                var publish = _contentService.SaveAndPublish(itemTypeFolder);
                if (publish.Result != PublishResultType.SuccessPublish)
                {
                    throw new Exception($"Creating the 'Bento Block Type Folder' named '{itemTypeFolderDoctypeName}s' failed");
                }
            }

            return(itemTypeFolder.Id);
        }
Exemple #21
0
        public ActionResult SubmitComment(int idProject, string userComment, string contentComment, string typeSubmit = "main-submit",
                                          int idMainPage = 0)
        {
            IContentService contentService = Services.ContentService;

            try
            {
                if (typeSubmit == "main-submit")
                {
                    var parent  = contentService.GetById(idProject);
                    var comment = contentService.CreateContent($"{userComment}-{DateTime.Now}", parent.GetUdi(), "comment");
                    comment.SetValue("nameComment", userComment);
                    comment.SetValue("time", DateTime.Now);
                    comment.SetValue("idComment", Guid.NewGuid());
                    comment.SetValue("commentContent", contentComment);

                    Services.ContentService.SaveAndPublish(comment);
                }
                else
                {
                    var parent  = contentService.GetById(idProject);
                    var comment = contentService.CreateContent($"{userComment}-{DateTime.Now}", parent.GetUdi(), "replyComment");
                    comment.SetValue("nameUserReply", userComment);
                    comment.SetValue("timeReply", DateTime.Now);
                    comment.SetValue("iDReplyComment", Guid.NewGuid());
                    comment.SetValue("contentReply", contentComment);

                    Services.ContentService.SaveAndPublish(comment);
                    return(RedirectToUmbracoPage(idMainPage));
                }
            }
            catch (Exception)
            {
                TempData["error-message"] = "Submit Failed !";
            }

            return(RedirectToUmbracoPage(idProject));
        }
Exemple #22
0
        public void SendNotiIntoUmbra(ContactModel contactModel)
        {
            IContentService contentService = Services.ContentService;
            var             parent         = contentService.GetById(1098);

            var message = contentService.CreateContent($"{contactModel.Name}-{DateTime.Now}", parent.GetUdi(), "contactContent");

            message.SetValue("nameUser", contactModel.Name);
            message.SetValue("email", contactModel.Email);
            message.SetValue("phoneNumber", contactModel.PhoneNumber);
            message.SetValue("message", contactModel.Message);

            Services.ContentService.SaveAndPublish(message);
        }
        private void CreateForbiddenErrorPage()
        {
            var homePage   = _umbracoHelper.TypedContentAtRoot().Single(el => el.DocumentTypeAlias.Equals(DocumentTypeAliasConstants.HomePage));
            var errorPages = homePage.Children.Where(el => el.DocumentTypeAlias.Equals(DocumentTypeAliasConstants.ErrorPage));

            if (errorPages.Any(ep => ep.Name == ForbiddenPageName))
            {
                return;
            }

            var content = _contentService.CreateContent(ForbiddenPageName, homePage.Id, DocumentTypeAliasConstants.ErrorPage);

            SetGridValueAndSaveAndPublishContent(content, "forbiddenPageGrid.json");
        }
        public IEnumerable <int> GetAndEnsureNodeIdsForTags(string currentNodeId, string tags, int containerId, string documentTypeAlias)
        {
            if (string.IsNullOrWhiteSpace(tags))
            {
                return(new List <int>());
            }

            // put posted tags in an array
            string[] postedTags = tags.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

            // get the current node
            IContent node = cs.GetById(int.Parse(currentNodeId));

            // get all existing tag nodes in container
            IContent tagContainer = cs.GetById(containerId);
            IEnumerable <IContent> allTagNodes = tagContainer.Children().Where(x => x.ContentType.Alias == documentTypeAlias);

            bool hasNewTags = false;

            foreach (string postedTag in postedTags)
            {
                // get tag names which do not already exist in the tag container
                bool found = allTagNodes.Any(x => x.Name == postedTag);
                if (!found)
                {
                    // tag node doesnt exist so create new node
                    var dic = new Dictionary <string, object>()
                    {
                        { documentTypeAlias, postedTag }
                    };
                    IContent newTag = cs.CreateContent(postedTag, tagContainer.Id, documentTypeAlias);
                    cs.SaveAndPublishWithStatus(newTag);
                    hasNewTags = true;
                }
            }

            // re-get container because new nodes might have been added.
            tagContainer = cs.GetById(containerId);
            if (hasNewTags)
            {
                // new tag so sort!
                cs.Sort(tagContainer.Children().OrderBy(x => x.Name));
            }

            // get all tag ids, and return
            IEnumerable <int> tagIds = tagContainer.Children().Where(x => postedTags.Contains(x.Name)).Select(x => x.Id);

            return(tagIds);
        }
Exemple #25
0
 public async Task <JsonResult> New(ContentInputViewModel contentInputViewModel, string id)
 {
     if (CurrentUserId == 0)
     {
         await TryAuthenticateFromHttpContext(_communityService, _notificationService);
     }
     if (ModelState.IsValid)
     {
         var contentDetails = new ContentDetails();
         contentDetails.SetValuesFrom(contentInputViewModel);
         contentDetails.CreatedByID = CurrentUserId;
         contentInputViewModel.ID   = contentDetails.ID = _contentService.CreateContent(contentDetails);
     }
     return(new JsonResult {
         Data = contentInputViewModel
     });
 }
Exemple #26
0
        public void SyncDataVnexpress()
        {
            IContentService contentService = Services.ContentService;
            var             parent         = contentService.GetById(1166);
            var             news           = CrawlerHtml();

            foreach (var item in news)
            {
                var message = contentService.CreateContent($"{item.Title}-{DateTime.Now}", parent.GetUdi(), "new");
                message.SetValue("title", item.Title);
                message.SetValue("description", item.Description);
                message.SetValue("content", item.Content);
                message.SetValue("image", item.LinkImage);

                Services.ContentService.SaveAndPublish(message);
            }
        }
Exemple #27
0
        private static int CreateCategoryNode(UCategory uCategory, int contentNodeParentId)
        {
            // create new content
            var content = _cs.CreateContent(uCategory.Name, contentNodeParentId, "ProductListing");

            // set content properties based on data from Able
            content.SetValue("headline", uCategory.Title);
            content.SetValue("metaDescription", uCategory.MetaDescription);
            content.SetValue("metaKeywords", uCategory.MetaKeywords);
            content.SetValue("pageTitle", uCategory.Title);
            content.SetValue("bodyText", uCategory.Description);
            content.SetValue("summary", uCategory.Summary);

            // publish content so we can get nodeId
            _cs.Publish(content);

            return(content.Id);
        }
        public static void MakeProduct(UProduct prod, int contentNodeParentId, Guid merchelloGuid)
        {
            // create new content
            var content = _cs.CreateContent(prod.Name.Trim(), contentNodeParentId, "Product");

            // set content properties based on data from Able
            content.SetValue("headline", prod.Name);
            content.SetValue("metaDescription", prod.MetaDescription);
            content.SetValue("metaKeywords", prod.MetaKeywords);
            content.SetValue("pageTitle", prod.Name);
            content.SetValue("bodyText", prod.Description);
            content.SetValue("brief", prod.Summary);

            // Establish link to merchello product
            content.SetValue("product", merchelloGuid.ToString());


            // publish content so we can get nodeId
            _cs.Publish(content);

            // pull in images if we have some
            if (prod.Images.Count > 0)
            {
                // make media objects for each product image
                List <string> mediaIds = new List <string>();
                foreach (string imageUrl in prod.Images)
                {
                    // make media and get ID
                    if (!string.IsNullOrEmpty(imageUrl))
                    {
                        string mediaNodeId = MakeMediaNode(content, imageUrl, prod.Name);
                        if (!string.IsNullOrEmpty(mediaNodeId))
                        {
                            mediaIds.Add(mediaNodeId);
                        }
                    }
                }

                // save all images to the media picker property value
                string idList = string.Join(",", mediaIds.ToArray());
                content.SetValue("images", idList);
                _cs.Save(content);
            }
        }
        /// <summary>
        /// Private method to create new content
        /// </summary>
        /// <param name="contentService"></param>
        /// <param name="contentTypeService"></param>
        private static void CreateNewContent(IContentService contentService, IContentTypeService contentTypeService)
        {
            //We find all ContentTypes so we can show a nice list of everything that is available
            var contentTypes       = contentTypeService.GetAllContentTypes();
            var contentTypeAliases = string.Join(", ", contentTypes.Select(x => x.Alias));

            Console.WriteLine("Please enter the Alias of the ContentType ({0}):", contentTypeAliases);
            var contentTypeAlias = Console.ReadLine();

            Console.WriteLine("Please enter the Id of the Parent:");
            var strParentId = Console.ReadLine();
            int parentId;

            if (int.TryParse(strParentId, out parentId) == false)
            {
                parentId = -1;//Default to -1 which is the root
            }
            Console.WriteLine("Please enter the name of the Content to create:");
            var name = Console.ReadLine();

            //Create the Content
            var content = contentService.CreateContent(name, parentId, contentTypeAlias);

            foreach (var property in content.Properties)
            {
                Console.WriteLine("Please enter the value for the Property with Alias '{0}':", property.Alias);
                var value   = Console.ReadLine();
                var isValid = property.IsValid(value);
                if (isValid)
                {
                    property.Value = value;
                }
                else
                {
                    Console.WriteLine("The entered value was not valid and thus not saved");
                }
            }

            //Save the Content
            contentService.Save(content);

            Console.WriteLine("Content was saved: " + content.HasIdentity);
        }
        public ServiceResult CreateEvent(IPublishedContent chapter, int userId, string name, string location, DateTime date, string time, string imageUrl, string address,
                                         string mapQuery, string description)
        {
            IPublishedContent eventsPage = chapter.GetPropertyValue <IPublishedContent>("eventsPage");

            IContent @event = _contentService.CreateContent(name, eventsPage.Id, "event", userId);

            @event.SetValue(EventPropertyNames.Location, location);
            @event.SetValue(EventPropertyNames.Date, date);

            if (!string.IsNullOrEmpty(time))
            {
                @event.SetValue(EventPropertyNames.Time, time);
            }

            if (!string.IsNullOrEmpty(imageUrl))
            {
                @event.SetValue(EventPropertyNames.ImageUrl, imageUrl);
            }

            if (!string.IsNullOrEmpty(address))
            {
                @event.SetValue(EventPropertyNames.Address, address);
            }

            if (!string.IsNullOrEmpty(mapQuery))
            {
                @event.SetValue(EventPropertyNames.MapQuery, mapQuery);
            }

            if (!string.IsNullOrEmpty(description))
            {
                @event.SetValue(EventPropertyNames.Description, description);
            }

            @event.SetValue(EventPropertyNames.Public, false);

            _contentService.Publish(@event, userId);

            return(new ServiceResult(true));
        }
        /// <summary>
        /// Private method to create new content
        /// </summary>
        /// <param name="contentService"></param>
        /// <param name="contentTypeService"></param>
        private static void CreateNewContent(IContentService contentService, IContentTypeService contentTypeService)
        {
            //We find all ContentTypes so we can show a nice list of everything that is available
            var contentTypes = contentTypeService.GetAllContentTypes();
            var contentTypeAliases = string.Join(", ", contentTypes.Select(x => x.Alias));

            Console.WriteLine("Please enter the Alias of the ContentType ({0}):", contentTypeAliases);
            var contentTypeAlias = Console.ReadLine();

            Console.WriteLine("Please enter the Id of the Parent:");
            var strParentId = Console.ReadLine();
            int parentId;
            if (int.TryParse(strParentId, out parentId) == false)
                parentId = -1;//Default to -1 which is the root

            Console.WriteLine("Please enter the name of the Content to create:");
            var name = Console.ReadLine();

            //Create the Content
            var content = contentService.CreateContent(name, parentId, contentTypeAlias);
            foreach (var property in content.Properties)
            {
                Console.WriteLine("Please enter the value for the Property with Alias '{0}':", property.Alias);
                var value = Console.ReadLine();
                var isValid = property.IsValid(value);
                if (isValid)
                {
                    property.Value = value;
                }
                else
                {
                    Console.WriteLine("The entered value was not valid and thus not saved");
                }
            }

            //Save the Content
            contentService.Save(content);

            Console.WriteLine("Content was saved: " + content.HasIdentity);
        }
		private IContent CreateProductContent(IContentService contentService, IContent testCategory, string title, string sku, string price, int stock, string metaDescription, string description, bool useVariantStock, string introduction = null, string features = null)
		{
			var product = contentService.CreateContent(title, testCategory, Product.NodeAlias);
			product.SetValue("title", title);
			product.SetValue("url", title);
			product.SetValue("sku", sku);
			product.SetValue("price", price);
			_stockService.SetStock(product.Id, stock, false, string.Empty);

			product.SetValue("metaDescription", metaDescription);
			product.SetValue("description", description);

			if (useVariantStock)
			{
				product.SetValue("useVariantStock", true);
			}

			if (introduction != null)
			{
				if (product.HasProperty("introduction"))
				{
					product.SetValue("introduction", introduction);
				}
			}

			if (features != null)
			{
				if (product.HasProperty("features"))
				{
					product.SetValue("features", features);
				}
			}

			return product;
		}
		private IContent CreateVariantContent(IContentService contentService, IContent testProductVariantGroup, string color, string sku, string price, int stock, string variantName, bool enableBackorders = false)
		{
			var testProductVariant = contentService.CreateContent(variantName, testProductVariantGroup, ProductVariant.NodeAlias);
			testProductVariant.SetValue("title", color);
			testProductVariant.SetValue("sku", sku);
			testProductVariant.SetValue("price", price);
			testProductVariant.SetValue("backorderStatus", "disable");
			_stockService.SubstractStock(testProductVariant.Id, stock, false, string.Empty);

			if (enableBackorders)
			{
				testProductVariant.SetValue("backorderStatus", "enable");
			}

			return testProductVariant;
		}
		internal static IContent GetOrCreateContent(IContentType contentType, string contentName, IContentTypeService contentTypeService, IContentService contentService, IContent parentContent, List<IContent> contentList)
		{   
			var content = contentService.GetContentOfContentType(contentType.Id).FirstOrDefault(x => !x.Trashed);
			if (content == null)
			{
				if (parentContent == null)
				{
					content = contentService.CreateContent(contentName, -1, contentType.Alias);
				}
				else
				{
					content = contentService.CreateContent(contentName, parentContent, contentType.Alias);
				}
				contentList.Add(content);
			}
			return content;
		}
		private static IContent CreateVariantGroupContent(IContentService contentService, IContent testProduct, string variantGroup, bool requiredVariant)
		{
			var testProductVariantGroup = contentService.CreateContent(variantGroup, testProduct, ProductVariantGroup.NodeAlias);
			testProductVariantGroup.SetValue("title", variantGroup);
			if (requiredVariant)
			{
				testProductVariantGroup.SetValue("required", true);
			}


			return testProductVariantGroup;
		}