/// <summary> /// Gets the property. /// </summary> /// <param name="property">The property.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> /// <returns></returns> public override object GetProperty(Umbraco.Core.Models.Property property, UmbracoPropertyConfiguration config, UmbracoDataMappingContext context) { if (property == null || property.Value == null) return null; var mediaService = new MediaService(new RepositoryFactory()); int id; if (!int.TryParse(property.Value.ToString(), out id)) return null; var file = mediaService.GetById(id); if (file != null) { int bytes; int.TryParse(file.Properties["umbracoBytes"].Value.ToString(), out bytes); var img = new File { Id = file.Id, Name = file.Name, Src = file.Properties["umbracoFile"].Value.ToString(), Extension = file.Properties["umbracoExtension"].Value.ToString(), Size = bytes }; return img; } return null; }
public override void PackagingDataType(Umbraco.Courier.ItemProviders.DataType item) { //to ensure UI is there, include the digibiz folder of files item.Dependencies.Add("~/umbraco/plugins/DigibizAdvancedMediaPicker", Umbraco.Courier.ItemProviders.ProviderIDCollection.folderItemProviderGuid); item.Resources.Add("~/bin/DigibizTree.dll"); var source = item.Prevalues.Where(x => x.SortOrder == 2).FirstOrDefault(); var defaultType = item.Prevalues.Where(x => x.SortOrder == 13).FirstOrDefault(); List<string> foundNodes = new List<string>(); if (source != null && source.Value != null){ source.Value = Dependencies.ConvertIdentifierCollection(source.Value.ToString(), out foundNodes); foreach (var g in foundNodes) item.Dependencies.Add(g, ProviderIDCollection.mediaItemProviderGuid); } if (defaultType != null && defaultType.Value != null) { defaultType.Value = Dependencies.ConvertIdentifierCollection(defaultType.Value.ToString(), out foundNodes); foreach (var g in foundNodes) item.Dependencies.Add(g, ProviderIDCollection.mediaTypeItemProviderGuid); } }
/// <summary> /// Hi hacjking in progress! WE are going to search here /// </summary> /// <param name="model"></param> /// <returns></returns> public override System.Web.Mvc.ActionResult Index(Umbraco.Web.Models.RenderModel model) { //the incoming search term string incomingSearch = Request.QueryString["query"]; //search result model var searchResultsToReturn = new SearchPageModel(); //let's check if the incoming string is empty or not if (!string.IsNullOrEmpty(incomingSearch)) { //let's get the searcher var umbBookSearch = Examine.ExamineManager.Instance.SearchProviderCollection["UmbBookSearchSearcher"]; //do some searching var searchResults = umbBookSearch.Search(incomingSearch, true); foreach (var item in searchResults) { SearchResultModel searchResult = new SearchResultModel(); searchResult.Name = item.Fields["nodeName"]; searchResult.UserId = item.Fields["id"]; searchResultsToReturn.Results.Add(searchResult); } } return CurrentTemplate(searchResultsToReturn); }
void ContentServicePublished(Umbraco.Core.Publishing.IPublishingStrategy sender, Umbraco.Core.Events.PublishEventArgs<IContent> e) { // when something is published, (if it's a ForumPost) // clear the relevant forum cache. // we do it in two steps because more than one post in a forum // may have been published, so we only need to clear the cache // once. List<string> invalidCacheList = new List<string>(); foreach (var item in e.PublishedEntities) { // is a forum post... if (item.ContentTypeId == postContentTypeId) { // get parent Forum. invalidCacheList = AddParentForumCaches(item, invalidCacheList); } } // clear the cache for any forums that have had child pages published... foreach (var cache in invalidCacheList) { LogHelper.Info<SimpilyForumCacheHandler>("Clearing Forum Info Cache: {0}", () => cache); ApplicationContext.Current.ApplicationCache.RuntimeCache.ClearCacheByKeySearch(cache); } }
/// <summary> /// Copies first name, last name and email address from saved member to Merchello customer. /// </summary> /// <param name="sender"> /// The <see cref="IMemberService"/>. /// </param> /// <param name="e"> /// The saved <see cref="IMember"/>s. /// </param> private static void MemberServiceSaved(IMemberService sender, Umbraco.Core.Events.SaveEventArgs<Umbraco.Core.Models.IMember> e) { var members = e.SavedEntities.ToArray(); // Allowed member types for Merchello customers var customerMemberTypes = MerchelloConfiguration.Current.CustomerMemberTypes.ToArray(); // Get a reference to Merchello's customer service var customerService = MerchelloContext.Current.Services.CustomerService; foreach (var member in members) { // verify the member is a customer type if (!customerMemberTypes.Contains(member.ContentTypeAlias)) continue; var customer = customerService.GetByLoginName(member.Username); if (customer == null) continue; customer.FirstName = member.GetValue<string>("firstName") ?? string.Empty; customer.LastName = member.GetValue<string>("lastName") ?? string.Empty; customer.Email = member.Username; customerService.Save(customer); } }
public object BasicGetPropertyAction(int id, string property) { var type = Umbraco.TypedContent(id); var val = type.GetProperty(property).Value; return(val); }
public ContentResult Dictionary() { ContentResult result = new ContentResult(); result.Content = Umbraco.GetDictionaryValue("Test"); return(result); }
/// <summary> /// when something is deleted it's plopped in the recycle bin /// </summary> void ContentService_Trashing(IContentService sender, Umbraco.Core.Events.MoveEventArgs<IContent> e) { LogHelper.Info<ContentEvents>("Trashing {0}", () => e.Entity.Name); ArchiveContentItem(e.Entity); }
public string GetApplication([FromBody] UserInfo userinfo) { var uid = userinfo.UID; var userinfoItems = Umbraco.Content(1083).Children.Where("UID==userinfo.UID"); var info = userinfoItems == null ? "" : userinfoItems[0]; return(Json(info)); }
public List <ExchangeModel> GetAllBlogItems() { var blogNodes = (IPublishedContent)Umbraco.ContentAtXPath("//home//blog").FirstOrDefault(); var resp = blogNodes.Children <Blogpost>(); var modifiedList = resp.Select(x => new ExchangeModel(x.Name, x.WriterName)).ToList(); return(modifiedList.ToList()); }
void MediaService_Trashing(IMediaService sender, Umbraco.Core.Events.MoveEventArgs<IMedia> e) { SourceInfo.Load(); LogHelper.Info<MediaEvents>("Archiving {0}", () => e.Entity.Name); MediaExporter me = new MediaExporter(); me.Archive(e.Entity); SourceInfo.Save(); }
/// <summary> /// Gets the Url for a given node ID /// </summary> /// <param name="id"></param> /// <returns></returns> public HttpResponseMessage GetNiceUrl(int id) { var url = Umbraco.NiceUrl(id); var response = Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(url, Encoding.UTF8, "application/json"); return(response); }
/// <summary> /// Generic get chart. /// Based on the Id it searches for the alias and then forwards the request to the applicable controllers /// </summary> /// <param name="id">Id of the content that we're in</param> /// <returns>Action result that comes from the different controllers</returns> public List <String> GetChart(int id) { String contentAlias = ((IPublishedContent)Umbraco.Content(id)).DocumentTypeAlias; MethodInfo mi = this.GetType().GetMethod("Get" + contentAlias + "Chart"); List <String> partialViewUrls = (List <String>)mi.Invoke(this, null); return(partialViewUrls); }
public bool BasicHasPropertyAction(int id, string property) { var type = Umbraco.TypedContent(id); var hasProperty = type.HasProperty(property); return(hasProperty); }
public string BasicContentTypeAction(int id) { var type = Umbraco.TypedContent(id); var alias = type.ContentType.Alias; return(alias); }
private void ContentService_Creating(IContentService sender, Umbraco.Core.Events.NewEventArgs<IContent> e) { //if (e.Alias == "SOSU-Nyhed") //{ // e.Entity.SetValue("contentDate", DateTime.Now); // // e.Entity.SetValue("umbracoNaviHide", true); //} }
public ActionResult ChangePassword() { var model = new YuzuFormViewModel(); IMember member = null; IPublishedContent memberModel = null; var userKey = Request.QueryString["id"]; if (!string.IsNullOrEmpty(userKey)) { member = memberService.GetByKey(Guid.Parse(userKey)); memberModel = Members.GetById(member.Id); } if (Umbraco.MemberIsLoggedOn() || member != null) { if (TempData["FormSuccess"] != null && TempData["FormSuccess"].ToString() == "True") { model.Form = viewmodelFactory.Success("Change Password", "Your password has been changed"); } else if (member != null && memberModel.Value <DateTime>("ForgottenPasswordExpiry") < DateTime.UtcNow) { model.Form = viewmodelFactory.Success("Change Password", "Password change link has timed out, please try again"); model.Form.ActionLinks = new List <vmBlock_DataLink>() { new vmBlock_DataLink() { Label = config.ForgottenPasswordLabel, Href = config.ForgottenPasswordUrl } }; } else { var formFields = new List <object>() { new vmBlock_FormTextInput() { Name = "changePasswordVm.Password", Type = "password", Label = "Password", Placeholder = "Password", IsRequired = true }, new vmBlock_FormTextInput() { Name = "changePasswordVm.ConfirmPassword", Type = "password", Label = "Confirm Password", Placeholder = "Confirm Password", IsRequired = true }, new vmBlock_FormHidden() { Name = "changePasswordVm.UserKey", Value = userKey } }; model.Form = viewmodelFactory.Form("Change Password", "Change Password", formFields); model.AddHandler <MemberHandlerController>(x => x.HandleChangePassword(null)); } } else { Response.Redirect(config.HomeUrl); } return(PartialView("YuzuForms", model)); }
public HttpResponseMessage GetPreviewMacro( int nodeId, string macroAlias, IDictionary <string, object> parameters) { var html = string.Empty; var response = new HttpResponseMessage(); var previewTemplate = Services.FileService.GetTemplate("PreviewFrame"); if (previewTemplate != null) { // Fix certificate problem... ServicePointManager.ServerCertificateValidationCallback += (senderr, cert, chain, sslPolicyErrors) => true; var p = JsonConvert.SerializeObject(parameters ?? new Dictionary <string, object>()); var additionalRouteVals = new Dictionary <string, object>(); additionalRouteVals.Add("alias", macroAlias); additionalRouteVals.Add("parameters", p); var ufprint = routeFactory.SurfaceAction( "GetMacroResult", "AjaxHelper", string.Empty, additionalRouteVals); var content = Umbraco.TypedContent(nodeId); var url = content.UrlWithDomain(); var req = WebRequest.Create(url); var postData = string.Format("ufprt={0}", ufprint); var send = Encoding.Default.GetBytes(postData); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = send.Length; var sout = req.GetRequestStream(); sout.Write(send, 0, send.Length); sout.Flush(); sout.Close(); var res = req.GetResponse(); var stream = res.GetResponseStream(); if (stream != null) { var sr = new StreamReader(stream); var previewHtml = sr.ReadToEnd(); HttpContext.Current.Items.Add("previewHtml", previewHtml); html = Umbraco.RenderTemplate(nodeId, previewTemplate.Id).ToHtmlString(); } } response.Content = new StringContent(html); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html"); return(response); }
/// <inheritdoc /> public override object Read(PropertyInfo propertyInfo, object value) { if (string.IsNullOrEmpty(value as string)) { return(null); } return(Umbraco.TypedMedia(value)); }
public ActionResult RedirectToCheckout(int id, string paymentId) { IPublishedContent content = Umbraco.Content(id); return(View(new RedirectToCheckoutModel(content) { PaymentId = paymentId })); }
public PageViewModel GetContent(IdModel data) { var id = data.id; var content = Umbraco.TypedContent(id); PageViewModel pvm = new PageViewModel(content); return(pvm); }
public PageViewModel GetMedia(IdModel data) { var id = data.id; var media = Umbraco.TypedMedia(id); PageViewModel pvm = new PageViewModel(media); return(pvm); }
public ActionResult HandleContactForm(ContactFormViewModel vm) { if (!ModelState.IsValid) { ModelState.AddModelError("Error", "Please check the form."); return(CurrentUmbracoPage()); } var siteSettings = Umbraco.ContentAtRoot().DescendantsOrSelfOfType("siteSettings").FirstOrDefault(); if (siteSettings != null) { var secretKey = siteSettings.Value <string>("recaptchaSecretKey"); //We might not have configure captcha so check if (!string.IsNullOrEmpty(secretKey) && !string.IsNullOrEmpty(Request.Form["GoogleCaptchaToken"])) { var isCaptchaValid = IsCaptchaValid(Request.Form["GoogleCaptchaToken"], secretKey); if (!isCaptchaValid) { ModelState.AddModelError("Captcha", "The captcha is not valid are you human?"); return(CurrentUmbracoPage()); } } } try { //Create a new contact form in umbraco //Get a handle to "Contact Forms" var contactForms = Umbraco.ContentAtRoot().DescendantsOrSelfOfType("contactForms").FirstOrDefault(); if (contactForms != null) { var newContact = Services.ContentService.Create("Contact", contactForms.Id, "contactForm"); newContact.SetValue("contactName", vm.Name); newContact.SetValue("contactEmail", vm.Email); newContact.SetValue("contactSubject", vm.Subject); newContact.SetValue("contactComments", vm.Comments); Services.ContentService.SaveAndPublish(newContact); } //Send out an email to site admin //SendContactFormReceivedEmail(vm); _emailService.SendContactNotificationToAdmin(vm); //Return confirmation message to user TempData["status"] = "OK"; return(RedirectToCurrentUmbracoPage()); } catch (Exception exc) { Logger.Error <ContactController>("There was an error in the contact form submission", exc.Message); ModelState.AddModelError("Error", "Sorry there was a problem noting your details. Would you please try again later?"); } return(CurrentUmbracoPage()); }
/// <summary> /// Parses the IContent to a IPublishedContent /// </summary> /// <param name="content">Content as IContent</param> /// <returns>IPublishedContent of the given IContent</returns> public IPublishedContent ToIPublishedContent(IContent content) { try { return(Umbraco.Content(content.Id)); } catch (Exception ex) { CustomLogHelper.logHelper.Log("Cannot convert to IPublishedContent the given " + content.Id + "Error message :" + ex.Message); return(null); } }
private string GetInternalLink(HomePageImages x) { if (x.InternalLink.GetValueOrDefault() > 0) { return(Umbraco.NiceUrl(x.InternalLink.GetValueOrDefault())); } return("#"); }
private static IEnumerable <T> GetRelatedContent <T>(string relationAlias, IEnumerable <IRelation> relations, Func <IRelation, int> selector) { return(Umbraco.TypedContent( relations .Where(r => r.RelationType.Alias.InvariantEquals(relationAlias)) .Select(selector) ) .OfType <T>()); }
public ActionResult Index(int year, int category, int page) { var home = Umbraco.TypedContentAtRoot().First(); var overview = home.FirstChild <NewsOverview>(); var items = new List <NewsItem>(); int totalPagesCount = 0; if (overview != null) { //Filter by year if (year == Consts.NewsConfig.YearAllInt) { items = overview.Children.SelectMany(i => i.Children <NewsItem>()).ToList(); } else { var newsByYear = overview.Children.FirstOrDefault(i => i.Name == year.ToString()); if (newsByYear != null) { items = newsByYear.Children <NewsItem>().ToList(); } } //Filter by category if (category == Consts.NewsConfig.NewsCategoryAnnounceInt) { items = items.Where(i => i.IsAnnounce).ToList(); } else if (category != Consts.NewsConfig.NewsCategoryAllInt) { var newsCategories = Utils.GetDataTypePreValues(NewsItem.GetModelPropertyType(i => i.Category).DataTypeId).ToList(); var categoryStr = newsCategories.First(i => i.Id == category).Value; items = items.Where(i => ((string)i.Category).Equals(categoryStr, StringComparison.InvariantCultureIgnoreCase)) .ToList(); } //Sort items items = SortNews(items); //Filter by page totalPagesCount = (int)Math.Ceiling(((double)items.Count / Consts.NewsConfig.NewsPerPage)); if (page != Consts.NewsConfig.PageAllInt) { items = items.Skip((page - 1) * Consts.NewsConfig.NewsPerPage).Take(Consts.NewsConfig.NewsPerPage).ToList(); } } var model = new NewsResult { Items = items, Page = page, TotalPages = totalPagesCount }; return(PartialView("NewsList", model)); }
protected override void OnInit(EventArgs e) { base.OnInit(e); var dataInstaller = new ArticulateDataInstaller(); var root = dataInstaller.Execute(); BlogUrl = Umbraco.TypedContent(root.Id).Url; }
public bool CreateNestedTestNodes(int quantityPerLevel, int numberOfLevels = 1) { var root = Umbraco.ContentAtRoot().First(); CreateTestNodeForEachParentLimitByLevel(quantityPerLevel, numberOfLevels, 1, new List <int> { root.Id }); return(true); }
private void ContentService_Creating(IContentService sender, Umbraco.Core.Events.NewEventArgs<IContent> e) { //Bruges til at udføre custom-handlinger når et dokument oprettes //Eksempel: sæt en default dato på egenskaben "contentDate" //if (e.Alias == "Kunde-Nyhed") //{ // e.Entity.SetValue("contentDate", DateTime.Now); //} }
public ActionResult RenderNavi() { //Get the homepage node var home = Umbraco.TypedContentAtRoot().SingleOrDefault(x => x.DocumentTypeAlias == "CWS-Home"); var pages = home.Children; //Return our collection of pages to the view return(PartialView("Navi", pages)); }
/// <summary> /// Handles the initialize event. /// </summary> /// <param name="e"> /// The <see cref="EventArgs"/>. /// </param> protected override void OnInit(EventArgs e) { base.OnInit(e); var dataInstaller = new BazaarDataInstaller(); var root = dataInstaller.Execute(); StoreUrl = Umbraco.TypedContent(root.Id).Url; }
//public string PublishVersion(Guid version) /////umbraco/api/DocumentationHistory/GetPublishVersion/?version= param guid verison public string GetPublishVersion(Guid version) { var content = Services.ContentService.GetByVersion(version); Services.ContentService.Publish(content); var newUrl = Umbraco.Url(content.Id); return(newUrl); }
public ActionResult ContactForm() { // In case you need it... var currentNode = Umbraco.TypedContent(UmbracoContext.PageId.GetValueOrDefault()); var model = new ContactViewModel(); return(PartialView("_ContactForm", model)); }
public override ActionResult Index(Umbraco.Web.Models.RenderModel model) { var image = _imageRepository.GetCurrentAndNextImage(); var homePageModel = new ImagePageModel(); homePageModel.CurrentImage = image.Item1; homePageModel.NextImage = image.Item2; ViewBag.ImageWidth = homePageModel.CurrentImage.Width; return View(@"~\Views\Home.cshtml", homePageModel); }
private int GetMaxPersons(string apartmentName) { var apartment = Umbraco.TypedContentAtRoot() .First(c => c.DocumentTypeAlias == "StronaGlowna").Children .First(c => c.DocumentTypeAlias == "Apartamenty") .Children.First(a => a.Name == apartmentName); return(apartment.GetPropertyValue <int>("maxIloscOsob")); }
private void DataTypeService_Saved(Umbraco.Core.Services.IDataTypeService sender, Umbraco.Core.Events.SaveEventArgs<IDataTypeDefinition> e) { var types = CodeFirstManager.Current.Modules.DataTypeModule.DataTypeRegister.GetTypesByDataTypeDefinitionIds(e.SavedEntities.Select(x => x.Id)); foreach (var type in types) { List<PreValue> val; _cache.TryRemove(type, out val); //invalidate any prevalue cache so prevalues are refreshed when next needed } }
/// <summary> /// get the TwitterOAuthData for the authenticated account /// </summary> /// <param name="contentId"></param> /// <returns></returns> private TwitterOAuthData getTwitterAccount(int contentId) { var contentPage = Umbraco.TypedContent(contentId); var homePage = contentPage != null?contentPage.AncestorOrSelf(1) : default(IPublishedContent); var twitterAccount = homePage != null && homePage.HasProperty("authenticatedTwitterAccount") && homePage.HasValue("authenticatedTwitterAccount") ? homePage.GetPropertyValue <TwitterOAuthData>("authenticatedTwitterAccount") : default(TwitterOAuthData); return(twitterAccount); }
public IHttpActionResult HasAccessPost() { var payload = new PayloadResult(); if (userService.IsAuthenticated()) { ContextService.UserHelper.LoginAsMember(); payload.SetMessageType(GenericMessages.Success); } //else if (CurrentPage.DocumentTypeAlias.Equals(nameof(LoginPageModel))) //{ // payload.SetMessageType(GenericMessages.Success); //} else if (Umbraco.IsProtected(CurrentPage.Path)) { // Do we have a logged in member ? if (Umbraco.MemberIsLoggedOn() == false) { payload.SetMessageType(GenericMessages.Danger); payload.SetMessage(Umbraco.GetDictionaryValue("Members.LoginExpired", "Members.LoginExpired")); payload.SetOrUpdate(nameof(PayloadFields.Status), MemberStatus.LoginExpired); return(Error(payload)); } // Do we have access to the current page ? if (Umbraco.MemberHasAccess(CurrentPage.Path) == false) { // If we get here the member has no access to this page, redirect them to there start page. payload.SetMessageType(GenericMessages.Danger); RedirectCurrentMemberToStartPage(ref payload); payload.SetOrUpdate(nameof(PayloadFields.Status), MemberStatus.AuthorizationFailure); } else { // Check if the backoffice user is signed out while the admin member is logged in. var member = (MemberPublishedContent)Umbraco.MembershipHelper.GetCurrentMember(); if (member.DocumentTypeAlias.Equals(nameof(AdminMember)) && userService.ValidateUser(member.Email)) { var user = Services.UserService.GetByEmail(member.Email); // This is a backoffice member lets log them in. UmbracoContext.Security.PerformLogin(user.Id); payload.SetOrUpdate(nameof(PayloadFields.Status), MemberStatus.AdminLoggedIn); } payload.SetMessageType(GenericMessages.Success); } } else { payload.SetMessageType(GenericMessages.Success); } return(Json(payload)); }
public ActionResult Index(int id) { //TODO: Seems hanslemans is slightly wrong compared to the other ones found on the interwebs //<opensearchdescription xmlns="http://a9.com/-/spec/opensearch/1.1/"> // <shortname>Hanselman Search</shortname> // <description>Search Scott Hanselman's Blog</description> // <url type="text/html" method="get" template="http://www.hanselman.com/blog?q={searchTerms}"> // <img width="16" height="16">http://www.hanselman.com/blog/favicon.ico // <inputencoding>UTF-8</inputencoding> // <searchform>http://www.hanselman.com/</searchform> //</url></opensearchdescription> //<?xml version="1.0" encoding="UTF-8" ?> //<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/"> // <ShortName>CodeClimber</ShortName> // <Description>Search CodeClimber</Description> // <InputEncoding>UTF-8</InputEncoding> // <Image width="16" height="16" type="image/x-icon">http://codeclimber.net.nz/App_Plugins/Articulate/Themes/PhantomV2/assets/img/favicon.ico</Image> // <Url type="text/html" method="get" template="http://codeclimber.net.com/search?term={searchTerms}"></Url> //</OpenSearchDescription> //<?xml version="1.0" encoding="UTF-8"?> //<OpenSearchDescription xmlns:moz="http://www.mozilla.org/2006/browser/search/" // xmlns="http://a9.com/-/spec/opensearch/1.1/"> // <ShortName>aaron.pk</ShortName> // <Description>Search aaron.pk</Description> // <InputEncoding>UTF-8</InputEncoding> // <Url method="get" type="text/html" // template="http://aaron.pk/search?q={searchTerms}"/> //</OpenSearchDescription> var node = Umbraco.TypedContent(id); if (node == null) { return(new HttpNotFoundResult()); } var model = new MasterModel(node); var searchTemplateUrl = Url.ArticulateSearchUrl(model, includeDomain: true) + "?term={searchTerms}"; XNamespace ns = "http://a9.com/-/spec/opensearch/1.1/"; var rsd = new XElement(ns + "OpenSearchDescription", new XElement(ns + "ShortName", model.PageTitle), new XElement(ns + "Description", model.PageDescription), new XElement(ns + "InputEncoding", "UTF-8"), new XElement(ns + "Url", new XAttribute("type", "text/html"), new XAttribute("method", "get"), new XAttribute("template", searchTemplateUrl))); return(new XmlResult(new XDocument(rsd))); }
void ContentService_Published(Umbraco.Core.Publishing.IPublishingStrategy sender, Umbraco.Core.Events.PublishEventArgs<IContent> e) { foreach (var item in e.PublishedEntities.Where(x => x.ContentType.Alias == "Project")) { if (item.GetValue<bool>("projectLive")) { UpdateProjectExamineIndex(item); } } }
public NewsController() { this.homePage = (Home)Umbraco.Content(1104); this.articles = new List <Article>(); foreach (var article in this.homePage.Articles) { articles.Add(new Article(article.Headline, article.Preamble, ("https://localhost:44359" + article.ArticleImage.Url.ToString()), article.DateCreated, article.DatePublished, Decimal.ToInt32(article.PoliticalSpectrum))); } }
public override System.Web.Mvc.ActionResult Index(Umbraco.Web.Models.RenderModel model) { MembersWallModel membersWall = new MembersWallModel(); if (User.Identity.IsAuthenticated) { //lets get the user id either from the query or the current user int userIdToView; int userCurrentUser = _myHelper.getBrowsingUserId(); if (!Int32.TryParse(Request.Params.Get("id"), out userIdToView) || userIdToView == 0) { userIdToView = userCurrentUser; } //store the user we are going to use var user = _memberService.GetById(userIdToView); //flag it if the browsing user is looking at his own profile if (userCurrentUser == userIdToView) { membersWall.isThisHisOwnWall = true; } //store the basic info membersWall.owner = user; //lets add the profile image to the user //first we need the relation type IRelationType relationTypeToFetch = _relationService.GetRelationTypeByAlias("memberToProfileImage"); //lets try to find a relationship between the member and some profile picture var memberToProfileImageRelation = _relationService.GetAllRelationsByRelationType(relationTypeToFetch.Id).Where(x => x.ParentId == membersWall.owner.Id); //get all the pictures var profileImageToUseRelation = memberToProfileImageRelation.Select(x => Umbraco.TypedMedia(x.ChildId)); //select the newest picture and get the url for it var profileImageToUseMedia = profileImageToUseRelation.OrderByDescending(x => x.CreateDate); if (profileImageToUseMedia.Count() > 0) { if (profileImageToUseMedia.First() != null) { membersWall.profileImage = profileImageToUseMedia.First().Url; } } } else { return PartialView("MemberLogin"); } return CurrentTemplate(membersWall); }
internal Property(Umbraco.Core.Models.Property property) { _id = property.Id; _property = property; _propertyType = property.PropertyType; //Just to ensure that there is a PropertyType available _pt = PropertyType.GetPropertyType(property.PropertyTypeId); _data = _pt.DataTypeDefinition.DataType.Data; _data.PropertyId = Id; }
void FormStorage_Deleted(object sender, Umbraco.Forms.Core.FormEventArgs e) { // If this Form was stored in a Folder, remove it. var form = e.Form; var folder = PerplexFolder.Get(f => f.Forms.Any(fid => fid == form.Id.ToString())); if (folder != null) { folder.Forms.Remove(form.Id.ToString()); PerplexFolder.SaveAll(); } }
void ContentService_Deleted(IContentService sender, Umbraco.Core.Events.DeleteEventArgs<Umbraco.Core.Models.IContent> e) { var fs = new ForumService(ApplicationContext.Current.DatabaseContext); foreach (var ent in e.DeletedEntities.Where(x => x.ContentType.Alias == "Forum")) { var f = fs.GetById(ent.Id); if (f != null) fs.Delete(f); } }
public static void FileService_SavedScript(Umbraco.Core.Services.IFileService sender, Umbraco.Core.Events.SaveEventArgs<Umbraco.Core.Models.Script> e) { // save triggered - need to work out for what foreach (var thing in e.SavedEntities) { string path = string.Format("~/usync6/{0}/{1}", thing.GetRealType().ToString(), thing.Name ) ; string realpath = Umbraco.Core.IO.IOHelper.MapPath(path); if (!Directory.Exists(realpath)) Directory.CreateDirectory(realpath); } }
public void ContentService_Published(Umbraco.Core.Publishing.IPublishingStrategy sender, Umbraco.Core.Events.PublishEventArgs<Umbraco.Core.Models.IContent> e) { foreach (var node in e.PublishedEntities) { if (node.ContentType.Alias.Equals("Box")) { // Ugh, restart the application to make the route table update, there must be a better way and this won't work in LB environment var webConfigPath = HttpContext.Current.Request.PhysicalApplicationPath + "\\\\Web.config"; System.IO.File.SetLastWriteTimeUtc(webConfigPath, DateTime.UtcNow); } } }
public static void RewriteUrl(Umbraco.Core.Models.IContent entity, IContentService contentService) { switch (entity.ContentType.Alias) { case "People": RewritePeople(entity, contentService); break; case "Person": RewritePerson(entity, contentService); break; } }
private void CacheAfterUnPublishNode(Umbraco.Core.Publishing.IPublishingStrategy sender, Umbraco.Core.Events.PublishEventArgs<IContent> e) { var motos = e.AsEnumerableOfOne(); foreach(var moto in motos) { if(moto.PublishedEntities.Any(z => z.Ancestors().Any(node => node.ContentType.Alias == "Catalog"))) { HttpContext.Current.Cache.Remove("Models"); HttpContext.Current.Cache.Remove("Motos"); continue; } } }
private void DocumentAfterSaving(IContentService sender, Umbraco.Core.Events.SaveEventArgs<Umbraco.Core.Models.IContent> e) { foreach (var item in e.SavedEntities) { if (item.ContentType.Alias == "Bike" && String.IsNullOrWhiteSpace(item.Properties["utpText"].Value.ToString())) { var umbracoHelper = Moto.UmbracoHelper; var settingsNode = umbracoHelper.TypedContentSingleAtXPath("/root/sysSiteSettings"); var contentForUtp = settingsNode.GetPropertyValue<string>("contentForUtp"); item.SetValue("utpText", contentForUtp); } } }
public ITextSource GetSource(Umbraco.Foundation.Localization.TextManager textManager, Assembly referenceAssembly, string targetNamespace) { var source = new SimpleTextSource(); source.Texts.Add(new LocalizedText { Namespace = targetNamespace, Key = "FactoryTest", Pattern = "I'm from a factory", Language = "en-US", Source = new TextSourceInfo { TextSource = source, ReferenceAssembly = referenceAssembly } }); return source; }
void ContentService_Created(IContentService sender, Umbraco.Core.Events.NewEventArgs<Umbraco.Core.Models.IContent> e) { if (e.Entity.ContentType.Alias == "BlogPost") { //Set the current date to the "Entry Date" field for Posts if (e.Entity.HasProperty("entryDate")) { e.Entity.SetValue("entryDate", DateTime.Now); } } else if (e.Entity.ContentType.Alias == "BlogListing") { //Set the current date to the "Entry Date" field for Posts if (e.Entity.HasProperty("postsPerPage")) { e.Entity.SetValue("postsPerPage", 10); } } }
void FormStorage_Created(object sender, Umbraco.Forms.Core.FormEventArgs e) { var form = e.Form; // Was this form created in a folder? var sessionId = UmbracoContext.Current.Security.GetSessionId(); var folderId = HttpContext.Current.Cache[sessionId + "_folderId"]; if (folderId == null) return; var folder = PerplexFolder.Get(folderId.ToString()); if (folder == null) return; folder.Forms.Add(form.Id.ToString()); PerplexFolder.SaveAll(); }
private void ContentService_Saved(IContentService sender, Umbraco.Core.Events.SaveEventArgs<IContent> e) { foreach (var content in e.SavedEntities) { if (content.ContentType.Alias.Equals("SOSU-Uddannelse")) { //Tjek om siden har en node af typen "SOSU-Kontainer-Uddannelse-Mediekarussel" i forvejen //if (!content.Children().Any(x => x.ContentType.Alias.Equals("SOSU-Kontainer-Uddannelse-Mediekarussel"))) //{ // var mediaContainer = sender.CreateContent("Mediekarussel", content, "SOSU-Kontainer-Uddannelse-Mediekarussel"); // sender.SaveAndPublish(mediaContainer); //} } } }
/// <summary> /// Sets the property. /// </summary> /// <param name="property">The property.</param> /// <param name="value">The value.</param> /// <param name="config">The config.</param> /// <param name="context">The context.</param> public override void SetProperty(Umbraco.Core.Models.Property property, object value, UmbracoPropertyConfiguration config, UmbracoDataMappingContext context) { throw new NotImplementedException(); /* Image img = value as Image; var item = field.Item; if (field == null) return; ImageField scImg = new ImageField(field); if (img == null) { scImg.Clear(); return; } if (scImg.MediaID.Guid != img.MediaId) { //this only handles empty guids, but do we need to remove the link before adding a new one? if (img.MediaId == Guid.Empty) { ItemLink link = new ItemLink(item.Database.Name, item.ID, scImg.InnerField.ID, scImg.MediaItem.Database.Name, scImg.MediaID, scImg.MediaItem.Paths.Path); scImg.RemoveLink(link); } else { ID newId = new ID(img.MediaId); Item target = item.Database.GetItem(newId); if (target != null) { scImg.MediaID = newId; ItemLink link = new ItemLink(item.Database.Name, item.ID, scImg.InnerField.ID, target.Database.Name, target.ID, target.Paths.FullPath); scImg.UpdateLink(link); } else throw new MapperException("No item with ID {0}. Can not update Media Item field".Formatted(newId)); } } scImg.Height = img.Height.ToString(); scImg.Width = img.Width.ToString(); scImg.HSpace = img.HSpace.ToString(); scImg.VSpace = img.VSpace.ToString(); scImg.Alt = img.Alt; scImg.Border = img.Border; scImg.Class = img.Class;*/ }
private void ContentService_Saved(IContentService sender, Umbraco.Core.Events.SaveEventArgs<IContent> e) { //Bruges til at udføre custom-handlinger når et dokument er gemt //Eksempel: Opretter en side under siden, hvis der ikke findes en af samme dokumentType i forvejen //foreach (var content in e.SavedEntities) //{ // if (content.ContentType.Alias.Equals("SOSU-Uddannelse")) // { // //Tjek om siden har en node af typen "SOSU-Kontainer-Uddannelse-Mediekarussel" i forvejen // if (!content.Children().Any(x => x.ContentType.Alias.Equals("SOSU-Kontainer-Uddannelse-Mediekarussel"))) // { // var mediaContainer = sender.CreateContent("Mediekarussel", content, "SOSU-Kontainer-Uddannelse-Mediekarussel"); // sender.SaveAndPublish(mediaContainer); // } // } //} }
internal Property(Umbraco.Core.Models.Property property) { _id = property.Id; _property = property; _propertyType = property.PropertyType; //Just to ensure that there is a PropertyType available _pt = PropertyType.GetPropertyType(property.PropertyTypeId); _data = _pt.DataTypeDefinition.DataType.Data; _data.PropertyId = Id; //set the value so it doesn't need to go to the database var dvs = _data as IDataValueSetter; if (dvs != null) { dvs.SetValue(property.Value, property.PropertyType.DataTypeDatabaseType.ToString()); } }
public override void InitializeAtStartup( Umbraco.Core.UmbracoApplicationBase umbracoApplication, Umbraco.Core.ApplicationContext applicationContext, out Func<IServiceLocator> locator, out System.Web.Mvc.IDependencyResolver resolver) { var builder = new ContainerBuilder(); builder.RegisterControllers(typeof(Macaw.Umbraco.Foundation.Controllers.DynamicBaseController).Assembly); builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly()); builder.Register(s => new SiteRepository( applicationContext.Services.ContentService, new UmbracoHelper(UmbracoContext.Current))) .As<ISiteRepository>() .InstancePerHttpRequest(); var container = builder.Build(); resolver = new Autofac.Integration.Mvc.AutofacDependencyResolver(container); locator = () => new AutofacServiceLocator(); }
public override void InitializeAtStartup( Umbraco.Core.UmbracoApplicationBase umbracoApplication, Umbraco.Core.ApplicationContext applicationContext, out Func<IServiceLocator> locator, out System.Web.Mvc.IDependencyResolver resolver) { //todo: http://our.umbraco.org/forum/getting-started/installing-umbraco/46674-U701-build-200-Failed-to-retrieve-data-for-application-tree-content var builder = new ContainerBuilder(); builder.RegisterApiControllers(typeof(UmbracoApiController).Assembly); builder.RegisterControllers(typeof(Macaw.Umbraco.Foundation.Controllers.DynamicBaseController).Assembly); builder.RegisterControllers(System.Reflection.Assembly.GetExecutingAssembly()); builder.Register(s => new SiteRepository( applicationContext.Services.ContentService, new UmbracoHelper(UmbracoContext.Current))) .As<ISiteRepository>() .InstancePerHttpRequest(); var container = builder.Build(); resolver = new Autofac.Integration.Mvc.AutofacDependencyResolver(container); locator = () => new AutofacServiceLocator(); }