Exemple #1
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);
                    }
                }
            }
        }
Exemple #2
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);
            }
        }
        /// <summary>
        /// Gets the list of personalisation group content items associated with the current content item
        /// </summary>
        /// <param name="content">Instance of IPublished content</param>
        /// <returns>List of personalisation group content items</returns>
        private static IList <IPublishedContent> GetPickedGroups(IPublishedContent content)
        {
            var propertyAlias = UmbracoConfig.For.PersonalisationGroups().GroupPickerAlias;

            if (content.HasProperty(propertyAlias))
            {
                // If on v7.6 (or if Umbraco Core Property Converters package installed on an earlier version)
                // we can retrieve typed property values.
                var propertyValueAsEnumerable = content.GetPropertyValue <IEnumerable <IPublishedContent> >(propertyAlias);
                if (propertyValueAsEnumerable != null)
                {
                    return(propertyValueAsEnumerable.ToList());
                }

                // Fall-back check for CSV of integers (format used for MNTP before v7.6)
                var propertyValueAsCsv = content.GetProperty(propertyAlias).DataValue.ToString();
                if (!string.IsNullOrEmpty(propertyValueAsCsv))
                {
                    var pickedGroupIds = propertyValueAsCsv
                                         .Split(',')
                                         .Select(int.Parse);

                    var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
                    return(umbracoHelper.TypedContent(pickedGroupIds).ToList());
                }
            }

            return(new List <IPublishedContent>());
        }
Exemple #4
0
        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);
        }
        /// <summary>
        /// Adds an extension method to UmbracoHelper to calculate a hash for the current visitor for all visitor groups
        /// </summary>
        /// <param name="helper">Instance of UmbracoHelper</param>
        /// <param name="personalisationGroupsRootNodeId">Id of root node for the personalisation groups</param>
        /// <param name="cacheUserIdentifier">Identifier for the user to use in the cache key (likely the session Id)</param>
        /// <param name="cacheForSeconds">Length of time in seconds to cache the generated personalisation group hash for the visitor</param>
        /// <returns>Has for the visitor for all groups</returns>
        public static string GetPersonalisationGroupsHashForVisitor(this UmbracoHelper helper, Guid personalisationGroupsRootNodeId,
                                                                    string cacheUserIdentifier, int cacheForSeconds)
        {
            var personalisationGroupsRootNode = helper.TypedContent(personalisationGroupsRootNodeId);

            if (personalisationGroupsRootNode.DocumentTypeAlias != AppConstants.DocumentTypeAliases.PersonalisationGroupsFolder)
            {
                throw new InvalidOperationException(
                          $"The personalisation groups hash for a visitor can only be calculated for a root node of type {AppConstants.DocumentTypeAliases.PersonalisationGroupsFolder}");
            }

            return(GetPersonalisationGroupsHashForVisitor(helper, personalisationGroupsRootNode, cacheUserIdentifier, cacheForSeconds));
        }
        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);
        }
        public static bool ShowToVisitor(this UmbracoHelper umbraco, IEnumerable <int> groupIds, bool showIfNoGroupDefined = true)
        {
            try
            {
                var pickedGroups = umbraco.TypedContent(groupIds).ToList();

                return(ShowToVisitor(pickedGroups, showIfNoGroupDefined));
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }

            return(false);
        }
        /// <summary>
        /// Gets the list of personalisation group content items associated with the current content item
        /// </summary>
        /// <param name="content">Instance of IPublished content</param>
        /// <returns>List of personalisation group content items</returns>
        private static IList <IPublishedContent> GetPickedGroups(IPublishedContent content)
        {
            var propertyAlias = GetGroupPickerAlias();

            if (content.HasProperty(propertyAlias))
            {
                var propertyValue = content.GetProperty(propertyAlias).DataValue.ToString();
                if (!string.IsNullOrEmpty(propertyValue))
                {
                    var pickedGroupIds = propertyValue
                                         .Split(',')
                                         .Select(x => int.Parse(x));

                    var umbracoHelper = new UmbracoHelper(UmbracoContext.Current);
                    return(umbracoHelper.TypedContent(pickedGroupIds).ToList());
                }
            }

            return(new List <IPublishedContent>());
        }
        /// <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));
        }
        /// <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));
        }
Exemple #11
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));
 }
Exemple #12
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));
 }
        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");
                        }
                    }
                }
            });
Exemple #14
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;
        }