public static bool CheckSolutionExist(Sitecore.Data.Database database, string strategist, Item allocationItem, string strategy) { if (database == null) { Log.Error(String.Format("Genworth.SitecoreExt.Utilities.ContentEditorHelper:CheckSolutionExist, database cannot be null or empty"), typeof(ContentEditorHelper)); return(false); } else if (String.IsNullOrEmpty(strategist)) { Log.Error(String.Format("Genworth.SitecoreExt.Utilities.ContentEditorHelper:CheckSolutionExist, strategy cannot be null or empty"), typeof(ContentEditorHelper)); return(false); } else if (String.IsNullOrEmpty(allocationItem["Title"])) { Log.Error(String.Format("Genworth.SitecoreExt.Utilities.ContentEditorHelper:CheckSolutionExist, allocation cannot be null or empty. Strategist: {0}", strategist), typeof(ContentEditorHelper)); return(false); } string sharedPath = "/sitecore/content/Shared Content/Investments/Strategists/#" + strategist + "#/#" + allocationItem.Name + "#/*[@@templatekey = 'solution' and @Code='" + strategy + "']"; Item strategyItem = database.SelectSingleItem(sharedPath); if (strategyItem == null) { return(false); } else { return(true); } }
//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); }
/// <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()); }
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(); }
/// <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()); } }
protected override void OnLoad(EventArgs e) { master = Factory.GetDatabase("master"); item = GetCurrentItem(); if (!Context.ClientPage.IsEvent) { if (string.IsNullOrEmpty(item.Fields["VideoID"].Value)) { VideoTitle.Value = item.Fields["Title"].Value; VideoDescription.Value = item.Fields["Description"].Value; VideoKeywords.Value = item.Fields["Keywords"].Value; ItemId.Value = item.ID.ToString(); VideoStatus.Visible = false; } else { form.Visible = false; StartButton.Visible = false; VideoStatus.Visible = true; this.YouTubeVideoID = item.Fields["VideoID"].Value; DisplayVideoStatus(); } } base.OnLoad(e); }
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); } } }
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 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)); }
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); }
/// <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); }
protected void InitializeImportBase() { this.ImportStatus = Enumerations.JobStatus.Running; this._database = SC.Configuration.Factory.GetDatabase("master"); this.ImportMessages = new List <StatusMessage>(); if (this._database == null) { throw new NullReferenceException("Master DB cannot be accessed. Please make sure the import is running with access to the Master DB."); } }
public void SetUp() { Sitecore.Context.IsUnitTesting = true; InitializeMongoConnection(); _SqlDatabase = Factory.GetDatabase("master"); _mongoTestDb = Factory.GetDatabase("nosqlmongotest"); CreateTestTemplate(_SqlDatabase); CreateTestContent(_SqlDatabase); TransferUtil.TransferPath("/sitecore/templates", _SqlDatabase, _mongoTestDb, null); TransferUtil.TransferPath("/sitecore/content", _SqlDatabase, _mongoTestDb, null); }
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())); } }
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); }
public static void Publish(Item itemToPublish, Sitecore.Data.Database publishDatabase) { var publishOptions = new Sitecore.Publishing.PublishOptions(itemToPublish.Database, publishDatabase, Sitecore.Publishing.PublishMode.SingleItem, itemToPublish.Language, DateTime.Now); var publisher = new Sitecore.Publishing.Publisher(publishOptions); publisher.Options.RootItem = itemToPublish; publisher.Options.Deep = true; publisher.Publish(); }
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()); } }
/// <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); }
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 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 RoleStruct[] GetUsers(string sDomain) { using (new Sitecore.SecurityModel.SecurityDisabler()) { Sitecore.SecurityModel.Domain domain = Sitecore.SecurityModel.Domain.FromName(sDomain); Sitecore.Data.Database db = domain.Database; if (db == null) { return(null); } // create a query that will handle the Role retrieval // here we simply rely on the Role's Template ID string query = "//*[@@templateid='" + Sitecore.TemplateIDs.User + "']"; Sitecore.Data.Items.Item[] items = db.SelectItems(query); Sitecore.SecurityModel.UserItem[] users = new Sitecore.SecurityModel.UserItem[items.Length]; List <RoleStruct> roles5x = new List <RoleStruct>(); // fill this array with Role Items for (int i = 0; i < users.Length; i++) { users[i] = new Sitecore.SecurityModel.UserItem(items[i], domain); RoleStruct role = new RoleStruct(); role.Name = users[i].Domain.Name + "\\" + users[i].Name; role.ID = users[i].ID.ToString(); role.Path = users[i].InnerItem.Paths.ContentPath; role.AccessRight = AccessRights.NotSet; role.Email = users[i].Email; role.FullName = users[i].Fullname; if (users[i].InnerItem.Fields["password"] != null) { role.PassWord = users[i].InnerItem.Fields["password"].Value; } role.IsAdmin = users[i].IsAdministrator; role.Roles = ""; for (int t = 0; t < users[i].Roles.RoleNames.Length; t++) { if (role.Roles != "") { role.Roles += "|"; } role.Roles += users[i].Roles.RoleNames[t]; } roles5x.Add(role); } return(roles5x.ToArray()); } }
public static List <Item> GetRedirectsForItem(ID itemID) { // Based off the config file, we can run different types of queries. Sitecore.Data.Database db = Database.GetDatabase("master"); IEnumerable <Item> ret = null; var redirectRoot = Sitecore.Configuration.Settings.GetSetting(Constants.Settings.RedirectRootNode); ret = db.SelectItems(String.Format("{0}//*[@Redirect To Item = '{1}']", redirectRoot, itemID.ToString())); // make sure to return an empty list instead of null if (ret == null) { return(new List <Item>()); } return(ret.ToList <Item>()); }
private bool mapItemToStrategist(Sitecore.Data.Database database, string strategist, Item allocationItem, string strategy, ID itemId) { bool bOk = false; try { if (ID.IsNullOrEmpty(itemId)) { Log.Error(String.Format("Genworth.SitecoreExt.Importers.FactSheetImporter:mapMediaItemToStrategist, mediaItem cannot be null or empty. Strategist: {0}, allocation: {1}", strategist, allocationItem["Title"]), this); return(false); } string sharedPath = "/sitecore/content/Shared Content/Investments/Strategists/#" + strategist + "#/#" + allocationItem.Name + "#/*[@@templatekey = 'solution' and @Code='" + strategy + "']"; Item strategyItem = database.SelectSingleItem(sharedPath); if (strategyItem == null) { Log.Error(String.Format("Genworth.SitecoreExt.Importers.FactSheetImporter:mapMediaItemToStrategist, solution node for strategy {0}, allocation approach {1}, does not exist, skipping. " + "This generally happens when the solution node is either missing or has a code that doesn't match the document naming convention. Path: {2}", strategist, allocationItem["Title"], sharedPath), this); return(false); } Sitecore.Data.Fields.ReferenceField referenceField = strategyItem.Fields["Fact Sheet"]; if (referenceField != null) { using (new Sitecore.SecurityModel.SecurityDisabler()) { strategyItem.Editing.BeginEdit(); referenceField.Value = itemId.ToString(); strategyItem.Editing.EndEdit(); } } bOk = true; } catch (Exception ex) { Log.Error(String.Format("Genworth.SitecoreExt.Importers.FactSheetImporter:mapMediaItemToStrategist, strategist: {0}, allocation: {1}, solution: {2}, exception: {3}", strategist, allocationItem["Title"], strategy, ex.ToString()), this); bOk = false; } return(bOk); }
/// <summary> /// Publishes the item. /// </summary> /// <param name="targetItem">The target item.</param> public static void PublishItem(Item targetItem, bool childs = false) { DateTime publishDate = DateTime.Now; Sitecore.Data.Database master = GetContentDatabase(); var targetDBs = GetPublishingTargets(master); foreach (var db in targetDBs) { foreach (Sitecore.Globalization.Language language in master.Languages) { Sitecore.Publishing.PublishOptions publishOptions = new Sitecore.Publishing.PublishOptions(master, db, Sitecore.Publishing.PublishMode.SingleItem, language, publishDate); publishOptions.RootItem = targetItem; publishOptions.Deep = childs; Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(publishOptions); publisher.Publish(); } } }
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); }
private DataTable getProductDataOld() { Sitecore.Data.Database masterDB = Sitecore.Configuration.Factory.GetDatabase("web"); DataTable dt = new DataTable(); dt.Columns.Add("ProductName"); Item[] productGroup = masterDB.SelectItems("fast://*[@@templatekey='ProductGroup']"); foreach (Item product in productGroup) { DataRow dr = dt.NewRow(); string value = product.Fields["Product Group Name"].Value.ToString().Trim().Replace("<sup>", "").Replace("</sup>", ""); dr["ProductName"] = value; dt.Rows.Add(dr); } DataView dv = new DataView(dt); return(dv.ToTable(true, "ProductName")); }
/// <summary> /// Get Sitecore Items by an enumerable of object values /// </summary> /// <param name="db">Sitecore Database</param> /// <param name="values">Values as ID, GUID, Path, or Item</param> /// <param name="ignoreNull">Disable to throw exception on null Item</param> /// <returns>List of Sitecore Items</returns> public static List <Item> GetItems(this SC.Data.Database db, IEnumerable values, bool ignoreNull = true) { List <Item> items = new List <Item>(); foreach (object value in values) { Item item = db.GetItemFromValue(value); if (item == null && !ignoreNull) { throw new NullReferenceException(string.Format("No item found matching {0}.", value.ToString())); } if (item != null) { items.Add(item); } } return(items); }
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); }
protected override void OnLoad(EventArgs e) { master = Factory.GetDatabase("master"); if (!Context.ClientPage.IsEvent) { item = GetCurrentItem(); if (!string.IsNullOrEmpty(item.Fields[Data.ProjectFieldId].Value) || item.TemplateID == Data.ProjectDetails) { StringBuilder result = new StringBuilder(); StringBuilder resultStatus = new StringBuilder(); RenderProjectItems(result, resultStatus); Links.Controls.Add(new LiteralControl(result.ToString())); Status.Controls.Add(new LiteralControl(resultStatus.ToString())); } } base.OnLoad(e); }
public ID CreateTeamSitecoreItem(Team Team) { try { Sitecore.Data.Database masterDB = Sitecore.Configuration.Factory.GetDatabase(DBNames.Master); Item _rootItem = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath); Item parentItem = _rootItem.Axes.GetDescendants().ToList().Where(p => p.IsDerived(Templates.TeamsListing.ID)).FirstOrDefault(); string name = ItemUtil.ProposeValidItemName(Team.TeamName); var teamTemplate = masterDB.GetTemplate(Templates.Team.ID); using (new Sitecore.SecurityModel.SecurityDisabler()) { Item newItem = parentItem.Add(name, teamTemplate); try { if (newItem != null) { newItem.Editing.BeginEdit(); newItem[Templates.Team.Fields.Name] = Team.TeamName; newItem[Templates.Team.Fields.EmailAddress] = Team.EmailAddress; newItem[Templates.Team.Fields.LoginName] = Team.LoginName; newItem[Templates.Team.Fields.Password] = Team.Password; newItem.Editing.EndEdit(); } } catch { newItem.Editing.CancelEdit(); } RegisterTeam(Team.LoginName, Team.Password); return(newItem.ID); } } catch (Exception ex) { Sitecore.Diagnostics.Log.Error(ex.Message, ex, this); } return(null); }
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(); }