/// <summary>
        /// Method to generate the items as per input in the CMS.
        /// </summary>
        /// <param name="ItemCreatorModel"> model containing parent item Id/Path, Template Id/Path, Languages, no. of items to create etc. </param>
        public string ItemGenerator(ItemCreatorModel model)
        {
            StringBuilder log = new StringBuilder();

            try
            {
                log.Append("Item Creation Process Started\n");

                for (int i = 0; i < model.NumberOfItems; i++)
                {
                    Sitecore.Data.Database masterDB = Sitecore.Data.Database.GetDatabase("master");

                    #region Item Creation
                    bool IsParentId = ID.IsID(model.ParentNode);
                    Item parentItem;
                    if (!IsParentId)
                    {
                        parentItem = masterDB.GetItem(model.ParentNode);
                    }
                    else
                    {
                        parentItem = masterDB.GetItem(ID.Parse(model.ParentNode));
                    }
                    TemplateItem template = masterDB.GetTemplate(model.TemplateId);
                    #endregion End Item Creation

                    Item newItem = parentItem.Add("Item-" + i, template);

                    #region Adding Language Versions

                    var languageCollection = model.Languages.Split(',');

                    foreach (string languageCode in languageCollection)
                    {
                        using (new LanguageSwitcher(languageCode))
                        {
                            Item parent = masterDB.GetItem(newItem.ParentID, Language.Parse(languageCode));

                            Item NewItem = parent.GetChildren().Where(x => x.ID == newItem.ID).FirstOrDefault();

                            NewItem.Editing.BeginEdit();

                            NewItem.Versions.AddVersion();

                            NewItem.Editing.EndEdit();
                        }
                    }

                    log.Append(newItem.Name + " Created successfully with ID: " + newItem.ID + "\n");
                    #endregion
                }
            }
            catch (Exception ex)
            {
                log.Append(ex.Message + "\n");
                log.Append(ex.StackTrace + "\n");
            }

            return(log.ToString());
        }
        private Item GetCurrentItem()
        {
            // Parse the querystring to get the item
            string   queryString = WebUtil.GetQueryString("id");
            Language language    = Language.Parse(WebUtil.GetQueryString("la"));

            Sitecore.Data.Version version = Sitecore.Data.Version.Parse(WebUtil.GetQueryString("vs"));
            return(master.GetItem(new ID(queryString), language, version));
        }
        private bool mapMediaItemToSharedContent(Sitecore.Data.Database database, Item allocationItem, string title, MediaItem mediaItem, out ID itemId)
        {
            bool bOk = false;

            itemId = null;

            try
            {
                Item docs = allocationItem.Children["Documents"];
                if (docs == null)
                {
                    Sitecore.Data.Items.TemplateItem docsTemplateItem = database.GetItem("/sitecore/templates/Genworth/Folder Types/Investment Folders/Investment Document Folder");
                    docs = allocationItem.Add("Documents", docsTemplateItem);
                }

                Item performanceItem = docs.Children[title];
                if (performanceItem == null)
                {
                    Sitecore.Data.Items.TemplateItem performanceTemplateItem = database.GetItem("/sitecore/templates/Genworth/Document Types/Investments/Portfolio Information/Monthly Strategist Performance Report");
                    performanceItem = docs.Add(title, performanceTemplateItem);
                }

                itemId = performanceItem.ID;

                using (new Sitecore.SecurityModel.SecurityDisabler())
                {
                    performanceItem.Editing.BeginEdit();

                    Sitecore.Data.Fields.FileField fileField = performanceItem.Fields["File"];
                    fileField.MediaID = mediaItem.ID;
                    fileField.Src     = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);

                    if (dictCategories.ContainsKey("Performance"))
                    {
                        performanceItem["Category"] = dictCategories["Performance"].ToString();
                    }

                    if (dictSources.ContainsKey("AssetMark"))
                    {
                        performanceItem["Source"] = dictSources["AssetMark"].ToString();
                    }

                    performanceItem["Date"] = Sitecore.DateUtil.ToIsoDate(DateTime.Now);

                    performanceItem.Editing.EndEdit();
                }

                bOk = true;
            }
            catch (Exception ex)
            {
                Log.Error(String.Format("Genworth.SitecoreExt.Importers.MonthlyPerformanceImporter:mapMediaItemToSharedContent, allocation: {1}, title {2}, exception: {3}", allocationItem["Title"], title, ex.ToString()), this);
            }

            return(bOk);
        }
        private bool mapMediaItemToSharedContent(Sitecore.Data.Database database, Item managerItem, string title, MediaItem mediaItem)
        {
            bool bOk = false;

            try
            {
                Item docs = managerItem.Children["Documents"];
                if (docs == null)
                {
                    Sitecore.Data.Items.TemplateItem docsTemplateItem = database.GetItem("/sitecore/templates/Genworth/Folder Types/Investment Folders/Investment Document Folder");
                    docs = managerItem.Add("Documents", docsTemplateItem);
                }

                Item commentaryItem = docs.Children[title];
                if (commentaryItem == null)
                {
                    Sitecore.Data.Items.TemplateItem commentaryTemplateItem = database.GetItem("/sitecore/templates/Genworth/Document Types/Investments/Product Commentary/Product Commentary");
                    commentaryItem = docs.Add(title, commentaryTemplateItem);
                }

                using (new Sitecore.SecurityModel.SecurityDisabler())
                {
                    commentaryItem.Editing.BeginEdit();

                    Sitecore.Data.Fields.FileField fileField = commentaryItem.Fields["File"];
                    fileField.MediaID = mediaItem.ID;
                    fileField.Src     = Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);

                    if (dictCategories.ContainsKey("Commentary"))
                    {
                        commentaryItem["Category"] = dictCategories["Commentary"].ToString();
                    }

                    if (dictSources.ContainsKey("AssetMark"))
                    {
                        commentaryItem["Source"] = dictSources["AssetMark"].ToString();
                    }

                    commentaryItem["Date"] = Sitecore.DateUtil.ToIsoDate(DateTime.Now);

                    commentaryItem.Editing.EndEdit();
                }

                bOk = true;
            }
            catch (Exception ex)
            {
                Log.Error(String.Format("Genworth.SitecoreExt.Importers.ExpenseRatioImporter:mapMediaItemToSharedContent, allocation: {1}, title {2}, exception: {3}", managerItem["Name"], title, ex.ToString()), this);
            }

            return(bOk);
        }
Ejemplo n.º 5
0
        public T GetItem <T>(string path) where T : new()
        {
            var item = database.GetItem(path);

            if (item == null)
            {
                return(default(T));
            }

            var t = new T();

            Assign(item, t);
            return(t);
        }
Ejemplo n.º 6
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();
                }
            }
        }
        /// <summary>
        /// Private function used by the getRelatedIds method to create new metadata for lookup content that doesn't exist yet
        /// </summary>
        /// <param name="Name">Name/title to use for content</param>
        /// <param name="Mapping">Mapping to relate the new metadata to</param>
        /// <returns>GUID of the new Metadata</returns>
        public static string addMetadata(string strippedName, string rawName, string folderID, string itemTemplateID)
        {
            using (new SecurityDisabler())
            {
                Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
                Sitecore.Data.Database web    = Sitecore.Configuration.Factory.GetDatabase("web");
                Item         container        = master.GetItem(folderID);
                TemplateItem metadataTemplate = master.Templates[itemTemplateID];
                Item         newItem          = container.Add(strippedName, metadataTemplate);

                newItem.Editing.BeginEdit();

                newItem["Content Title"] = rawName;

                newItem.Editing.EndEdit();

                PublishItem(newItem, master);
                PublishItem(newItem, web);

                //if (container.TemplateID.ToString().ToLower() == AssistiveToolsSkillFolderItem.TemplateId.ToLower())
                //{
                //    if (!CSMUserReviewExtensions.SkillExists(newItem.ID.ToGuid()))
                //        CSMUserReviewExtensions.InsertSkill(newItem.ID.ToGuid());
                //}

                return(newItem.ID.ToString());
            }
        }
Ejemplo n.º 8
0
        protected void Page_Load(object sender, EventArgs e)
        {
            master = Factory.GetDatabase("master");
            MediaItem media = master.GetItem(new ID(Request.QueryString["title"]));
            var item = MediaManager.GetMedia(media);


            HttpWebRequest httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(Request.QueryString["image"]);
            HttpWebResponse httpWebReponse = (HttpWebResponse)httpWebRequest.GetResponse();

            byte[] b = null;
            using (Stream stream = httpWebReponse.GetResponseStream())
            using (MemoryStream ms = new MemoryStream())
            {
                int count = 0;
                do
                {
                    byte[] buf = new byte[1024];
                    count = stream.Read(buf, 0, 1024);
                    ms.Write(buf, 0, count);
                } while (stream.CanRead && count > 0);
                b = ms.ToArray();

                item.SetStream(ms, Request.QueryString["type"]);
            }

            

            httpWebReponse.Close();
            
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Executes the command in the specified context.
        /// </summary>
        /// <param name="context">The context.</param>
        public override void Execute(CommandContext context)
        {
            // Get selected items ids for the cookies
            System.Web.HttpContext itemContext = System.Web.HttpContext.Current;
            string sc_selectedItems            = itemContext.Request.Cookies["sc_selectedItems"].Value;

            // Check if there is item selected
            if (string.IsNullOrEmpty(sc_selectedItems))
            {
                // Return alert to inform the user that no items are selected
                SheerResponse.Alert("No items have been selected, please select items using the check box and then click on 'Publish Selected Items'", Array.Empty <string>());
                return;
            }



            List <NameValueCollection> NameValueCollectionList = new List <NameValueCollection>();
            var itemIDs = sc_selectedItems.Split(',');

            //Start collecting the items to be published
            foreach (var itemID in itemIDs)
            {
                Item item = _master.GetItem(ID.Parse(itemID));
                NameValueCollection nameValueCollection = new NameValueCollection();
                nameValueCollection["id"]       = item.ID.ToString();
                nameValueCollection["language"] = item.Language.ToString();
                nameValueCollection["version"]  = item.Version.ToString();
                nameValueCollection["workflow"] = "0";
                nameValueCollection["related"]  = context.Parameters["related"];
                nameValueCollection["subitems"] = context.Parameters["subitems"];
                nameValueCollection["smart"]    = context.Parameters["smart"];
                NameValueCollectionList.Add(nameValueCollection);
            }
            PublishMultiItems(NameValueCollectionList);
        }
Ejemplo n.º 10
0
        public void SetRight(string strDatabase, string strItem, string strAccount, string strRights, Sitecore.Security.AccessControl.AccessPermission rightState, Sitecore.Security.AccessControl.PropagationType propagationType, Credentials credentials)
        {
            Error.AssertString(strDatabase, "strDatabase", false);
            Error.AssertString(strItem, "strItem", false);
            Error.AssertString(strAccount, "strAccount", false);
            Error.AssertString(strRights, "strRights", false);

            Login(credentials);

            Sitecore.Data.Database   db   = Sitecore.Configuration.Factory.GetDatabase(strDatabase);
            Sitecore.Data.Items.Item item = db.GetItem(strItem);
            Sitecore.Security.Accounts.AccountType accountType = Sitecore.Security.Accounts.AccountType.User;
            if (Sitecore.Security.SecurityUtility.IsRole(strAccount))
            {
                accountType = Sitecore.Security.Accounts.AccountType.Role;
            }
            Sitecore.Security.Accounts.Account account = Sitecore.Security.Accounts.Account.FromName(strAccount, accountType);

            // Always ensure that a minimum of 1 "|" character exists
            if (strRights.IndexOf("|") == -1)
            {
                strRights += '|';
            }

            string[] strRightsList = strRights.Split('|');
            for (int t = 0; t < strRightsList.Length; t++)
            {
                string strRight = strRightsList[t];
                if ((strRight != null) && (strRight != ""))
                {
                    Sitecore.Security.AccessControl.AccessRight right = Sitecore.Security.AccessControl.AccessRight.FromName(strRight);
                    SetRight(item, account, right, rightState, propagationType);
                }
            }
        }
        //compares the context item to the master db's home item in order to properly resolve URLs
        private string UrlFromItemCompare(Item item, SiteContext siteContext)
        {
            //get the home item since we'll need to do a comparison on it.
            string homeItemPath = Sitecore.Context.Site.StartPath.ToString();

            Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
            Item startItem = master.GetItem(homeItemPath);

            //get some ID's for comparison
            ID homeItemID = startItem.ID;
            ID argItemID  = item.ID;

            //gen an empty string to build into for the url
            string itemURL = "";

            if (argItemID != homeItemID) //if the item is anything but Home use the normal site options including the use of full server URL and .aspx extension
            {
                itemURL = LinkManager.GetItemUrl(item, DisplayLinks.GetItemUrlOptions(siteContext));
            }
            else //if the item is the home item, then omit the badly appended .aspx extension which otherwise appears
            {
                itemURL = LinkManager.GetItemUrl(item, DisplayLinks.GetHomeUrlOptions(siteContext));
            }

            return(itemURL);
        }
 public override void Execute(Sitecore.Shell.Framework.Commands.CommandContext context)
 {
     if (context.Parameters != null && context.Parameters.Count > 0)
     {
         string id                 = context.Parameters["id"] ?? "";
         string fieldName          = context.Parameters["fieldName"] ?? "";
         string fieldValue         = context.Parameters["fieldValue"] ?? "";
         Sitecore.Data.Database db = Sitecore.Data.Database.GetDatabase("master");
         if (db != null)
         {
             Item i = db.GetItem(id);
             if (i != null && !String.IsNullOrEmpty(fieldName) && !String.IsNullOrEmpty(fieldValue))
             {
                 using (new EditContext(i))
                 {
                     if (i.Fields[fieldName] != null && i.Fields[fieldName].CanWrite)
                     {
                         i.Fields[fieldName].SetValue(fieldValue, true);
                     }
                 }
                 //String refresh = String.Format("item:refreshchildren(id={0})", Sitecore.Context.Item.Parent.ID);
                 //Sitecore.Context.ClientPage.ClientResponse.Timer(refresh, 2);
             }
         }
     }
 }
        public void Process(WorkflowPipelineArgs args)
        {
            Item      workflowItem = args.DataItem;
            IWorkflow itemwf       = this.master.WorkflowProvider.GetWorkflow(workflowItem);

            // Only run on project workflow
            if (itemwf.WorkflowID != Data.ProjectWorkflow.ToString())
            {
                return;
            }

            // Find other items that are in the same project
            var items = master.SelectItems("fast:/sitecore/content//*[@Project = '" + workflowItem.Fields[Data.ProjectFieldId].Value + "']");

            // Get the project defintion
            var       projectDefinition  = master.GetItem(workflowItem.Fields[Data.ProjectFieldId].Value);
            DateField projectReleaseDate = projectDefinition.Fields[Data.ProjectDetailsReleaseDate];

            // If there are no other items in the project, and it's after the project release date, continue the workflow.
            if (items == null && projectReleaseDate.DateTime < DateTime.Now)
            {
                // no other items using this so, send back
                RevertItemsWorkflowToOrigional(workflowItem);
                AutoPublish(args);
            }
            else
            {
                foreach (var item in items)
                {
                    // is the item in the same project
                    if (item.Fields[Data.ProjectFieldId].Value == workflowItem.Fields[Data.ProjectFieldId].Value)
                    {
                        // is it not in the waiting state
                        if (item.Fields["__Workflow state"].Value != Data.ProjectWorkflowReadytoGoLiveState.ToString())
                        {
                            if (item.ID != workflowItem.ID) // ignore if same item
                            {
                                AllItemsReady = false;
                                break;
                            }
                        }
                    }
                }

                if (AllItemsReady && projectReleaseDate.DateTime < DateTime.Now)
                {
                    foreach (var item in items)
                    {
                        // is the item in the same project
                        if (item.Fields[Data.ProjectFieldId].Value == workflowItem.Fields[Data.ProjectFieldId].Value)
                        {
                            RevertItemsWorkflowToOrigional(item);
                        }
                    }

                    AutoPublish(args);
                }
            }
        }
        public static Item ResolvePublishItem(Item item, Item stopItem, Sitecore.Data.Database publishDatabase)
        {
            if (item.Parent == null || item.Parent.ID == stopItem.ID || publishDatabase.GetItem(item.ID) != null)
            {
                return(item);
            }

            return(ResolvePublishItem(item.Parent, stopItem, publishDatabase));
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Gets an item with specified language and guid
        /// </summary>
        /// <param name="str">Contains item guid and item language</param>
        /// <returns>item from guid and language values</returns>
        public static Item GetItemFromStr(string str)
        {
            string[] itemParams = str.ToString().Split(new char[] { '^' });
            Language language   = Language.Parse(itemParams[1]);

            Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
            Item item = master.GetItem(itemParams[0], language);

            return(item);
        }
 public override void Execute(Sitecore.Shell.Framework.Commands.CommandContext context)
 {
     if (context.Parameters != null && context.Parameters.Count > 0)
     {
         try
         {
             string itemID = context.Parameters["itemID"] ?? "";
             itemID = Util.FormatID(itemID);
             string dsID = context.Parameters["dataSourceID"] ?? "";
             dsID = Util.FormatID(dsID);
             string renderingID = context.Parameters["renderingID"] ?? "";
             renderingID = Util.FormatID(renderingID);
             string deviceID = context.Parameters["deviceID"] ?? "";
             deviceID = Util.FormatID(deviceID);
             string dbName             = context.Parameters["dbName"] ?? "";
             Sitecore.Data.Database db = Sitecore.Data.Database.GetDatabase(dbName);
             if (db != null)
             {
                 Item i = db.GetItem(itemID);
                 try
                 {
                     string name = i.Name;
                 }
                 catch { }
                 if (i != null && Sitecore.Data.ID.IsID(renderingID) && Sitecore.Data.ID.IsID(dsID))
                 {
                     using (new EditContext(i))
                     {
                         Sitecore.Data.Fields.LayoutField  layoutField      = new Sitecore.Data.Fields.LayoutField(i.Fields[Sitecore.FieldIDs.LayoutField]);
                         Sitecore.Layouts.LayoutDefinition layoutDefinition = Sitecore.Layouts.LayoutDefinition.Parse(layoutField.Value);
                         Sitecore.Layouts.DeviceDefinition deviceDefinition = layoutDefinition.GetDevice(deviceID);
                         foreach (Sitecore.Layouts.RenderingDefinition rd in deviceDefinition.Renderings)
                         {
                             if (HealthIS.Apps.Util.FormatID(rd.UniqueId) == renderingID)
                             {
                                 rd.Datasource     = HealthIS.Apps.Util.FormatID(dsID);
                                 layoutField.Value = layoutDefinition.ToXml();
                             }
                         }
                     }
                 }
                 else
                 {
                     Exception ex = new Exception("Update Datasource Issue with id: " + itemID + " or dsID: " + dsID + " or i: " + i);
                     Util.LogError(ex.Message, ex, this);
                 }
             }
         }
         catch (Exception ex)
         {
             Util.LogError(ex.Message, ex, this);
         }
     }
 }
 /// <summary>
 /// Get Sitecore Item by value
 /// </summary>
 /// <param name="db">Sitecore Database</param>
 /// <param name="value">Value as ID, GUID, Path, or Item</param>
 /// <returns>Sitecore Item</returns>
 public static Item GetItemFromValue(this SC.Data.Database db, object value)
 {
     if (value is Item)
     {
         return((Item)value);
     }
     else
     {
         return(db.GetItem(value.ToString()));
     }
 }
            /// <summary>
            /// Called when loading or reloading the mapping
            /// </summary>
            /// <param name="Container">GUID of the container to load</param>
            /// <returns>Dictionary that represents the children of the container. Key is the name of the item, Value is the GUID</returns>
            private Dictionary <string, string> getChildren(string Container)
            {
                Dictionary <string, string> ret = new Dictionary <string, string>();

                Sitecore.Data.Database   master    = Sitecore.Configuration.Factory.GetDatabase(Instance.Settings.MasterDatabaseName);
                Sitecore.Data.Items.Item container = master.GetItem(Container);

                foreach (Sitecore.Data.Items.Item item in container.Children)
                {
                    ret.Add(item.Name, item.ID.ToString());
                }

                return(ret);
            }
        private Item GetContextItem(string placeholderKey)
        {
            HttpContext httpContext = HttpContext.Current;
            Item        contextItem = Sc.Context.Item;

            if (contextItem == null)
            {
                string           itemId = GetContextItemId();
                Sc.Data.Database master = Sc.Configuration.Factory.GetDatabase("master");
                contextItem = master.GetItem(new Sc.Data.ID(itemId));
            }

            return(contextItem);
        }
        private void SetRight(string strDatabase, string strItem, string strAccount, List <AccessRight> rights)
        {
            //Get Access Rules, Set Access Rules
            try
            {
                Sitecore.Data.Database db    = Sitecore.Configuration.Factory.GetDatabase(strDatabase);
                Item             item        = db.GetItem(strItem);
                AccountType      accountType = AccountType.User;
                Account          account     = Account.FromName(strAccount, accountType);
                AccessPermission rightState  = AccessPermission.Allow;

                if (Sitecore.Security.SecurityUtility.IsRole(strAccount))
                {
                    accountType = Sitecore.Security.Accounts.AccountType.Role;
                }

                AccessRuleCollection accessRules = item.Security.GetAccessRules();

                foreach (AccessRight right in rights)
                {
                    try
                    {
                        accessRules.Helper.RemoveExactMatches(account, right);
                    }
                    catch (Exception ex)
                    {
                        Log.Debug("accessRules.Helper.RemoveExactMatches " + ex.Message.ToString());
                    }

                    try
                    {
                        accessRules.Helper.AddAccessPermission(account, right, PropagationType.Entity, rightState);
                        accessRules.Helper.AddAccessPermission(account, right, PropagationType.Descendants, rightState);
                        Log.Debug(account.Name.ToString() + " has access right of " + right.Name.ToString() + " for " + strItem);
                    }
                    catch (Exception ex)
                    {
                        Log.Debug("accessRules.Helper.AddAccessPermission " + ex.Message.ToString());
                    }
                }


                item.Security.SetAccessRules(accessRules);
            }
            catch
            (Exception ex)
            {
                Log.Debug(ex.Message.ToString());
            }
        }
Ejemplo n.º 21
0
        private SearchConfigurations BuildSearchConfigurations(SearchParameters parameters)
        {
            Sitecore.Data.Database contextDb = Sitecore.Context.Database;
            if (contextDb == null)
            {
                contextDb = Sitecore.Configuration.Factory.GetDatabase((String.IsNullOrEmpty(parameters.DatabaseName) ? parameters.DatabaseName : "web"));
            }
            Item tabItem = contextDb.GetItem(Sitecore.Data.ID.Parse(parameters.TabId));

            Item configurationsItem = tabItem.Parent;

            SearchConfigurations configurations = new SearchConfigurations(configurationsItem, parameters.TabId);

            return(configurations);
        }
        public static UploadFileInfo RetrieveFile(string fileId, Sitecore.Data.Database database)
        {
            var item = database.GetItem(new ID(fileId));

            if (item != null)
            {
                var mediaItem = new Sitecore.Data.Items.MediaItem(item);

                return(new UploadFileInfo
                {
                    Id = fileId,
                    Name = mediaItem.InnerItem.Name + "." + mediaItem.Extension,
                    Bytes = mediaItem.GetMediaStream().ToBytes(mediaItem.Size)
                });
            }

            return(null);
        }
Ejemplo n.º 23
0
        public IEnumerable <FileDefinition> Fetch(Sitecore.Data.Database db)
        {
            if (db == null)
            {
                throw new ArgumentNullException("db");
            }

            List <FileDefinition> defs = new List <FileDefinition>();

            Item definitionFolder = db.GetItem(SitemapDefinitionsFolderID);

            foreach (Item definition in definitionFolder.Children)
            {
                FileDefinition sd = new FileDefinition(definition);
                defs.Add(sd);
            }

            return(defs);
        }
Ejemplo n.º 24
0
        public static IEnumerable <Tag> GetTagsOrderedByCount(Dictionary <string, int> tagCount)
        {
            IList <Tag> tagList = new List <Tag>();
            // order the count descending then build list based on this order.
            var items = from pair in tagCount
                        orderby pair.Value descending
                        select pair;

            Sitecore.Data.Database context = Sitecore.Context.Database;
            foreach (KeyValuePair <string, int> pair in items)
            {
                if (Sitecore.Data.ID.IsID(pair.Key))
                {
                    Tag thisItem = context.GetItem(Sitecore.Data.ID.Parse(pair.Key)).CreateAs <Tag>();
                    tagList.Add(thisItem);
                }
            }

            return(tagList);
        }
        public static void DeleteMediaItem(Item root, string itemId, Sitecore.Data.Database contentDatabase, Sitecore.Data.Database publishDatabase)
        {
            var itemToDelete = contentDatabase.GetItem(new ID(itemId));

            if (itemToDelete != null && itemToDelete.Parent.ID == root.ID)
            {
                using (new SecurityDisabler())
                {
                    itemToDelete.Editing.BeginEdit();
                    itemToDelete.Publishing.NeverPublish = true;
                    itemToDelete.Editing.EndEdit();
                }

                Publish(itemToDelete, publishDatabase);

                using (new SecurityDisabler())
                {
                    itemToDelete.Delete();
                }
            }
        }
Ejemplo n.º 26
0
        private ContentDataItem[] GetItemSubTreeSelectedNodeFromDB(string itemId, string dbName)
        {
            ContentDataItem tree = null;

            if (string.IsNullOrWhiteSpace(itemId))
            {
                return(null);
            }

            if (!string.IsNullOrWhiteSpace(dbName))
            {
                using (new Sitecore.SecurityModel.SecurityDisabler())
                {
                    Sitecore.Data.Database database = Sitecore.Data.Database.GetDatabase(dbName);

                    var rootItem = database.GetItem(new Sitecore.Data.ID(itemId));
                    tree = GetChildren(rootItem);
                }
            }

            return(new ContentDataItem[] { tree });
        }
Ejemplo n.º 27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            master = Factory.GetDatabase("master");
            MediaItem media = master.GetItem(new ID(Request.QueryString["id"]));

            Stream mediaStream = media.GetMediaStream();

            var filename = media.DisplayName + "." + media.Extension;
            var filenamepath = Path.Combine(Server.MapPath("~/App_Data"), filename);

            String strUrl = HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.PathAndQuery, "/");
            strUrl = strUrl +  "/sitecore modules/pixlr/";
            

            SaveStreamToFile(filenamepath, mediaStream);
            
            UploadFile[] files = new UploadFile[] 
            { 
                new UploadFile(filenamepath)
            }; 

            
            NameValueCollection nv = new NameValueCollection();
            nv.Add("target", strUrl + "save.aspx");
            nv.Add("exit", strUrl + "exit.aspx");
            nv.Add("method", "get");
            nv.Add("title", media.ID.ToString().Replace("{", "").Replace("}", ""));
            nv.Add("locktarget", "true");
            nv.Add("locktitle", "true");
            nv.Add("referrer", "Sitecore");

            var response = Utils.HttpUploadHelper.Upload("http://pixlr.com/" + Request.QueryString["mode"] + "/",files , nv);

            File.Delete(filenamepath);

            Response.Redirect(response, true);
            Response.End();
        }
Ejemplo n.º 28
0
        public void CreateTeamMemberSitecoreItem(ID TeamId, TeamMember TeamMember)
        {
            try
            {
                Sitecore.Data.Database masterDB = Sitecore.Configuration.Factory.GetDatabase(DBNames.Master);

                Item parentItem = masterDB.GetItem(TeamId);

                string name         = ItemUtil.ProposeValidItemName(TeamMember.FullName);
                var    teamTemplate = masterDB.GetTemplate(Templates.TeamMember.ID);

                using (new Sitecore.SecurityModel.SecurityDisabler())
                {
                    Item newItem = parentItem.Add(name, teamTemplate);
                    try
                    {
                        if (newItem != null)
                        {
                            newItem.Editing.BeginEdit();
                            newItem[Templates.TeamMember.Fields.FullName]     = TeamMember.FullName;
                            newItem[Templates.TeamMember.Fields.EmailAddress] = TeamMember.EmailAddress;
                            newItem[Templates.TeamMember.Fields.LinkedInUrl]  = TeamMember.LinkedInUrl;
                            newItem[Templates.TeamMember.Fields.TwitterUrl]   = TeamMember.TwitterUrl;
                            newItem[Templates.TeamMember.Fields.Country]      = TeamMember.Country;
                            newItem.Editing.EndEdit();
                        }
                    }
                    catch
                    {
                        newItem.Editing.CancelEdit();
                    }
                }
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error(ex.Message, ex, this);
            }
        }
Ejemplo n.º 29
0
        private void ValidateSearchConfigurations(SearchParameters parameters)
        {
            if (parameters.TabId == null)
            {
                throw new Exception("Error: TabId is not set");
            }
            Sitecore.Data.Database contextDb = Sitecore.Context.Database;
            if (contextDb == null)
            {
                contextDb = Sitecore.Configuration.Factory.GetDatabase((String.IsNullOrEmpty(parameters.DatabaseName) ? parameters.DatabaseName : "web"));
            }
            parameters.DatabaseName = contextDb.Name;
            Item tabItem = contextDb.GetItem(Sitecore.Data.ID.Parse(parameters.TabId));

            if (tabItem == null)
            {
                throw new Exception("Error: Tab item does not exists in sitecore - " + contextDb.Name + " Database");
            }
            if (tabItem.TemplateID != SearchTemplates.Tab.ID)
            {
                throw new Exception("Error: Setting item template is incorrect");
            }
        }
Ejemplo n.º 30
0
        private static Item CreateFolder(string itemName, Item parentItem)
        {
            Item newItem = null;

            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                // Get the master database
                Sitecore.Data.Database master = Sitecore.Data.Database.GetDatabase("master");
                // Get the template to base the new item on
                TemplateID templateID = new TemplateID(master.GetItem(new ID(new Guid(Constants.SubArticlesFolderTemplateID))).ID);

                // Add the item to the site tree
                newItem = parentItem.Add(itemName, templateID);

                // Set the new item in editing mode
                // Fields can only be updated when in editing mode
                // (It's like the begin tarnsaction on a database)
                newItem.Editing.BeginEdit();
                try
                {
                    // End editing will write the new values back to the Sitecore
                    // database (It's like commit transaction of a database)
                    newItem.Editing.EndEdit();
                }
                catch (System.Exception ex)
                {
                    // The update failed, write a message to the log
                    Sitecore.Diagnostics.Log.Error("Could not update item " + newItem.Paths.FullPath + ": " + ex.Message, true);

                    // Cancel the edit (not really needed, as Sitecore automatically aborts
                    // the transaction on exceptions, but it wont hurt your code)
                    newItem.Editing.CancelEdit();
                }
            }

            return(newItem);
        }
Ejemplo n.º 31
0
        public bool CreateModule(ModuleItem moduleItem)
        {
            Sitecore.Diagnostics.Assert.ArgumentNotNull(moduleItem, "Module Item");

            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                Sitecore.Data.Database master = Database.GetDatabase(MasterDatabase);
                Sitecore.Diagnostics.Assert.ArgumentNotNull(master, "Master Database");

                TemplateItem template = master.GetTemplate(IDs.TemplateId);
                Sitecore.Diagnostics.Assert.ArgumentNotNull(template, "Module Templete");

                Item parentItem = master.GetItem(IDs.ModuleFolderId);
                Sitecore.Diagnostics.Assert.ArgumentNotNull(parentItem, "Module Parent Folder");

                string itemName = Sitecore.Data.Items.ItemUtil.ProposeValidItemName($"{moduleItem.Title}-{moduleItem.Author}", "Module Item");

                using (new Sitecore.SecurityModel.SecurityDisabler())
                {
                    try
                    {
                        Item newItem = parentItem.Add(itemName, template);

                        if (newItem != null)
                        {
                            newItem.Editing.BeginEdit();

                            newItem.Fields[IDs.Fields.GitHubURL].Value                    = moduleItem.GitHubURL;
                            newItem.Fields[IDs.Fields.DocumentationURL].Value             = moduleItem.DocumentationURL;
                            newItem.Fields[IDs.Fields.Title].Value                        = moduleItem.Title;
                            newItem.Fields[IDs.Fields.Summary].Value                      = moduleItem.Summary;
                            newItem.Fields[IDs.Fields.Author].Value                       = moduleItem.Author;
                            newItem.Fields[IDs.Fields.TestedAgainstSitecoreVersion].Value = moduleItem.TestedAgainstSitecoreVersion;
                            newItem.Fields[IDs.Fields.ProductLine].Value                  = moduleItem.ProductLine;

                            Sitecore.Data.Fields.DateField releaseDateField = newItem.Fields[IDs.Fields.ReleaseDate];
                            releaseDateField.Value = DateUtil.ToIsoDate(moduleItem.ReleaseDate);

                            Sitecore.Data.Fields.DateField lastCommitDateField = newItem.Fields[IDs.Fields.LastCommitDate];
                            lastCommitDateField.Value = DateUtil.ToIsoDate(moduleItem.LastCommitDate);

                            newItem.Fields[IDs.Fields.Stars].Value         = moduleItem.Stars.ToString();
                            newItem.Fields[IDs.Fields.DownloadCount].Value = moduleItem.DownloadCount.ToString();


                            newItem.Editing.EndEdit();

                            TagItem(newItem);
                            PublishItem(newItem);
                            return(true);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        Sitecore.Diagnostics.Log.Error($"Could not create new item {itemName}", ex, this);
                        // newItem.Editing.CancelEdit();
                    }
                }

                return(false);
            }
        }
Ejemplo n.º 32
0
 /// <summary>
 /// Publishes the item.
 /// </summary>
 /// <param name="targetItemID">The target item ID.</param>
 /// <param name="childs">If true publish the children of the item as well</param>
 public static void PublishItem(ID targetItemID, bool childs = false)
 {
     Sitecore.Data.Database   master = GetContentDatabase();
     Sitecore.Data.Items.Item home   = master.GetItem(targetItemID);
     PublishItem(home, false);
 }