public string GetValue(Item item, string[] fieldNames, TemplateID templateId)
        {
            if (item == null)
            {
                return(null);
            }
            if (item.IsNotMasterOrWebIndex())
            {
                return(null);
            }
            if (!item.IsContentOrMediaItem())
            {
                return(null);
            }
            if (!item.InheritsFromTemplate(templateId))
            {
                return(null);
            }

            var content = new StringBuilder();

            AddContent(content, item, fieldNames);

            return(content.ToString().ToValueOrNull());
        }
Example #2
0
        public string newPost(string blogid, string username, string password, XmlRpcStruct rpcstruct, bool publish)
        {
            Authenticate(username, password);
            CheckUserRights(blogid, username);

            var entryTitle  = rpcstruct["title"].ToString();
            var currentBlog = ContentHelper.GetContentDatabase().GetItem(blogid);

            if (currentBlog != null)
            {
                // test
                var access = Sitecore.Security.AccessControl.AuthorizationManager.GetAccess(currentBlog, Sitecore.Context.User, Sitecore.Security.AccessControl.AccessRight.ItemCreate);
                // end test

                BlogHomeItem blogItem = currentBlog;
                var          template = new TemplateID(blogItem.BlogSettings.EntryTemplateID);
                var          newItem  = ItemManager.AddFromTemplate(entryTitle, template, currentBlog);

                SetItemData(newItem, rpcstruct);

                if (publish)
                {
                    ContentHelper.PublishItemAndRequiredAncestors(newItem.ID);
                }

                return(newItem.ID.ToString());
            }
            else
            {
                return(string.Empty);
            }
        }
Example #3
0
        public ActionResult Index(string UserName, string UserComment)
        {
            var contextItem          = RenderingContext.Current.ContextItem;
            var templateId           = new TemplateID(new ID("{C280DFD4-E3D4-4121-BA28-64DB2D9BE9B4}"));
            var database             = Sitecore.Configuration.Factory.GetDatabase("master");
            var parentItemfromMaster = database.GetItem(contextItem.ID);

            using (new SecurityDisabler())
            {
                Item newCommentItem = parentItemfromMaster.Add(UserName, templateId);
                newCommentItem.Editing.BeginEdit();
                newCommentItem["UserName"]    = UserName;
                newCommentItem["UserComment"] = UserComment;
                newCommentItem.Editing.EndEdit();

                Database master = Sitecore.Configuration.Factory.GetDatabase("master");
                Database web    = Sitecore.Configuration.Factory.GetDatabase("web");

                PublishOptions publishOptions = new PublishOptions(master,
                                                                   web,
                                                                   PublishMode.SingleItem,
                                                                   newCommentItem.Language,
                                                                   System.DateTime.Now);
                Publisher publisher = new Publisher(publishOptions);
                publisher.Options.RootItem = newCommentItem;
                publisher.Options.Deep     = true;
                publisher.Publish();
            }
            return(View("ThankYouPage"));
        }
        public ActionResult Index(HttpPostedFileBase file, string parentPath)
        {
            IEnumerable <Event> events = null;
            var database   = Sitecore.Configuration.Factory.GetDatabase("master");
            var parentItem = database.GetItem(parentPath);
            var templateID = new TemplateID(new ID("{3B9C5F33-3A68-4E8F-B635-FE8FFE981461}"));

            using (new SecurityDisabler())
            {
                foreach (var ev in events)
                {
                    var  name = ItemUtil.ProposeValidItemName(ev.ContentHeading);
                    Item item = parentItem.Add(name, templateID);
                    item.Editing.BeginEdit();
                    item["ContentHeading"] = ev.ContentHeading;
                    item.Editing.EndEdit();
                }
            }
            string message = null;

            using (var reader = new System.IO.StreamReader(file.InputStream))
            {
                var contents = reader.ReadToEnd();
                try
                {
                    events = JsonConvert.DeserializeObject <IEnumerable <Event> >(contents);
                }
                catch (Exception ex)
                {
                }
            }
            return(View());
        }
        public void CreateAndEditItemTest()
        {
            //setup database so we have a rood node to add our content to
            var homeFakeItem = new FakeItem();
            Item homeItem = (Item) homeFakeItem;

            //Define some Field IDs
            TemplateID templateId = new TemplateID(ID.NewID);
            Item subNode;
            ID fieldIdA = ID.NewID;
            ID fieldIdB = ID.NewID;

            //add and edit the ite,
            using (new SecurityDisabler())
            {
                subNode = homeItem.Add("SubNode", templateId);
                using (new EditContext(subNode))
                {
                    subNode[fieldIdA] = "test";
                    subNode[fieldIdB] = "testBBB";
                }

            }
            subNode[fieldIdA].ShouldAllBeEquivalentTo("test");
            subNode[fieldIdB].ShouldAllBeEquivalentTo("testBBB"); ;
        }
        public void AddItems(Item parent, IEnumerable <Event> events, TemplateID templateID)
        {
            var  children = parent.GetChildren();
            Item foundItem;

            using (new SecurityDisabler())
            {
                foreach (var currentEvent in events)
                {
                    var name = ItemUtil.ProposeValidItemName(currentEvent.ContentHeading);
                    if (EventExists(children, name, out foundItem))
                    {
                        if (foundItem != null)
                        {
                            UpdateItem(foundItem, currentEvent);
                            UpdateCount++;
                        }
                    }
                    else
                    {
                        AddItem(parent, currentEvent, templateID);
                        AddCount++;
                    }
                }
            }
        }
Example #7
0
        public override PipelineProcessorResponseValue ProcessRequest()
        {
            var itemTitle = RequestContext.Argument;

            if (ItemUtil.IsItemNameValid(itemTitle))
            {
                var currentItem = RequestContext.Item;
                var currentBlog = ManagerFactory.BlogManagerInstance.GetCurrentBlog(currentItem);
                if (currentBlog != null)
                {
                    var template   = new TemplateID(currentBlog.BlogSettings.CategoryTemplateID);
                    var categories = ManagerFactory.CategoryManagerInstance.GetCategoryRoot(currentItem);
                    var newItem    = ItemManager.AddFromTemplate(itemTitle, template, categories);

                    return(new PipelineProcessorResponseValue
                    {
                        Value = newItem.ID.Guid
                    });
                }
            }
            return(new PipelineProcessorResponseValue
            {
                Value = null
            });
        }
Example #8
0
        public string newPost(string blogid, string username, string password, XmlRpcStruct rpcstruct, bool publish)
        {
            Authenticate(username, password);
            CheckUserRights(blogid, username);

            var entryTitleRaw = rpcstruct["title"];

            if (entryTitleRaw == null)
            {
                throw new ArgumentException("'title' must be provided");
            }

            var entryTitle  = entryTitleRaw.ToString();
            var currentBlog = GetContentDatabase().GetItem(blogid);

            if (currentBlog != null)
            {
                BlogHomeItem blogItem = currentBlog;
                var          template = new TemplateID(blogItem.BlogSettings.EntryTemplateID);
                var          newItem  = ItemManager.AddFromTemplate(entryTitle, template, currentBlog);

                SetItemData(newItem, rpcstruct);

                if (publish)
                {
                    ContentHelper.PublishItemAndRequiredAncestors(newItem.ID);
                }

                return(newItem.ID.ToString());
            }
            else
            {
                return(string.Empty);
            }
        }
Example #9
0
        public string GetValue(IIndexable indexable, string fieldName, TemplateID templateId)
        {
            var item = indexable.ToItem();

            if (item == null)
            {
                return(null);
            }
            if (item.IsNotMasterOrWebIndex())
            {
                return(null);
            }
            if (!item.IsContentOrMediaItem())
            {
                return(null);
            }

            if (!item.InheritsFromTemplate(templateId))
            {
                return(null);
            }

            var title = item.GetFieldValue(fieldName);

            return(title.ToValueOrNull());
        }
Example #10
0
        /// <summary>
        /// Handles the Postback of the Sheer Dialogs
        /// </summary>
        protected static void Run(ClientPipelineArgs args)
        {
            Assert.ArgumentNotNull((object)args, "args");
            var  language = Language.Parse(args.Parameters["language"]);
            Item parent   = Context.ContentDatabase.Items[args.Parameters["parentId"], language];

            Assert.IsNotNull((object)parent, typeof(Item));

            // Retrieval of custom parameters
            ID templateId = VNavAddToLocation.GetSitecoreId(args.Parameters, "templateId");
            ID fieldId    = VNavAddToLocation.GetSitecoreId(args.Parameters, "fieldId");

            Assert.IsNotNull((object)templateId, typeof(ID));

            if (!parent.Access.CanCreate())
            {
                Context.ClientPage.ClientResponse.Alert("You do not have permission to create an item here.");
            }
            else
            {
                var tid = new TemplateID(templateId);
                Assert.IsNotNull((object)tid, typeof(TemplateID));
                SheerResponse.Eval("console.log('TID: " + tid.ID + "');");
                Item item = parent.Add("Vertical Nav Item", tid);
                Context.ClientPage.SendMessage(Context.ClientPage, "webedit:fieldeditor(command={11111111-1111-1111-1111-111111111111}, fields=Title|Link, id=" + item.ID + ")");
                //SheerResponse.Alert("Page will now reload");
            }
        }
Example #11
0
        /// <summary>
        /// Use this method to retrieve the sitecore's item Template ID from the config setting's name.
        /// The config file will be set in the includes area of the project, typically in the App_config/Include/ area of your project.
        /// The config file will extend the main web config and contains setting in the structure
        /// &lt;setting name="HomeTemplateID" value="{00000000-0000-0000-0000-000000000000}"/ &gt;
        /// and then you pass in the name and the method will pull out the value and validate it against the current sitecore instance,
        /// once the template is validated, this is returned back (otherwise return a null id) then the item can be retrieved by that template id
        /// </summary>
        /// <param name="settingName">
        /// </param>
        /// <param name="contextItem"></param>
        /// <returns>
        /// </returns>
        public virtual TemplateID GetTemplateIdFromConfig(string settingName, Item contextItem = null)
        {
            //if we have a context item passed in then get the database from the item
            if (contextItem != null)
            {
                MasterDatabase = contextItem.Database;
            }

            //set the default return ID as null
            var itemTemplateId = new TemplateID();

            //check the string value sent in is not null
            if (!string.IsNullOrWhiteSpace(settingName))
            {
                var configSetting = Sitecore.Configuration.Settings.GetSetting(settingName);
                // check if we have any settings
                if (!string.IsNullOrWhiteSpace(configSetting))
                {
                    var sitecoreItemTemplateId = new TemplateID(new ID(configSetting));
                    //validate the template id
                    if (sitecoreItemTemplateId.ID != new TemplateID())
                    {
                        //once our id is validated , check if the template is in the master database
                        var databaseTemplateItem = MasterDatabase.GetTemplate(sitecoreItemTemplateId);
                        //check if the database template is not null then return the validated template id
                        if (databaseTemplateItem != null)
                        {
                            itemTemplateId = sitecoreItemTemplateId;
                        }
                    }
                }
            }
            // return the template id either a new one or a verified one
            return(itemTemplateId);
        }
Example #12
0
        protected virtual void EnsureTemplateExists()
        {
            using (new SecurityDisabler())
            {
                var parent = Database.GetItem(TemplateParent);
                if (parent == null)
                {
                    throw new InvalidOperationException("Template parent path did not exist.");
                }

                var existingTemplate = parent.Children["Authentication Challenge"];

                if (existingTemplate != null)
                {
                    ChallengeTemplateId = new TemplateID(existingTemplate.ID);
                    return;
                }

                var template        = parent.Add("Authentication Challenge", new TemplateID(TemplateIDs.Template));
                var section         = template.Add("Challenge", new TemplateID(TemplateIDs.TemplateSection));
                var expirationField = section.Add("Expires", new TemplateID(TemplateIDs.TemplateField));

                using (new EditContext(expirationField))
                {
                    expirationField[TemplateFieldIDs.Shared] = "1";
                }

                ChallengeTemplateId = new TemplateID(template.ID);
            }
        }
        public void StandardValueTest(string defaultValue)
        {
            var templateId = new TemplateID(ID.NewID);

            using (var db = new Db
            {
                new DbTemplate("Sample", templateId)
                {
                    { "Title", defaultValue }
                }
            })
            {
                var contentRoot = db.GetItem(ItemIDs.ContentRoot);
                var item        = contentRoot.Add("Home", templateId);

                var indexable = new SitecoreIndexableItem(item);

                var context = new Mock <IProviderUpdateContext>();
                var index   = new IndexBuilder()
                              .WithSimpleFieldTypeMap("text")
                              .Build();
                context.Setup(t => t.Index).Returns(index);
                var sut = new AlgoliaDocumentBuilder(indexable, context.Object);

                var field = new SitecoreItemDataField(item.Fields["Title"]);

                //Act
                sut.AddField(field);

                //Assert
                JObject doc = sut.Document;
                Assert.AreEqual("Home", (string)doc["title"]);
            }
        }
        private void CreateEvents(IEnumerable <Event> events, string parentPath)
        {
            var database   = Factory.GetDatabase("master");
            var parent     = database.GetItem(parentPath);
            var templateId = new TemplateID(new ID("{901656E7-1376-400C-AEF2-D8B8684B9FB4}"));

            using (new SecurityDisabler())
            {
                foreach (var ev in events)
                {
                    var name = ItemUtil.ProposeValidItemName(ev.ContentHeading);
                    var item = parent.Add(name, templateId);
                    using (new EditContext(item))
                    {
                        item["ContentHeading"]       = ev.ContentHeading;
                        item["ContentIntro"]         = ev.ContentIntro;
                        item["Difficulty Level"]     = ev.Difficulty.ToString();
                        item["Duration"]             = ev.Duration.ToString();
                        item["Highlights"]           = ev.Highlights;
                        item["Start Date"]           = DateUtil.ToIsoDate(ev.StartDate);
                        item[FieldIDs.Workflow]      = "{97EE4F91-4053-4F5B-A000-F86CABB14781}";
                        item[FieldIDs.WorkflowState] = "{870CA50B-225D-4481-A839-EB99E83F40E8}";
                    }
                }
            }
        }
        public void CreateAndEditItemTestMultilesubItems()
        {
            FakeDatabase database = (FakeDatabase)Factory.GetDatabase("master");

            var homeItem = new FakeItem("master","homeItem");
            var home = (Item)homeItem;

            TemplateID templateId = new TemplateID(ID.NewID);
            Item subNode;

            ID fieldIdA = ID.NewID;
            ID fieldIdB = ID.NewID;
            Item subsubnode;
            ID subsubNodeId;
            using (new SecurityDisabler())
            {
                subNode = home.Add("SubNode", templateId);
                using (new EditContext(subNode))
                {
                    subNode[fieldIdA] = "test";
                    subNode[fieldIdB] = "testBBB";
                }
               subsubnode  = subNode.Add("SubSubNode", templateId);
                subsubNodeId = subsubnode.ID;
            }

            //THE master database should contain the subsubnode
            Item n = database.GetItem(subsubNodeId);

            //And the subsubnode should have inserted content
            n.Name.ShouldAllBeEquivalentTo("SubSubNode");
        }
Example #16
0
 private void rTB_Template_TextChanged(object sender, EventArgs e)
 {
     DataRow[] rows = sqlTemplatesDataSet.sqlBlockTemplates.Select("ID=" + TemplateID.ToString());
     if (rows.Length == 1)
     {
         rows[0]["BlockTemplate"] = rTB_Template.Text;
     }
 }
Example #17
0
        public override Item Add(string name, TemplateID templateID)
        {
            var db      = (FakeDatabase)this.Database;
            var newItem = new FakeItem(ID.NewID, templateID, name);

            db.FakeAddItem(newItem);
            return(newItem);
        }
Example #18
0
 public override string ToString()
 {
     return(ID.ToString("x") + '~' +
            TemplateID.ToString("x") + '~' +
            Quantity.ToString("x") + '~' +
            (Slot != ItemSlotEnum.SLOT_INVENTAIRE ? ((int)Slot).ToString("x") : "") + '~' +
            GetStats().ToItemStats() + ';');
 }
Example #19
0
        public CreateUsergroup(ISubmitActionData submitActionData) : base(submitActionData)
        {
            _templateId = new TemplateID(new ID(Settings.GetSetting("GOTO-Usergroup.Feature.Usergroup.CreateUsergroup.TemplateId", "{B6EF3982-5312-46CA-8934-E3DAD6F0D53A}")));
            _database   = Database.GetDatabase(Settings.GetSetting("GOTO-Usergroup.Feature.UsergroupCreateUsergroup..Database", "master"));
            _rootItem   = _database.GetItem(new ID(Settings.GetSetting("GOTO-Usergroup.Feature.Usergroup.CreateUsergroup.RootId", "{8EDAE83B-BB11-49FF-831D-7EA394C9738C}")));

            _xconnectService = ServiceLocator.ServiceProvider.GetService <IXConnectService>();
        }
Example #20
0
        public TextualBlock(string text, TemplateID token)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < text.Length; i++)
            {
                //Convert multiple whitespace chars to single
                //whilst building new string
                if (!char.IsWhiteSpace(text[i]))
                {
                    sb.Append(text[i]);
                }
                else
                {
                    if (char.IsWhiteSpace(text[i + 1]))
                    {
                        continue;
                    }
                    sb.Append(' ');
                }
            }
            myText          = sb.ToString();
            Token           = token;
            currentPosition = 0;
            Label           = string.Empty;
            while (myText[currentPosition] != '{')
            {
                currentPosition++;
            }

            if (currentPosition == 0)
            {
                throw new Exception("Token " + token + " was not found.");
            }

            string s  = myText.Substring(0, currentPosition);
            int    ws = s.IndexOf(' ');

            if (ws != -1)
            {
                Label = s.Substring(ws, s.Length - ws).Trim(new char[] { });
                s     = s.Substring(0, ws);
            }

            TemplateID currentToken;

            if (!Enum.TryParse(s, true, out currentToken))
            {
                throw new Exception("Invalid token " + s);
            }

            if (currentToken != Token)
            {
                throw new Exception("Expected the " + Token + " token, got " + currentToken);
            }

            currentPosition++;
        }
Example #21
0
        private BinaryBlock(byte[] bytes, TemplateID token, int floatingPointSize)
        {
            FloatingPointSize = floatingPointSize;
            myStream          = new MemoryStream(bytes);
            myReader          = new BinaryReader(myStream);
            Token             = token;
            long startPosition;

            while (myStream.Position < myStream.Length)
            {
                startPosition = myStream.Position;
                string currentToken = getNextToken();
                switch (currentToken)
                {
                case "int_list":
                    int integerCount = (int)myReader.ReadInt32();
                    for (int i = 0; i < integerCount; i++)
                    {
                        cachedIntegers.Add(myReader.ReadInt32());
                    }
                    break;

                case "float_list":
                    int floatCount = (int)myReader.ReadInt32();
                    switch (FloatingPointSize)
                    {
                    case 32:
                        for (int i = 0; i < floatCount; i++)
                        {
                            cachedFloats.Add(myReader.ReadSingle());
                        }

                        break;

                    case 64:
                        for (int i = 0; i < floatCount; i++)
                        {
                            cachedFloats.Add(myReader.ReadDouble());
                        }
                        break;

                    default:
                        throw new Exception("Unsupported Floating Point Size");
                    }
                    break;

                default:
                    cachedStrings.Add(currentToken);
                    TemplateID newBlockToken;
                    if (Enum.TryParse(currentToken, true, out newBlockToken))
                    {
                        myStream.Position = startPosition;
                        return;
                    }
                    break;
                }
            }
        }
Example #22
0
        private string SavePreviewTemplate()
        {
            string extension = string.Empty;

            byte[] body = null;

            DownLoadTemplateFromBase(out extension, out body);
            //вложить в cache папку

            if (body == null || string.IsNullOrEmpty(extension))
            {
                return(string.Empty);
            }

            var pathForFormat = DirectoryPath + string.Format(@"\{0}{1}", TemplateID.ToString(), extension);

            try
            {
                File.WriteAllBytes(pathForFormat, body);
            }
            catch
            {
                throw new Exception(string.Format("Файл с расширением {0} не загрузился", extension));
            }

            try
            {
                if (TemplateType == "wordbased")
                {
                    using (var wi = new WordInterop())
                        wi.SaveWithHtmlExtension(pathForFormat);
                }
                else if (TemplateType == "excelbased")
                {
                    using (var ei = new ExcelInterop())
                        ei.SaveWithHtmlExtension(pathForFormat);
                }
            }

            catch
            {
#if EXCLUDED
                throw new Exception("Не сохранился файл с расширением html");
#endif
                return(string.Empty);
            }

            try
            {
                File.Delete(pathForFormat);
            }
            catch
            {
                throw new Exception(string.Format("Файл с расширением {0} не удалился", extension));
            }

            return(TemplateID.ToString() + ".html");
        }
Example #23
0
        public string GetPreviewTemplate()
        {
            var tempData = Path.GetDirectoryName(DirectoryPath);

            if (tempData == null)
            {
                return(null);
            }

            if (!Directory.Exists(tempData))
            {
                Directory.CreateDirectory(tempData);
            }

            if (!Directory.Exists(DirectoryPath))
            {
                Directory.CreateDirectory(DirectoryPath);
            }

            var path = new StringBuilder();

            var dir = new DirectoryInfo(DirectoryPath);

            DirectoryInfo[] dirArr = dir.GetDirectories(TemplateID.ToString(), SearchOption.TopDirectoryOnly);

            //добавляем в путь имя папки
            DirectoryPath += string.Format(@"\{0}", TemplateID.ToString());

            if (dirArr.Count() == 0)
            {
                Directory.CreateDirectory(DirectoryPath);

                path.Append(SavePreviewTemplate());
            }
            else
            {
                FileInfo[] fileArr = dirArr[0].GetFiles(string.Format("{0}.html", TemplateID.ToString()));
                if (fileArr.Count() == 0)
                {
                    path.Append(SavePreviewTemplate());
                }
                else
                {
                    path.AppendFormat("{0}.html", TemplateID.ToString());
                }
            }

            if (!string.IsNullOrEmpty(path.ToString()))
            {
                path.Insert(0, TemplateID.ToString() + "/");
                path.Insert(0, "temp_data/cache/");
            }

            return(path.ToString());
        }
        /// <summary>
        /// Get the content or media Item of this indexable that inherits the template, or null if not found.
        /// </summary>
        /// <param name="indexable"></param>
        /// <param name="templateId"></param>
        /// <returns></returns>
        public static Item Get(IIndexable indexable, TemplateID templateId)
        {
            var item = Get(indexable);

            if (!item.InheritsFromTemplate(templateId))
            {
                return(null);
            }

            return(item);
        }
Example #25
0
        public override Block ReadSubBlock(TemplateID newToken)
        {
            Block b = ReadSubBlock();

            if (b.Token != newToken)
            {
                throw new Exception();
            }

            return(b);
        }
Example #26
0
        internal TestItemContext(TemplateID templateId)
        {
            var testName = "test-" + ID.NewID.ToShortID();
            var database = Factory.GetDatabase("master");

            using (new SecurityDisabler())
            {
                var parent = database.GetItem(ROOT_PATH);
                TestItem = parent.Add(testName, templateId);
            }
        }
Example #27
0
        protected void Run(ClientPipelineArgs args)
        {
            if (args.IsPostBack)
            {
                if (args.HasResult)
                {
                    var itemTitle = args.Result;

                    var db = Sitecore.Configuration.Factory.GetDatabase(args.Parameters["database"]);
                    if (db != null)
                    {
                        var currentItem = db.GetItem(args.Parameters["currentid"]);
                        if (currentItem != null)
                        {
                            var currentBlog = ManagerFactory.BlogManagerInstance.GetCurrentBlog(currentItem);
                            if (currentBlog != null)
                            {
                                var  template = new TemplateID(currentBlog.BlogSettings.EntryTemplateID);
                                Item newItem  = ItemManager.AddFromTemplate(itemTitle, template, currentBlog);

                                ContentHelper.PublishItem(newItem);
                            }
                            else
                            {
                                Log.Error("Failed to locate blog root item", this);
                            }
                        }
                    }
                }
            }
            else
            {
                var db = Sitecore.Configuration.Factory.GetDatabase(args.Parameters["database"]);
                if (db == null)
                {
                    return;
                }
                var currentItem = db.GetItem(args.Parameters["currentid"]);
                if (currentItem == null)
                {
                    return;
                }

                if (!currentItem.TemplateIsOrBasedOn(Settings.BlogTemplateID) && !currentItem.TemplateIsOrBasedOn(Settings.EntryTemplateID))
                {
                    Context.ClientPage.ClientResponse.Alert("Please create or select a blog first");
                }
                else
                {
                    SheerResponse.Input("Enter the title of your new entry:", "", Configuration.Settings.ItemNameValidation, Translator.Text("'$Input' is not a valid title."), 100);
                    args.WaitForPostBack(true);
                }
            }
        }
Example #28
0
        protected void Run(ClientPipelineArgs args)
        {
            if (args.IsPostBack)
            {
                if (args.HasResult)
                {
                    var itemTitle = args.Result;

                    var db = Sitecore.Configuration.Factory.GetDatabase(args.Parameters["database"]);
                    if (db != null)
                    {
                        var currentItem = db.GetItem(args.Parameters["currentid"]);
                        if (currentItem != null)
                        {
                            var currentBlog = ManagerFactory.BlogManagerInstance.GetCurrentBlog(currentItem);
                            if (currentBlog != null)
                            {
                                var template = new TemplateID(currentBlog.BlogSettings.EntryTemplateID);
                                Item newItem = ItemManager.AddFromTemplate(itemTitle, template, currentBlog);

                                ContentHelper.PublishItem(newItem);
                            }
                            else
                                Log.Error("Failed to locate blog root item", this);
                        }
                    }
                }
            }
            else
            {
                var db = Sitecore.Configuration.Factory.GetDatabase(args.Parameters["database"]);
                if (db == null)
                {
                    return;
                }
                var currentItem = db.GetItem(args.Parameters["currentid"]);
                if (currentItem == null)
                {
                    return;
                }

                if (!currentItem.TemplateIsOrBasedOn(Settings.BlogTemplateID) && !currentItem.TemplateIsOrBasedOn(Settings.EntryTemplateID))
                {
                    Context.ClientPage.ClientResponse.Alert("Please create or select a blog first");
                }
                else
                {
                    SheerResponse.Input("Enter the title of your new entry:", "", Configuration.Settings.ItemNameValidation, Translator.Text("'$Input' is not a valid title."), 100);
                    args.WaitForPostBack(true);
                }
            }
        }
Example #29
0
        public ActionResult Index(HttpPostedFileBase file, string parentPath)
        {
            IEnumerable <Event> events = null;

            //string message = null;

            // parse json
            using (var reader = new System.IO.StreamReader(file.InputStream))
            {
                var content = reader.ReadToEnd();
                try
                {
                    events = JsonConvert.DeserializeObject <IEnumerable <Event> >(content);
                }
                catch (Exception)
                {
                }
            }

            // create content items
            var master     = Factory.GetDatabase("master");
            var parentItem = master.GetItem(parentPath);
            var templateID = new TemplateID(new ID("{884674D4-3556-47F0-92F1-EEDFA2D67BFA}"));

            ViewBag.events = new List <string>();
            using (new SecurityDisabler())
            {
                foreach (var ev in events)
                {
                    try
                    {
                        var name = ItemUtil.ProposeValidItemName(ev.ContentHeading);
                        var item = parentItem.Add(name, templateID);
                        item.Editing.BeginEdit();
                        item["ContentHeading"] = ev.ContentHeading;
                        item["ContentIntro"]   = ev.ContentIntro;
                        item["Highlights"]     = ev.Highlights;
                        item["StartDate"]      = ev.StartDate.ToString();
                        item["Duration"]       = ev.Duration.ToString();
                        item["Difficulty"]     = ev.Difficulty.ToString();
                        item.Editing.EndEdit();

                        ViewBag.events.Add(ev.ContentHeading);
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return(View("Result"));
        }
Example #30
0
        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            TreeNode node = e.Node;
            Category cat  = (Category)node.Tag;

            TemplateID = cat.ID;
            showTemplate(TemplateID);
            if (rTB_Template.Text == "")
            {
                rTB_Template.Text = cat.NodeText;
            }
            tSSL_NodeID.Text = TemplateID.ToString();
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            // Get master database

            // Get the context item from the master database (e.g. by ID)

            // Use a simple method of disabling security for the duration of your editing

            // Add a new comment item - use DateUtil.IsoNow to give it a timestamp name

            // Begin editing

            // Set the author and text field values from the form

            // End editing

            using (new Sitecore.SecurityModel.SecurityDisabler())
            {

                Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
                Sitecore.Data.Items.Item comments = master.GetItem("/sitecore/content/HaiNguyen/Comments");

                Sitecore.Data.Items.Item templateItem = master.GetItem(new ID(TemplateReferences.COMMENT_TEMPLATE_ID));
                Sitecore.Data.TemplateID templateID = new TemplateID(templateItem.ID);

                Sitecore.Data.Items.Item newComment = comments.Add(txtAuthor.Text, templateID);

                //TODO: eliminate SecurityDisabler if possible
                newComment.Editing.BeginEdit();
                try
                {
                    newComment.Name = txtAuthor.Text;
                    newComment["Comment Author"] = txtAuthor.Text;
                    newComment["Comment Text"] = txtContent.Text;

                    LinkField link = newComment.Fields["Comment Author Website"];
                    link.Url = txtLink.Text;
                    link.Text = txtLink.Text;
                    link.Target = "_blank";
                    link.LinkType = "external";

                    //TODO: update home
                    newComment.Editing.EndEdit();
                }
                catch (Exception ex)
                {
                    newComment.Editing.CancelEdit();
                }

            }
        }
Example #32
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            // Get master database

            // Get the context item from the master database (e.g. by ID)

            // Use a simple method of disabling security for the duration of your editing

            // Add a new comment item - use DateUtil.IsoNow to give it a timestamp name

            // Begin editing

            // Set the author and text field values from the form

            // End editing

            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                Sitecore.Data.Database   master   = Sitecore.Configuration.Factory.GetDatabase("master");
                Sitecore.Data.Items.Item comments = master.GetItem("/sitecore/content/HaiNguyen/Comments");

                Sitecore.Data.Items.Item templateItem = master.GetItem(new ID(TemplateReferences.COMMENT_TEMPLATE_ID));
                Sitecore.Data.TemplateID templateID   = new TemplateID(templateItem.ID);

                Sitecore.Data.Items.Item newComment = comments.Add(txtAuthor.Text, templateID);

                //TODO: eliminate SecurityDisabler if possible
                newComment.Editing.BeginEdit();
                try
                {
                    newComment.Name = txtAuthor.Text;
                    newComment["Comment Author"] = txtAuthor.Text;
                    newComment["Comment Text"]   = txtContent.Text;

                    LinkField link = newComment.Fields["Comment Author Website"];
                    link.Url      = txtLink.Text;
                    link.Text     = txtLink.Text;
                    link.Target   = "_blank";
                    link.LinkType = "external";

                    //TODO: update home
                    newComment.Editing.EndEdit();
                }
                catch (Exception ex)
                {
                    newComment.Editing.CancelEdit();
                }
            }
        }
        private void AddItem(Item parent, Event currentEvent, TemplateID templateID)
        {
            var  name = ItemUtil.ProposeValidItemName(currentEvent.ContentHeading);
            Item item = parent.Add(name, templateID);

            item.Editing.BeginEdit();
            item[FieldIDs.Workflow]      = "{8272D338-C40A-40DD-95A7-E88E8B4BDABB}";
            item[FieldIDs.WorkflowState] = "{2C88B62D-A1AB-4A41-96E8-7E842BC8C22F}";
            item["ContentHeading"]       = currentEvent.ContentHeading;
            item["ContentIntro"]         = currentEvent.ContentIntro;
            item["DifficultyLevel"]      = currentEvent.Difficulty.ToString();
            item["Duration"]             = currentEvent.Duration.ToString();
            item["Highlights"]           = currentEvent.Highlights;
            item["StartDate"]            = Sitecore.DateUtil.ToIsoDate(currentEvent.StartDate);
            item.Editing.EndEdit();
        }
Example #34
0
        public ActionResult Index(HttpPostedFileBase file, string parentPath)
        {
            IEnumerable <Event> events = null;

            using (var reader = new System.IO.StreamReader(file.InputStream))
            {
                var content = reader.ReadToEnd();

                try
                {
                    events = JsonConvert.DeserializeObject <IEnumerable <Event> >(content);

                    if (events.Any())
                    {
                        var eventDetailsTemplateId = new TemplateID(new ID("{1EE92533-8833-4210-818C-7D27E6245462}"));

                        Database database   = Sitecore.Configuration.Factory.GetDatabase(masterDB);
                        Item     parentItem = database.GetItem(parentPath);

                        using (new SecurityDisabler())
                        {
                            foreach (var @event in events)
                            {
                                string name = ItemUtil.ProposeValidItemName(@event.ContentHeading);
                                Item   item = parentItem.Add(name, eventDetailsTemplateId);

                                /* Transaction starts */
                                item.Editing.BeginEdit();
                                item["ContentHeading"]  = @event.ContentHeading;
                                item["ContentIntro"]    = @event.ContentIntro;
                                item["Highlights"]      = @event.Highlights;
                                item["StartDate"]       = Sitecore.DateUtil.ToIsoDate(@event.StartDate);
                                item["Duration"]        = @event.Duration.ToString();
                                item["DifficultyLevel"] = @event.Difficulty.ToString();
                                item.Editing.EndEdit();
                                /* Transaction ends */
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    // to be added later
                }
            }
            return(View());
        }
Example #35
0
        protected void Run(ClientPipelineArgs args)
        {
            var db = ContentHelper.GetContentDatabase();
            var currentItem = db.GetItem(args.Parameters["currentid"]);

            if (args.IsPostBack)
            {
                if (args.HasResult)
                {
                    string itemTitle = args.Result;

                    var blogItem = ManagerFactory.BlogManagerInstance.GetCurrentBlog(currentItem);

                    if(blogItem == null)
                    {
                        SheerResponse.Alert("Failed to locate the blog item to add the category to.", true);
                        return;
                    }

                    var template = new TemplateID(blogItem.BlogSettings.CategoryTemplateID);
                    var categories = ManagerFactory.CategoryManagerInstance.GetCategoryRoot(currentItem);
                    var newItem = ItemManager.AddFromTemplate(itemTitle, template, categories);

                    ContentHelper.PublishItem(newItem);

                    SheerResponse.Eval("scForm.browser.getParentWindow(scForm.browser.getFrameElement(window).ownerDocument).location.reload(true)");

                    args.WaitForPostBack(true);
                }
            }
            else
            {
                if (!currentItem.TemplateIsOrBasedOn(Settings.BlogTemplateID) && !currentItem.TemplateIsOrBasedOn(Settings.EntryTemplateID))
                {
                    Context.ClientPage.ClientResponse.Alert("Please create or select a blog first");
                }
                else
                {
                    SheerResponse.Input("Enter the name of your new category:", "", Configuration.Settings.ItemNameValidation, Translator.Text("'$Input' is not a valid name."), 100);
                    args.WaitForPostBack(true);
                }
            }
        }
        public ActionResult Index(sc80basicsitecoremvc.Models.CommentForm commentsForm)
        {
            using (new SecurityDisabler())
            {
                Database master = Sitecore.Configuration.Factory.GetDatabase("master");
                master.GetItem("/sitecore/content/home");
                Item item = Sitecore.Context.Database.GetItem(new ID("{C9E3730D-E1C6-466F-9524-DA44861A45CB}"));
                ID sitecoreID = new Sitecore.Data.ID(item.ID.ToString());
                TemplateID templateID = new TemplateID(sitecoreID);
                string name = ItemUtil.ProposeValidItemName(Sitecore.DateUtil.IsoNow);
                Item newComment = Sitecore.Context.Item.Add(name, templateID);
                newComment.Editing.BeginEdit();
                newComment.Fields["Comment Author"].Value = commentsForm.CommentsAuthor.ToString();
                newComment.Fields["Comment Text"].Value = commentsForm.CommentsText.ToString();
                LinkField website = newComment.Fields["Comment Author Website"];
                website.Url = commentsForm.CommentsAuthorWebsite.ToString();
                website.Text = commentsForm.CommentsAuthorWebsite.ToString();
                website.Target = "_blank";
                website.LinkType = "external";
                newComment.Editing.EndEdit();
            }

            return View();
        }
        public void CreateItemTest()
        {
            FakeDatabase database = (FakeDatabase)Factory.GetDatabase("web");

            var homeItem = new FakeItem(new FieldList());
            database.FakeAddItem(homeItem);
            var home = database.GetItem(homeItem.ID);

            TemplateID templateId = new TemplateID(ID.NewID);
            Item subNode;
            using (new SecurityDisabler())
            {
                subNode = home.Add("SubNode", templateId);

            }
            subNode.Name.ShouldAllBeEquivalentTo("SubNode");
        }
Example #38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TItemBase"/> class.
 /// </summary>
 /// <param name="name">
 /// The name.
 /// </param>
 /// <param name="templateID">
 /// The template id.
 /// </param>
 public TItemBase(string name, TemplateID templateID)
     : this(name, ID.NewID, templateID)
 {
 }
Example #39
0
 public static Sitecore.Data.Items.Item AddBucketUnorganisedChild(this Sitecore.Data.Items.Item item, TemplateID templateID, string itemName)
 {
     using (var securityDisabler = new Sitecore.SecurityModel.SecurityDisabler())
     {
         Sitecore.Data.Items.Item childItem = item.Add(itemName, templateID);
         childItem.Editing.BeginEdit();
         ((CheckboxField)childItem.Fields["ShouldNotOrganiseInBucket"]).Checked = true;
         childItem.Editing.EndEdit();
         return childItem;
     }
 }
		protected virtual void EnsureTemplateExists()
		{
			using (new SecurityDisabler())
			{
				var parent = Database.GetItem(TemplateParent);
				if (parent == null) throw new InvalidOperationException("Template parent path did not exist.");

				var existingTemplate = parent.Children["Authentication Challenge"];

				if (existingTemplate != null)
				{
					ChallengeTemplateId = new TemplateID(existingTemplate.ID);
					return;
				}

				var template = parent.Add("Authentication Challenge", new TemplateID(TemplateIDs.Template));
				var section = template.Add("Challenge", new TemplateID(TemplateIDs.TemplateSection));
				var expirationField = section.Add("Expires", new TemplateID(TemplateIDs.TemplateField));

				using (new EditContext(expirationField))
				{
					expirationField[TemplateFieldIDs.Shared] = "1";
				}

				ChallengeTemplateId = new TemplateID(template.ID);
			}
		}
Example #41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TItemBase"/> class.
 /// </summary>
 /// <param name="name">
 /// The name.
 /// </param>
 /// <param name="id">
 /// The id.
 /// </param>
 /// <param name="templateID">
 /// The template id.
 /// </param>
 /// <param name="parentID">
 /// The parent id.
 /// </param>
 public TItemBase(string name, ID id, TemplateID templateID, ID parentID)
     : base(id)
 {
     this.TemplateID = templateID;
       this.ParentID = parentID;
       this.Name = name;
 }
Example #42
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TItemBase"/> class.
 /// </summary>
 /// <param name="name">
 /// The name.
 /// </param>
 /// <param name="id">
 /// The id.
 /// </param>
 /// <param name="templateID">
 /// The template id.
 /// </param>
 public TItemBase(string name, ID id, TemplateID templateID)
     : this(name, id, templateID, ID.Null)
 {
 }
Example #43
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TItemBase"/> class.
 /// </summary>
 /// <param name="templateID">
 /// The template id.
 /// </param>
 public TItemBase(TemplateID templateID)
     : this(ID.NewID, templateID)
 {
 }
Example #44
0
        public string newPost(string blogid, string username, string password, XmlRpcStruct rpcstruct, bool publish)
        {
            Authenticate(username, password);
            CheckUserRights(blogid, username);

            var entryTitleRaw = rpcstruct["title"];
            if (entryTitleRaw == null)
                throw new ArgumentException("'title' must be provided");

            var entryTitle = entryTitleRaw.ToString();
            var currentBlog = GetContentDatabase().GetItem(blogid);

            if (currentBlog != null)
            {
                BlogHomeItem blogItem = currentBlog;
                var template = new TemplateID(blogItem.BlogSettings.EntryTemplateID);
                var newItem = ItemManager.AddFromTemplate(entryTitle, template, currentBlog);

                SetItemData(newItem, rpcstruct);

                if (publish)
                    ContentHelper.PublishItemAndRequiredAncestors(newItem.ID);

                return newItem.ID.ToString();
            }
            else
                return string.Empty;
        }
Example #45
0
 /// <summary>
 /// Initializes a new instance of the <see cref="TItemBase"/> class.
 /// </summary>
 /// <param name="id">
 /// The id.
 /// </param>
 /// <param name="templateID">
 /// The template id.
 /// </param>
 public TItemBase(ID id, TemplateID templateID)
     : this(string.Empty, id, templateID)
 {
 }
Example #46
0
        public string newPost(string blogid, string username, string password, XmlRpcStruct rpcstruct, bool publish)
        {
            Authenticate(username, password);
            CheckUserRights(blogid, username);

            var entryTitle = rpcstruct["title"].ToString();
            var currentBlog = ContentHelper.GetContentDatabase().GetItem(blogid);

            if (currentBlog != null)
            {
                // test
                var access = Sitecore.Security.AccessControl.AuthorizationManager.GetAccess(currentBlog, Sitecore.Context.User, Sitecore.Security.AccessControl.AccessRight.ItemCreate);
                // end test

                BlogHomeItem blogItem = currentBlog;
                var template = new TemplateID(blogItem.BlogSettings.EntryTemplateID);
                var newItem = ItemManager.AddFromTemplate(entryTitle, template, currentBlog);

                SetItemData(newItem, rpcstruct);

                if (publish)
                    ContentHelper.PublishItemAndRequiredAncestors(newItem.ID);

                return newItem.ID.ToString();
            }
            else
                return string.Empty;
        }
        protected virtual bool UpdateVariableValues(MultivariateTestVariableItem variableItem, out List<ID> modifiedVariations)
        {
            Assert.ArgumentNotNull(variableItem, "variableItem");
            modifiedVariations = new List<ID>();
            List<VariableValueItemStub> variableValues = VariableValues;
            var list2 = new List<MultivariateTestValueItem>(TestingUtil.MultiVariateTesting.GetVariableValues(variableItem));
            var comparer = new DefaultComparer();
            list2.Sort((lhs, rhs) => comparer.Compare(lhs, rhs));
            int num = (list2.Count > 0) ? (list2[0].InnerItem.Appearance.Sortorder - 1) : Settings.DefaultSortOrder;
            var templateID = new TemplateID(MultivariateTestValueItem.TemplateID);
            var list3 = new List<KeyValuePair<MultivariateTestValueItem, VariableValueItemStub>>();
            var list4 = new List<KeyValuePair<int, VariableValueItemStub>>();
            for (int i = variableValues.Count - 1; i >= 0; i--)
            {
                VariableValueItemStub stub = variableValues[i];
                ID currentId = stub.Id;
                int index = list2.FindIndex(item => item.ID == currentId);
                if (index < 0)
                {
                    var pair = new KeyValuePair<int, VariableValueItemStub>(num--, stub);
                    list4.Add(pair);
                }
                else
                {
                    MultivariateTestValueItem item = list2[index];
                    if (IsVariableValueChanged(item, stub))
                    {
                        list3.Add(new KeyValuePair<MultivariateTestValueItem, VariableValueItemStub>(item, stub));
                    }
                    list2.RemoveAt(index);
                }
            }
            if (list2.Count != 0)
            {
            }

                foreach (Item item2 in list2)
                {
                    modifiedVariations.Add(item2.ID);
                    item2.Delete();
                }
                foreach (var pair2 in list4)
                {
                    VariableValueItemStub variableStub = pair2.Value;
                    int key = pair2.Key;
                    string name = variableStub.Name;
                    if (ContainsNonASCIISymbols(name))
                    {
                        Item item3 = variableItem.Database.GetItem(templateID.ID);
                        name = (item3 != null) ? item3.Name : "Unnamed item";
                    }
                    if (!ItemUtil.IsItemNameValid(name))
                    {
                        try
                        {
                            name = ItemUtil.ProposeValidItemName(name);
                        }
                        catch (Exception)
                        {
                            return false;
                        }
                    }
                    name = ItemUtil.GetUniqueName(variableItem, name);
                    Item item4 = variableItem.InnerItem.Add(name, templateID);
                    Assert.IsNotNull(item4, "newVariableValue");
                    UpdateVariableValueItem((MultivariateTestValueItem) item4, variableStub, key);
                }
                foreach (var pair3 in list3)
                {
                    MultivariateTestValueItem variableValue = pair3.Key;
                    VariableValueItemStub stub3 = pair3.Value;
                    modifiedVariations.Add(variableValue.ID);
                    UpdateVariableValueItem(variableValue, stub3);
                }
            return true;
        }
Example #48
0
    public void HasFieldValue_FieldHasStandardValue_ShouldReturnTrue(Db db, string itemName, TemplateID templateId, ID fieldId, string value)
    {
      var template = new DbTemplate("Sample", templateId)
                     {
                       {fieldId, value}
                     };
      db.Add(template);
      //Arrange
      var contentRoot = db.GetItem(ItemIDs.ContentRoot);
      var item = contentRoot.Add("Home", new TemplateID(template.ID));

      //Act
      item.FieldHasValue(fieldId).Should().BeTrue();
    }
Example #49
0
 public virtual IItem Add(string name, TemplateID templateID)
 {
     return ItemFactory.BuildItem(_item.Add(name, templateID));
 }