コード例 #1
0
        public static bool SendEmail(string EmailTemplateName, string FromEmail, string ToEmail, Dictionary <string, string> EmailFields)
        {
            // get the email master outer template
            int    siteSettingsID      = 1098;
            var    uh                  = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
            var    siteSettingsNode    = uh.TypedContent(siteSettingsID);
            string emailMasterTemplate = siteSettingsNode.GetPropertyValue <string>("emailMasterTemplate");
            var    emailNode           = siteSettingsNode.Children().Where(x => x.Name == EmailTemplateName).First();
            string emailBodyTemplate   = emailNode.GetPropertyValue <string>("emailBody");
            string EmailSubject        = emailNode.GetPropertyValue <string>("emailSubject");

            string EmailBody = emailMasterTemplate.Replace("[[CONTENT]]", emailBodyTemplate);

            try
            {
                // send email
                MailMessage message = new MailMessage();

                message.To.Add(ToEmail);
                message.From    = new System.Net.Mail.MailAddress(FromEmail, "UMBRACOMEMBERS : WEBSITE"); // Change me :)
                message.Subject = ReplaceFields(EmailSubject, EmailFields);

                message.IsBodyHtml = true;
                message.Body       = ReplaceFields(EmailBody, EmailFields);
                SmtpClient smtp = new SmtpClient();
                smtp.Send(message);
                return(true);
            }
            catch (Exception e)
            {
                LogHelper.Info(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Error trying to Send Email" + e);
                return(false);
            }
        }
コード例 #2
0
        public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            // This project uses dependency injection
            // Read more about umbraco and dependency injection here:
            // https://glcheetham.name/2016/05/27/implementing-ioc-in-umbraco-unit-testing-like-a-boss/
            // https://glcheetham.name/2017/01/29/mocking-umbracohelper-using-dependency-injection-the-right-way/


            var umbracoContext = umbracoApplication.Context.GetUmbracoContext();

            var builder = new ContainerBuilder();

            var umbracoHelper = new Umbraco.Web.UmbracoHelper(umbracoContext);

            // Register our controllers from this assembly with Autofac
            builder.RegisterControllers(Assembly.GetExecutingAssembly());
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            // Register controllers from the Umbraco assemblies with Autofac
            builder.RegisterControllers(typeof(UmbracoApplication).Assembly);
            builder.RegisterApiControllers(typeof(UmbracoApplication).Assembly);
            // Register the types we need to resolve with Autofac
            builder.RegisterInstance(ExamineManager.Instance).As <ExamineManager>();
            builder.RegisterInstance(umbracoHelper.ContentQuery).As <ITypedPublishedContentQuery>();

            // Set up MVC to use Autofac as a dependency resolver
            var container = builder.Build();

            System.Web.Mvc.DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // And WebAPI
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
        }
コード例 #3
0
        private void MediaService_Saving(IMediaService sender, SaveEventArgs <IMedia> e)
        {
            var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);

            _customVisionPredictionKey = umbracoHelper.TypedContent(1127).GetPropertyValue <string>("customVisionPredictionKey");
            _customVisionApiProjectId  = umbracoHelper.TypedContent(1127).GetPropertyValue <string>("customVisionProjectId");


            if (!string.IsNullOrWhiteSpace(_customVisionPredictionKey) && !string.IsNullOrWhiteSpace(_customVisionApiProjectId))
            {
                PredictionEndpoint endpoint = new PredictionEndpoint()
                {
                    ApiKey = _customVisionPredictionKey
                };

                foreach (IMedia media in e.SavedEntities.Where(a => a.ContentType.Name.Equals(Constants.Conventions.MediaTypes.Image)))
                {
                    string relativeImagePath = ImagePathHelper.GetImageFilePath(media);

                    using (Stream imageFileStream = _fs.OpenFile(relativeImagePath))
                    {
                        var result = endpoint.PredictImage(Guid.Parse(_customVisionApiProjectId), imageFileStream);
                        IEnumerable <string> tags = result.Predictions.Where(a => a.Probability > 0.75).Select(a => a.Tag);
                        media.SetTags("customVisionTags", tags, true);
                    }
                }
            }
        }
コード例 #4
0
ファイル: UmbracoAdapter.cs プロジェクト: SxChoc/ModShots
        public string getImageURL(int nodeID, string zProperty)
        {
            var    umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
            var    node          = umbracoHelper.TypedContent(nodeID);
            string myURL         = node.GetPropertyValue <IPublishedContent>(zProperty).Url;

            return(myURL);
        }
コード例 #5
0
    public static string GetImageUrl(IPublishedContent content, string property, string crop)
    {
        var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);

        var profile    = umbracoHelper.TypedMember(content.Id);
        var profilePic = profile.GetCropUrl("profilePic", "profile-square");

        return(profilePic);
    }
コード例 #6
0
        public virtual void SetUp()
        {
            this.SetupHttpContext();
            this.SetupCultureDictionaries();
            this.SetupPublishedContentQuerying();
            this.SetupMembership();

            this.ServiceContext = ServiceContext.CreatePartial();
            this.UmbracoHelper  = new Umbraco.Web.UmbracoHelper(Mock.Of <IPublishedContent>(), Mock.Of <ITagQuery>(), this.CultureDictionaryFactory.Object, Mock.Of <IUmbracoComponentRenderer>(), this.PublishedContentQuery.Object, this.MembershipHelper);
            this.UmbracoMapper  = new UmbracoMapper(new MapDefinitionCollection(new List <IMapDefinition>()));
        }
コード例 #7
0
ファイル: UmbracoAdapter.cs プロジェクト: SxChoc/ModShots
        public string getImageURLFromUDI(string imageUDI)
        {
            try {
                var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);

                var imageGuidUdi = GuidUdi.Parse(imageUDI);
                var imageNodeID  = ApplicationContext.Current.Services.EntityService.GetIdForKey(imageGuidUdi.Guid, (UmbracoObjectTypes)Enum.Parse(typeof(UmbracoObjectTypes), imageGuidUdi.EntityType, true));
                var imageNode    = umbracoHelper.TypedMedia(imageNodeID.Result);

                return(imageNode.Url);
            }
            catch { return(""); }
        }
コード例 #8
0
        private int GetNodeIdFromPath(string startNode)
        {
            if (startNode == null || string.IsNullOrWhiteSpace(startNode))
            {
                return(-1);
            }

            var requestContext = new HttpContext(new HttpRequest("", "http://localhost/", ""), new HttpResponse(null));
            var context        = UmbracoContext.EnsureContext(new HttpContextWrapper(requestContext), ApplicationContext.Current);

            var helper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
            IEnumerable <IPublishedContent> rootItems;

            if (_targetType.Implements <IMediaPicker>())
            {
                rootItems = helper.TypedMediaAtRoot();
            }
            else if (_targetType.Implements <IDocumentPicker>())
            {
                rootItems = helper.TypedContentAtRoot();
            }
            else //TODO proper support for members?
            {
                //TODO this is a bit dodge and won't work for members. How do start nodes even work for member pickers?
                rootItems = helper.TypedContentAtRoot().Union(helper.TypedMediaAtRoot());
            }

            var pieces = _startNodeInput.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            int i      = 0;

            if (pieces.Length == 0)
            {
                return(-1);
            }
            IPublishedContent current = rootItems.FirstOrDefault(x => x.Name == pieces[i]);

            i++;
            while (current != null && i < pieces.Length)
            {
                current = current.Children.FirstOrDefault(x => x.Name == pieces[i]);
                i++;
            }
            if (current == null)
            {
                return(-1);
            }
            else
            {
                return(current.Id);
            }
        }
コード例 #9
0
        public static string GetSingleUrlFromJObject(JObject link, out string linkTitle, out string linkTarget, out string linkIcon, out IPublishedContent node)
        {
            string linkURL = String.Empty;

            linkTitle  = String.Empty;
            linkTarget = String.Empty;
            linkIcon   = String.Empty;
            node       = null;

            if (link.Value <bool>("isInternal"))
            {
                var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);

                node = umbracoHelper.TypedContent(link.Value <int>("internal"));

                if (node != null)
                {
                    linkURL = node.Url;

                    if (link.Value <bool>("newWindow"))
                    {
                        linkTitle  = " title=\"" + umbraco.library.GetDictionaryItem("USN New Window Title Tag") + "\" ";
                        linkTarget = "target=\"_blank\"";
                        linkIcon   = "<i class=\"ion-android-open after\"></i>";
                    }

                    //Document types ending _AN should be linked to anchor position on page.
                    if (node.DocumentTypeAlias.IndexOf("_AN") != -1)
                    {
                        var    pageComponentsNode = node.Parent;
                        var    parentNode         = pageComponentsNode.Parent;
                        string anchor             = "#pos_" + node.Id.ToString();
                        linkURL = parentNode.Url + anchor;
                    }
                }
            }
            else
            {
                linkURL = link.Value <string>("link");

                if (link.Value <bool>("newWindow"))
                {
                    linkTitle  = " title=\"" + umbraco.library.GetDictionaryItem("USN New Window Title Tag") + "\" ";
                    linkTarget = "target=\"_blank\"";
                    linkIcon   = "<i class=\"ion-android-open after\"></i>";
                }
            }

            return(linkURL);
        }
コード例 #10
0
        public static List <IMedia> GetDownloads(string key, string t)
        {
            List <IMedia> list = new List <IMedia>();

            if (!string.IsNullOrWhiteSpace(t) && !string.IsNullOrWhiteSpace(key))
            {
                UmbracoHelper umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
                IMediaService mediaService  = ApplicationContext.Current.Services.MediaService;
                IMedia        media         = null;

                // - find download item
                foreach (var rm in umbracoHelper.TypedMediaAtRoot())
                {
                    foreach (IMedia m in mediaService.GetDescendants(rm.Id))
                    {
                        if (m.HasProperty("downloadKey") && m.GetValue <string>("downloadKey").Equals(key, System.StringComparison.InvariantCultureIgnoreCase))
                        {
                            // - found the matching media/folder
                            media = m;
                            var children = mediaService.GetDescendants(m.Id);
                            if (children.Count() > 0)
                            {
                                // - has children (= build list)
                                foreach (IMedia child in children)
                                {
                                    list.Add(child);
                                }
                            }
                            else
                            {
                                // - only add the single item
                                list.Add(m);
                            }
                            break;
                        }
                    }
                    if (media != null)
                    {
                        break;
                    }
                }
            }

            return(list);
        }
コード例 #11
0
        /*Including a MVC Controller into the Umbraco routing!!! My CustomUmbracoApplication : UmbracoApplication wis replacing the UmbracoApplication in the Global.asax
         * so my SimpleController : Controller will be included in the Umbraco routing*/
        public ActionResult Index()
        {
            //being that we are in a custom class, outside of an Umbraco controller, we have to instantiate our own Helper
            var umbracoHelper = new Umbraco.Web.UmbracoHelper(_umbracoContext);

            //On most website builds, you may only have one node as the root node
            //In these scenarios, you can use this snippet to get the homepage from the Umbraco Helper:
            var rootNodes = umbracoHelper.TypedContentAtRoot();
            var homePage  = rootNodes.FirstOrDefault();

            var homeNodeById = rootNodes.First(x => x.Id == 1053);

            //If like me you're not very keen on hardcoding ID in your code, a more sage approach would be to filter by document type alias,
            //because in theory you should never have more than one homepage
            var homeNodeByAlias = rootNodes.FirstOrDefault(x => x.DocumentTypeAlias == "umbHomePage");

            //@* Get the top item in the content tree, this will always be the Last ancestor found *@
            //var websiteRoot = Model.AncestorsOrSelf().Last();


            var documentType = homePage.GetPropertyValue <string>("documentType");

            var documentTypeAlias = homePage.DocumentTypeAlias;

            ViewBag.Intro = homePage.GetPropertyValue <string>("intro");

            ViewBag.Id = homePage.GetPropertyValue("_umb_id");

            ViewBag.HomePageDocType = "test";

            //Umbraco expects a model of type RenderModel

            var model = new RenderModel(_umbracoContext.ContentCache.GetById(1053), Thread.CurrentThread.CurrentCulture);

            return(View(model));
        }
コード例 #12
0
        protected override T GetModelFromId(int id)
        {
            var node = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current).TypedMedia(id);

            return(node == null ? null : node.ConvertMediaToModel <T>(CodeFirstModelContext.GetContext(this)));
        }
コード例 #13
0
        /// <summary>
        /// Gets the NiceUrlWithDomain for the content item
        /// </summary>
        /// <param name="doc"></param>
        /// <returns></returns>
        public static string NiceUrlWithDomain(this IPublishedContent doc)
        {
            var umbHelper = new UmbracoHelper(UmbracoContext.Current);

            return(umbHelper.NiceUrlWithDomain(doc.Id));
        }
コード例 #14
0
 protected UmbracoWebService(IProfilingLogger profilingLogger, IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper umbraco, ServiceContext services, IGlobalSettings globalSettings)
 {
     Logger                 = profilingLogger;
     ProfilingLogger        = profilingLogger;
     UmbracoContextAccessor = umbracoContextAccessor;
     Umbraco                = umbraco;
     Services               = services;
     GlobalSettings         = globalSettings;
 }
コード例 #15
0
 /// <summary>
 /// Gets a content item from the cache.
 /// </summary>
 /// <param name="helper">The instance of <see cref="UmbracoHelper"/> to add extension method.</param>
 /// <param name="udi">The <see cref="Udi"/> of the content item.</param>
 /// <param name="usingUdiToIdCache">Flag indicating intention to use Udi to Id cache</param>
 /// <returns>The content, or null of the content item is not in the cache.</returns>
 public static IPublishedContent TypedContent(this UmbracoHelper helper, Udi udi, bool usingUdiToIdCache)
 {
     return(usingUdiToIdCache && udi is GuidUdi guidUdi && GuidToIdCache.TryGetId(guidUdi.Guid, out int id)
         ? helper.TypedContent(id)
         : helper.TypedContent(udi));
 }
        /// <summary>
        /// Adds an extension method to UmbracoHelper to determine if the content item should be shown to the current site
        /// visitor, based on the personalisation groups associated with the Ids passed into the method
        /// </summary>
        /// <param name="umbraco">Instance of UmbracoHelper</param>
        /// <param name="groupIds">List of group Ids</param>
        /// <param name="showIfNoGroupsDefined">Indicates the response to return if groups cannot be found on the content</param>
        /// <returns>True if content should be shown to visitor</returns>
        public static bool ShowToVisitor(this UmbracoHelper umbraco, IEnumerable <int> groupIds, bool showIfNoGroupsDefined = true)
        {
            var groups = umbraco.TypedContent(groupIds).ToList();

            return(ShowToVisitor(groups, showIfNoGroupsDefined));
        }
        /// <summary>
        /// Adds an extension method to UmbracoHelper to score the content item for the current site
        /// visitor, based on the personalisation groups associated with the Ids passed into the method
        /// </summary>
        /// <param name="umbraco">Instance of UmbracoHelper</param>
        /// <param name="groupIds">List of group Ids</param>
        /// <returns>True if content should be shown to visitor</returns>
        public static int ScoreForVisitor(this UmbracoHelper umbraco, IEnumerable <int> groupIds)
        {
            var groups = umbraco.TypedContent(groupIds).ToList();

            return(ScoreForVisitor(groups));
        }
コード例 #18
0
        public int CreateOrderItemInDbFromOrderItemSeedModel(OrderItemSeedModel model, bool doReindex = true, bool doSignal = true)
        {
            // Temporary OrderId with MD5 Hash
            var orderId     = "cthb-" + Helpers.CalculateMD5Hash(DateTime.Now.Ticks.ToString());
            var contentName = orderId;

            // Create the OrderItem
            var      uh      = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
            IContent content = _contentService.CreateContent(contentName, uh.TypedContentAtXPath("//" + ConfigurationManager.AppSettings["umbracoOrderListContentDocumentType"]).First().Id, "ChalmersILLOrderItem");

            // Set properties
            content.SetValue("originalOrder", model.Message);
            content.SetValue("reference", model.MessagePrefix + model.Message);
            content.SetValue("patronName", model.PatronName);
            content.SetValue("patronEmail", model.PatronEmail);
            content.SetValue("patronCardNo", model.PatronCardNumber);
            content.SetValue("followUpDate", DateTime.Now);
            content.SetValue("editedBy", "");
            content.SetValue("status", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderStatusDataTypeDefinitionName"], "01:Ny"));
            content.SetValue("pType", model.SierraPatronInfo.ptype);
            content.SetValue("homeLibrary", model.SierraPatronInfo.home_library);
            content.SetValue("log", JsonConvert.SerializeObject(new List <LogItem>()));
            content.SetValue("attachments", JsonConvert.SerializeObject(new List <OrderAttachment>()));
            content.SetValue("sierraInfo", JsonConvert.SerializeObject(model.SierraPatronInfo));
            content.SetValue("sierraPatronRecordId", model.SierraPatronInfo.record_id);
            content.SetValue("seedId", model.Id);

            if (model.DeliveryLibrarySigel == "Z")
            {
                content.SetValue("deliveryLibrary", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderDeliveryLibraryDataTypeDefinitionName"], "Huvudbiblioteket"));
            }
            else if (model.DeliveryLibrarySigel == "ZL")
            {
                content.SetValue("deliveryLibrary", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderDeliveryLibraryDataTypeDefinitionName"], "Lindholmenbiblioteket"));
            }
            else if (model.DeliveryLibrarySigel == "ZA")
            {
                content.SetValue("deliveryLibrary", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderDeliveryLibraryDataTypeDefinitionName"], "Arkitekturbiblioteket"));
            }
            else if (!String.IsNullOrEmpty(model.SierraPatronInfo.home_library))
            {
                if (model.SierraPatronInfo.home_library.ToLower() == "hbib")
                {
                    content.SetValue("deliveryLibrary", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderDeliveryLibraryDataTypeDefinitionName"], "Huvudbiblioteket"));
                }
                else if (model.SierraPatronInfo.home_library.ToLower() == "abib")
                {
                    content.SetValue("deliveryLibrary", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderDeliveryLibraryDataTypeDefinitionName"], "Arkitekturbiblioteket"));
                }
                else if (model.SierraPatronInfo.home_library.ToLower() == "lbib")
                {
                    content.SetValue("deliveryLibrary", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderDeliveryLibraryDataTypeDefinitionName"], "Lindholmenbiblioteket"));
                }
                else
                {
                    content.SetValue("deliveryLibrary", "");
                }
            }

            // Save the OrderItem to get an Id
            SaveWithoutEventsAndWithSynchronousReindexing(content, false, false);

            // Shorten the OrderId and include the NodeId
            content.SetValue("orderId", orderId.Substring(0, 13) + "-" + content.Id.ToString());
            content.Name = orderId.Substring(0, 13) + "-" + content.Id.ToString();

            // Save
            SaveWithoutEventsAndWithSynchronousReindexing(content, doReindex, doSignal);

            return(content.Id);
        }
コード例 #19
0
        /// <summary>
        /// Gets the unfiltered blog posts for the page
        /// </summary>
        /// <returns>All Blog Posts in desending Date Order</returns>
        private IEnumerable<IPublishedContent> GetPagedBlogPosts()
        {
            IEnumerable<IPublishedContent> AllPosts = Content.Children;
            if(!string.IsNullOrWhiteSpace(Search)){
                var searchProvider = ExamineManager.Instance.DefaultSearchProvider.Name;
                //var searchResults = ExamineManager.Instance.SearchProviderCollection[searchProvider].Search(Search, true);

                var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);

                return GetPagedPosts(umbracoHelper.TypedSearch(Search, true, searchProvider).Where(r=>r.ContentType.Alias == "BlogPost").ToList());
            }

            return GetPagedPosts(AllPosts.ToList());
        }
コード例 #20
0
 /// <summary>
 /// Gets a content item from the cache.
 /// </summary>
 /// <param name="helper">The instance of <see cref="UmbracoHelper"/> to add extension method.</param>
 /// <param name="guid">The key of the content item.</param>
 /// <param name="usingUdiToIdCache">Flag indicating intention to use Udi to Id cache</param>
 /// <returns>The content, or null of the content item is not in the cache.</returns>
 public static IPublishedContent TypedContent(this UmbracoHelper helper, Guid guid, bool usingUdiToIdCache)
 {
     return(usingUdiToIdCache && GuidToIdCache.TryGetId(guid, out int id)
         ? helper.TypedContent(id)
         : helper.TypedContent(guid));
 }
コード例 #21
0
        public static void ConfigureHmacBearerTokenAuthentication(this IAppBuilder appBuilder, string[] authenticatedPaths)
        {
            appBuilder.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
                Provider = new OAuthBearerAuthenticationProvider
                {
                    //This is the first callback made when OWIN starts
                    //to process the request, here we need to set the token
                    //to null if we don't want it to be processed - basically
                    //this is where we need to:
                    // * check the current request URL to see if we should auth the request (only deploy end points)
                    OnRequestToken = context =>
                    {
                        var umbPath = GlobalSettings.UmbracoMvcArea;

                        var applicationBasePath = (context.Request.PathBase.HasValue ? context.Request.PathBase.Value : string.Empty).EnsureEndsWith('/');

                        var requestPath = context.Request.Uri.CleanPathAndQuery();

                        //Only authenticated endpoints to be authenticated and these must have the projectid
                        //and memberid headers in the request
                        if (authenticatedPaths.Any(s => requestPath.StartsWith($"{applicationBasePath}{umbPath}/{s}", StringComparison.InvariantCultureIgnoreCase)) &&
                            EnsureHeaderValues(context, ProjectAuthConstants.ProjectIdHeader, ProjectAuthConstants.MemberIdHeader))
                        {
                            return(Task.FromResult(0));
                        }

                        context.Token = null;
                        return(Task.FromResult(0));
                    }
                },
                AccessTokenProvider = new AuthenticationTokenProvider
                {
                    //Callback used to parse the token in the request,
                    //if the token parses correctly then we should assign a ticket
                    //to the request, this is the "User" that will get assigned to
                    //the request with Claims.
                    //If the token is invalid, then don't assign a ticket and OWIN
                    //will take care of the rest (not authenticated)
                    OnReceive = context =>
                    {
                        var requestPath = context.Request.Uri.CleanPathAndQuery();
                        if (!TryGetHeaderValue(context, ProjectAuthConstants.ProjectIdHeader, out var projectId))
                        {
                            throw new InvalidOperationException("No project Id found in request"); // this will never happen
                        }
                        if (!TryGetHeaderValue(context, ProjectAuthConstants.MemberIdHeader, out var memberId))
                        {
                            throw new InvalidOperationException("No member Id found in request"); // this will never happen
                        }
                        var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
                        var project       = umbracoHelper.TypedContent(projectId);

                        if (project.GetPropertyValue <int>("owner") != memberId)
                        {
                            throw new InvalidOperationException("The user does not have owner permissions of the package"); // we generate the key ourselves, so would only happen if people edited the key themselves
                        }
                        //Get the stored auth key for this project and member
                        var tokenService = new ProjectAuthKeyService(ApplicationContext.Current.DatabaseContext);
                        var authKeys     = tokenService.GetAllAuthKeysForProject(projectId);

                        var timestamp = new DateTime();

                        if (authKeys.Any(authKey =>
                                         HMACAuthentication.ValidateToken(context.Token, requestPath, authKey, out timestamp)))
                        {
                            //If ok, create a ticket here with the Claims we need to check for in AuthZ
                            var ticket = new AuthenticationTicket(
                                new ClaimsIdentity(
                                    new List <Claim>
                            {
                                new Claim(ProjectAuthConstants.BearerTokenClaimType, ProjectAuthConstants.BearerTokenClaimValue),
                                new Claim(ProjectAuthConstants.ProjectIdClaim, projectId.ToInvariantString()),
                                new Claim(ProjectAuthConstants.MemberIdClaim, memberId.ToInvariantString()),
                            },

                                    //The authentication type = this is important, if not set
                                    //then the ticket's IsAuthenticated property will be false
                                    authenticationType: ProjectAuthConstants.BearerTokenAuthenticationType),
                                new AuthenticationProperties
                            {
                                //Expires after 5 minutes in case there are some long running operations
                                ExpiresUtc = timestamp.AddMinutes(5)
                            });

                            context.SetTicket(ticket);
                        }
                        else
                        {
                            throw new InvalidOperationException("Token validation failed");
                        }
                    }
                }
            });
コード例 #22
0
        public SiteDetails GetSiteDetails()
        {
            var helper = new Umbraco.Web.UmbracoHelper(UmbracoContext.Current);
            var root = helper.TypedContentAtRoot().FirstOrDefault();

            return new SiteDetails()
            {
                SiteName = root == null || !root.HasProperty("siteName") ? "" : root.GetProperty("siteName").Value.ToString(),
                SiteLogo = root == null || !root.HasProperty("siteLogo") ? "" : Umbraco.TypedMedia(root.GetProperty("siteLogo").Value.ToString()).Url
            };
        }
コード例 #23
0
 protected UmbracoAuthorizedHttpHandler(IUmbracoContextAccessor umbracoContextAccessor, UmbracoHelper umbracoHelper, ServiceContext service, IProfilingLogger plogger) : base(umbracoContextAccessor, umbracoHelper, service, plogger)
 {
 }
コード例 #24
0
 public RelatedLinksTypeConverter(UmbracoHelper umbracoHelper)
 {
     _umbracoHelper = umbracoHelper;
 }
コード例 #25
0
        public static Website Website(this UW.UmbracoHelper umbracoHelper)
        {
            var siteService = UW.Composing.Current.Factory.GetInstance <ISiteService>();

            return(siteService.GetWebsiteById(umbracoHelper.AssignedContentItem.Id));
        }
コード例 #26
0
        public void Load()
        {
            var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
            BlogRoot = Content.Parent;
            EntryDate = (Content.HasValue("entryDate")) ? DateTime.Parse(Content.GetPropertyValue<string>("entryDate")) : Content.CreateDate;
            BlogContent = Content.GetPropertyValue<HtmlString>("content");
            Categories = (Content.HasValue("categories")) ? umbracoHelper.Content(Content.GetPropertyValue<string>("categories").Split(',')) : new List<IPublishedContent>().AsEnumerable();
            Tags = (Content.HasValue("tags")) ? Content.GetPropertyValue<string>("tags").Split(',') : new string[0];
            MainImage = (Content.HasValue("mainImage")) ? JsonConvert.DeserializeObject<ImageCropDataSet>(Content.GetPropertyValue <string>("mainImage") ): null;

            Blurb = (Content.HasValue("blurb")) ? Content.GetPropertyValue<HtmlString>("blurb") : (HtmlString)umbracoHelper.Truncate(BlogContent, 800);
            Title = Content.Name;
            CommentsEnabled = (Content.HasValue("commentsEnabled", true)) ? Content.GetPropertyValue<bool>("commentsEnabled", true) : false;
            DisqusShortname = (Content.HasValue("disqusShortname", true)) ? Content.GetPropertyValue<string>("disqusShortname", true) : null;
            TwitterUsername = Content.GetPropertyValue<string>("twitterUsername", true);
            ShareDescription = Content.GetPropertyValue<string>("shareDescription", true);
            FullUrl = Content.UrlWithDomain();
            var authorId = Content.GetProperty("author");
            Author = (authorId != null && authorId.HasValue) ? new BlogAuthor(
                Convert.ToInt32( authorId.Value)
                ) : null;
            EnableShareIcons = (Content.HasValue("enableShareIcons", true)) ? Content.GetPropertyValue<bool>("enableShareIcons", true) : false;
        }
コード例 #27
0
        public int CreateOrderItemInDbFromMailQueueModel(MailQueueModel model, bool doReindex = true, bool doSignal = true)
        {
            IContentService cs = new Umbraco.Core.Services.ContentService();

            // Temporary OrderId with MD5 Hash
            var orderId     = "cthb-" + Helpers.CalculateMD5Hash(DateTime.Now.Ticks.ToString());
            var contentName = orderId;

            // Create the OrderItem
            var      uh      = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
            IContent content = cs.CreateContent(contentName, uh.TypedContentAtXPath("//" + ConfigurationManager.AppSettings["umbracoOrderListContentDocumentType"]).First().Id, "ChalmersILLOrderItem");

            // Set properties
            var originalOrder = UrlDecodeAndEscapeAllLinks(model.OriginalOrder);

            content.SetValue("originalOrder", originalOrder);
            content.SetValue("reference", originalOrder);
            content.SetValue("patronName", model.PatronName);
            content.SetValue("patronEmail", model.PatronEmail);
            content.SetValue("patronCardNo", model.PatronCardNo);
            content.SetValue("followUpDate", DateTime.Now);
            content.SetValue("editedBy", "");
            content.SetValue("status", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderStatusDataTypeDefinitionName"], "01:Ny"));
            content.SetValue("pType", model.SierraPatronInfo.ptype);
            content.SetValue("homeLibrary", model.SierraPatronInfo.home_library);
            content.SetValue("log", JsonConvert.SerializeObject(new List <LogItem>()));
            content.SetValue("attachments", JsonConvert.SerializeObject(new List <OrderAttachment>()));
            content.SetValue("sierraInfo", JsonConvert.SerializeObject(model.SierraPatronInfo));
            content.SetValue("sierraPatronRecordId", model.SierraPatronInfo.record_id);
            content.SetValue("dueDate", DateTime.Now);
            content.SetValue("providerDueDate", DateTime.Now);
            content.SetValue("deliveryDate", new DateTime(1970, 1, 1));
            content.SetValue("bookId", "");
            content.SetValue("providerInformation", "");
            content.SetValue("readOnlyAtLibrary", "0");

            if (!String.IsNullOrEmpty(model.SierraPatronInfo.home_library))
            {
                if (model.SierraPatronInfo.home_library.ToLower() == "hbib")
                {
                    content.SetValue("deliveryLibrary", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderDeliveryLibraryDataTypeDefinitionName"], "Huvudbiblioteket"));
                }
                else if (model.SierraPatronInfo.home_library.ToLower() == "abib")
                {
                    content.SetValue("deliveryLibrary", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderDeliveryLibraryDataTypeDefinitionName"], "Arkitekturbiblioteket"));
                }
                else if (model.SierraPatronInfo.home_library.ToLower() == "lbib")
                {
                    content.SetValue("deliveryLibrary", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderDeliveryLibraryDataTypeDefinitionName"], "Lindholmenbiblioteket"));
                }
                else
                {
                    content.SetValue("deliveryLibrary", "");
                }
            }

            // Set Type directly if "IsPurchaseRequest" is true
            if (model.IsPurchaseRequest)
            {
                content.SetValue("type", _umbraco.DataTypePrevalueId(ConfigurationManager.AppSettings["umbracoOrderTypeDataTypeDefinitionName"], "Inköpsförslag"));
            }

            // Save the OrderItem to get an Id
            SaveWithoutEventsAndWithSynchronousReindexing(content, false, false);

            // Shorten the OrderId and include the NodeId
            content.SetValue("orderId", orderId.Substring(0, 13) + "-" + content.Id.ToString());
            content.Name = orderId.Substring(0, 13) + "-" + content.Id.ToString();

            // Save
            SaveWithoutEventsAndWithSynchronousReindexing(content, doReindex, doSignal);

            return(content.Id);
        }
コード例 #28
0
        public static void GeneratePdf(IConverter _pdfConverter, IContent content)
        {
            try
            {
                if (content != null)
                {
                    var umbracoHelper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
                    var pdfpage       = umbracoHelper.TypedContent(content.Id);

                    if (pdfpage != null)
                    {
                        // decide if to publish or not
                        var generatePDF = content.GetValue <bool>("generatePDF");

                        if (generatePDF)
                        {
                            // now set the properties
                            var pdfTitle  = content.GetValue <string>("pDFDocumentTitle");
                            var pdfOutput = content.GetValue <string>("pDFDocumentPath");
                            var pdfUrl    = content.GetValue <string>("pDFUrl");

                            var pdfRenderDelay = 10000;
                            LogHelper.Info(typeof(PagePdf), "PDF Render delay: " + pdfRenderDelay);

                            var customPaperSize = new PechkinPaperSize("208mm", "297mm");
                            LogHelper.Info(typeof(PagePdf), "Generating PDF for url: " + pdfUrl);
                            var document = new HtmlToPdfDocument
                            {
                                GlobalSettings =
                                {
                                    ProduceOutline = false,
                                    DocumentTitle  = pdfTitle,
                                    //PaperSize = PaperKind.A4,

                                    PaperSize = customPaperSize,
                                    Margins   =
                                    {
                                        All  =               0,
                                        Unit = Unit.Millimeters
                                    }
                                },
                                Objects =
                                {
                                    new ObjectSettings {
                                        PageUrl      = pdfUrl,
                                        LoadSettings = new LoadSettings
                                        {
                                            RenderDelay     = pdfRenderDelay,
                                            DebugJavascript = false,
                                            StopSlowScript  = false,
                                        },
                                    },
                                }
                            };

                            byte[] result = _pdfConverter.Convert(document);
                            System.IO.File.WriteAllBytes(HttpContext.Current.Server.MapPath(pdfOutput), result);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(typeof(CorrespondentPdf), "Error: Unable to generate Correspondents PDF", ex);
            }
            return;
        }
 private static IPublishedContent GetGroupsRootFolder(UmbracoHelper helper)
 {
     return(helper.TypedContentAtRoot()
            .FirstOrDefault(x => x.DocumentTypeAlias == AppConstants.DocumentTypeAliases.PersonalisationGroupsFolder));
 }
コード例 #30
0
 public UmbracoHelperAdapter(Umbraco.Web.UmbracoHelper umbracoHelper)
 {
     _umbracoHelper = umbracoHelper;
     umbracoHelper.Content(2).AncestorsOrSelf();
 }
 /// <summary>
 /// Adds an extension method to UmbracoHelper to determine if the current site
 /// visitor matches a single personalisation group.
 /// </summary>
 /// <param name="helper">Instance of UmbracoHelper</param>
 /// <param name="groupName">Name of group node to match</param>
 /// <returns>True if visitor matches group</returns>
 public static bool MatchesGroup(this UmbracoHelper helper, string groupName)
 {
     return(MatchesGroups(helper, new string[] { groupName }, PersonalisationGroupDefinitionMatch.Any));
 }
 /// <summary>
 /// Adds an extension method to UmbracoHelper to determine if the current site
 /// visitor matches all of a set of personalisation groups.
 /// </summary>
 /// <param name="helper">Instance of UmbracoHelper</param>
 /// <param name="groupNames">Names of group nodes to match</param>
 /// <returns>True if visitor matches all groups</returns>
 public static bool MatchesAllGroups(this UmbracoHelper helper, string[] groupNames)
 {
     return(MatchesGroups(helper, groupNames, PersonalisationGroupDefinitionMatch.All));
 }
コード例 #33
0
        private int GetNodeIdFromPath(string startNode)
        {
            if (startNode == null || string.IsNullOrWhiteSpace(startNode))
            {
                return -1;
            }

            var requestContext = new HttpContext(new HttpRequest("", "http://localhost/", ""), new HttpResponse(null));
            var context = UmbracoContext.EnsureContext(new HttpContextWrapper(requestContext), ApplicationContext.Current);

            var helper = new Umbraco.Web.UmbracoHelper(Umbraco.Web.UmbracoContext.Current);
            IEnumerable<IPublishedContent> rootItems;

            if (_targetType.Implements<IMediaPicker>())
            {
                rootItems = helper.TypedMediaAtRoot();
            }
            else if (_targetType.Implements<IDocumentPicker>())
            {
                rootItems = helper.TypedContentAtRoot();
            }
            else //TODO proper support for members?
            {
                //TODO this is a bit dodge and won't work for members. How do start nodes even work for member pickers?
                rootItems = helper.TypedContentAtRoot().Union(helper.TypedMediaAtRoot());
            }

            var pieces = _startNodeInput.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
            int i = 0;
            if (pieces.Length == 0)
            {
                return -1;
            }
            IPublishedContent current = rootItems.FirstOrDefault(x => x.Name == pieces[i]);
            i++;
            while (current != null && i < pieces.Length)
            {
                current = current.Children.FirstOrDefault(x => x.Name == pieces[i]);
                i++;
            }
            if (current == null)
            {
                return -1;
            }
            else
            {
                return current.Id;
            }
        }
コード例 #34
0
ファイル: UmbracoTrains.cs プロジェクト: Kelsay/trains
 public static IEnumerable<IPublishedContent> GetTrains(IPublishedContent page)
 {
     var Umbraco = new Umbraco.Web.UmbracoHelper(UmbracoContext.Current);
     IPublishedContent root = Umbraco.TypedContentAtRoot().FirstOrDefault();
     return root.Descendants("Train");
 }