/// <summary>On event, after publishing document.</summary> /// <param name="sender">The sender (a document object).</param> /// <param name="e">The <see cref="umbraco.cms.businesslogic.PublishEventArgs"/> instance containing the event data.</param> protected void Document_AfterPublish(Document sender, PublishEventArgs e) { var isCopied = false; // Validate document have a relation. if(sender.Relations.Length > 0 && sender.Level > 1) { foreach(var r in sender.Parent.Relations) { // Validate document has been copied by relation type. if(r.RelType.Alias == "relateDocumentOnCopy") { isCopied = true; break; } } } // Validate document is new. if(!isCopied && sender.Level > 1) { var parent = new Document(sender.Parent.Id); // Validate document's parent have a relation. if(parent.Relations.Length > 0) { foreach(var r in parent.Relations) { // Validate document's parent is from "Main Site" sender's parent and relation type. if(r.Parent.Id == sender.ParentId && r.RelType.Alias == "relateDocumentOnCopy") { // Copy document (including current data) under parent of related child. sender.Copy(r.Child.Id, sender.User, true); // Append log, audit trail. Log.Add(LogTypes.Copy, sender.Id, String.Format("Copy related document under parent document (name:{0} id:{1})", r.Child.Text, r.Child.Id)); } } } } }
/// <summary> /// Код, выполняющийся при публикации и распубликации узлов. /// </summary> /// <param name="sender"></param> /// <param name="args"></param> private void ContentPublishedUnpublishedEventHandler(IPublishingStrategy sender, PublishEventArgs<IContent> args) { if (args.PublishedEntities.Any(x => x.ContentType.Alias == SiteSettings.DocumentTypeAlias)) { SiteSettings.Referesh(); //сброс синглетона настроек } if (args.PublishedEntities.Any(x => x.ContentType.Alias == Unico.Etechno.OrderAdmin.OrdersController.OrderStatusDoctypeAlias)) { Unico.Etechno.OrderAdmin.OrderModel.InvalidateStatusCache(); //сброс кэша статусов заказов } if (args.PublishedEntities.Any(x => x.ContentType.Alias == Product.ProductDocumentTypeAlias || x.ContentType.Alias == Category.CategoryDocumentTypeAlias || x.ContentType.Alias == Brand.BrandDocumentTypeAlias)) { Unico.Etechno.Catalog.Filter.InvalidateCache(); //сброс кэша фильтров Unico.Etechno.Searcher.Invalidate(); //сброс поисковика } if (args.PublishedEntities.Any(x => x.ContentType.Alias == "catProduct")) { Unico.Etechno.Catalog.Filter.GetPriceMax(); } var promoEvents = args.PublishedEntities.Where(x => x.ContentType.Alias == Unico.Etechno.PromoEvent.PromoEventDocumentTypeAlias); if (promoEvents.Any()) { foreach (var promoEvent in promoEvents) { Unico.Etechno.PromoEvent.EnsureOthersDontHave(promoEvent); } Unico.Etechno.PromoEvent.InvalidateCache(); //сброс кэша акций } }
//every time we save a document, we rewrite the urls void ContentService_Published(IPublishingStrategy sender, PublishEventArgs<IContent> e) { IContentService contentService = ApplicationContext.Current.Services.ContentService; foreach(var entity in e.PublishedEntities) { UrlRewriter.RewriteUrl(entity, contentService); } }
private void Document_BeforePublish(Document sender, PublishEventArgs e) { //Do what you need to do. In this case logging to the Umbraco log Log.Add(LogTypes.Debug, sender.Id, "the document " + sender.Text + " is about to be published"); //cancel the publishing if you want. e.Cancel = true; }
void ContentServicePublishedEvent(IPublishingStrategy sender, PublishEventArgs<IContent> e) { // Clear all AtoZs // could be cleverer - the cache has the root ID in it, so you could just clear caches where // the ID is a parent of the current page - not sure it makes much diffrence, because the // rebuild only happens once, and it doesn't take 'that' long to rebuild ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch("AtoZPages"); }
void Document_BeforePublish(Document sender, PublishEventArgs e) { try { if (sender.ContentType.Alias == "uBlogsyPost") { bool sendNewsletter = (sender.getProperty("sendNewsletter").Value.ToString() == "0") ? false : true; if (sendNewsletter) { var sum = sender.getProperty("uBlogsyContentSummary").Value; string title = sender.getProperty("uBlogsyContentTitle").Value.ToString(); Dictionary<string, object> lookup = new Dictionary<string, object>() { { "title", "" } }; campaignsInput input = new campaignsInput(lookup); campaigns camps = new campaigns(); if (camps.Execute(input).result.Where(t => t.title == title).Count() == 0) { campaignCreateInput campInput = new campaignCreateInput(); campInput.parms.apikey = PerceptiveMCAPI.MCAPISettings.default_apikey; campInput.parms.options.title = title; campInput.parms.options.list_id = "68972d2e33"; campInput.parms.options.auto_footer = true; campInput.parms.options.subject = "The Newsletter - " + title; campInput.parms.options.tracking = new campaignTracking(true, true, true); campInput.parms.options.template_id = 88565; campInput.parms.options.analytics.Add("google", title); campInput.parms.options.to_email = "*|FNAME|*"; campInput.parms.options.from_email = "*****@*****.**"; campInput.parms.options.from_name = "American City Plumbing"; campInput.parms.content.Add("html_std_content", sum.ToString()); campaignCreate create = new campaignCreate(); campaignCreateOutput campOut = create.Execute(campInput); var r = campOut.result; if (campOut != null) { var c = camps.Execute(new campaignsInput(new Dictionary<string, object>() { { "title", title } })); campaignSendNowInput sendInput = new campaignSendNowInput(r); campaignSendNow now = new campaignSendNow(); var sI = now.Execute(sendInput); var s = sI.result; } } } } } catch (Exception ex) { ex.ToString(); throw; } //cancel the publishing // e.Cancel = true; }
void ContentServicePublished(IPublishingStrategy sender, PublishEventArgs<IContent> e) { if (HttpContext.Current == null) return; foreach (var entity in e.PublishedEntities) { UnVersionContext.Instance.UnVersionService.UnVersion(entity); } }
void DeleteNodesFromTimetable(IPublishingStrategy sender, PublishEventArgs<IContent> e) { if (e.PublishedEntities.Any()) { foreach (var entity in e.PublishedEntities) { if (entity.ContentType.Alias == "Service") { TimetableHelper.Delete(entity.Id); } } } }
/// <summary> /// Called when an item is published /// </summary> /// <param name="sender"></param> /// <param name="publishEventArgs"></param> private void ContentServiceOnPublished(IPublishingStrategy sender, PublishEventArgs<IContent> publishEventArgs) { if (!publishEventArgs.PublishedEntities.Any()) return; foreach (var entity in publishEventArgs.PublishedEntities) { DbProvider.RemoveMediaTrack(entity.Id); if (_verbose) { LogHelper.Info<MediaTrackerHandler>(string.Format("All previous tracking for the page '{0}' was removed because the page is about to be published.", entity.Name)); } var content = ApplicationContext.Current.Services.ContentService.GetById(entity.Id); var validProperties = content.Properties.Where(x => _trackedProperties.Contains(x.Alias)).ToList(); foreach (var property in validProperties) { var propertyType = entity.PropertyTypes.Single(x => x.Alias == property.Alias); var editorType = GetInstanceField(typeof (PropertyType), propertyType, "PropertyEditorAlias").ToString(); var propertyVal = property.Value.ToString(); if (string.IsNullOrEmpty(propertyVal)) continue; switch (editorType) { case "Umbraco.MediaPicker": CreateMediaRecord( EnsureModel(content.Id, Convert.ToInt32(propertyVal), propertyType.Id) , content, property); break; case "Umbraco.MultipleMediaPicker": var mediaIds = propertyVal.Split(new[] {','}); foreach (var mediaId in mediaIds) { CreateMediaRecord( EnsureModel(content.Id, Convert.ToInt32(mediaId), propertyType.Id) , content, property); } break; default: // assume content with embedded image links var matches = _imgtagRegex.Matches(propertyVal); foreach (Match m in matches) { var imgTag = m.Value; var src = _imgsrcRegex.Match(imgTag).Groups["src"].Value; var id = _dataidRegex.Match(imgTag).Groups["dataid"].Value; CreateMediaRecord( EnsureModel(content.Id, EvaluateDataId(id, src), propertyType.Id) , content, property); } break; } } } }
private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e) { var args = new PublishEventArgs() { EventType = "TabControlChanged", EventId = 3333 }; args.AddParams(openorclose.IsSelected, this); args.AddParams(fault.IsSelected, this); args.AddParams(energy.IsSelected, this); args.AddParams(online.IsSelected, this); EventPublish.PublishEvent(args); }
public override void ExPublishedEvent(PublishEventArgs args) { if (args.EventId == Wlst.Sr.EquipmentInfoHolding.Services.EventIdAssign.EventTaskAllNeedUpdate) { if (DateTime.Now.Ticks - dtSnd.Ticks < 600000000) { Msg = DateTime.Now + " 更新成功!"; } else { Msg = DateTime.Now + " 收到更新数据!"; } } }
public bool FundOrderFilter(PublishEventArgs args) //接收终端选中变更事件 { try { if (args.EventType == EventType && args.EventId == EventId) { return(true); } } catch (Exception ex) { } return(false); }
/// <summary> /// 删除部件 /// </summary> /// <param name="id">需要删除的部件id</param> public void DeleteMenuItem(int id) { if (_dictionaryMenuItems.ContainsKey(id)) { _dictionaryMenuItems.Remove(id); var args = new PublishEventArgs() { EventType = PublishEventType.Core, EventId = Services.EventIdAssign.SettingModuleComponentUpdate, }; args.AddParams(id); EventPublish.PublishEvent(args); } }
/// <summary> /// 当选择的终端发送变化时,如果 /// </summary> public override void OnNodeSelectActive() { //base.OnNodeSelect(); //发布事件 选中当前节点 var args = new PublishEventArgs { EventType = PublishEventType.Core, EventId = Sr.EquipmentInfoHolding.Services.EventIdAssign.EquipmentSelected, }; args.AddParams(NodeId); EventPublish.PublishEvent(args); LoadNodes(); }
/// <summary> /// 当选择的终端发送变化时,如果 /// </summary> public override void OnNodeSelectActive() { //ResetContextMenu(); var ar = new PublishEventArgs() { EventId = Sr.EquipmentInfoHolding.Services.EventIdAssign.EquipmentSelected, EventType = PublishEventType.Core }; ar.AddParams(this.Father.Father.NodeId); //终端地址 ar.AddParams(this.Father.NodeId); //集中器地址 ar.AddParams(this.NodeId); //线路ID EventPublisher.EventPublish(ar); }
//ToDo 1、分组参数变更时 数据更新;2、分组、终端增删改变动时时数据更新 /// <summary> /// 事件过滤 /// 目前只处理 /// 1、系统当前选中的终端或分组变更,提供联动 /// 2、终端参数发生变化的时候,即使更新显示数据 /// </summary> /// <param name="args"></param> /// <returns></returns> public bool FundOrderFilter(PublishEventArgs args) //接收终端选中变更事件 { if (args.EventType == PublishEventType.Core && args.EventId == 52303 && NodeType == TreeNodeType.IsTml && NodeId == (int)args.GetParams()[0]) { //switch (args.EventSection) //{ // case PublishEventSection.Update: // return true; //} return(false); } return(false); }
public override void OnDoubleClick() { base.OnDoubleClick(); //发布事件 选中当前节点 var args = new PublishEventArgs { EventType = PublishEventType.Core, EventId = EventIdAssign.EquipmentSelected, }; args.AddParams(NodeId); EventPublisher.EventPublish(args); }
/// <summary> /// 当节点被选中的时候调用,实现了刷新右键菜单; /// 是否需要发送事件需要在此实现;以及其他的需要处理的事件; /// 动态加载子节点 /// </summary> public void OnNodeSelect() { if (ViewId > 1000) { //发布事件 选中当前节点 var args = new PublishEventArgs { EventType = SettingViewModel.EventType, EventId = SettingViewModel.EventId, }; args.AddParams(ViewId); EventPublish.PublishEvent(args); } }
/// <summary> /// 事件过滤 /// </summary> /// <param name="args"></param> /// <returns></returns> private bool FundOrderFilter(PublishEventArgs args) { //if (EventFilterTipeAndId.ContainsKey(-1)) return true; if (EventFilterTipeAndId.ContainsKey(0) && args.EventType == EventFilterTipeAndId[0].Item1) { return(true); } if (EventFilterTipeAndId.ContainsKey(args.EventId) && args.EventType == EventFilterTipeAndId[args.EventId].Item1) { return(FundOrderFilterForExtendCheck(args)); } return(false); }
public override void OnNodeSelectActive() { //base.OnNodeSelectActive(); var args = new PublishEventArgs { EventType = PublishEventType.Core, EventId = Sr.EquipmentInfoHolding.Services.EventIdAssign.EquipmentSelected, }; args.AddParams(FatherId); args.AddParams(NodeId); EventPublisher.EventPublish(args); }
void ContentService_Published(IPublishingStrategy sender, PublishEventArgs<Umbraco.Core.Models.IContent> e) { const string publishedDateKey = "publishedDate"; var contentService = ApplicationContext.Current.Services.ContentService; foreach (var content in e.PublishedEntities.Where(x => x.HasProperty(publishedDateKey))) { var existingValue = content.GetValue(publishedDateKey); if (existingValue == null) { content.SetValue(publishedDateKey, DateTime.Now.ToString()); contentService.SaveAndPublishWithStatus(content, raiseEvents: false); } } }
private void ExDeleteFolderFolder() { int nodid = this.NodeId; if (NodeId != 0 && _father != null)//todo youhua { if (NodeType == TreeNodeType.IsGrp) { //int fatherId = _father.NodeId; //getGrpsInfoForUse.DeleteGrpInfo(NodeId, fatherId); if (_father != null) { _father._ChildTreeItems.Remove(this); var args = new PublishEventArgs() { EventType = PublishEventTypeLocal.Name, EventId = PublishEventTypeLocal.GrpSingleReloadTmlGroup }; args.AddParams(nodid); args.AddParams(0); EventPublish.PublishEvent(args); } } else if (NodeType == TreeNodeType.IsTml) { //if (getGrpsInfoForUse.GrpInfoDictionary.ContainsKey(this.Father.NodeId)) //{ // if (getGrpsInfoForUse.GrpInfoDictionary[this.Father.NodeId].LstTml.Contains(this.NodeId)) // { // getGrpsInfoForUse.GrpInfoDictionary[this.Father.NodeId].LstTml.Remove(this.NodeId); // } //} this._father.ChildTreeItems.Remove(this); var args = new PublishEventArgs() { EventType = PublishEventTypeLocal.Name, EventId = PublishEventTypeLocal.GrpSingleReloadTmlGroup }; args.AddParams(nodid); args.AddParams(1); EventPublish.PublishEvent(args); } } // if (_father != null) _father.AddChild(); }
//Prepublishing / preunpublishing private void SetUrlsToPurge(IPublishingStrategy sender, PublishEventArgs <IContent> e) { var helper = new UmbracoHelper(UmbracoContext.Current); string domain = WebConfigurationManager.AppSettings[FastlyDomainKey]; //Loop through content to publish and store the URLs for after publish finishes foreach (IContent content in e.PublishedEntities) { if (content.Status == ContentStatus.Published) { IPublishedContent publishedContent = (IPublishedContent)helper.Content(content.Id); urlsToPurge.Add(new Uri(domain + publishedContent.Url)); } } }
/// <summary> /// When publishing a page, call Save() first as it prevents the bug from occurring /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs <global::Umbraco.Core.Models.IContent> e) { foreach (var entity in e.PublishedEntities) { // Minimise calls to Save which appear in the audit log. Aim is to work around a bug which only occurs // when you set a release date, so check first that there is one. Time check means it should save when you // hit 'Save and publish' but when the release date comes and this event fires again, the release date will // be a few seconds in the past and it won't do an unnecessary extra Save(). if (entity.ReleaseDate.HasValue && entity.ReleaseDate.Value.ToUniversalTime() > DateTime.UtcNow) { ApplicationContext.Current.Services.ContentService.Save(entity); } } }
/// <summary> /// 删除实例关系,立即回写数据库并发布事件 /// </summary> /// <param name="instancesId"></param> public void DeleteMenuInstanceRelation(int instancesId) { if (DicInstanceRelation.ContainsKey(instancesId)) { DicInstanceRelation.Remove(instancesId); var args = new PublishEventArgs() { EventType = PublishEventType.Core, EventId = EventIdAssign.MenuInstanceRelationUpdate }; args.AddParams(instancesId); EventPublish.PublishEvent(args); } WriteDeleteDbByPrivate(instancesId); }
/// <summary> /// 当节点被选中的时候调用,实现了刷新右键菜单; /// 是否需要发送事件需要在此实现;以及其他的需要处理的事件; /// 动态加载子节点 /// </summary> public void OnEquipmentSelected() { IsCanRefreshMenu = true; this.RaisePropertyChanged(() => this.Cm); IsCanRefreshMenu = false; //发布事件 选中当前节点 var args = new PublishEventArgs { EventId = Sr.EquipmentInfoHolding.Services.EventIdAssign.EquipmentSelected, EventType = PublishEventType.Core, }; args.AddParams(EquipmentRtuId); EventPublisher.EventPublish(args); }
/// <summary> /// 删除快捷键信息,立即回写数据库并发布事件 /// </summary> /// <param name="menuId"></param> public void DeleteShortCut(int menuId) { if (DicClassic.ContainsKey(menuId)) { DicClassic.Remove(menuId); var args = new PublishEventArgs() { EventType = PublishEventType.Core, EventId = EventIdAssign.MenuShourtCutsUpdate, }; args.AddParams(menuId); EventPublish.PublishEvent(args); this.WriteDeleteDbByPrivate(menuId); } }
public void FundEventHandler(PublishEventArgs args) // should do somework { try { int id = Convert.ToInt32(args.GetParams()[0]); if (id > 0) { MenuId = id; } } catch (Exception ex) { ex.ToString(); } }
public void FundEventHandler(PublishEventArgs args) { if (args.EventType == PublishEventType.Core && args.EventId == 52303) { if (Sr.EquipmentInfoHolding.Services.EquipmentDataInfoHold .InfoItems .ContainsKey(NodeId)) { var t = Sr.EquipmentInfoHolding.Services.EquipmentDataInfoHold .InfoItems [NodeId]; NodeName = t.RtuName; } } }
public void OnPublish(IPublishingStrategy sender, PublishEventArgs <IContent> e) { var rule = _config.RulesNode.RuleList.FirstOrDefault(x => x.Name == ruleName); if (rule == null) { return; } var aliases = rule.AddList.Select(x => x.DocTypeAlias); if (!aliases.Any()) { return; } //one of the documents we publish has a restriction var restrictedEntities = e.PublishedEntities.Where(x => aliases.Contains(x.ContentType.Alias)); if (!restrictedEntities.Any()) { return; } foreach (var entity in restrictedEntities) { //element not at the root level if (entity.ParentId != -1) { continue; } //umbraco context is already defined as we are in one of the pluggins var siblingsAliases = Umbraco.Web.UmbracoContext.Current.ContentCache.GetAtRoot() .Where(x => x.Id != entity.Id) .Select(x => x.DocumentTypeAlias) .ToList(); //any siblings with the same doc type ? var cachedDocumentsCondition = restrictedEntities.Any(x => siblingsAliases.Contains(x.ContentType.Alias)); //documents with the restriction have been found if (cachedDocumentsCondition) { e.CancelOperation(new EventMessage("Content Restriction", rule.ErrorMessage, EventMessageType.Error)); } } }
public void ContentServicePublished(IPublishingStrategy sender, PublishEventArgs <IContent> args) { var memberService = ApplicationContext.Current.Services.MemberService; foreach (var node in args.PublishedEntities) { if (node.Id <= 0) //new record { var members = memberService.GetAllMembers(); foreach (var member in members) { GlobalHelpers.SendGridEmailMessage("*****@*****.**", member.Email, "Blog Post Published", string.Format("A new Blog Post was created called {0}, fancy having a look at <a href='http://www.biggsy150.co.uk/blog/' >{1}</a>.", node.Name, node.CreateDate)); } } } }
public void ProcessContentPublished(IPublishingStrategy sender, PublishEventArgs <IContent> args) { foreach (var entity in args.PublishedEntities) { _contentIndexer.FillIndex(entity.Id); if (IsGlobalPanel(entity)) { _umbracoHelper.TypedContentAtRoot() .SelectMany(c => c.DescendantsOrSelf()) .Where(c => ContainsGlobalPanel(c, entity)) .Select(c => c.Id) .ToList() .ForEach(_contentIndexer.FillIndex); } } }
/// <summary> /// 事件过滤 /// </summary> /// <param name="args"></param> /// <returns></returns> public bool FundOrderFilter(PublishEventArgs args) //接收终端选中变更事件 { try { if (args.EventType == PublishEventType.Core && args.EventId == 52309 && //终端信息修改 NodeType == TreeNodeType.IsTml && NodeId == (int)args.GetParams()[0]) { return(true); } } catch (Exception ex) { Wlst.Cr.Core.UtilityFunction.WriteLog.WriteLogError("Error:" + ex); } return(false); }
public void FundEventHandlers(PublishEventArgs args) { try { if (args.EventType == PublishEventType.None && args.EventId == Services.EventIdAssign.AnimationOperatorDataQueryViewModelEnterId && !_isdetailin) { Animations.Animation.EnterFromLeftAndTop(detail, 1, true); _isdetailin = true; } } catch (Exception xe) { WriteLog.WriteLogError("ReSetAnimation error in FundEventHandlers:ex:" + xe); } }
public static void Published(IPublishingStrategy sender, PublishEventArgs <IContent> e) { foreach (var content in e.PublishedEntities) { switch (content.ContentType.Alias) { case ContentTypeAliases.ServerError: if (content.Published) { PublishErrorPage(e, content); } break; } } }
private void ValidateModel(PublishEventArgs <IContent> e, IDomainModel model) { dynamic castModel = Convert.ChangeType(model, model.GetType()); var result = validateBus.Validate(castModel); if (!result.IsValid) { e.Cancel = true; foreach (var error in result.Errors) { var errors = new EventMessage(error.PropertyName, error.ErrorMessage, EventMessageType.Error); e.CancelOperation(errors); } } }
/// <summary> /// 不管三七二十一 直接重绘主菜单 /// </summary> /// <param name="args"></param> public void FundEventHandler(PublishEventArgs args) { if (args.EventType == PublishEventType.SvAv) { ResetM(); } else { ResetM(); } //if (PropertyChanged != null) //{ // this.PropertyChanged(this, new PropertyChangedEventArgs("Items")); //} }
public bool FundOrderFilters(PublishEventArgs args) //接收终端选中变更事件 { try { if (args.EventType == PublishEventType.None && args.EventId == Services.EventIdAssign.AnimationOperatorDataQueryViewModelEnterId) { return(true); } } catch (Exception ex) { WriteLog.WriteLogError("Error:" + ex); } return(false); }
public static void Published(IPublishingStrategy sender, PublishEventArgs<IContent> e) { foreach (var content in e.PublishedEntities) { switch (content.ContentType.Alias) { case ContentTypeAliases.ServerError: if (content.Published) { PublishErrorPage(e, content); } break; } } }
// UNPUBLISH & REMOVE Incomplete Orders AFTER EXPIREDATE HAS BEEN PASSED protected void DocumentBeforePublish(Document sender, PublishEventArgs e) { if (Category.IsAlias(sender.ContentType.Alias)) { SetAliasedPropertiesIfEnabled(sender, "categoryUrl"); } if (Product.IsAlias(sender.ContentType.Alias)) { SetAliasedPropertiesIfEnabled(sender, "productUrl"); } if (sender.ContentType.Alias == Order.NodeAlias) { // order => todo: delete node, update SQL } }
/// <summary> /// Document_s the before publish. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="umbraco.cms.businesslogic.PublishEventArgs"/> instance containing the event data.</param> private void Document_BeforePublish(Document sender, PublishEventArgs e) { var propertyTypes = sender.ContentType.PropertyTypes; foreach (var propertyType in propertyTypes) { try { var property = sender.getProperty(propertyType); if (property.Value == null) { continue; } var xDocument = XDocument.Parse(property.Value.ToString()); // Check if this is TextImage data if (xDocument.Element("TextImage") == null) { continue; } // Extract text from xml and generate an fresh image var text = xDocument.Descendants().Elements("Text").First().Value; if (text == string.Empty) { continue; } var imageUrl = xDocument.Descendants().Elements("Url").First().Value; var imageFile = IOHelper.MapPath(imageUrl); var imageName = Path.GetFileNameWithoutExtension(imageFile); var parameters = GetParameters(text, property.PropertyType.DataTypeDefinition); // Delete old and Save updated image File.Delete(imageFile); MediaHelper.SaveTextImage(parameters, imageName); } catch { continue; } } }
void PublishingStrategy_UnPublished(IPublishingStrategy sender, PublishEventArgs<IContent> e) { if (e.PublishedEntities.Any()) { if (e.PublishedEntities.Count() > 1) { foreach (var c in e.PublishedEntities) { UnPublishSingle(c); } } else { var content = e.PublishedEntities.FirstOrDefault(); UnPublishSingle(content); } } }
private void Content_AfterPublish(IPublishingStrategy sender, PublishEventArgs<IContent> args) { foreach (var content in args.PublishedEntities) { if (content.ContentType.Alias == "Dealer") { var typedContent = ((Content)content); var addressJson = typedContent.GetValue<string>("address"); var addressObj = Newtonsoft.Json.Linq.JObject.Parse(addressJson); var sql = "spUpdateDealerLocation @0, @1, @2"; var sqlArgs = new List<object>(); sqlArgs.Add(typedContent.Id); sqlArgs.Add(addressObj.Value<decimal>("long")); sqlArgs.Add(addressObj.Value<decimal>("lat")); ApplicationContext.Current.DatabaseContext.Database.Execute(sql, sqlArgs.ToArray()); } } }
void PublishingStrategy_Published(IPublishingStrategy sender, PublishEventArgs<IContent> e) { if (e.PublishedEntities.Any()) { if (e.IsAllRepublished) { UpdateEntireCache(); return; } if (e.PublishedEntities.Count() > 1) { UpdateMultipleContentCache(e.PublishedEntities); } else { var content = e.PublishedEntities.FirstOrDefault(); UpdateSingleContentCache(content); } } }
void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e) { // When content is renamed or 'umbracoUrlName' property value is added/updated foreach (IContent content in e.PublishedEntities) { #if !DEBUG try #endif { Node node = new Node(content.Id); if (node.Name != content.Name && !string.IsNullOrEmpty(node.Name)) // If name is null, it's a new document { // Rename occurred UrlTrackerRepository.AddUrlMapping(content, node.GetDomainRootNode().Id, node.NiceUrl, AutoTrackingTypes.Renamed); if (ClientTools != null) ClientTools.ChangeContentFrameUrl(string.Concat("/umbraco/editContent.aspx?id=", content.Id)); } if (content.HasProperty("umbracoUrlName")) { string contentUmbracoUrlNameValue = content.GetValue("umbracoUrlName") != null ? content.GetValue("umbracoUrlName").ToString() : string.Empty; string nodeUmbracoUrlNameValue = node.GetProperty("umbracoUrlName") != null ? node.GetProperty("umbracoUrlName").Value : string.Empty; if (contentUmbracoUrlNameValue != nodeUmbracoUrlNameValue) { // 'umbracoUrlName' property value added/changed UrlTrackerRepository.AddUrlMapping(content, node.GetDomainRootNode().Id, node.NiceUrl, AutoTrackingTypes.UrlOverwritten); if (ClientTools != null) ClientTools.ChangeContentFrameUrl(string.Concat("/umbraco/editContent.aspx?id=", content.Id)); } } } #if !DEBUG catch (Exception ex) { ex.LogException(); } #endif } }
protected void PurgeCloudflareCache(IPublishingStrategy strategy, PublishEventArgs<IContent> e) { //If we have the cache buster turned off then just return. if (!CloudflareConfiguration.Instance.PurgeCacheOn) { return; } List<string> urls = new List<string>(); //Else we can continue to delete the cache for the saved entities. foreach(IContent content in e.PublishedEntities) { try { //Check to see if the page has cache purging on publish disabled. if(content.GetValue<bool>("cloudflareDisabledOnPublish")) { //it was disabled so just continue; continue; } } catch(Exception ex) { //continue; } urls.AddRange(UmbracoFlareDomainManager.Instance.GetUrlsForNode(content, false)); } List<StatusWithMessage> results = CloudflareManager.Instance.PurgePages(urls); if (results.Any() && results.Where(x => !x.Success).Any()) { e.Messages.Add(new EventMessage("Cloudflare Caching", "We could not purge the Cloudflare cache. \n \n" + CloudflareManager.PrintResultsSummary(results), EventMessageType.Warning)); } else if (results.Any()) { e.Messages.Add(new EventMessage("Cloudflare Caching", "Successfully purged the cloudflare cache.", EventMessageType.Success)); } }
static void PublishingStrategyPublishing(IPublishingStrategy sender, PublishEventArgs<IContent> e) { foreach (var i in e.PublishedEntities.Where(i => i.Name == "Text Page 2")) { e.Cancel = true; } }
/// <summary> /// Adds relation between Content and Media when Content is published /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ContentService_Published(IPublishingStrategy sender, PublishEventArgs<IContent> e) { // RelationService IRelationService rs = ApplicationContext.Current.Services.RelationService; // ContentService IContentService cs = ApplicationContext.Current.Services.ContentService; // RelationType IRelationType relationType = rs.GetRelationTypeByAlias(Constants.RelationTypeAlias); // Published Documents foreach (var contentNode in e.PublishedEntities) { // Content is child, query by child and RelationType var relations = rs.GetByChild(cs.GetById(contentNode.Id), Constants.RelationTypeAlias); // Remove current relations if (relations.Count() > 0) { LogHelper.Info<MediaContentUsage>(String.Format("Removing all Media relations for published Content with id '{0}'", contentNode.Id)); foreach (var relation in relations) { rs.Delete(relation); LogHelper.Debug<MediaContentUsage>(String.Format("Deleted relation: ParentId {0} ChildId {1}", relation.ParentId, relation.ChildId)); } } // Relate found Media to this Content foreach (var mediaNodeId in FindMedia(contentNode.Id)) { Relation relation = new Relation(mediaNodeId, contentNode.Id, relationType); rs.Save(relation); LogHelper.Debug<MediaContentUsage>(String.Format("Saved relation: ParentId {0} ChildId {1}", relation.ParentId, relation.ChildId)); } } }
public void PublishWithSubs(User u) { PublishEventArgs e = new PublishEventArgs(); FireBeforePublish(e); if (!e.Cancel) { IEnumerable<Attempt<PublishStatus>> publishedResults = ((ContentService)ApplicationContext.Current.Services.ContentService) .PublishWithChildrenInternal(Content, u.Id); FireAfterPublish(e); } }
internal IEnumerable<Attempt<PublishStatus>> PublishWithSubs(int userId, bool includeUnpublished) { PublishEventArgs e = new PublishEventArgs(); FireBeforePublish(e); IEnumerable<Attempt<PublishStatus>> publishedResults = Enumerable.Empty<Attempt<PublishStatus>>(); if (!e.Cancel) { publishedResults = ((ContentService) ApplicationContext.Current.Services.ContentService) .PublishWithChildrenInternal(Content, userId, includeUnpublished); FireAfterPublish(e); } return publishedResults; }
/// <summary> /// Document_s the before publish. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="umbraco.cms.businesslogic.PublishEventArgs"/> instance containing the event data.</param> private void Document_BeforePublish(Document sender, PublishEventArgs e) { var propertyTypes = sender.ContentType.PropertyTypes; foreach (var propertyType in propertyTypes) { try { var property = sender.getProperty(propertyType); if (property.Value == null) continue; var xDocument = XDocument.Parse(property.Value.ToString()); // Check if this is TextImage data if (xDocument.Element("TextImage") == null) continue; // Extract text from xml and generate an fresh image var text = xDocument.Descendants().Elements("Text").First().Value; if (text == string.Empty) continue; var imageUrl = xDocument.Descendants().Elements("Url").First().Value; var imageFile = IOHelper.MapPath(imageUrl); var imageName = Path.GetFileNameWithoutExtension(imageFile); var parameters = GetParameters(text, property.PropertyType.DataTypeDefinition); // Delete old and Save updated image File.Delete(imageFile); MediaHelper.SaveTextImage(parameters, imageName); } catch { continue; } } }
public void Publish() { CreatedPackage package = this; PackageInstance pack = package.Data; try { PublishEventArgs e = new PublishEventArgs(); package.FireBeforePublish(e); if (!e.Cancel) { int outInt = 0; //Path checking... string localPath = IOHelper.MapPath(SystemDirectories.Media + "/" + pack.Folder); if (!System.IO.Directory.Exists(localPath)) System.IO.Directory.CreateDirectory(localPath); //Init package file... createPackageManifest(); //Info section.. appendElement(utill.PackageInfo(pack, _packageManifest)); //Documents... int _contentNodeID = 0; if (!String.IsNullOrEmpty(pack.ContentNodeId) && int.TryParse(pack.ContentNodeId, out _contentNodeID)) { XmlNode documents = _packageManifest.CreateElement("Documents"); XmlNode documentSet = _packageManifest.CreateElement("DocumentSet"); XmlAttribute importMode = _packageManifest.CreateAttribute("importMode", ""); importMode.Value = "root"; documentSet.Attributes.Append(importMode); documents.AppendChild(documentSet); //load content from umbraco. cms.businesslogic.web.Document umbDocument = new Document(_contentNodeID); documentSet.AppendChild(umbDocument.ToXml(_packageManifest, pack.ContentLoadChildNodes)); appendElement(documents); } //Document types.. List<DocumentType> dtl = new List<DocumentType>(); XmlNode docTypes = _packageManifest.CreateElement("DocumentTypes"); foreach (string dtId in pack.Documenttypes) { if (int.TryParse(dtId, out outInt)) { DocumentType docT = new DocumentType(outInt); AddDocumentType(docT, ref dtl); } } foreach (DocumentType d in dtl) { docTypes.AppendChild(d.ToXml(_packageManifest)); } appendElement(docTypes); //Templates XmlNode templates = _packageManifest.CreateElement("Templates"); foreach (string templateId in pack.Templates) { if (int.TryParse(templateId, out outInt)) { Template t = new Template(outInt); templates.AppendChild(t.ToXml(_packageManifest)); } } appendElement(templates); //Stylesheets XmlNode stylesheets = _packageManifest.CreateElement("Stylesheets"); foreach (string ssId in pack.Stylesheets) { if (int.TryParse(ssId, out outInt)) { StyleSheet s = new StyleSheet(outInt); stylesheets.AppendChild(s.ToXml(_packageManifest)); } } appendElement(stylesheets); //Macros XmlNode macros = _packageManifest.CreateElement("Macros"); foreach (string macroId in pack.Macros) { if (int.TryParse(macroId, out outInt)) { macros.AppendChild(utill.Macro(int.Parse(macroId), true, localPath, _packageManifest)); } } appendElement(macros); //Dictionary Items XmlNode dictionaryItems = _packageManifest.CreateElement("DictionaryItems"); foreach (string dictionaryId in pack.DictionaryItems) { if (int.TryParse(dictionaryId, out outInt)) { Dictionary.DictionaryItem di = new Dictionary.DictionaryItem(outInt); dictionaryItems.AppendChild(di.ToXml(_packageManifest)); } } appendElement(dictionaryItems); //Languages XmlNode languages = _packageManifest.CreateElement("Languages"); foreach (string langId in pack.Languages) { if (int.TryParse(langId, out outInt)) { language.Language lang = new umbraco.cms.businesslogic.language.Language(outInt); languages.AppendChild(lang.ToXml(_packageManifest)); } } appendElement(languages); //Datatypes XmlNode dataTypes = _packageManifest.CreateElement("DataTypes"); foreach (string dtId in pack.DataTypes) { if (int.TryParse(dtId, out outInt)) { cms.businesslogic.datatype.DataTypeDefinition dtd = new umbraco.cms.businesslogic.datatype.DataTypeDefinition(outInt); dataTypes.AppendChild(dtd.ToXml(_packageManifest)); } } appendElement(dataTypes); //Files foreach (string fileName in pack.Files) { utill.AppendFileToManifest(fileName, localPath, _packageManifest); } //Load control on install... if (!string.IsNullOrEmpty(pack.LoadControl)) { XmlNode control = _packageManifest.CreateElement("control"); control.InnerText = pack.LoadControl; utill.AppendFileToManifest(pack.LoadControl, localPath, _packageManifest); appendElement(control); } //Actions if (!string.IsNullOrEmpty(pack.Actions)) { try { XmlDocument xd_actions = new XmlDocument(); xd_actions.LoadXml("<Actions>" + pack.Actions + "</Actions>"); XmlNode actions = xd_actions.DocumentElement.SelectSingleNode("."); if (actions != null) { actions = _packageManifest.ImportNode(actions, true).Clone(); appendElement(actions); } } catch { } } string manifestFileName = localPath + "/package.xml"; if (System.IO.File.Exists(manifestFileName)) System.IO.File.Delete(manifestFileName); _packageManifest.Save(manifestFileName); _packageManifest = null; //string packPath = Settings.PackagerRoot.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), "/") + "/" + pack.Name.Replace(' ', '_') + "_" + pack.Version.Replace(' ', '_') + "." + Settings.PackageFileExtension; // check if there's a packages directory below media string packagesDirectory = SystemDirectories.Media + "/created-packages"; if (!System.IO.Directory.Exists(IOHelper.MapPath(packagesDirectory))) System.IO.Directory.CreateDirectory(IOHelper.MapPath(packagesDirectory)); string packPath = packagesDirectory + "/" + (pack.Name + "_" + pack.Version).Replace(' ', '_') + "." + Settings.PackageFileExtension; utill.ZipPackage(localPath, IOHelper.MapPath(packPath)); pack.PackagePath = packPath; if (pack.PackageGuid.Trim() == "") pack.PackageGuid = Guid.NewGuid().ToString(); package.Save(); //Clean up.. System.IO.File.Delete(localPath + "/package.xml"); System.IO.Directory.Delete(localPath, true); package.FireAfterPublish(e); } } catch (Exception ex) { LogHelper.Error<CreatedPackage>("An error occurred", ex); } }
protected void UpdateContentIdToUrlCache(IPublishingStrategy strategy, PublishEventArgs<IContent> e) { UmbracoHelper uh = new UmbracoHelper(UmbracoContext.Current); foreach(IContent c in e.PublishedEntities) { if(c.HasPublishedVersion) { IEnumerable<string> urls = UmbracoFlareDomainManager.Instance.GetUrlsForNode(c, false); if(urls.Contains("#")) { //When a piece of content is first saved, we cannot get the url, if that is the case then we need to just //invalidate the who ContentIdToUrlCache, that way when we request all of the urls agian, it will pick it up. UmbracoUrlWildCardManager.Instance.DeletedContentIdToUrlCache(); } else { UmbracoUrlWildCardManager.Instance.UpdateContentIdToUrlCache(c.Id, urls); } } //TODO: Does this need to be here? //We also need to update the descendants now because their urls changed IEnumerable<IContent> descendants = c.Descendants(); foreach(IContent desc in descendants) { IEnumerable<string> descUrls = UmbracoFlareDomainManager.Instance.GetUrlsForNode(desc.Id, false); UmbracoUrlWildCardManager.Instance.UpdateContentIdToUrlCache(c.Id, descUrls); } } }
protected virtual void FireBeforePublish(PublishEventArgs e) { if (BeforePublish != null) BeforePublish(this, e); }
internal Attempt<PublishStatus> SaveAndPublishWithResult(User u) { foreach (var property in GenericProperties) { Content.SetValue(property.PropertyType.Alias, property.Value); } var saveArgs = new SaveEventArgs(); FireBeforeSave(saveArgs); if (!saveArgs.Cancel) { var publishArgs = new PublishEventArgs(); FireBeforePublish(publishArgs); if (!publishArgs.Cancel) { //NOTE: The 'false' parameter will cause the PublishingStrategy events to fire which will ensure that the cache is refreshed. var result = ((ContentService)ApplicationContext.Current.Services.ContentService) .SaveAndPublishInternal(Content, u.Id); base.VersionDate = Content.UpdateDate; this.UpdateDate = Content.UpdateDate; //NOTE: This is just going to call the CMSNode Save which will launch into the CMSNode.BeforeSave and CMSNode.AfterSave evenths // which actually do dick all and there's no point in even having them there but just in case for some insane reason someone // has bound to those events, I suppose we'll need to keep this here. base.Save(); //Launch the After Save event since we're doing 2 things in one operation: Saving and publishing. FireAfterSave(saveArgs); //Now we need to fire the After publish event FireAfterPublish(publishArgs); return result; } return Attempt<PublishStatus>.Fail(); } return Attempt<PublishStatus>.Fail(); }
private void DocumentBeforePublish(Document document, PublishEventArgs e) { _autoDocuments.BeforeDocumentPublish(document); }
protected override void OnShown(EventArgs e) { base.OnShown(e); Update(); PublishEventArgs args = new PublishEventArgs(_publish); if (PrePublish != null) PrePublish(this, args); if (args.Cancel) { _cancelReason = args.CancelReason; SetDialogResult(DialogResult.Abort); return; } StartUpdate(); }
protected virtual void FireAfterPublish(PublishEventArgs e) { if (AfterPublish != null) AfterPublish(this, e); }
void Document_BeforePublish(Document sender, PublishEventArgs e) { //lets log this stuff LogHelper.Debug(typeof(RegisterEvents),"the document " + sender.Text + " is about to be published"); e.Cancel = true; }
static void DocumentBeforePublish(Document sender, PublishEventArgs e) { #region Forum Events if ((sender.ContentType.Alias == "Forum")) { CacheHelper.Clear(CacheHelper.CacheNameSettings()); } #endregion }