public static string Move(int ID, int target) { int _currentMember = HttpContext.Current.User.Identity.IsAuthenticated ? (int)Membership.GetUser().ProviderUserKey : 0; if (Xslt.IsMemberInGroup("admin", _currentMember) || Xslt.IsMemberInGroup("wiki editor", _currentMember)) { Document d = new Document(ID); Document t = new Document(target); if(t.ContentType.Alias == "WikiPage"){ Document o = new Document(d.Parent.Id); d.Move(t.Id); d.Save(); d.Publish(new umbraco.BusinessLogic.User(0)); t.Publish(new umbraco.BusinessLogic.User(0)); o.Publish(new umbraco.BusinessLogic.User(0)); umbraco.library.UpdateDocumentCache(d.Id); umbraco.library.UpdateDocumentCache(t.Id); umbraco.library.UpdateDocumentCache(o.Id); umbraco.library.RefreshContent(); return umbraco.library.NiceUrl(d.Id); } } return ""; }
public static int CreateComment(int parentId) { HttpRequest post = HttpContext.Current.Request; string email = post["email"]; string comment = post["comment"]; string name = post["author"]; string website = post["url"]; //if all values are there + valid email.. we start to create the comment if (!string.IsNullOrEmpty(email) && isValidEmail(email) && !string.IsNullOrEmpty(comment) && !string.IsNullOrEmpty(name)) { Document blogpost = new Document(parentId); //if parent is actually a blogpost if(blogpost != null && blogpost.ContentType.Alias == "BlogPost"){ umbraco.presentation.nodeFactory.Node blog = new umbraco.presentation.nodeFactory.Node(parentId); while (blog.NodeTypeAlias != "Blog") { blog = blog.Parent; } int blogid = blog.Id; bool isspam = false; SpamChecker checker = Config.GetChecker(); if (checker != null) { isspam = checker.Check(parentId, post.UserAgent, post.UserHostAddress, name, email, website, comment); } ISqlHelper SqlHelper = DataLayerHelper.CreateSqlHelper(umbraco.GlobalSettings.DbDSN); SqlHelper.ExecuteNonQuery( @"insert into Comment(mainid,nodeid,name,email,website,comment,spam,created) values(@mainid,@nodeid,@name,@email,@website,@comment,@spam,@created)", SqlHelper.CreateParameter("@mainid", blogid), SqlHelper.CreateParameter("@nodeid", blogpost.Id), SqlHelper.CreateParameter("@name", name), SqlHelper.CreateParameter("@email", email), SqlHelper.CreateParameter("@website", website), SqlHelper.CreateParameter("@comment", comment), SqlHelper.CreateParameter("@spam", isspam), SqlHelper.CreateParameter("@created", DateTime.Now)); return 1; } } //if nothing gets created, we return zero return 0; }
protected override void OnInit(EventArgs e) { base.OnInit(e); if (!(Page.Request.CurrentExecutionFilePath ?? string.Empty).Contains("editContent.aspx")) return; _lblOrderInfo = new Label(); var documentId = int.Parse(HttpContext.Current.Request.QueryString["id"]); var orderDoc = new Document(documentId); var orderGuidValue = orderDoc.getProperty("orderGuid").Value; if (orderGuidValue != null && !string.IsNullOrEmpty(orderGuidValue.ToString())) { var orderGuid = Guid.Parse(orderDoc.getProperty("orderGuid").Value.ToString()); var orderInfoXml = OrderHelper.GetOrderXML(orderGuid); var parameters = new Dictionary<string, object>(1) {{"uniqueOrderId", orderGuid.ToString()}}; var transformation = macro.GetXsltTransformResult(orderInfoXml, macro.getXslt("uwbsOrderInfo.xslt"), parameters); _lblOrderInfo.Text = transformation ?? "uwbsOrderInfo.xslt render issue"; } else { _lblOrderInfo.Text = "Unique Order ID not found. Republish might solve this issue"; } if (ContentTemplateContainer != null) ContentTemplateContainer.Controls.Add(_lblOrderInfo); }
public void Save() { if (!(Page.Request.CurrentExecutionFilePath ?? string.Empty).Contains("editContent.aspx")) return; int currentId; int.TryParse(Page.Request.QueryString["id"], out currentId); var currentDoc = new Document(currentId); // Get the current property type var propertyTypeId = ((DefaultData) this._data).PropertyId; var property = currentDoc.GenericProperties.FirstOrDefault(x => x.Id == propertyTypeId); var propertyAlias = property.PropertyType.Alias; // test if the property alias contains an shopalias var storeAlias = GetStoreAliasFromProperyAlias(propertyAlias); int newStock; int.TryParse(_txtStock.Text, out newStock); if (currentId != 0) { UWebshopStock.UpdateStock(currentId, newStock, false, storeAlias); } }
public override ActionResult Index(RenderModel model) { if (model.Content.TemplateId.Equals(Template.GetTemplateIdFromAlias("ProjectCreate"))) { var member = Member.GetCurrentMember(); if (member != null) { if (Request.HttpMethod.Equals("GET")) return CurrentTemplate(model); var project = CreateProject(member); if (project != null) return this.Redirect(umbraco.library.NiceUrl(project.Id)); } return this.Redirect(Request.UrlReferrer.AbsoluteUri); } else { var id = Convert.ToInt32(Request.Params["id"]); var project = new Document(id); var member = Member.GetCurrentMember(); var authorId = project.getProperty("author").Value; if (member != null && member.Id.Equals(authorId)) { if (Request.HttpMethod.Equals("GET")) return base.View(model); SaveProject(project, member); } return this.Redirect(umbraco.library.NiceUrl(id)); } }
private void SaveProject(Document project, Member user) { if (!string.IsNullOrWhiteSpace(Request["title"])) { project.getProperty("title").Value = Request["title"]; } if (!string.IsNullOrWhiteSpace(Request["description"])) project.getProperty("description").Value = Request["description"]; if (!string.IsNullOrWhiteSpace(Request["projectType"])) project.getProperty("projectType").Value = Convert.ToInt32(Request["projectType"]); if (!string.IsNullOrWhiteSpace(Request["area"])) project.getProperty("area").Value = Convert.ToInt32(Request["area"]); project.getProperty("allowComments").Value = !string.IsNullOrWhiteSpace(Request["allowComments"]) && Request["allowComments"].ToLower().Equals("on"); project.getProperty("author").Value = user.Id; if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0) { var uploadedFile = Request.Files[0]; var fileName = Path.GetFileName(uploadedFile.FileName); var fileSavePath = Server.MapPath("~/media/projects/" + fileName); uploadedFile.SaveAs(fileSavePath); project.getProperty("image").Value = "/media/projects/" + fileName; } project.SaveAndPublish(user.User); umbraco.library.UpdateDocumentCache(project.Id); }
public void Save() { string[] keys = Page.Request.Form.AllKeys; foreach (string key in keys) { if (key.StartsWith("DictionaryHelper")) { string strDocId = key.Substring(key.IndexOf("docId_") + 6); string property = key.Remove(key.IndexOf("docId_") - 1).Substring(17); string value = Page.Request.Form[key]; Document doc = new Document(int.Parse(strDocId)); if (property == "Text" || property == "Default" || property == "Help") { Property prop = doc.getProperty(property); if (prop != null) { prop.Value = value; } } else if (property == "Key") { doc.Text = value; } } } }
public static string MarkAsSolution(string pageId) { if (MembershipHelper.IsAuthenticated()) { var m = Member.GetCurrentMember(); var forumPost = _mapper.MapForumPost(new Node(Convert.ToInt32(pageId))); if (forumPost != null) { var forumTopic = _mapper.MapForumTopic(new Node(forumPost.ParentId.ToInt32())); // If this current member id doesn't own the topic then ignore, also // if the topic is already solved then ignore. if (m.Id == forumTopic.Owner.MemberId && !forumTopic.IsSolved) { // Get a user to save both documents with var usr = new User(0); // First mark the post as the solution var p = new Document(forumPost.Id); p.getProperty("forumPostIsSolution").Value = 1; p.Publish(usr); library.UpdateDocumentCache(p.Id); // Now update the topic var t = new Document(forumTopic.Id); t.getProperty("forumTopicSolved").Value = 1; t.Publish(usr); library.UpdateDocumentCache(t.Id); return library.GetDictionaryItem("Updated"); } } } return library.GetDictionaryItem("Error"); }
/// <summary> /// Gets the image property. /// </summary> /// <returns></returns> internal static string GetOriginalUrl(int nodeId, ImageResizerPrevalueEditor imagePrevalueEditor) { Property imageProperty; var node = new CMSNode(nodeId); if (node.nodeObjectType == Document._objectType) { imageProperty = new Document(nodeId).getProperty(imagePrevalueEditor.PropertyAlias); } else if (node.nodeObjectType == Media._objectType) { imageProperty = new Media(nodeId).getProperty(imagePrevalueEditor.PropertyAlias); } else { if (node.nodeObjectType != Member._objectType) { throw new Exception("Unsupported Umbraco Node type for Image Resizer (only Document, Media and Members are supported."); } imageProperty = new Member(nodeId).getProperty(imagePrevalueEditor.PropertyAlias); } try { return imageProperty.Value.ToString(); } catch { return string.Empty; } }
protected void BtnMoveClick(object sender, EventArgs e) { if (Category.Id != ddlCategories.SelectedValue.ToInt32()) { // Get the document you will move by its ID var doc = new Document(Topic.Id); // Create a user we can use for both var user = new User(0); // The new parent ID var newParentId = ddlCategories.SelectedValue.ToInt32(); // Now update the topic parent category ID doc.getProperty("forumTopicParentCategoryID").Value = newParentId; // publish application node doc.Publish(user); // Move the document the new parent doc.Move(newParentId); // update the document cache so its available in the XML umbraco.library.UpdateDocumentCache(doc.Id); // Redirect and show message Response.Redirect(string.Concat(CurrentPageAbsoluteUrl, "?m=", library.GetDictionaryItem("TopicHasBeenMovedText"))); } else { // Can't move as they have selected the category that the topic is already in Response.Redirect(string.Concat(CurrentPageAbsoluteUrl, "?m=", library.GetDictionaryItem("TopicAlreadyInThisCategory"))); } }
public System.Xml.Linq.XElement GetProperty(umbraco.cms.businesslogic.property.Property prop) { //get access to media item based on some path. var itm = new Document(int.Parse(prop.Value.ToString())); return new XElement(prop.PropertyType.Alias, itm.ConfigPath()); }
private void ClearFeedCache(Document sender) { int rootId; if (sender.Level <= 1) { return; } if (sender.ContentType.Alias == "Newslist") { rootId = sender.Id; } else if (new Document(sender.ParentId).ContentType.Alias == "Newslist") { rootId = sender.ParentId; } else { return; } var cacheName = string.Format(MainHelper.FeedCache, rootId); var cache = HttpRuntime.Cache[cacheName]; if (cache == null) { return; } HttpRuntime.Cache.Remove(cacheName); }
private void CopyProperties(Document fromDoc, Document toDoc) { foreach (umbraco.cms.businesslogic.propertytype.PropertyType propertyType in ParentDocument.ContentType.PropertyTypes) { toDoc.getProperty(propertyType.Alias).Value = fromDoc.getProperty(propertyType.Alias).Value; } }
public WikiPage(int id) { umbraco.cms.businesslogic.web.Document doc = new umbraco.cms.businesslogic.web.Document(id); if (doc != null) { if (doc.ContentType.Alias == "WikiPage") { Exists = true; Body = doc.getProperty("bodyText").Value.ToString(); Locked = (doc.getProperty("umbracoNoEdit").Value.ToString() == "1"); if (doc.getProperty("keywords") != null) { Keywords = doc.getProperty("keywords").Value.ToString(); } Title = doc.Text; Author = (int)doc.getProperty("author").Value; Version = doc.Version; Node = doc; NodeId = doc.Id; ParentId = Node.Parent.Id; } } }
/// <summary> /// Initializes a new instance of the <see cref="page"/> class for a yet unpublished document. /// </summary> /// <param name="document">The document.</param> public page(Document document) { var docParentId = -1; try { docParentId = document.Parent.Id; } catch (ArgumentException) { //ignore if no parent } populatePageData(document.Id, document.Text, document.ContentType.Id, document.ContentType.Alias, document.User.Name, document.Creator.Name, document.CreateDateTime, document.UpdateDate, document.Path, document.Version, docParentId); foreach (Property prop in document.GenericProperties) { string value = prop.Value != null ? prop.Value.ToString() : String.Empty; _elements.Add(prop.PropertyType.Alias, value); } _template = document.Template; }
public List<INode> FindPossibleThemesForArticle(Document doc) { string docType = doc.ContentType.Alias; var themes = new List<INode>(); if (!docType.Equals("Article")) { throw new ArgumentException("Finding possible themes is only possible for the Article node type."); } string[] pathIds = (doc.Path.Split(',')); foreach (var idString in pathIds) { if (idString != "-1") { int id = -10; int.TryParse(idString, out id); Document pathDoc = new Document(id); if (pathDoc.ContentType.Alias.Equals("Category")) { // Only published themes are found, because we are using the Node API themes = FindThemes(new Node(pathDoc.Id)); } } } return themes; }
/// <summary>Copy document under another document.</summary> public static void CopyDocument(Document cmsSourceDocument, int cmsTargetDocumentId, bool relateToOriginal = false) { // Validate dependencies. if(cmsSourceDocument != null && cmsTargetDocumentId >= 0) { cmsSourceDocument.Copy(cmsTargetDocumentId, cmsSourceDocument.User, relateToOriginal); } }
/// <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)); } } } } }
protected void Page_Load(object s, EventArgs e) { var user = global::umbraco.BusinessLogic.User.GetUser(0); using (CmsContext.Editing) { var result = new StringBuilder(); foreach (var newspage in CmsService.Instance.SelectItems<NewsPage>("/Content//*{NewsPage}")) { var sender = new Document(newspage.Id.IntValue); if (newspage.Date.HasValue) { var newsArchivePart = CmsService.Instance.GetSystemPath("NewsArchivePage"); var yearPart = newspage.Date.Value.Year.ToString(); var monthPart = Urls.MonthArray.Split('|')[newspage.Date.Value.Month - 1]; var truePath = Paths.Combine(newsArchivePart, yearPart, monthPart, sender.Text); if (truePath != newspage.Path) { var yearPage = CmsService.Instance.GetItem<NewsListPage>(Paths.Combine(newsArchivePart, yearPart)); if (yearPage == null) { var archivePage = CmsService.Instance.GetItem<NewsListPage>(newsArchivePart); yearPage = CmsService.Instance.CreateEntity<NewsListPage>(yearPart, archivePage); } var monthPage = CmsService.Instance.GetItem<NewsListPage>(Paths.Combine(newsArchivePart, yearPart, monthPart)); if (monthPage == null) monthPage = CmsService.Instance.CreateEntity<NewsListPage>(monthPart, yearPage); sender.Move(monthPage.Id.IntValue); } } } library.RefreshContent(); litOutput.Text = result.ToString(); } }
public override TaskExecutionDetails Execute(string Value) { TaskExecutionDetails d = new TaskExecutionDetails(); if (HttpContext.Current != null && HttpContext.Current.Items["pageID"] != null) { string id = HttpContext.Current.Items["pageID"].ToString(); Document doc = new Document(Convert.ToInt32(id)); if (doc.getProperty(PropertyAlias) != null) { d.OriginalValue = doc.getProperty(PropertyAlias).Value.ToString(); doc.getProperty(PropertyAlias).Value = Value; doc.Publish(new BusinessLogic.User(0)); d.NewValue = Value; d.TaskExecutionStatus = TaskExecutionStatus.Completed; } else d.TaskExecutionStatus = TaskExecutionStatus.Cancelled; } else d.TaskExecutionStatus = TaskExecutionStatus.Cancelled; return d; }
private INode SaveDoc(Document doc) { doc.Save(); doc.Publish(User.GetAllByLoginName("visitor", false).FirstOrDefault()); umbraco.library.UpdateDocumentCache(doc.Id); return new Node(doc.Id); }
public void Run(IWorkflowInstance workflowInstance, IWorkflowRuntime runtime) { // Cast to Umbraco worklow instance. var umbracoWorkflowInstance = (UmbracoWorkflowInstance) workflowInstance; var count = 0; var newCmsNodes = new List<int>(); foreach(var nodeId in umbracoWorkflowInstance.CmsNodes) { var n = new CMSNode(nodeId); if(!n.IsDocument()) continue; var d = new Document(nodeId); if (!DocumentTypes.Contains(d.ContentType.Id)) continue; newCmsNodes.Add(nodeId); count++; } umbracoWorkflowInstance.CmsNodes = newCmsNodes; var transition = (count > 0) ? "contains_docs" : "does_not_contain_docs"; runtime.Transition(workflowInstance, this, transition); }
private static string GetFriendlyPathForDocument(Document document) { const string separator = "->"; var nodesInPath = document.Path.Split(',').Skip(1); var retVal = new StringBuilder(); foreach (var nodeId in nodesInPath) { var currentDoc = new Document(int.Parse(nodeId)); var displayText = ""; if (currentDoc == null || string.IsNullOrEmpty(currentDoc.Path)) continue; if (nodeId == "-20" || nodeId == "-21") displayText = "Recycle Bin"; else displayText = currentDoc.Text; retVal.AppendFormat("{0} {1} ", displayText, separator); } return retVal.ToString().Substring(0, retVal.ToString().LastIndexOf(separator)).Trim(); }
public JsonResult PublishDocument(int documentId, bool publishDescendants, bool includeUnpublished) { var content = Services.ContentService.GetById(documentId); var doc = new Document(content); //var contentService = (ContentService) Services.ContentService; if (publishDescendants == false) { //var result = contentService.SaveAndPublishInternal(content); var result = doc.SaveAndPublish(UmbracoUser.Id); return Json(new { success = result.Success, message = GetMessageForStatus(result.Result) }); } else { /*var result = ((ContentService) Services.ContentService) .PublishWithChildrenInternal(content, UmbracoUser.Id, includeUnpublished) .ToArray();*/ var result = doc.PublishWithSubs(UmbracoUser.Id, includeUnpublished); return Json(new { success = result.All(x => x.Success), message = GetMessageForStatuses(result.Select(x => x.Result), content) }); } }
/// <summary> Document_BeforeSave(Document sender, umbraco.cms.businesslogic.SaveEventArgs e) umbraco Document BeforeSave event :Document prüfen /// </summary> void Document_BeforeSave(Document sender, umbraco.cms.businesslogic.SaveEventArgs e) { try { Config config = Config.GetConfig(); foreach (ConfigDatatype author in config.Datatypes) { foreach (Property pr in sender.GenericProperties) { if (author.Guid == pr.PropertyType.DataTypeDefinition.DataType.Id) { Property fileprop = sender.getProperty("" + pr.PropertyType.Alias + ""); e.Cancel = File_Scanner(fileprop); } } } } catch (Exception ex) { } if (html_msg.Length > 0) { HtmlContent(html_msg); html_msg.Clear(); } }
/// <summary> /// Saveses this instance. /// </summary> public void Save() { // get the data Document document = new Document(NodeId.Value); Property editProperty = document.getProperty(Field); IDataType editDataType = null; if (editProperty != null) { // save the property PropertyType editPropertyType = editProperty.PropertyType; editDataType = editPropertyType.DataTypeDefinition.DataType; editDataType.Data.PropertyId = editProperty.Id; editDataType.Data.Value = Data; } else { if (Field == "pageName") { document.Text = Data.ToString(); } } document.Save(); }
void Document_AfterPublish(Document sender, umbraco.cms.businesslogic.PublishEventArgs e) { if (sender.ContentType.Alias == "BlogPost") { string urls = GetValueRecursively("pingServices", sender.Id); if (!string.IsNullOrEmpty(urls)) { string blogUrl; XmlDocument xd = new XmlDocument(); try { xd.LoadXml(urls); } catch { } string blogName = GetValueRecursively("blogName", sender.Id); string currentDomain = HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToLower(); library.UpdateDocumentCache(sender.Id); try { blogUrl = library.NiceUrlFullPath(sender.Id); if (!UmbracoSettings.UseDomainPrefixes) blogUrl = "http://" + currentDomain + blogUrl; } catch (Exception) { Log.Add(LogTypes.Debug, sender.Id, "Cound not get 'NiceUrlFullPath' from current application"); blogUrl = "http://" + currentDomain + "/" + library.NiceUrl(sender.Id); } foreach (XmlNode link in xd.SelectNodes("//link [@type = 'external']")) { string ping = link.Attributes["link"].Value; //Log.Add(LogTypes.Debug, sender.Id, ping + " n:" + blogName + " u:" + blogUrl); PingService(ping, blogName, blogUrl); } } } }
protected static void OnDocumentDeleted(Document sender, umbraco.cms.businesslogic.DeleteEventArgs e) { var page = CmsService.Instance.GetItem<Page>(new Id(sender.Id)); if (!page.Template.Path.StartsWith("/WebPage")) return; SearchBackgroundCrawler.QueueDocumentDelete(page); }
// Implement the Run method of IRunnableWorkflowTask public void Run(IWorkflowInstance workflowInstance, IWorkflowRuntime runtime) { // In Umbraco the workflowInstance should always be castable to an UmbracoWorkflowInstance var wf = (UmbracoWorkflowInstance) workflowInstance; // UmbracoWorkflowInstance has a list of node Ids that are associated with the workflow in the CmsNodes property foreach(var nodeId in wf.CmsNodes) { // We'll assume that only documents are attached to this workflow var doc = new Document(nodeId); var property = doc.getProperty(DocumentTypeProperty); if (!String.IsNullOrEmpty((string) property.Value)) continue; var host = HttpContext.Current.Request.Url.Host; var pageUrl = "http://" + host + umbraco.library.NiceUrl(nodeId); var shortUrl = API.Bit(BitLyLogin, BitLyApiKey, pageUrl, "Shorten"); property.Value = shortUrl; } // The run method of a workflow task is responsible for informing the runtime of the outcome. // The outcome should be one of the items in the AvailableTransitions list. runtime.Transition(workflowInstance, this, "done"); }
private void BaseTree_BeforeNodeRender(ref XmlTree sender, ref XmlTreeNode node, EventArgs e) { if (node.TreeType.ToLower() == "content") { try { Document document = new Document(Convert.ToInt32(node.NodeID)); //this changes the create action b/c of the UI.xml entry if (CreateDocTypes.Contains(document.ContentType.Alias)) { node.NodeType = "uNews"; } if (RemoveCreateDocTypes.Contains(document.ContentType.Alias)) { node.Menu.Remove(ActionNew.Instance); } } catch (Exception e2) { } } }
public string Move(int wikiId, int target) { var currentMemberId = Members.GetCurrentMember().Id; if (Xslt.IsMemberInGroup("admin", currentMemberId) || Xslt.IsMemberInGroup("wiki editor", currentMemberId)) { Document document = new Document(wikiId); Document documentTarget = new Document(target); if (documentTarget.ContentType.Alias == "WikiPage") { Document o = new Document(document.Parent.Id); document.Move(documentTarget.Id); document.Save(); document.Publish(new umbraco.BusinessLogic.User(0)); documentTarget.Publish(new umbraco.BusinessLogic.User(0)); o.Publish(new umbraco.BusinessLogic.User(0)); umbraco.library.UpdateDocumentCache(document.Id); umbraco.library.UpdateDocumentCache(documentTarget.Id); umbraco.library.UpdateDocumentCache(o.Id); umbraco.library.RefreshContent(); return umbraco.library.NiceUrl(document.Id); } } return ""; }
public void Save() { if (NodeId == 0) { if (!string.IsNullOrEmpty(Title) && !string.IsNullOrEmpty(Body)) { CreateEventArgs e = new CreateEventArgs(); FireBeforeCreate(e); if (!e.Cancel) { Document childDoc = Document.MakeNew(Title, DocumentType.GetByAlias("WikiPage"), new umbraco.BusinessLogic.User(0), ParentId); childDoc.getProperty("author").Value = Author; childDoc.getProperty("bodyText").Value = Body; childDoc.getProperty("keywords").Value = Keywords; childDoc.Save(); childDoc.Publish(new umbraco.BusinessLogic.User(0)); umbraco.library.UpdateDocumentCache(childDoc.Id); Node = childDoc; NodeId = childDoc.Id; Version = childDoc.Version; Exists = true; FireAfterCreate(e); } } } else { UpdateEventArgs e = new UpdateEventArgs(); FireBeforeUpdate(e); if (!e.Cancel) { if (Node == null) { Node = new Document(NodeId); } Node.Text = Title; Node.getProperty("author").Value = Author; Node.getProperty("bodyText").Value = Body; Node.getProperty("keywords").Value = Keywords; Node.Save(); Node.Publish(new umbraco.BusinessLogic.User(0)); umbraco.library.UpdateDocumentCache(Node.Id); FireAfterUpdate(e); } } }
void Document_AfterSave(umbraco.cms.businesslogic.web.Document sender, umbraco.cms.businesslogic.SaveEventArgs e) { if (sender.ContentType.Alias == "WikiPage") { Hashtable fields = new Hashtable(); fields.Add("id", sender.Id); fields.Add("name", sender.Text); fields.Add("content", umbraco.library.StripHtml(sender.getProperty("bodyText").Value.ToString())); fields.Add("path", (sender.Path.Replace("-1,", "").Replace(",", new Businesslogic.Settings().PathSplit))); Businesslogic.Indexer i = new uSearch.Businesslogic.Indexer(); i.AddToIndex("wiki_" + sender.Id.ToString(), "wiki", fields); } }
public List <documentCarrier> readList(int parentid, string username, string password) { Authenticate(username, password); umbraco.cms.businesslogic.web.Document[] docList; umbraco.cms.businesslogic.web.Document doc = null; List <documentCarrier> carriers = new List <documentCarrier>(); if (parentid == 0) { docList = Document.GetRootDocuments(); } else { try { doc = new umbraco.cms.businesslogic.web.Document(parentid); } catch {} if (doc == null) { throw new Exception("Parent document with ID " + parentid + " not found"); } try { if (!doc.HasChildren) { return(carriers); } docList = doc.Children; } catch (Exception exception) { throw new Exception("Could not load children: " + exception.Message); } } // Loop the nodes in docList foreach (Document childdoc in docList) { carriers.Add(createCarrier(childdoc)); } return(carriers); }
public static string Rollback(int ID, string guid) { int _currentMember = HttpContext.Current.User.Identity.IsAuthenticated ? (int)Membership.GetUser().ProviderUserKey : 0; umbraco.cms.businesslogic.web.Document olddoc = new umbraco.cms.businesslogic.web.Document(ID, new Guid(guid)); Businesslogic.WikiPage wp = new uWiki.Businesslogic.WikiPage(ID); if (olddoc != null && wp.Exists && !wp.Locked && _currentMember > 0 && wp.Version.ToString() != guid) { wp.Body = olddoc.getProperty("bodyText").Value.ToString(); wp.Title = olddoc.Text; wp.Author = _currentMember; wp.Save(); return(umbraco.library.NiceUrl(wp.NodeId)); } return(""); }
/// <summary> /// Executes on the current document object when the specified actions occur /// </summary> /// <param name="documentObject">The document object.</param> /// <param name="action">The action.</param> /// <returns>Returns true if successfull, otherwise false</returns> public bool Execute(umbraco.cms.businesslogic.web.Document documentObject, interfaces.IAction action) { if (UmbracoSettings.EnsureUniqueNaming) { string currentName = documentObject.Text; int uniqueNumber = 1; // Check for all items underneath the parent to see if they match // as any new created documents are stored in the bottom, we can just // keep checking for other documents with a uniquenumber from //store children array here because iterating over an Array property object is very inneficient. var c = Document.GetChildrenBySearch(documentObject.ParentId, currentName + "%"); // must sort the list or else duplicate name will exist if pages are out out sequence //e.g. Page (1), Page (3), Page (2) var results = c.OrderBy(x => x.Text, new SimilarNodeNameComparer()); foreach (Document d in results) { if (d.Id != documentObject.Id && d.Text.ToLower() == currentName.ToLower()) { currentName = documentObject.Text + " (" + uniqueNumber.ToString() + ")"; uniqueNumber++; } } // if name has been changed, update the documentobject if (currentName != documentObject.Text) { // add name change to the log LogHelper.Debug <umbEnsureUniqueName>("Title changed from '" + documentObject.Text + "' to '" + currentName + "' for document id" + documentObject.Id); documentObject.Text = currentName; return(true); } } return(false); }
public documentCarrier read(int id, string username, string password) { Authenticate(username, password); umbraco.cms.businesslogic.web.Document doc = null; try { doc = new umbraco.cms.businesslogic.web.Document(id); } catch {} if (doc == null) { throw new Exception("Could not load Document with ID: " + id); } documentCarrier carrier = createCarrier(doc); return(carrier); }
public static string Create(int parentID) { string _body = HttpContext.Current.Request["body"]; string _title = HttpContext.Current.Request["title"]; string _keywords = HttpContext.Current.Request["keywords"]; int _currentMember = HttpContext.Current.User.Identity.IsAuthenticated ? (int)Membership.GetUser().ProviderUserKey : 0; if (parentID > 0 && _currentMember > 0) { bool isAdmin = (Library.Xslt.IsInGroup("admin") || Library.Xslt.IsInGroup("wiki editor")); umbraco.cms.businesslogic.web.Document doc = new umbraco.cms.businesslogic.web.Document(parentID); bool isLocked = (doc.getProperty("umbracoNoEdit").Value.ToString() == "1"); if ((isAdmin || !isLocked) && doc.ContentType.Alias == "WikiPage") { Businesslogic.WikiPage wp = Businesslogic.WikiPage.Create(parentID, _currentMember, _body, _title, _keywords); return(umbraco.library.NiceUrl(wp.NodeId)); } } return(""); }
/// <summary> /// Executes on the current document object when the specified actions occur /// </summary> /// <param name="documentObject">The document object.</param> /// <param name="action">The action.</param> /// <returns>Returns true if successfull, otherwise false</returns> public bool Execute(umbraco.cms.businesslogic.web.Document documentObject, interfaces.IAction action) { if (UmbracoSettings.EnsureUniqueNaming) { string currentName = documentObject.Text; int uniqueNumber = 1; // Check for all items underneath the parent to see if they match // as any new created documents are stored in the bottom, we can just // keep checking for other documents with a uniquenumber from //store children array here because iterating over an Array property object is very inneficient. var c = Document.GetChildrenBySearch(documentObject.ParentId, currentName + "%"); foreach (Document d in c) { if (d.Id != documentObject.Id && d.Text.ToLower() == currentName.ToLower()) { currentName = documentObject.Text + " (" + uniqueNumber.ToString() + ")"; uniqueNumber++; } } // if name has been changed, update the documentobject if (currentName != documentObject.Text) { // add name change to the log umbraco.BusinessLogic.Log.Add(umbraco.BusinessLogic.LogTypes.Debug, umbraco.BusinessLogic.User.GetUser(0), documentObject.Id, "Title changed from '" + documentObject.Text + "' to '" + currentName + "'"); documentObject.Text = currentName; return(true); } } return(false); }