// POST umbraco/api/umbcontact/post public HttpResponseMessage Post([FromBody]UmbContactMail message) { // Return errors if the model validation fails // The model defines validations for empty or invalid email addresses // See the UmbContactMail class below if (ModelState.IsValid == false) return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState.First().Value.Errors.First().ErrorMessage); // In order to allow editors to configure the email address where contact // mails will be sent, we require that to be set in a property with the // alias umbEmailTo - This property needs to be sent into this API call var umbraco = new UmbracoHelper(UmbracoContext); var content = umbraco.TypedContent(message.SettingsNodeId); if (content == null) return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Please provide a valid node Id on which the umbEmailTo property is defined."); var mailTo = content.GetPropertyValue<string>("umbEmailTo"); if (string.IsNullOrWhiteSpace(mailTo)) return Request.CreateErrorResponse(HttpStatusCode.BadRequest, string.Format("The umbEmailTo property on node {0} (Id {1}) does not exists or has not been filled in.", content.Name, content.Id)); // If we have a valid email address to send the email to, we can try to // send it. If the is an error, it's most likely caused by a wrong SMTP configuration return TrySendMail(message, mailTo) ? new HttpResponseMessage(HttpStatusCode.OK) : Request.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, "Could not send email. Make sure the server settings in the mailSettings section of the Web.config file are configured correctly. For a detailed error, check ~/App_Data/Logs/UmbracoTraceLog.txt."); }
public List<CommentViewModel> GetListOfCommentsForPage() { UmbracoHelper helper = new UmbracoHelper(this.UmbracoContext); // IPublishedContent content = helper.TypedContent(PageId); IPublishedContent content = helper.TypedContentAtRoot().FirstOrDefault(); List<CommentViewModel> ListOfComments = new List<CommentViewModel>(); var ListOfCommentsContent = content.DescendantsOrSelf("Comment"); foreach (var item in ListOfCommentsContent) { if (item.ContentType.Alias == "Comment") { ListOfComments.Add(new CommentViewModel { Name = item.GetPropertyValue("name").ToString(), Email = item.GetPropertyValue("email").ToString(), Comment = item.GetPropertyValue("comment").ToString(), DateAndTime = item.GetPropertyValue("dateAndTime").ToString() }); } } return ListOfComments; }
public static IList<MenuItem> CreateMainNav(this IPublishedContent currentContent) { var items = new List<MenuItem>(); var homeNode = currentContent.AncestorOrSelf(1); var umbracoConextProvider = DependencyResolver.Current.GetService<IUmbracoConextProvider>(); var umbracoHelper = new UmbracoHelper(umbracoConextProvider.GetUmbracoContext()); //Home Page //items.Add(new MenuItem //{ // Id = homeNode.Id, // IsActive = homeNode.Id == currentContent.Id, // Name = homeNode.Name, // NodeTypeAlias = homeNode.DocumentTypeAlias, // Url = homeNode.Url, // SortOrder = homeNode.SortOrder, // Content=homeNode, // IsVisible = homeNode.IsVisible() //}); items.AddRange(GetMenuItmes(homeNode, currentContent, 2, umbracoHelper)); return items; }
protected UmbracoApiController(UmbracoContext umbracoContext) { if (umbracoContext == null) throw new ArgumentNullException("umbracoContext"); UmbracoContext = umbracoContext; InstanceId = Guid.NewGuid(); Umbraco = new UmbracoHelper(umbracoContext); }
/// <summary> /// The crawl. /// </summary> /// <param name="site"> /// The site. /// </param> /// <param name="doc"> /// The doc. /// </param> public void Crawl(UmbracoContext site, XmlDocument doc) { /* * We're going to crawl the site layer-by-layer which will put the upper levels * of the site nearer the top of the sitemap.xml document as opposed to crawling * the tree by parent/child relationships, which will go deep on each branch before * crawling the entire site. */ var helper = new UmbracoHelper(UmbracoContext.Current); var siteRoot = helper.TypedContentAtRoot().First(); var node = SitemapGenerator.CreateNode(siteRoot, site); if (node.IsPage && node.IsListedInNavigation && node.ShouldIndex) { SitemapGenerator.AppendUrlElement(doc, node); } var items = siteRoot.Descendants(); if (items != null) { foreach (var item in items) { node = SitemapGenerator.CreateNode(item, site); if (node.IsPage && node.IsListedInNavigation && node.ShouldIndex) { SitemapGenerator.AppendUrlElement(doc, node); } } } }
protected override void Configure() { Mapper.CreateMap<IPublishedContent, ContentInteractiveImageModel>() .ForMember(model => model.ExplanationsText, expression => expression.ResolveUsing(node => node.GetPropertyValue<string>("explanationsText"))) .ForMember(model => model.FooterText, expression => expression.ResolveUsing(node => node.GetPropertyValue<string>("bodyText"))) .ForMember(model => model.Image, expression => expression.ResolveUsing(node => { var helper = new UmbracoHelper(UmbracoContext.Current); var imageMedia = helper.TypedMedia(node.GetPropertyValue<int>("image")); if (imageMedia == null) return string.Empty; return imageMedia.Url; })) .ForMember(model => model.Items, expression => expression.ResolveUsing(node => { var items = new List<ContentInteractiveImageItemModel>(); foreach (var childNode in node.Children.Where(content => content.DocumentTypeAlias.Equals("InteractiveImagePopUp", StringComparison.OrdinalIgnoreCase))) { items.Add(new ContentInteractiveImageItemModel { BodyText = childNode.GetPropertyValue<string>("bodyText"), Title = childNode.GetPropertyValue<string>("title"), BottomRightY = childNode.GetPropertyValue<int>("bottomRightY"), BottomRightX = childNode.GetPropertyValue<int>("bottomRightX"), TopLeftX = childNode.GetPropertyValue<int>("topLeftX"), TopLeftY = childNode.GetPropertyValue<int>("topLeftY") }); } return items; })); }
public IPublishedContent Company() { var memberCompany = GetMember(); var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); // DKO: získá napojení na stránku firmy z nastavení uživatele v členské sekci return umbracoHelper.Content(memberCompany.Properties["CompanyPage"].Value); }
private List<BannerItem> UmbracoEvents() { var helper = new UmbracoHelper(UmbracoContext.Current); List<BannerItem> ue = new List<BannerItem>(); IPublishedContent root = helper.Content(1068); IPublishedContent eventRoot = helper.Content(Convert.ToInt32(root.GetProperty("seminars").Value)); foreach (var itm in eventRoot.Children.Where("Visible").Where("end >= DateTime.Now.Date").OrderBy("start")) { string input = itm.GetProperty("end").Value.ToString(); DateTime dateTime; if (DateTime.TryParse(input, out dateTime)) { if (dateTime > DateTime.Now) { var bi = new BannerItem(); bi.title = itm.HasValue("subHeader") ? itm.GetProperty("subHeader").Value.ToString() : itm.Name; if (itm.HasValue("country")) bi.Country = itm.GetProperty("country").ToString(); bi.link = new entryLink { href = itm.Url, target = "_self" }; bi.published = bi.StartDateTime = "Seminar starts "+itm.GetProperty("start").Value.ToString().ToDate().ToShortDateString(); bi.updated = itm.UpdateDate.ToShortDateString(); bi.TypeOfContent = Enum.GetName(typeof(TypeOfContent),TypeOfContent.UmbracoEvent); ue.Add(bi); } } } return ue; }
public static string GetImageUrl(this UmbracoContext context, IPublishedContent node, string propertyName) { var helper = new UmbracoHelper(context); var imageId = node.GetPropertyValue<int>(propertyName); var typedMedia = helper.TypedMedia(imageId); return typedMedia != null ? typedMedia.Url : null; }
public IEnumerable<string> GetAllUrlsForWildCardUrls(IEnumerable<string> wildCardUrls, UmbracoHelper uh) { List<string> resolvedUrls = new List<string>(); if (wildCardUrls == null || !wildCardUrls.Any()) { return resolvedUrls; } IEnumerable<string> allContentUrls = GetAllContentUrls(uh); foreach(string wildCardUrl in wildCardUrls) { if(!wildCardUrl.Contains('*')) { //it doesnt even contain a wildcard. continue; } //Make one for modifing string mutableWildCardUrl = wildCardUrl; //take off the trailing slash if there is one mutableWildCardUrl = mutableWildCardUrl.TrimEnd('/'); //take off the * mutableWildCardUrl = mutableWildCardUrl.TrimEnd('*'); //We can get wild cards by seeing if any of the urls start with the mutable wild card url resolvedUrls.AddRange(allContentUrls.Where(x => x.StartsWith(mutableWildCardUrl))); } return resolvedUrls; }
/// <summary> /// Возвращает дерево узлов для вывода человеческой карты сайта. /// Каждый объект в коллекции представляет собой дублет, где /// Item1 — узел документа (IPublishedContent), /// Item2 — поддерево аналогичной структуры (пустое для листьев). /// </summary> /// <returns></returns> public static Tuple<IPublishedContent, dynamic> GetSiteMap() { var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var mainPage = umbracoHelper.TypedContentSingleAtXPath("/root/pubMainPage"); if (mainPage == null) throw new Exception("Не найдена главная страница сайта."); return Tuple.Create<IPublishedContent, dynamic>(mainPage, GetBranch(mainPage)); }
public static HtmlString RenderDocTypeGridEditorItem(this HtmlHelper helper, IPublishedContent content, string viewPath = "", string actionName = "", object model = null) { if (content == null) return new HtmlString(string.Empty); var controllerName = content.DocumentTypeAlias + "Surface"; if (!string.IsNullOrWhiteSpace(viewPath)) viewPath = viewPath.TrimEnd('/') + "/"; if (string.IsNullOrWhiteSpace(actionName)) actionName = content.DocumentTypeAlias; var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); if (umbracoHelper.SurfaceControllerExists(controllerName, actionName, true)) { return helper.Action(actionName, controllerName, new { dtgeModel = model ?? content, dtgeViewPath = viewPath }); } if (!string.IsNullOrWhiteSpace(viewPath)) return helper.Partial(viewPath + content.DocumentTypeAlias + ".cshtml", content); return helper.Partial(content.DocumentTypeAlias, content); }
/// <summary> /// Gets images url list. /// /// Gets crops if cropname specified /// </summary> /// <param name="post"></param> /// <param name="cropName"></param> /// <returns></returns> public static IEnumerable<String> GetImagesUrl(IPublishedContent post, String cropName = "", String fieldAlias = "images") { List<string> result = new List<string>(); var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); try { var pictureIDsVal = post.GetPropertyValue<String>(fieldAlias); if (!String.IsNullOrEmpty(pictureIDsVal)) { var pictureIDs = pictureIDsVal.Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries); foreach (var pictureIDstr in pictureIDs) { if (!String.IsNullOrEmpty(pictureIDstr)) { int id = Int32.Parse(pictureIDstr); var url = GetImageUrl(id, cropName); result.Add(url); } } } } catch (Exception e) { if (UmbracoContext.Current.IsDebug) { //throw e; } } return result; }
// private readonly IMemberService _memberService; public VideoService(IContentService content) { _content = content; _context = new UmbracoContextProvider(); //var umbracoConextProvider = DependencyResolver.Current.GetService<IUmbracoConextProvider>(); _umbracoHelper = new UmbracoHelper(UmbracoContext.Current); }
/// /// Utility extension to map a to a BasketViewLine item. /// Notice that the ContentId is pulled from the extended data. The name can either /// be the Merchello product name via lineItem.Name or the Umbraco content page /// name with umbracoHelper.Content(contentId).Name /// /// ///The to be mapped /// private static BasketViewLineItem ToBasketViewLineItem(this ILineItem lineItem) { var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var contentId = lineItem.ExtendedData.ContainsKey("umbracoContentId") ? int.Parse(lineItem.ExtendedData["umbracoContentId"]) : 0; var umbracoName = umbracoHelper.Content(contentId).Name; var merchelloProductName = lineItem.Name; return new BasketViewLineItem() { Key = lineItem.ExtendedData.GetProductKey(),// lineItem.Key, ContentId = contentId, ExtendedData = DictionaryToString(lineItem.ExtendedData), Name = merchelloProductName, //Name = umbracoName, Sku = lineItem.Sku, UnitPrice = lineItem.Price, TotalPrice = lineItem.TotalPrice, Quantity = lineItem.Quantity, Images = lineItem.ExtendedData.GetValue("images") }; }
/// <summary> /// The get store root. /// </summary> /// <returns> /// The <see cref="IPublishedContent"/>. /// </returns> public static IPublishedContent GetStoreRoot() { if (StoreRoot != null) return StoreRoot; var umbraco = new UmbracoHelper(UmbracoContext.Current); StoreRoot = umbraco.TypedContentSingleAtXPath(WebConfigurationManager.AppSettings["Bazaar:XpathToStore"]); return StoreRoot; }
public bool Init(int CurrentNodeId, string PropertyData, out object instance) { //we're going to send the string through the macro parser and create the output string. if (UmbracoContext.Current != null) { var sb = new StringBuilder(); var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); MacroTagParser.ParseMacros( PropertyData, //callback for when text block is found textBlock => sb.Append(textBlock), //callback for when macro syntax is found (macroAlias, macroAttributes) => sb.Append(umbracoHelper.RenderMacro( macroAlias, //needs to be explicitly casted to Dictionary<string, object> macroAttributes.ConvertTo(x => (string)x, x => (object)x)).ToString())); instance = new HtmlString(sb.ToString()); } else { //we have no umbraco context, so best we can do is convert to html string instance = new HtmlString(PropertyData); } return true; }
public XmlRssHandler() { umbContext = UmbracoContext.Current; appContext = ApplicationContext.Current; services = appContext.Services; helper = new UmbracoHelper( umbContext ); }
private void UpdateProjectExamineIndex(IEntity item) { var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var content = umbracoHelper.TypedContent(item.Id); var downloads = Utils.GetProjectTotalDownloadCount(content.Id); UpdateProjectExamineIndex(content, downloads); }
protected override ApiController CreateController(Type controllerType, HttpRequestMessage msg, UmbracoHelper helper, ITypedPublishedContentQuery qry, ServiceContext serviceContext, BaseSearchProvider searchProvider) { _onServicesCreated(msg, helper.UmbracoContext, qry, serviceContext, searchProvider); //Create the controller with all dependencies var ctor = controllerType.GetConstructor(new[] { typeof(UmbracoContext), typeof(UmbracoHelper), typeof(BaseSearchProvider) }); if (ctor == null) { throw new MethodAccessException("Could not find the required constructor for the controller"); } var created = (ApiController)ctor.Invoke(new object[] { //ctor args helper.UmbracoContext, helper, searchProvider }); return created; }
public void Run() { Initialise("TypeSet3"); ts.MasterRenamed mas = new ts.MasterRenamed() { MasterTab = new ts.MasterTab() { MasterDatePickerTab = new DataTypes.BuiltIn.DatePicker() { Value = DateTime.Parse("2015-09-21 16:54:23.000") }, MasterRichtextEditorTab = new DataTypes.BuiltIn.RichtextEditor() { Value = "<p>this is <strong>STRONG</strong></p>" }, MasterTextstringTab = new DataTypes.BuiltIn.Textstring() { Value = "TEXTSTRINGS" } }, MasterTextstringRenamedRoot = new DataTypes.BuiltIn.Textstring() { Value = "OTHERONES!!" }, MasterTrueFalseRoot = new DataTypes.BuiltIn.TrueFalse() { Value = true } }; mas.NodeDetails.Name = "Master Test"; mas.Persist(publish: true); for (int i = 0; i < 20; i++) { ts.Child2 ch2 = GetChild(); ch2.NodeDetails.Name = Guid.NewGuid().ToString(); ch2.Persist(mas.NodeDetails.UmbracoId, publish: true); } umbraco.library.RefreshContent(); var pubmas = new UmbracoHelper(UmbracoContext.Current).TypedContent(mas.NodeDetails.UmbracoId); var kids = pubmas.ChildrenOfType<ts.Child2>().ToList(); var trd = kids.First().Composition.CompositionNumericRoot; }
public IEnumerable<ICategory> GetAllCategories() { var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var content = umbracoHelper.TypedContent(int.Parse(ConfigurationManager.AppSettings["deliProjectRoot"])); var contents = content.Descendants().Where(x => x.DocumentTypeAlias == "ProjectGroup"); return contents.ToICategoryList(); }
public void can_retrieve_content_via_UmbracoHelper() { var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var content = umbracoHelper.TypedContentAtRoot(); Assert.NotEmpty(content); var home = content.FirstOrDefault(x => x.ContentType.Alias == "HomePage"); Assert.NotNull(home); }
public ActionResult Index() { var help = new UmbracoHelper(UmbracoContext.Current); var url =Request.Url.AbsolutePath.Replace("sitemap.xml", ""); var model = uQuery.GetNodeByUrl(url); return View("~/Views/Sitemap.cshtml", help.TypedContent(model.Id)); }
public string GetOfficeAddress(string cityName) { UmbracoHelper helper = new UmbracoHelper(UmbracoContext.Current); string result = string.Empty; try{ result = helper.TypedContentSingleAtXPath("/root/sysDataDocType/cities/city[@nodeName='" + cityName + "']").GetPropertyValue<string>("offices"); }catch (Exception ) { } return result; }
///umbraco/Api/news/getnews?id=1054 public NewsItem GetNews(int id) { UmbracoHelper help = new UmbracoHelper(UmbracoContext); var content = help.TypedContent(id); return new NewsItem { Name = content.Name, Id = content.Id }; }
public BaseConverter() { var Context = UmbracoContext.Current; Helper = new UmbracoHelper(Context); //todo: use dependency injection.. Initialize(new Macaw.Umbraco.Foundation.Infrastructure.SiteRepository( ApplicationContext.Current.Services.ContentService, Helper)); }
public SiteNavigation() { UmbracoHelper umbracoHelper = new UmbracoHelper(UmbracoContext.Current); _publishedContent = umbracoHelper.TypedContentAtRoot().FirstOrDefault(); // Check Current Page Id, if null (non umbraco page) default current page to root nome page. _currentPage = UmbracoContext.Current.PageId != null ? umbracoHelper.AssignedContentItem : _publishedContent; PopulateTopNavigation(); }
/// <summary> /// Initializes a new instance of the <see cref="BasketLineItemFactory"/> class. /// </summary> /// <param name="umbraco"> /// The umbraco. /// </param> /// <param name="currentCustomer"> /// The current Customer. /// </param> /// <param name="currency"> /// The currency. /// </param> public BasketLineItemFactory(UmbracoHelper umbraco, ICustomerBase currentCustomer, ICurrency currency) { Mandate.ParameterNotNull(umbraco, "umbraco"); Mandate.ParameterNotNull(currency, "currency"); Mandate.ParameterNotNull(currentCustomer, "currentCustomer"); this._umbraco = umbraco; this._currency = currency; this._currentCustomer = currentCustomer; }
/// <summary> /// get project listing based on ID /// </summary> /// <param name="id"></param> /// <param name="optimized"></param> /// <param name="projectKarma"></param> /// <returns></returns> public IListingItem GetListing(int id, bool optimized = false, int projectKarma = -1) { var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var content = umbracoHelper.TypedContent(id); if (content != null) return GetListing(content, optimized, projectKarma); throw new NullReferenceException("Content is Null cannot find a node with the id:" + id); }
protected ContentTreeControllerBase(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper) { }
public UmbracoIdentityAccountController(UmbracoContext umbracoContext, UmbracoHelper umbracoHelper, UmbracoMembersUserManager <UmbracoApplicationMember> userManager, UmbracoMembersRoleManager <UmbracoApplicationRole> roleManager) : base(umbracoContext, umbracoHelper) { _userManager = userManager; _roleManager = roleManager; }
public SearchHelper(UmbracoHelper umbracoHelper) { this.umbracoHelper = umbracoHelper; }
protected void createEvent(object sender, EventArgs e) { var hasAnchors = false; var hasLowKarma = false; var karma = int.Parse(_member.getProperty("reputationTotal").Value.ToString()); if (karma < 50) { hasLowKarma = true; } var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var contentService = ApplicationContext.Current.Services.ContentService; IContent content; //edit? if (string.IsNullOrEmpty(Request.QueryString["id"]) == false) { content = contentService.GetById(int.Parse(Request.QueryString["id"])); var publishedContent = umbracoHelper.TypedContent(Request.QueryString["id"]); //allowed? if (publishedContent.DocumentTypeAlias == "Event" && publishedContent.GetPropertyValue <int>("owner") == _member.Id) { content = SetDescription(content, hasLowKarma, ref hasAnchors); content.Name = tb_name.Text; content.SetValue("venue", tb_venue.Text); content.SetValue("latitude", tb_lat.Value); content.SetValue("longitude", tb_lng.Value); content.SetValue("capacity", tb_capacity.Text); var startDate = GetProperDate(dp_startdate.Text); var endDate = GetProperDate(dp_enddate.Text); content.SetValue("start", startDate); content.SetValue("end", endDate); var sync = tb_capacity.Text != publishedContent.GetPropertyValue <string>("capacity"); contentService.SaveAndPublishWithStatus(content); if (sync) { var ev = new Event(publishedContent); ev.syncCapacity(); } } } else { content = contentService.CreateContent(tb_name.Text, EventsRoot, "Event"); content = SetDescription(content, hasLowKarma, ref hasAnchors); content.SetValue("venue", tb_venue.Text); content.SetValue("latitude", tb_lat.Value); content.SetValue("longitude", tb_lng.Value); content.SetValue("capacity", tb_capacity.Text); var startDate = GetProperDate(dp_startdate.Text); var endDate = GetProperDate(dp_enddate.Text); content.SetValue("start", startDate); content.SetValue("end", endDate); content.SetValue("owner", _member.Id); content.SetValue("signedup", 0); contentService.SaveAndPublishWithStatus(content); } var redirectUrl = umbraco.library.NiceUrl(content.Id); if (hasLowKarma && hasAnchors) { SendPotentialSpamNotification(tb_name.Text, redirectUrl, _member.Id); } Response.Redirect(redirectUrl); }
public ActionResult HandleSubmit(RegisterModel model) { var locationInvalid = string.IsNullOrEmpty(model.Latitude) || string.IsNullOrEmpty(model.Longitude); if (!ModelState.IsValid || locationInvalid || model.AgreeTerms == false) { if (locationInvalid) { ModelState.AddModelError("Location", "Please tell us a little bit about where you live."); } if (model.AgreeTerms == false) { ModelState.AddModelError("AgreeTerms", "You can only continue if you agree to our terms and conditions."); } return(CurrentUmbracoPage()); } var memberService = Services.MemberService; if (memberService.GetByEmail(model.Email) != null) { ModelState.AddModelError("Email", "A member with that email address already exists"); return(CurrentUmbracoPage()); } // If spammer then this will stop account creation var spamResult = Forum.Library.Utils.CheckForSpam(model.Email, model.Name, true); if (spamResult != null && spamResult.Blocked) { return(Redirect("/")); } if (string.IsNullOrWhiteSpace(model.Flickr) == false || string.IsNullOrWhiteSpace(model.Bio) == false) { //These fields are hidden, only a bot will know to fill them in //This honeypot catches them return(Redirect("/")); } // these values are enforced in MemberDto which is internal ;-( // we should really have ways to query for Core meta-data! const int maxEmailLength = 400; const int maxLoginNameLength = 200; const int maxPasswordLength = 400; const int maxPropertyLength = 400; if (model.Email != null && model.Email.Length > maxEmailLength || model.Name != null && model.Name.Length > maxLoginNameLength || model.Password != null && model.Password.Length > maxPasswordLength || model.Location != null && model.Location.Length > maxPropertyLength || model.Longitude != null && model.Longitude.Length > maxPropertyLength || model.Latitude != null && model.Latitude.Length > maxPropertyLength || model.TwitterAlias != null && model.TwitterAlias.Length > maxPropertyLength ) { // has to be a rogue registration // go away! return(Redirect("/")); } var member = memberService.CreateMember(model.Email, model.Email, model.Name, "member"); member.SetValue("location", model.Location); member.SetValue("longitude", model.Longitude); member.SetValue("latitude", model.Latitude); member.SetValue("company", model.Company); member.SetValue("twitter", model.TwitterAlias); member.SetValue("treshold", "-10"); member.SetValue("bugMeNot", false); member.SetValue("reputationTotal", 20); member.SetValue("reputationCurrent", 20); member.SetValue("forumPosts", 0); member.SetValue("tos", DateTime.Now); member.IsApproved = false; memberService.Save(member); // Now that we have a memberId we can use it var avatarPath = GetAvatarPath(member); member.SetValue("avatar", avatarPath); memberService.Save(member); memberService.AssignRole(member.Username, "standard"); memberService.SavePassword(member, model.Password); Members.Login(model.Email, model.Password); if (spamResult != null && spamResult.TotalScore >= int.Parse(ConfigurationManager.AppSettings["PotentialSpammerThreshold"])) { spamResult.MemberId = member.Id; memberService.AssignRole(member.Id, "potentialspam"); Forum.Library.Utils.SendPotentialSpamMemberMail(spamResult); } else { Forum.Library.Utils.SendActivationMail(member); Forum.Library.Utils.SendMemberSignupMail(member); } memberService.AssignRole(member.Id, "notactivated"); memberService.AssignRole(member.Id, "newaccount"); var redirectPage = "/"; var contentService = ApplicationContext.Current.Services.ContentService; var rootNode = contentService.GetRootContent().OrderBy(x => x.SortOrder).First(x => x.ContentType.Alias == "Community"); var memberNode = rootNode.Children().FirstOrDefault(x => x.Name == "Member"); if (memberNode != null) { var umbracoHelper = new UmbracoHelper(UmbracoContext.Current); var pendingActivationPage = memberNode.Children().FirstOrDefault(x => x.Name == "Pending activation"); if (pendingActivationPage != null) { var pendingActivationContentItem = umbracoHelper.TypedContent(pendingActivationPage.Id); if (pendingActivationContentItem != null) { redirectPage = pendingActivationContentItem.Url; } } } return(Redirect(redirectPage)); }
public BackOfficeController(ManifestParser manifestParser, UmbracoFeatures features, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ServiceContext services, AppCaches appCaches, IProfilingLogger profilingLogger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper) : base(globalSettings, umbracoContextAccessor, services, appCaches, profilingLogger, umbracoHelper) { _manifestParser = manifestParser; _features = features; _runtimeState = runtimeState; }
public UmbLoginController(IUmbracoContextAccessor umbracoContextAccessor, IUmbracoDatabaseFactory databaseFactory, ServiceContext services, AppCaches appCaches, ILogger logger, IProfilingLogger profilingLogger, UmbracoHelper umbracoHelper) : base(umbracoContextAccessor, databaseFactory, services, appCaches, logger, profilingLogger, umbracoHelper) { }
public PageContext(T page, UmbracoHelper umbracoHelper) : base(umbracoHelper) { Page = page ?? throw new ArgumentNullException(nameof(page)); }
/// <summary> /// Konstruktor klasy /// </summary> public SearchService() { _umbracoHelper = new UmbracoHelper(UmbracoContext.Current); }
public static GlobalSettings GlobalSettings(this UmbracoHelper umbraco) { return(umbraco.ContentSingleAtXPath("//globalSettings") as GlobalSettings); }
public TestController(IMatchDataSource matchDataSource, ISeasonDataSource seasonDataSource, Uri requestUrl, UmbracoHelper umbracoHelper) : base( Mock.Of <IGlobalSettings>(), Mock.Of <IUmbracoContextAccessor>(), null, AppCaches.NoCache, Mock.Of <IProfilingLogger>(), umbracoHelper, matchDataSource, Mock.Of <IAuthorizationPolicy <Stoolball.Matches.Match> >(), Mock.Of <IDateTimeFormatter>(), seasonDataSource) { var request = new Mock <HttpRequestBase>(); request.SetupGet(x => x.Url).Returns(requestUrl); var context = new Mock <HttpContextBase>(); context.SetupGet(x => x.Request).Returns(request.Object); var controllerContext = new Mock <ControllerContext>(); controllerContext.Setup(p => p.HttpContext).Returns(context.Object); controllerContext.Setup(p => p.HttpContext.User).Returns(new GenericPrincipal(new GenericIdentity("test"), null)); ControllerContext = controllerContext.Object; }
protected ListControllerBase(UmbracoContext umbracoContext, UmbracoHelper umbracoHelper) : base(umbracoContext, umbracoHelper) { }
public HttpResponseMessage PrerenderPages() // /umbraco/api/carbidesupport/prerenderpages/ { string result = ""; if (HttpContext.Current.Application["RebuildCacheStatus"] == null) { var context = HttpContext.Current; context.Application["RebuildCacheStatus"] = "running"; context.Application["RebuildCacheHistory"] = "<h4 style=\"font-size: 1.1rem; margin-bottom: 1.5rem;\">Started " + Temporal.DateFormat(DateTime.Now, DateFormats.European).ToUpper() + " @ " + Temporal.TimeFormat(DateTime.Now, TimeFormats.SqlMilitary) + "</h4>"; result = context.Application["RebuildCacheHistory"].ToString(); Thread workerThread = new Thread(new ThreadStart(() => { StopWatch timer = new StopWatch(); StopWatch timer2 = new StopWatch(); try { timer.Start(); context.Server.ScriptTimeout = 100000; context.Application["RebuildCacheHistory"] += "<ol style=\"padding: 0.25rem 0 0 1rem;\">"; context.Application["RebuildCacheHistory"] += "<li style=\"padding-bottom: 1rem;\">Pre-rendering templates... "; timer2.Reset(); timer2.Start(); var umbracoHelper = new UmbracoHelper(Carbide.ContextHelpers.EnsureUmbracoContext()); int pageCounter = 0; List <int> templates = new List <int>(); foreach (var node in umbracoHelper.TypedContentAtRoot()) { ListChildNodes(node, ref pageCounter, ref context, ref templates); } if (pageCounter > 1) { var msg = context.Application["RebuildCacheHistory"].ToString(); msg = msg.Substring(0, msg.LastIndexOf("...")); context.Application["RebuildCacheHistory"] = msg + "... "; } timer2.Stop(); context.Application["RebuildCacheHistory"] += "<strong>" + pageCounter + " template" + (pageCounter != 1 ? "s" : "") + " in " + timer2.GetSeconds <int>() + " seconds</strong></li>"; timer.Stop(); context.Application.SafeRemove("RebuildCacheStatus"); context.Application["RebuildCacheHistory"] += "</ol>"; context.Application["RebuildCacheHistory"] += "<h4 style=\"font-size: 1.1rem;\">Finished in " + timer.GetSeconds <int>() + " seconds</h4>"; } catch (Exception e) { timer.Stop(); timer2.Stop(); context.Application.SafeRemove("RebuildCacheStatus"); context.Application["RebuildCacheHistory"] = "</li></ol><p><strong>Error in " + timer.GetSeconds <int>() + " seconds on " + Temporal.DateFormat(DateTime.Now, DateFormats.European).ToUpper() + " @ " + Temporal.TimeFormat(DateTime.Now, TimeFormats.SqlMilitary) + "</strong></p>" + e.Message; result = context.Application["RebuildCacheHistory"].ToString(); } })) { IsBackground = true }; workerThread.Start(); while (HttpContext.Current.Application["RebuildCacheStatus"] == null) { // Wait for worker thread to start up and initialize System.Threading.Thread.Sleep(50); } } else { result = HttpContext.Current.Application["RebuildCacheHistory"].ToString(); } var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content = new StringContent(result, Encoding.UTF8, "text/plain"); return(response); }
public TestController(IMatchDataSource matchDataSource, ICommentsDataSource <Stoolball.Matches.Match> commentsDataSource, UmbracoHelper umbracoHelper) : base( Mock.Of <IGlobalSettings>(), Mock.Of <IUmbracoContextAccessor>(), null, AppCaches.NoCache, Mock.Of <IProfilingLogger>(), umbracoHelper, matchDataSource, commentsDataSource, Mock.Of <IAuthorizationPolicy <Stoolball.Matches.Match> >(), Mock.Of <IDateTimeFormatter>(), Mock.Of <IEmailProtector>(), Mock.Of <IBadLanguageFilter>()) { var request = new Mock <HttpRequestBase>(); request.SetupGet(x => x.Url).Returns(new Uri("https://example.org")); var context = new Mock <HttpContextBase>(); context.SetupGet(x => x.Request).Returns(request.Object); var controllerContext = new Mock <ControllerContext>(); controllerContext.Setup(p => p.HttpContext).Returns(context.Object); controllerContext.Setup(p => p.HttpContext.User).Returns(new GenericPrincipal(new GenericIdentity("test"), null)); ControllerContext = controllerContext.Object; }
/// <summary> /// Default constructor for SearchHelper /// </summary> /// <param name="uHelper">An umbraco helper to use in your class</param> public SearchHelper(UmbracoHelper uHelper) { _uHelper = uHelper; }
public SearchContentEventService(IContentIndexer contentIndexer, IGridHelper gridHelper, UmbracoHelper umbracoHelper) { _contentIndexer = contentIndexer; _gridHelper = gridHelper; _umbracoHelper = umbracoHelper; }
public MacrosController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper) { _macroService = Services.MacroService; }
public MardownEditorApiController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper, IMediaFileSystem mediaFileSystem) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper) { _mediaFileSystem = mediaFileSystem; }
public ContentTreeController(UmbracoTreeSearcher treeSearcher, ActionCollection actions, IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper) { _treeSearcher = treeSearcher; _actions = actions; }
/// <summary> /// 建構元 /// </summary> /// <param name="service">服務</param> /// <param name="helper">輔助</param> public AgencyRepository(IContentService service, UmbracoHelper helper) : base(service) { this._helper = helper; }
public ApplicationTreeController(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, ITreeService treeService, ISectionService sectionService, UmbracoHelper umbracoHelper) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper) { _treeService = treeService; _sectionService = sectionService; }
/// <summary> /// Initializes a new instance of the <see cref="UmbracoApiControllerBase"/> class with all its dependencies. /// </summary> protected UmbracoApiControllerBase(IGlobalSettings globalSettings, IUmbracoContextAccessor umbracoContextAccessor, ISqlContext sqlContext, ServiceContext services, AppCaches appCaches, IProfilingLogger logger, IRuntimeState runtimeState, UmbracoHelper umbracoHelper) { UmbracoContextAccessor = umbracoContextAccessor; GlobalSettings = globalSettings; SqlContext = sqlContext; Services = services; AppCaches = appCaches; Logger = logger; RuntimeState = runtimeState; Umbraco = umbracoHelper; // fixme - can we break all ctors? Mapper = Current.Mapper; }
public PackageRepositoryService(UmbracoHelper umbracoHelper, MembershipHelper membershipHelper, DatabaseContext databaseContext) { UmbracoHelper = umbracoHelper; MembershipHelper = membershipHelper; DatabaseContext = databaseContext; }
protected PagePromotionServiceBase(ICacheService cacheService, UmbracoHelper umbracoHelper, IDocumentTypeAliasProvider documentTypeAliasProvider) { _cacheService = cacheService; _umbracoHelper = umbracoHelper; _documentTypeAliasProvider = documentTypeAliasProvider; }
public bool ValidateAdditionalData(HttpContextBase context, string additionalData) { if (!additionalData.DetectIsJson()) { return(false); //must be json } AdditionalData json; try { json = JsonConvert.DeserializeObject <AdditionalData>(additionalData); } catch { return(false); //couldn't parse } if (json.Stamp == default) { return(false); } //if there was a wrapped provider, validate it, else validate the static value var validateWrapped = _defaultProvider?.ValidateAdditionalData(context, json.WrappedValue) ?? json.WrappedValue == "default"; if (!validateWrapped) { return(false); } var ufprtRequest = context.Request["ufprt"]?.ToString(); //if the custom BeginUmbracoForms route value is not there, then it's nothing more to validate if (ufprtRequest.IsNullOrWhiteSpace() && json.Ufprt.IsNullOrWhiteSpace()) { return(true); } //if one or the other is null then something is wrong if (!ufprtRequest.IsNullOrWhiteSpace() && json.Ufprt.IsNullOrWhiteSpace()) { return(false); } if (ufprtRequest.IsNullOrWhiteSpace() && !json.Ufprt.IsNullOrWhiteSpace()) { return(false); } if (!UmbracoHelper.DecryptAndValidateEncryptedRouteString(json.Ufprt, out var additionalDataParts)) { return(false); } if (!UmbracoHelper.DecryptAndValidateEncryptedRouteString(ufprtRequest, out var requestParts)) { return(false); } //ensure they all match return(additionalDataParts.Count == requestParts.Count && additionalDataParts[RenderRouteHandler.ReservedAdditionalKeys.Controller] == requestParts[RenderRouteHandler.ReservedAdditionalKeys.Controller] && additionalDataParts[RenderRouteHandler.ReservedAdditionalKeys.Action] == requestParts[RenderRouteHandler.ReservedAdditionalKeys.Action] && additionalDataParts[RenderRouteHandler.ReservedAdditionalKeys.Area] == requestParts[RenderRouteHandler.ReservedAdditionalKeys.Area]); }
/// <summary> /// Initializes a new instance of the <see cref="RightsOfWayDepositsViewModelFromExamine" /> class. /// </summary> /// <param name="umbracoParentNodeId">The umbraco parent node identifier.</param> /// <param name="baseUrl">The base URL for linking to details of each deposit - expected to be the URL of the deposits listings page.</param> /// <param name="searchTerm">The search term.</param> /// <param name="searchFilters">The search filters.</param> /// <param name="umbracoHelper">The Umbraco helper.</param> /// <exception cref="ArgumentNullException">baseUrl</exception> /// <exception cref="System.ArgumentNullException">baseUrl</exception> public RightsOfWayDepositsViewModelFromExamine(int umbracoParentNodeId, Uri baseUrl, string searchTerm, IEnumerable <ISearchFilter> searchFilters, UmbracoHelper umbracoHelper) { if (baseUrl == null) { throw new ArgumentNullException(nameof(baseUrl)); } _umbracoParentNodeId = umbracoParentNodeId; _baseUrl = baseUrl; _umbracoHelper = umbracoHelper; AddFilteredSearchTerm(searchTerm, searchFilters); }
public RadioButtonValueConverter(UmbracoHelper umbracoHelper) { _umbracoHelper = umbracoHelper; }
/// <summary> /// Initializes a new instance of the <see cref="RightsOfWayModificationsViewModelFromExamine" /> class. /// </summary> /// <param name="umbracoParentNodeId">The umbraco parent node identifier.</param> /// <param name="baseUrl">The base URL for linking to details of each modification order - expected to be the URL of the modification orders listings page.</param> /// <param name="searcher">The Examine searcher for rights of way deposits</param> /// <param name="searchTerm">The search term.</param> /// <param name="searchFilters">The search filters.</param> /// <param name="umbracoHelper">The Umbraco helper.</param> /// <exception cref="ArgumentNullException">baseUrl</exception> /// <exception cref="System.ArgumentNullException">baseUrl</exception> public RightsOfWayModificationsViewModelFromExamine(int umbracoParentNodeId, Uri baseUrl, ISearcher searcher, string searchTerm, IEnumerable <ISearchFilter> searchFilters, UmbracoHelper umbracoHelper) { if (baseUrl == null) { throw new ArgumentNullException(nameof(baseUrl)); } _umbracoParentNodeId = umbracoParentNodeId; _baseUrl = baseUrl; _searcher = searcher ?? throw new ArgumentNullException(nameof(searcher)); _includeCompleted = true; _umbracoHelper = umbracoHelper; AddFilteredSearchTerm(searchTerm, searchFilters); }
static TransferRequestHelper() { UmbracoHelper = DependencyResolver.Current.GetService <UmbracoHelper>(); AliasProvider = DependencyResolver.Current.GetService <IDocumentTypeAliasProvider>(); }
/// <summary> /// Initializes a new instance of the <see cref="MediaPickerDataTypeHandler"/> class. /// </summary> public MediaPickerDataTypeHandler() { this.umbracoHelper = new UmbracoHelper(UmbracoContext.Current); }