public void PublishItem(int changeId, string approvalStatus) { List <ItemChangeHistory> changeList = GetItemChangeHistory(changeId, approvalStatus); if (changeList.Count > 0) { ItemChangeHistory change = GetItemChangeHistory(changeId, approvalStatus)[0]; string itemId = change.ItemId; string changeType = change.ChangeType; ETDataExtension etd = new ETDataExtension(); etd.InsertIntoDataExtension(change.ItemHtml, change.ChangeType, change.ProductCategory); Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master"); Sitecore.Data.Database web = Sitecore.Configuration.Factory.GetDatabase("web"); Sitecore.Data.Items.Item item = master.Items.GetItem(itemId); Sitecore.Publishing.PublishOptions publishOptions = new Sitecore.Publishing.PublishOptions(item.Database, web, Sitecore.Publishing.PublishMode.SingleItem, item.Language, System.DateTime.Now); Sitecore.Publishing.Publisher publisher = new Sitecore.Publishing.Publisher(publishOptions); publisher.Options.RootItem = item; publisher.Options.Deep = true; publisher.Publish(); } }
public static Item GetItemByIdAndVersion(string Ciid, string version, Sitecore.Data.Database database) { var itemVersion = new Sitecore.Data.Version(version); var language = Language.Parse(ContextExtension.CurrentLanguageCode); return(database.GetItem(Ciid, language, itemVersion)); }
/// <summary> /// Returns the publishing targets defined in the specified database. /// </summary> /// <param name="database">The database containing the publishing target definition /// items.</param> /// <returns>The publishing targets in the specified database.</returns> public static PublishingTarget[] GetPublishingTargets( Sitecore.Data.Database database) { Sitecore.Data.Items.Item[] items = Sitecore.Publishing.PublishManager.GetPublishingTargets(database).ToArray(); return(GetPublishingTargets(items)); }
/// <summary> /// Returns the default publishing targets defined in the Master database. /// </summary> /// <returns>The default publishing targets defined in the Master database. /// </returns> public static PublishingTarget[] GetPublishingTargets() { Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master"); Sitecore.Diagnostics.Assert.IsNotNull(master, "master"); return(GetPublishingTargets(master)); }
protected void Run() { if (this.MaxVersions < 1) { this.MaxVersions = 10; } if (String.IsNullOrEmpty(this.Database)) { this.Database = "master"; } Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase(this.Database); Sitecore.Diagnostics.Assert.IsNotNull(db, this.Database); if (String.IsNullOrEmpty(this.RootItem)) { this.RootItem = db.GetRootItem().Paths.FullPath; } foreach (Sitecore.Globalization.Language language in db.Languages) { this.Iterate(db.GetItem(this.RootItem, language)); } }
public static Sitecore.Data.Items.Item GetHomeItem( this Sitecore.Sites.SiteContext me, Sitecore.Data.Database database) { Sitecore.Diagnostics.Assert.ArgumentNotNull(database, "database"); return(database.GetItem(me.StartPath)); }
// GET: Home public ActionResult Index() { Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase("master"); var Item = db.GetItem("/sitecore/content/Home"); return(View()); }
protected void ValidateAndSetDatabase() { Sitecore.Diagnostics.Assert.IsNotNullOrEmpty(this.Database, "Database"); this._database = Sitecore.Configuration.Factory.GetDatabase( this.Database); Sitecore.Diagnostics.Assert.IsNotNull(this._database, this.Database); }
// Product Symbols #region Create Item private Item CreateItem(string rootItempath, string templateItempath, string itemName, Dictionary <string, string> fieldsToUpdate, bool addVersion, Item defaultLanguageItem, string lang, string postid, string posttype) { Item newItem = null; // The SecurityDisabler overrides the current security model, allowing you // to access the item without any security. It's like the user being an administrator 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 TemplateItem template = master.GetItem(templateItempath); // Get the place in the site tree where the new item must be inserted Item parentItem = master.GetItem(rootItempath); if (addVersion == false) { newItem = CreateDefaultLanguageItem(itemName + postid, fieldsToUpdate, newItem, template, parentItem); } if (newItem == null) { newItem = defaultLanguageItem; } newItem = AddLanguageVersionItem(posttype, itemName, fieldsToUpdate, template, newItem, master, lang, postid); } return(newItem); }
protected void Run(Sitecore.Web.UI.Sheer.ClientPipelineArgs args) { if (!Sitecore.Web.UI.Sheer.SheerResponse.CheckModified()) { return; } if (args.IsPostBack) { Sitecore.Web.UI.Sheer.SheerResponse.Confirm(Sitecore.Globalization.Translate.Text( "Reset {0} to its standard value?", new object[] { args.Parameters["field"] })); args.WaitForPostBack(); } if (!args.HasResult) { return; } if (args.Result != "yes") { return; } Sitecore.Data.Database database = Sitecore.Configuration.Factory.GetDatabase(args.Parameters["database"]); Sitecore.Globalization.Language language = Sitecore.Globalization.Language.Parse(args.Parameters["language"]); Sitecore.Data.Version version = Sitecore.Data.Version.Parse(args.Parameters["version"]); Sitecore.Data.Items.Item item = database.GetItem(args.Parameters["id"], language, version); using (new Sitecore.Data.Items.EditContext(item)) { item.Fields[args.Parameters["field"]].Reset(); } }
public override void Process(PipelineStep pipelineStep, PipelineContext pipelineContext) { var logger = pipelineContext.PipelineBatchContext.Logger; var settings = pipelineStep.GetPlugin <PublishContentSettings>(); if (settings == null) { logger.Error( "No Publish Content Settings Detected. " + "(pipeline step: {0})", pipelineStep.Name); return; } Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master"); Sitecore.Data.Database target = Sitecore.Configuration.Factory.GetDatabase(settings.Target); var rootItem = master.GetItem(new Sitecore.Data.ID(settings.RootItem)); logger.Info("About to Start Publish"); Sitecore.Publishing.PublishManager.PublishItem(rootItem, new Sitecore.Data.Database[] { target }, settings.Languages.ToArray(), settings.ChildItems, true, //always smart publish settings.RelatedItems); logger.Info("Publish Started for {0}", rootItem.Name); }
/// <summary> /// Triggered by Sitecore to initialize the index rebuilding strategy. /// </summary> /// <param name="index">Index associated with the index rebuilding strategy.</param> public void Initialize(SC.ContentSearch.ISearchIndex index) { Assert.ArgumentNotNull(index, "index"); if (this._ruleDatabase == null && !string.IsNullOrEmpty(index.Name)) { string[] parts = index.Name.Split('_'); if (parts.Length > 1) { this._ruleDatabase = SC.Configuration.Factory.GetDatabase(parts[1]); } } SC.Diagnostics.Assert.IsNotNull(this._ruleDatabase, "_ruleDatabase"); if (string.IsNullOrEmpty(this._indexedDatabaseName)) { this._indexedDatabaseName = this._ruleDatabase.Name; } SC.ContentSearch.Diagnostics.CrawlingLog.Log.Info(string.Format( "[Index={0}] Initializing {1} with interval '{2}'.", index.Name, this.GetType().Name, this._alarmClock.Interval)); this._index = index; this._alarmClock.Ring += (sender, args) => this.Handle(args); }
public object ComputeFieldValue(IIndexable indexable) { var indexItem = indexable as SitecoreIndexableItem; if (indexItem?.Item == null) { return(null); } string date = null; Item item = indexItem.Item; if (Context.Site == null) { Context.SetActiveSite("shell"); } if (item.TemplateID.Equals(Templates.EventPage.ID)) { Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master"); Item eventItem = master.GetItem(item.Fields[Templates.EventPage.Fields.Event].Value); date = eventItem.Fields[Templates.Event.Fields.EventStart].Value; } return(date); }
protected void btnGetPersonalization_ServerClick(object sender, EventArgs e) { var data = new List <PersonalizationData>(); Sitecore.Data.Database master = Sitecore.Data.Database.GetDatabase("master"); var startItem = master.GetItem("/sitecore/content"); DeviceItem device = master.Resources.Devices["Default"]; foreach (var item in startItem.Axes.GetDescendants()) { PersonalizationData details = new PersonalizationData(); Sitecore.Data.Fields.LayoutField layoutField = item.Fields["__renderings"]; List <Sitecore.Layouts.RenderingReference> renderings = layoutField.GetReferences(device) != null?layoutField.GetReferences(device).ToList() : null; if (renderings != null) { Sitecore.Data.Fields.LayoutField finalLayoutField = item.Fields["__final renderings"]; List <Sitecore.Layouts.RenderingReference> finalRenderings = finalLayoutField.GetReferences(device) != null?finalLayoutField.GetReferences(device).ToList() : null; if (finalRenderings != null) { renderings.AddRange(finalRenderings); var renderingsWithPersonalization = renderings.Where(r => r.Settings.Rules.Count > 0).ToList(); details.ItemName = item.Name; details.RederingDetails = new List <RenderingDetails>(); if (details.ItemName != null && renderingsWithPersonalization != null && renderingsWithPersonalization.Count > 0) { foreach (var rendering in renderingsWithPersonalization) { RenderingDetails renderingDetail = new RenderingDetails(); renderingDetail.RenderingID = master.GetItem(rendering.RenderingID).Paths.FullPath.ToString(); renderingDetail.RenderingName = master.GetItem(rendering.RenderingID).Name; details.RederingDetails.Add(renderingDetail); } } } data.Add(details); } data = data.Where(x => x.RederingDetails.Count() > 0).ToList(); } personalizedData.Text = ""; if (data.Count > 0) { foreach (var finalData in data) { personalizedData.Text += "Item Name : <strong>" + finalData.ItemName + "</strong></br>"; personalizedData.Text += "Renderings with Personalizations defined : </br>"; foreach (var renderingData in finalData.RederingDetails) { personalizedData.Text += "Rendering - Path -" + renderingData.RenderingID + "</br>"; } personalizedData.Text += "</br>"; } } else { personalizedData.Text += "No renderings with Personalization found"; } }
public List <Item> GetCampaignItems(string path) { Sitecore.Data.Database context = Sitecore.Configuration.Factory.GetDatabase("master"); Item item = context.SelectSingleItem(path); List <Item> items = item.Axes.GetDescendants().Where(x => x.TemplateID.ToString() == "{94FD1606-139E-46EE-86FF-BC5BF3C79804}").ToList(); return(items); }
private static void DeserializationFinished(string databaseName) { EventManager.RaiseEvent <Sitecore.Data.Serialization.SerializationFinishedEvent>(new Sitecore.Data.Serialization.SerializationFinishedEvent()); Sitecore.Data.Database database = Sitecore.Configuration.Factory.GetDatabase(databaseName, false); if (database != null) { database.RemoteEvents.Queue.QueueEvent <Sitecore.Data.Serialization.SerializationFinishedEvent>(new Sitecore.Data.Serialization.SerializationFinishedEvent()); } }
protected override void Render(HtmlTextWriter writer) { string itemId = S.Web.WebUtil.GetQueryString("id"); Assert.IsNotNullOrEmpty(itemId, "itemId"); string dbName = S.Web.WebUtil.GetQueryString("database"); Assert.IsNotNullOrEmpty(dbName, "dbName"); S.Data.Database db = S.Configuration.Factory.GetDatabase(dbName); Assert.IsNotNull(db, "db: " + dbName); S.Data.Items.Item item = db.GetItem(itemId); Assert.IsNotNull(item, "item: " + itemId + " in " + dbName); string value = item["Type"]; Assert.IsNotNullOrEmpty(value, "value: Type of " + item.Paths.FullPath); string name = string.Empty; string dll = string.Empty; int comma = value.IndexOf(','); if (comma >= 0) { name = value.Substring(0, comma).Trim(); dll = value.Substring(comma + 1).Trim(); } Assembly assembly = S.Reflection.ReflectionUtil.LoadAssembly(dll); Assert.IsNotNull(assembly, "assembly: " + dll); Type type = assembly.GetType(name, false, true); if (type == null) { type = assembly.GetType(name + "`1"); } Assert.IsNotNull(type, "Type : " + name); dll = S.IO.FileUtil.MapPath("/bin/" + dll + ".dll"); Assert.IsTrue(File.Exists(dll), "dll.Exists(): " + dll); string tempFile = string.Format( "{0}.{1}.il", type, DateTime.Now.ToString("yyyyMMddTHHmmssffff")); S.IO.TempFolder.EnsureFolder(); tempFile = S.IO.FileUtil.MapPath( S.IO.FileUtil.MakePath(S.IO.TempFolder.Folder, tempFile, '/')); S.Sharedsource.Diagnostics.CommandLineTool clt = new S.Sharedsource.Diagnostics.CommandLineTool( "c:\\Program Files (x86)\\Microsoft SDKs\\Windows\\v8.0A\\bin\\NETFX 4.0 Tools\\x64\\ildasm.exe"); clt.Execute( true /*log*/, "/source /html /linenum /item=" + type + " /out=" + tempFile + " " + dll); // /pubonly Assert.IsTrue(File.Exists(tempFile), "tempFile.Exists(): " + tempFile); this.Response.Output.Write(S.IO.FileUtil.ReadFromFile(tempFile)); this.Response.End(); File.Delete(tempFile); }
public List <Item> GetGoalItems(string path) { Sitecore.Data.Database context = Sitecore.Configuration.Factory.GetDatabase("master"); var item = context.GetItem(path); var items = item.Children.ToList(); return(items); }
private void BuildProducts() { Sitecore.Data.Database database = Sitecore.Data.Database.GetDatabase("web"); Sitecore.Data.Items.Item[] Productsitems = database.SelectItems("fast:/sitecore/content/home//*[@@templateid='{2EE70A6B-AF13-498E-8419-BDA52C8C05DD}']"); foreach (var Product in Productsitems) { var item = Context.Database.GetItem(Product.ID); var attributes = new List <XElement>(); if (!string.IsNullOrEmpty(Product.Fields["EanBarcode"].Value)) { XAttribute[] familyAttributes = { new XAttribute("id", "BV_FE_FAMILY") }; XAttribute[] expandAttributes = { new XAttribute("id", "BV_FE_EXPAND") }; attributes.Add(new XElement(Bv + "Attribute", familyAttributes, new XElement(Bv + "Value", Product.Fields["EanBarcode"].Value))); attributes.Add(new XElement(Bv + "Attribute", expandAttributes, new XElement(Bv + "Value", "BV_FE_FAMILY:" + Product.Fields["EanBarcode"].Value))); } var productdesc = RemoveHTMLTags(Product.Fields["ProductIntroduction"].Value); var desc = !ExtensionMethods.IsNullOrEmpty(productdesc) ? new XCData(productdesc) : new XCData(""); var options = Sitecore.Links.LinkManager.GetDefaultUrlOptions(); options.LanguageEmbedding = Sitecore.Links.LanguageEmbedding.Never; var productUrl = LinkManager.GetItemUrl(item, options); var catExternalId = item.Parent.ParentID.ToShortID().ToString(); if (catExternalId.IsNullOrEmpty()) { continue; } var brandExternalId = item.ParentID.ToShortID().ToString();; string ImageUrl = string.Empty; Sitecore.Data.Fields.ImageField imageField = item.Fields["ReferenceImage"]; if (imageField != null && imageField.MediaItem != null) { Sitecore.Data.Items.MediaItem image = new Sitecore.Data.Items.MediaItem(imageField.MediaItem); ImageUrl = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(image)); } //Add a single product var prod = new XElement(Bv + "Product"); prod.Add(new XElement(Bv + "ExternalId", Product.Fields["EanBarcode"].Value)); prod.Add(new XElement(Bv + "Name", new XCData(Product.Fields["__Display Name"].Value))); prod.Add(new XElement(Bv + "Description", desc)); prod.Add(new XElement(Bv + "CategoryExternalId", catExternalId)); prod.Add(new XElement(Bv + "ProductPageUrl", GetFullUrl(productUrl))); prod.Add(new XElement(Bv + "ImageUrl", GetFullUrl(ImageUrl))); prod.Add(new XElement(Bv + "EANs", new XElement(Bv + "EAN", Product.Fields["EanBarcode"].Value))); prod.Add(new XElement(Bv + "Attributes", attributes)); if (!string.IsNullOrEmpty(brandExternalId)) { prod.Add(new XElement(Bv + "BrandExternalId", brandExternalId)); } Products.Add(prod); } }
protected override void OnLoad(EventArgs e) { master = Factory.GetDatabase("master"); if (!Context.ClientPage.IsEvent) { Treeview.SetSelectedItem(master.GetItem(Data.ProjectRootFolder)); } base.OnLoad(e); }
public virtual void CreateItem(Registration registration) { Sitecore.Data.Database masterDB = Sitecore.Configuration.Factory.GetDatabase("master"); var eventItemName = StringHelpers.CleanEventName(registration.Event.Name); Item eventItem = masterDB.GetItem($"{eventsPath}{eventItemName}"); if (eventItem == null) { return; } var teamTemplate = masterDB.GetTemplate(_teamTemplate); using (new Sitecore.SecurityModel.SecurityDisabler()) { var teamItemName = StringHelpers.CleanTeamName(registration.Team.TeamName); //No dupes pls. if (masterDB.GetItem($"{eventsPath}{eventItemName}/{teamItemName}") != null) { teamItemName = StringHelpers.CleanTeamName($"{System.Guid.NewGuid().ToString()}_{teamItemName}"); } Item teamItem = eventItem.Add(teamItemName, teamTemplate); if (teamItem != null) { teamItem.Editing.BeginEdit(); teamItem["Team Name"] = registration.Team.TeamName; teamItem["Slogan"] = registration.Team.Slogan; teamItem["Repository Name"] = registration.Team.RepositoryName; teamItem["Repository Url"] = registration.Team.RepositoryUrl; teamItem.Fields[Sitecore.FieldIDs.Workflow].Value = _workflowID; IWorkflow wf = masterDB.WorkflowProvider.GetWorkflow(_workflowID); wf.Start(teamItem); teamItem.Editing.EndEdit(); } var memberTemplate = masterDB.GetTemplate(_participantTemplate); foreach (Participant member in registration.Team.Members) { var participantItemName = StringHelpers.CleanParticipantName(member.Name); Item participantItem = teamItem.Add(participantItemName, memberTemplate); participantItem.Editing.BeginEdit(); participantItem["Participant Name"] = member.Name; participantItem["Email"] = member.Email; participantItem["Github"] = member.Github; participantItem["LinkedIn"] = member.LinkedIn; participantItem["Slack"] = member.Slack; participantItem["Twitter"] = member.Twitter; participantItem["Location"] = member.Location; participantItem.Editing.EndEdit(); } } }
/// <summary> /// Execute the debug command. /// </summary> /// <param name="context">The command context.</param> public override void Execute( Sitecore.Shell.Framework.Commands.CommandContext context) { // Prompt to save if necessary. Context.ClientPage.ClientResponse.CheckModified(false); // Database selected by user. Sitecore.Data.Database contentDatabase = Context.ContentDatabase; // Database associated with item selected by user. if ((context.Items != null) && (context.Items.Length == 1)) { contentDatabase = context.Items[0].Database; } // Default URL for context (shell) site. Sitecore.Text.UrlString webSiteUrl = Sitecore.Sites.SiteContext.GetWebSiteUrl(); // Enable debugging. webSiteUrl.Add("sc_debug", "1"); if ((context.Items != null) && (context.Items.Length == 1)) { Sitecore.Data.Items.Item item = context.Items[0]; if (item.Visualization.Layout != null) { // Set the item to debug. webSiteUrl.Add("sc_itemid", item.ID.ToString()); } // Set the language to debug. webSiteUrl.Add("sc_lang", item.Language.ToString()); } // Set the database to debug. if (contentDatabase != null) { webSiteUrl.Add("sc_database", contentDatabase.Name); } // Enable profiling. webSiteUrl.Add("sc_prof", "1"); // Enable tracing. webSiteUrl.Add("sc_trace", "1"); // Enable rendering information. webSiteUrl.Add("sc_ri", "1"); // Show the debugging window. Context.ClientPage.ClientResponse.Eval("window.open('" + webSiteUrl + "', '_blank')"); }
/// <summary> /// /// </summary> /// <param name="args"></param> protected void Run(Sitecore.Web.UI.Sheer.ClientPipelineArgs args) { if (args.IsPostBack) { if ((!String.IsNullOrEmpty(args.Result)) && args.Result != "undefined") { Sitecore.Data.Database db = Sitecore.Configuration.Factory.GetDatabase(args.Parameters["database"]); Sitecore.Data.Items.Item item = db.GetItem(args.Parameters["id"], Sitecore.Globalization.Language.Parse(args.Parameters["language"])); } } }
protected override void OnLoad(EventArgs e) { master = Factory.GetDatabase("master"); if (!Context.ClientPage.IsEvent) { Treeview.SetSelectedItem(master.GetItem(Data.ProjectRootFolder)); } base.OnLoad(e); }
private void CreateProfileData(string profile, List <KeyValuePair <string, string> > profileDataList) { // The SecurityDisabler is required which will overrides the current security model, allowing the code // to access the item without any security. using (new Sitecore.SecurityModel.SecurityDisabler()) { Item newItem = null; // Get the master database Sitecore.Data.Database master = Sitecore.Data.Database.GetDatabase("master"); // Get the template for which you need to create item TemplateItem template = master.GetItem("/sitecore/templates/SCEBTemplates/Forms/ContactProfileData"); // Get the place in the site tree where the new item must be inserted Item parentItem = master.GetItem("/sitecore/content/EmployeeBenefits/ContactProfiles/ProfileData"); try { var dataCount = 0; if (parentItem.HasChildren) { dataCount = parentItem.Children.Count; } // Assign values to the fields of the new item foreach (var profileData in profileDataList) { dataCount = dataCount + 1; // Add the item to the site tree newItem = parentItem.Add("ProfileData" + Convert.ToString(dataCount), template); // Set the new item in editing mode // Fields can only be updated when in editing mode // (It's like the begin transaction on a database) newItem.Editing.BeginEdit(); newItem.Fields["ProfileDataId"].Value = Convert.ToString(dataCount);; newItem.Fields["ContactProfile"].Value = profile; newItem.Fields["ProfileField"].Value = profileData.Key; newItem.Fields["ProfileValue"].Value = profileData.Value; newItem.Fields["IsActive"].Value = Convert.ToString(1); // 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) { // Log the message on any failure to sitecore log Sitecore.Diagnostics.Log.Error("Could not update item " + newItem.Paths.FullPath + ": " + ex.Message, this); // Cancel the edit (not really needed, as Sitecore automatically aborts // the transaction on exceptions, but it wont hurt your code) newItem.Editing.CancelEdit(); } } }
public GenericRepository() { var siteName = SettingsHelper.GetSiteConfigName(); var site = Sitecore.Configuration.Factory.GetSite(siteName); if (site == null) { throw new Exception(string.Format("Site configuration for '{0}' could not be found!", siteName)); } Db = Sitecore.Data.Database.GetDatabase(site.Database.Name); }
public void HowToGetItemFromSitecoreDatabase() { using (new Sitecore.FakeDb.Db { new Sitecore.FakeDb.DbItem("Home") }) { Sitecore.Data.Database database = Sitecore.Configuration.Factory.GetDatabase("master"); Xunit.Assert.NotNull(database.GetItem("/sitecore/content/home")); } }
private void Page_Load(object sender, EventArgs e) { Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master"); Sitecore.Data.Items.Item comments = master.GetItem("/sitecore/content/HaiNguyen/Comments"); // Put user code to initialize the page here var children = comments.Children.Where(x => x.TemplateName == "Comment"); if (children.Any()) { rpComments.DataSource = children; // children; /* Context item's children */; rpComments.DataBind(); } }
public void OnRemoteEvent(object sender, EventArgs args) { var remoteEventArgs = args as RemoteEventArgs; Log.Info($"Remote event raised: {remoteEventArgs.ItemName}", nameof(RemoteEventHandler)); using (new SecurityDisabler()) { Sitecore.Data.Database masterDB = Sitecore.Configuration.Factory.GetDatabase("master"); Sitecore.Data.Items.Item home = masterDB.GetItem("/sitecore/content/home"); Sitecore.Data.Items.TemplateItem sample = masterDB.Templates[new Sitecore.Data.ID("{76036F5E-CBCE-46D1-AF0A-4143F9B557AA}")]; Sitecore.Data.Items.Item myItem = home.Add(remoteEventArgs.ItemName, sample); } }
protected void OnItemSaving(object sender, EventArgs args) { if (args == null) { return; } Item newItem = Event.ExtractParameter(args, 0) as Item; if (newItem == null || newItem.TemplateName != "Product") { return; } Sitecore.Data.Database web = Sitecore.Configuration.Factory.GetDatabase("web"); Item originalItem = web.Items.GetItem(newItem.ID); string changeType = "Update"; if (originalItem == null) { changeType = "Add"; originalItem = newItem.Database.GetItem(newItem.ID, newItem.Language, newItem.Version); } var differences = FindDifferences(newItem, originalItem); if (differences.Count > 0 || originalItem.Name != newItem.Name) { int changeId = SaveItemChangeHistory(newItem, changeType); if (changeId > 0) { foreach (String fieldName in differences) { var fieldNameModified = fieldName.ToString().Replace("_x", ""); fieldNameModified = fieldName.ToString().Replace("_", ""); if (fieldNameModified.ToLower() != "created" && fieldNameModified.ToLower() != "sortorder" && fieldNameModified.ToLower() != "updated" && fieldNameModified.ToLower() != "revision") { SaveItemHistoryDetails(changeId, fieldName, originalItem.Fields[fieldName].Value.ToString(), newItem.Fields[fieldName].Value.ToString()); } } if (originalItem.Name != newItem.Name) { SaveItemHistoryDetails(changeId, "ItemName", originalItem.Name, newItem.Name); } } } }
// Access workflow process to get info public void Process(WorkflowPipelineArgs args) { Item currentPost = args.DataItem; string titleField = FieldValidation(currentPost, "Title"); string thumbnailImage = FieldValidation(currentPost, "ThumbnailImage"); string description = FieldValidation(currentPost, "Description"); string content = FieldValidation(currentPost, "Content"); string publishedDate = FieldValidation(currentPost, "PubDate"); // Validate required fields if (IsFieldAvailable(currentPost, "Title") && String.IsNullOrEmpty(titleField) || IsFieldAvailable(currentPost, "ThumbnailImage") && String.IsNullOrEmpty(thumbnailImage) || IsFieldAvailable(currentPost, "Description") && String.IsNullOrEmpty(description) || IsFieldAvailable(currentPost, "Content") && String.IsNullOrEmpty(content)) { Sitecore.Diagnostics.Log.Audit("Blog WP- One of required fields is empty. Stop submitting the request at " + currentPost.Paths.FullPath, this); SheerResponse.Alert("One of required fields is empty"); args.AbortPipeline(); } else { Sitecore.Data.Database webDb = Sitecore.Configuration.Factory.GetDatabase("web"); // if the item has not been published if (currentPost != null && webDb.GetItem(currentPost.ID) == null) { string sitecoreTime = Sitecore.DateUtil.ToIsoDate(DateTime.Now); // Update publish date using (new Sitecore.SecurityModel.SecurityDisabler()) { currentPost.Editing.BeginEdit(); currentPost.Fields["__Display name"].Value = currentPost.DisplayName.Replace("_Draft", ""); // Update pubDate field for RSS Feed currentPost.Fields["pubDate"].Value = sitecoreTime; // Update __Created date field for Bucket Sync currentPost.Fields["__Created"].Value = sitecoreTime; currentPost.Editing.EndEdit(); // Bucket sync BucketManager.Sync(currentPost.Database.GetItem(BlogSettings.ArticleRootPath.ID)); } // Refresh the new post for search index master var tempItem = (SitecoreIndexableItem)currentPost; string searchIndexMaster = BlogSettings.SearchIndexName; Sitecore.ContentSearch.ContentSearchManager.GetIndex(searchIndexMaster).Refresh(tempItem); Sitecore.Diagnostics.Log.Audit("Search Indexing: " + searchIndexMaster, this); } } }
public YouTubeStats(string VideoID) { this.videoID = VideoID; master = Factory.GetDatabase("master"); Item settings = master.GetItem(Data.YouTubeSettingsID); if (settings == null) { Log.Error("YouTube Settings not found!", this); return; } else { devKey = settings.Fields[Data.DevKeyFieldID].Value; clientID = settings.Fields[Data.ClientIDFieldID].Value; username = settings.Fields[Data.UserNameFieldID].Value; password = settings.Fields[Data.PasswordFieldID].Value; GetStats(); } }
/// <summary> /// Set up master database /// </summary> public static void SetUpMasterDatabase() { masterDB = masterDB ?? Sitecore.Configuration.Factory.GetDatabase("master"); }
public ContentProvider(string databaseName, ContentProviderSettings contentProviderSettings) { _db = Sitecore.Data.Database.GetDatabase(databaseName); _contentProviderSettings = contentProviderSettings; }