Example #1
0
        private string GetPropertyValue(umbraco.NodeFactory.Node umbracoNode, string propertyAlias)
        {
            if (umbracoNode.GetProperty(propertyAlias) == null && string.IsNullOrWhiteSpace(umbracoNode.GetProperty(propertyAlias).Value))
            {
                return(string.Empty);
            }

            return(umbracoNode.GetProperty(propertyAlias).Value);
        }
Example #2
0
        /// <summary>
        /// Method for getting a file url
        /// </summary>
        /// <param name="node">Node with file property</param>
        /// <param name="filePropertyAlias">Property alias</param>
        /// <returns>string</returns>
        public static string GetFileUrl(Node node, string filePropertyAlias)
        {
            if (!string.IsNullOrEmpty(node.GetProperty<string>(filePropertyAlias)))
            {
                var file =
                    ApplicationContext.Current.Services.MediaService.GetById(node.GetProperty<int>(filePropertyAlias));

                return file.GetValue<string>("umbracoFile");
            }

            return string.Empty;
        }
Example #3
0
        public static void ImportPageContent(int importPageId)
        {
            Node importPage = new Node(importPageId);

            var rawData = APIHelper.GetPageRaw(importPage.GetProperty("gatherContentId").ToString());
            var structure = GetPageContentStructure(rawData);
            var pageContent = DecodeFrom64(structure.page.config);
            var pageStructure = GetPageStructure(pageContent);
            AddPageContent(pageStructure, importPageId);
        }
 public static bool NodeVisible(Node node)
 {
     if (node.HasProperty("umbracoNaviHide")) return !node.GetProperty<bool>("umbracoNaviHide");
     if (node.HasProperty("visible")) return node.GetProperty<bool>("visible");
     return false;
 }
        private static bool MatchesPropertyValue(int pageId)
        {
            var appSetting = Settings.GetValueFromKey(Settings.AppKey_Properties);

            if (string.IsNullOrEmpty(appSetting))
                return false;

            var node = new Node(pageId);
            var items = appSetting.Split(new[] { Settings.COMMA }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var item in items)
            {
                var parts = item.Split(new[] { Settings.COLON }, StringSplitOptions.RemoveEmptyEntries);
                if (parts.Length == 0)
                    continue;

                var propertyAlias = parts[0];
                var propertyValue = Settings.CHECKBOX_TRUE;

                if (parts.Length > 1)
                    propertyValue = parts[1];

                var property = node.GetProperty(propertyAlias);
                if (property == null)
                    continue;

                var match = string.Equals(property.Value, propertyValue, StringComparison.InvariantCultureIgnoreCase);
                if (match)
                    return true;
            }

            return false;
        }
        void Document_BeforePublish(Document doc, PublishEventArgs e)
        {
            // When document is renamed or 'umbracoUrlName' property value is added/updated
            #if !DEBUG
            try
            #endif
            {
                Node node = new Node(doc.Id);
                if (node.Name != doc.Text && !string.IsNullOrEmpty(node.Name)) // If name is null, it's a new document
                {
                    // Rename occurred
                    UrlTrackerRepository.AddUrlMapping(doc, node.GetDomainRootNode().Id, node.NiceUrl, AutoTrackingTypes.Renamed);

                    if (BasePage.Current != null)
                        BasePage.Current.ClientTools.ChangeContentFrameUrl(string.Concat("/umbraco/editContent.aspx?id=", doc.Id));
                }
                if (doc.getProperty("umbracoUrlName") != null && node.GetProperty("umbracoUrlName") != null && node.GetProperty("umbracoUrlName").Value != doc.getProperty("umbracoUrlName").Value.ToString())
                {
                    // 'umbracoUrlName' property value added/changed
                    UrlTrackerRepository.AddUrlMapping(doc, node.GetDomainRootNode().Id, node.NiceUrl, AutoTrackingTypes.UrlOverwritten);

                    if (BasePage.Current != null)
                        BasePage.Current.ClientTools.ChangeContentFrameUrl(string.Concat("/umbraco/editContent.aspx?id=", doc.Id));
                }
            }
            #if !DEBUG
            catch (Exception ex)
            {
                ex.LogException(doc.Id);
            }
            #endif
        }
        public ActionResult GetDistributorResults(DistributorParameters dp, FormCollection form)
        {
            int stateZoom = Convert.ToInt32(CurrentPage.GetProperty("stateSearchMapZoom").ToString());
            int zipZoom   = Convert.ToInt32(CurrentPage.GetProperty("zipSearchMapZoom").ToString());

            Session["distributors"] = null;
            string whereClause = "WHERE";
            string resultsFor  = "";
            bool   isZipSearch = false;

            if (string.IsNullOrWhiteSpace(dp.City) && string.IsNullOrWhiteSpace(dp.State) && string.IsNullOrWhiteSpace(dp.ZipCode))
            {
                //Display Error when no selections have been made
                TempData["error"] = CurrentPage.GetProperty("requiredValidationText") != null?CurrentPage.GetProperty("requiredValidationText").ToString() : "Please indicate State or Zip.";
            }
            else if (!string.IsNullOrWhiteSpace(dp.ZipCode))
            {
                //Zip takes priority over City/State
                isZipSearch = true;
                string selectedZip = dp.ZipCode;
                if (ModelState.IsValid)
                {
                    whereClause = whereClause + " a.postal_code = '" + selectedZip + "'";
                    resultsFor  = "'" + selectedZip + "'";
                }
            }
            else
            {
                if (!string.IsNullOrWhiteSpace(dp.City) && string.IsNullOrWhiteSpace(dp.State))
                {
                    //search by City only if no State is selected
                    string selectedCity = dp.City;
                    whereClause = whereClause + " a.city LIKE '%" + selectedCity + "%'";
                    resultsFor  = "'" + selectedCity.ToUpper() + "'";
                }
                else if (string.IsNullOrWhiteSpace(dp.City) && !string.IsNullOrWhiteSpace(dp.State))
                {
                    //search by State only if no City is selected
                    string selectedState = dp.State;
                    whereClause = whereClause + " a.state = '" + selectedState + "'";
                    resultsFor  = "'" + selectedState.ToUpper() + "'";
                }
                else
                {
                    //search by State and City
                    string selectedCity  = dp.City;
                    string selectedState = dp.State;
                    whereClause = whereClause + " a.city LIKE '%" + selectedCity + "%' AND a.state = '" + selectedState + "'";
                    resultsFor  = "'" + selectedCity.ToUpper() + ", " + selectedState.ToUpper() + "'";
                }
            }

            if (whereClause != "WHERE")
            {
                TempData["resultsFor"]  = (CurrentPage.GetProperty("resultsForTextOverride") != null ? CurrentPage.GetProperty("resultsForTextOverride").ToString() : "RESULTS FOR") + " " + resultsFor;
                TempData["resultsFlag"] = true;

                DistributorResultSet drs = new DistributorResultSet();

                if (!isZipSearch)
                {
                    TempData["mapZoom"] = stateZoom;
                    DataSet            ds           = new DataSet();
                    List <Distributor> distributors = new List <Distributor>();
                    using (SqlConnection con = new SqlConnection(connStr))
                    {
                        string sql = "SELECT a.[name],a.[address1],a.[city],a.[state],a.[postal_code],a.[phone],a.[fax],a.[website], b.lat, b.long FROM  [dbo].[distributor] a LEFT JOIN  [dbo].[zips] b on a.postal_code = b.zip " + whereClause + " AND[type] = 1   ORDER BY a.[name]";
                        using (SqlCommand sqlcmd = new SqlCommand(sql))
                        {
                            sqlcmd.Connection = con;
                            using (SqlDataAdapter sda = new SqlDataAdapter(sqlcmd))
                            {
                                sda.Fill(ds);
                            }
                        }
                    }
                    int markerId = 1;
                    foreach (DataRow row in ds.Tables[0].Rows)
                    {
                        Distributor distributor = new Distributor();
                        distributor.Name       = Convert.ToString(row["name"]);
                        distributor.Address    = Convert.ToString(row["address1"]);
                        distributor.City       = Convert.ToString(row["city"]).Replace(' ', '-');
                        distributor.StateValue = Convert.ToString(row["state"]).Replace(' ', '-');
                        distributor.State      = Convert.ToString(row["state"]);
                        distributor.Zip        = Convert.ToString(row["postal_code"]);
                        distributor.Phone      = Convert.ToString(row["phone"]);
                        distributor.Fax        = Convert.ToString(row["fax"]);
                        distributor.Website    = Convert.ToString(row["website"]);
                        if (row["lat"] != DBNull.Value && row["long"] != DBNull.Value)
                        {
                            distributor.Lat      = Convert.ToString(row["lat"]);
                            distributor.Long     = "-" + Convert.ToString(row["long"]);
                            distributor.MarkerId = markerId;
                            markerId++;
                        }
                        else
                        {
                            distributor.Lat      = "";
                            distributor.Long     = "";
                            distributor.MarkerId = 0;
                        }
                        distributor.Distance = "undefined";
                        distributors.Add(distributor);
                    }



                    foreach (Distributor dis in distributors)
                    {
                        if (dis.Website.Length > 4 && !(dis.Website.Substring(0, 4) == "http"))
                        {
                            dis.Website = "http://" + dis.Website;
                        }
                    }



                    //foreach (Distributor dis in distributors)
                    //{
                    //	using (WebClient wc = new WebClient())
                    //	{
                    //		var json = wc.DownloadString("https://maps.googleapis.com/maps/api/geocode/json?address=" + dis.Address + " " + dis.City + ", " + dis.State + " " + dis.Zip + "&key=AIzaSyCShc6ISfXBfzjitikfWY6pJIaQpw4dpxs");
                    //		GoogleMapJSON googleMapJSON = JsonConvert.DeserializeObject<GoogleMapJSON>(json);
                    //		dis.Lat = googleMapJSON.results[0].geometry.location.lat;
                    //		dis.Long = googleMapJSON.results[0].geometry.location.lng;
                    //	}
                    //}
                    drs.Distributors = distributors;
                }
                else
                {
                    TempData["mapZoom"]     = zipZoom;
                    TempData["resultsFor"]  = (CurrentPage.GetProperty("resultsForTextOverride") != null ? CurrentPage.GetProperty("resultsForTextOverride").ToString() : "RESULTS FOR") + " " + resultsFor;
                    TempData["resultsFlag"] = true;
                    drs.Distributors        = GetDistributorsByZip(dp.ZipCode, 50);
                }

                if (drs.Distributors.Count > 0)
                {
                    Session["distributors"] = drs;
                }
                else
                {
                    TempData["resultsFor"] = (CurrentPage.GetProperty("noResultsForTextOverride") != null ? CurrentPage.GetProperty("noResultsForTextOverride").ToString() : "NO RESULTS FOR") + " " + resultsFor;
                }
            }
            return(CurrentUmbracoPage());
        }
		// unsure about location! (maybe another service)
		public string GetMultiStoreContentProperty(int contentId, string propertyAlias, ILocalization localization, bool globalOverrulesStore = false)
		{
			var examineNode = Helpers.GetNodeFromExamine(contentId, "GetMultiStoreItem::" + propertyAlias);
			if (localization == null)
			{
				localization = StoreHelper.CurrentLocalization;
			}
			var multiStoreAlias = StoreHelper.CreateMultiStorePropertyAlias(propertyAlias, localization.StoreAlias);
			var multiStoreMultiCurrencyAlias = StoreHelper.CreateFullLocalizedPropertyAlias(propertyAlias, localization);
			if (examineNode != null)
			{
				
				if (multiStoreAlias.StartsWith("description"))
				{
					multiStoreAlias = "RTEItem" + multiStoreAlias;
					propertyAlias = "RTEItem" + propertyAlias;
				}

				if (globalOverrulesStore && examineNode.Fields.ContainsKey(propertyAlias))
				{
					return examineNode.Fields[propertyAlias] ?? string.Empty;
				}

				if (examineNode.Fields.ContainsKey(multiStoreMultiCurrencyAlias))
				{
					return examineNode.Fields[multiStoreMultiCurrencyAlias] ?? string.Empty;
				}

				if (examineNode.Fields.ContainsKey(multiStoreAlias))
				{
					return examineNode.Fields[multiStoreAlias] ?? string.Empty;
				}

				if (examineNode.Fields.ContainsKey(propertyAlias))
				{
					return examineNode.Fields[propertyAlias] ?? string.Empty;
				}

				Log.Instance.LogDebug("GetMultiStoreContentProperty Fallback to node after this");
			}

			var node = new Node(contentId);
			if (node.Name != null)
			{
				var property = node.GetProperty(propertyAlias);
				if (globalOverrulesStore && property != null && !string.IsNullOrEmpty(property.Value))
				{
					return property.Value;
				}
				var propertyMultiStoreMultiCurrency = node.GetProperty(multiStoreMultiCurrencyAlias);
				if (propertyMultiStoreMultiCurrency != null && !string.IsNullOrEmpty(propertyMultiStoreMultiCurrency.Value))
				{
					return propertyMultiStoreMultiCurrency.Value;
				}
				var propertyMultistore = node.GetProperty(multiStoreAlias);
				if (propertyMultistore != null && !string.IsNullOrEmpty(propertyMultistore.Value))
				{
					return propertyMultistore.Value;
				}
				if (property != null)
				{
					return property.Value;
				}
			}
			return string.Empty;
		}
Example #9
0
 public NewsItem MapNewsItem(Node newsNode)
 {
     return new NewsItem
     {
         Id = newsNode.Id,
         Title = !string.IsNullOrEmpty(newsNode.GetProperty<string>("Title"))
             ? newsNode.GetProperty<string>("Title")
             : newsNode.Name,
         Text = newsNode.GetProperty<string>("Content"),
         Author = newsNode.GetProperty<string>("Author"),
         PublishedTime = newsNode.GetProperty<DateTime>("PublishedTime"),
         Url = newsNode.Url
     };
 }
 protected void Page_Load(object sender, EventArgs e)
 {
     var mainForumNode = new Node(new ForumFactory().ReturnRootForumId());
     litLoginDescription.Text = mainForumNode.GetProperty("loginDescription").Value;
 }
 protected string GetCreatedBy(Node notice)
 {
     return notice.GetProperty("createdBy") != null ? notice.GetProperty("createdBy").Value : "-";
 }
        /// <summary>
        /// Executes the specified URL.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <returns>Returns whether the NotFoundHandler has a match.</returns>
        public bool Execute(string url)
        {
            HttpContext.Current.Response.StatusCode = (int)HttpStatusCode.NotFound;

            var success = false;

            // get the current domain name
            var domainName = HttpContext.Current.Request.ServerVariables["SERVER_NAME"];

            // if there is a port number, append it
            var port = HttpContext.Current.Request.ServerVariables["SERVER_PORT"];
            if (!string.IsNullOrEmpty(port) && port != "80")
            {
                domainName = string.Concat(domainName, ":", port);
            }

            // get the root node id of the domain
            var rootNodeId = Domain.GetRootFromDomain(domainName);

            try
            {
                if (rootNodeId > 0)
                {
                    // get the node
                    var node = new Node(rootNodeId);

                    // get the property that holds the node id for the 404 page
                    var property = node.GetProperty("umbracoPageNotFound");
                    if (property != null)
                    {
                        var errorId = property.Value;
                        if (!string.IsNullOrEmpty(errorId))
                        {
                            // if the node id is numeric, then set the redirectId
                            success = int.TryParse(errorId, out this._redirectId);
                        }
                    }
                }
            }
            catch
            {
                success = false;
            }

            return success;
        }
        public formResponse sendForm(formRequest request)
        {
            formResponse nr = new formResponse();
            nr.Result = "1";
            nr.Msg = string.Empty;

            try
            {
                // start Node Factory
                Node page = new Node(request.Id);

                string autoResponderEmail = string.Empty;
                string autoResponderId = string.Empty;
                if (page.GetProperty("emailField") != null)
                {
                    autoResponderId = page.GetProperty("emailField").Value;
                }

                // construct the email message
                int rowCount = 0;
                string message = "<html><head></head><body><table border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"font-family: sans-serif; font-size: 13px; color: #222; border-collapse: collapse;\">";
                for (int i = 0; i < request.Values.Length; i++)
                {
                    string name = request.Names[i];
                    //string nodeName = string.Empty;
                    int index = request.FieldIds[i].LastIndexOf('_') + 1;
                    if (index > 0)
                    {
                        string fullId = request.FieldIds[i].Substring(index, request.FieldIds[i].Length - index);

                        if (fullId == autoResponderId)
                        {
                            autoResponderEmail = request.Values[i];
                        }

                        int id;
                        if (int.TryParse(fullId, out id))
                        {
                            Node node = new Node(id);
                            if (node != null)
                            {
                                //nodeName = node.Name;
                                name = node.Name;
                                try
                                {
                                    if (node.GetProperty("label").Value.Length > 0)
                                    {
                                        name = node.GetProperty("label").Value;
                                    }
                                    else if (node.NodeTypeAlias == "PliableText")
                                    {
                                        if (node.GetProperty("defaultValue").Value.Length > 0)
                                        {
                                            name = node.GetProperty("defaultValue").Value;
                                        }
                                    }
                                }
                                catch { }
                            }
                        }
                    }
                    if (name.Length > 0)
                    {
                        rowCount++;
                        try
                        {
                            if (rowCount % 2 == 0)
                            {
                                message += string.Format("<tr><td style=\"background-color: #ffffff; padding: 4px 8px; vertical-align: top; width: 120px;\">{0}</td><td style=\"background-color: #ffffff; padding: 4px 8px; vertical-align: top;\">{1}</td></tr>", name, request.Values[i]);
                            }
                            else
                            {
                                message += string.Format("<tr><td style=\"background-color: #ebf5ff; padding: 4px 8px; vertical-align: top; width: 120px;\">{0}</td><td style=\"background-color: #ebf5ff; padding: 4px 8px; vertical-align: top;\">{1}</td></tr>", name, request.Values[i]);
                            }
                        }
                        catch { }
                    }
                }
                message += "</table></body></html>";

                // determine the to address
                string emailTo = page.GetProperty("toAddress").Value;

                if (string.IsNullOrEmpty(emailTo))
                {
                    emailTo = ConfigurationManager.AppSettings["PliableForm.defaultToAddress"];
                    if (emailTo == null)
                    {
                        emailTo = umbraco.library.GetDictionaryItem("PliableForm.defaultToAddress");
                    }
                }
                string subject = page.GetProperty("emailSubject").Value;
                if (string.IsNullOrEmpty(subject))
                {
                    subject = ConfigurationManager.AppSettings["PliableForm.defaultEmailSubject"];
                    if (subject == null)
                    {
                        subject = umbraco.library.GetDictionaryItem("PliableForm.defaultEmailSubject");
                    }
                }

                req = request;
                MatchEvaluator reEval = new MatchEvaluator(this.replaceFields);

                // send the email
                SendEmailMessage(emailTo, message, Regex.Replace(subject, "{([^}]+)}", reEval), true);
                nr.Result = "2";

                // send the autoresponder email
                if (!string.IsNullOrEmpty(autoResponderEmail))
                {
                    string ARbody = string.Empty;
                    try
                    {
                        ARbody = page.GetProperty("autoResponderText").Value;
                    }
                    catch { /* Swallow Exception */ }

                    bool ARisHtml = false;
                    if (string.IsNullOrEmpty(ARbody))
                    {
                        ARbody = page.GetProperty("autoResponderHtml").Value;
                        ARbody = ARbody.Replace("[OriginalMessage]", message.Replace("<html><head></head><body>", string.Empty).Replace("</body></html>", string.Empty));
                        ARisHtml = true;
                    }

                    ARbody = Regex.Replace(ARbody, "{([^}]+)}", reEval);
                    SendEmailMessage(autoResponderEmail, ARbody, Regex.Replace(page.GetProperty("autoResponderSubject").Value, "{([^}]+)}", reEval), ARisHtml);
                }

            }
            catch (Exception ex)
            {
                nr.Result = "3";

                var innerEx = string.Empty;
                if(ex.InnerException != null)
                {
                    innerEx = ex.InnerException.StackTrace;
                }
                nr.Msg = string.Format("Message: {0} StackTrace: {1} {2}", ex.Message, ex.StackTrace, innerEx);
            }

            return nr;
        }
Example #14
0
        /// <summary>
        /// Method for getting multiple image urls
        /// </summary>
        /// <param name="node">Node with image property</param>
        /// <param name="imagePropertyAlias">Property alias</param>
        /// <param name="cropUpAlias">CropUp alias (optional)</param>
        /// <returns>Collection of string</returns>
        public static List<string> GetImagesUrls(Node node, string imagePropertyAlias, string cropUpAlias = null)
        {
            var imageUrls = new List<string>();
            if (!string.IsNullOrEmpty(node.GetProperty<string>(imagePropertyAlias)))
            {
                foreach (var imageId in node.GetProperty<string>(imagePropertyAlias).Split(','))
                {
                    var image = ApplicationContext.Current.Services.MediaService.GetById(int.Parse(imageId));
                    imageUrls.Add(GetCropUpUrl(image, cropUpAlias));
                }
            }

            return imageUrls;
        }
 Node GetTemplateNode(Node nMail)
 {
     // Determine if any basic template has been selected for this email
     string templateId = nMail.GetProperty(EnmUmbracoPropertyAlias.emailTemplate);
     int nodeId;
     if (int.TryParse(templateId, out nodeId))
         return new Node(nodeId);
     else
         return null;
 }
Example #16
0
        /// <summary>
        /// Method for getting an image url with a specified width and height
        /// </summary>
        /// <param name="node">Node with image property</param>
        /// <param name="imagePropertyAlias">Property alias</param>
        /// <param name="width">The width of the image in pixels</param>
        /// <param name="height">The height of the image in pixels</param>
        /// <returns>string</returns>
        public static string GetImageUrl(Node node, string imagePropertyAlias, int width = 0, int height = 0)
        {
            string imageUrl = string.Empty;
            if (!string.IsNullOrEmpty(node.GetProperty<string>(imagePropertyAlias)))
            {
                var image =
                    ApplicationContext.Current.Services.MediaService.GetById(node.GetProperty<int>(imagePropertyAlias));

                return GetCropUpUrl(image, width, height);
            }

            return imageUrl;
        }
        /// <summary>
        /// Create an email object, but load the basic configuration from an umbraco email node
        /// </summary>
        /// <param name="umbracoEmailNodeId">The Umbraco node id of the email to load the configuration from</param>
        /// <param name="values">Contains the values to replace the tags in the email with</param>
        Email(int umbracoEmailNodeId, List<EmailTag> values = null)
        {
            // Input validation
            if (umbracoEmailNodeId == 0)
                throw new ArgumentException(String.Format("Invalid Umbraco Node Id '{0}' (must be >= 1000)", umbracoEmailNodeId), "mailNodeID");

            // Validate the specified node
            Node nMail = new Node(umbracoEmailNodeId);
            if (nMail == null || nMail.Id == 0)
                throw new Exception(String.Format("The specified Umbraco Node with id '{0}' does not exist", umbracoEmailNodeId));

            Initialize(values);

            // Optional: If SMTP credentials have been entered from Umbraco, use them instead of the default web.config's settings
            var nEmails = nMail.Parent;
            var p = nEmails.GetProperty("smtpHost");
            if (p != null && !String.IsNullOrEmpty(p.Value))
                _smtp.Host = p.Value;
            p = nEmails.GetProperty("smtpLogin");
            if (p != null && !String.IsNullOrEmpty(p.Value))
            {
                _smtp.UseDefaultCredentials = false;
                var c = new System.Net.NetworkCredential();
                c.UserName = p.Value;
                p = nEmails.GetProperty("smtpPassword");
                if (p != null && !String.IsNullOrEmpty(p.Value))
                    c.Password = p.Value;
                _smtp.Credentials = c;
                int port;
                p = nEmails.GetProperty("smtpPort");
                if (p != null && int.TryParse(p.Value, out port) && port > 0)
                    _smtp.Port = port;
            }

            // Default: NO header data or elements
            HeadTag = "";

            // Add the email template ID so it will get logged to the DB
            EmailId = nMail.Id;
            // Load sender
            From = GetEmailAdressesFromUmbracoProperty(nMail, EnmUmbracoPropertyAlias.from).FirstOrDefault();
            // Load to receivers
            foreach (var emailadres in GetEmailAdressesFromUmbracoProperty(nMail, EnmUmbracoPropertyAlias.to))
                To.Add(emailadres);
            // Load replyto list
            foreach (var emailadres in GetEmailAdressesFromUmbracoProperty(nMail, EnmUmbracoPropertyAlias.replyTo))
                ReplyToList.Add(emailadres);
            // Load CC recipients
            foreach (var emailadres in GetEmailAdressesFromUmbracoProperty(nMail, EnmUmbracoPropertyAlias.cc))
                CC.Add(emailadres);
            // Load BCC recipients
            foreach (var emailadres in GetEmailAdressesFromUmbracoProperty(nMail, EnmUmbracoPropertyAlias.bcc))
                BCC.Add(emailadres);

            // Get the subject header and replace tags
            Subject = ReplaceTags(nMail.GetProperty(EnmUmbracoPropertyAlias.subject));

            // Load the body template (including parent template if selected)
            Body = BuildEmailBody(nMail);

            // Determine if any attachment is to be sent with the e-mail
            String attachments = nMail.GetProperty(EnmUmbracoPropertyAlias.attachments);
            if (!String.IsNullOrEmpty(attachments))
                // Loop through all picked Umbraco media items
                foreach (String attachment in attachments.Split(','))
                {
                    int attachmentId;
                    // Valid media item?
                    if (!string.IsNullOrEmpty(attachment) && int.TryParse(attachment.Trim(), out attachmentId) && attachmentId > 0)
                    {
                        var a = new Attachment(attachmentId);
                        if (!a.IsEmpty)
                            Attachments.Add(a);
                    }
                }

            // If any text-only version has been specified, include it
            AlternativeView = ReplaceTags(nMail.GetProperty(EnmUmbracoPropertyAlias.textVersion));

            // Determine if any template has been selected for the email
            string templateID = nMail.GetProperty(EnmUmbracoPropertyAlias.emailTemplate);
            int id;
            if (!string.IsNullOrEmpty(templateID) && int.TryParse(templateID, out id))
            {
                // A basic template has been selected for this e-mail, fetch the node
                Node nTemplate = new Node(id);
                // Attempt to load the umbraco node property containing the CSS
                string CSS = nTemplate.GetProperty(EnmUmbracoPropertyAlias.css);
                if (!String.IsNullOrEmpty(CSS))
                {
                    if (IsInlinerDisabled(nMail))
                        // We are not inlining our CSS, so place the style tag in the header of the e-mail.
                        // The recipient will have to interpret the stylesheet for the e-mail
                        HeadTag = "<style>" + CSS + "</style>";
                }
            }
        }
Example #18
0
        void ExamineEventsInternal_GatheringNodeData(object sender, IndexingNodeDataEventArgs e)
        {
            //need to fudge rte field so that we have internal link nodeids in the internal index
            var rteFields = RteFields;

            if (e.IndexType == IndexTypes.Content)
            {
                var d = new Document(e.NodeId);
                foreach (var rteField in rteFields)
                {
                    if (d.getProperty(rteField) != null && d.getProperty(rteField).Value != null)
                    {
                        var rteEncoded = HttpUtility.HtmlEncode(d.getProperty(rteField).Value.ToString().Replace("localLink:", "localLink: ").Replace("}", " } "));
                        e.Fields.Add("rteLink" + rteField, rteEncoded);
                    }
                }

                var treePickerFields = TreePickerFields;
                foreach (var treePickerField in treePickerFields)
                {
                    if (e.Fields.ContainsKey(treePickerField))
                    {
                        var content = e.Fields[treePickerField];

                        // if it's a csv type and there's more than one item,
                        // separate with a space so the nodes are indexed separately
                        if (content.Contains(","))
                        {
                            content = content.Replace(",", " ");
                        }
                        else
                        {
                            // if it's an XML type tree picker, get the xml and transform into a space separated list
                            var node = new Node(e.NodeId);
                            var value = node.GetProperty(treePickerField).Value;

                            if (value.Contains("<MultiNodePicker"))
                            {
                                var dynamicXml = new DynamicXml(value);
                                content = string.Join(" ", dynamicXml.Descendants().Select(de => de.InnerText));
                            }
                        }
                        e.Fields[treePickerField] = content;
                    }
                }

                e.Fields.Add("IsPublished", d.Published.ToString());
            }
        }
        /// <summary>
        /// Loads the unparsed body text for the e-mail and returns it as a single (unparsed) string.
        /// </summary>
        /// <param name="nMail">The e-mail node</param>
        /// <returns>Unparsed body string</returns>
        string BuildEmailBody(Node nMail)
        {
            #region 1. Build the basic template of the email. Here we will determine where the email content will be placed and we will parse all email tags
            // Retrieve the template from the email node in Umbraco
            string bodyContent;
            try
            {
                // Try as grid
                bodyContent = GetContentAsGrid(nMail);
            }
            catch (Exception ex)
            {
                // Non-grid
                bodyContent = nMail.GetProperty(EnmUmbracoPropertyAlias.body);
                System.Diagnostics.Debug.WriteLine("Error loading 'Body' content: " + ex.ToString());
            }

            // Determine if any basic template has been selected for this email
            var nTemplate = GetTemplateNode(nMail);
            string CSS = String.Empty;
            if (nTemplate != null && nTemplate.Id > 0)
            {
                // Place the email body in the basic template. The special contenttag in the baisc template will be used for this
                var template = nTemplate.GetProperty(EnmUmbracoPropertyAlias.templateMail);
                if (String.IsNullOrEmpty(template))
                    // Perhaps this Umbraco installation still has the old template alias
                    template = nTemplate.GetProperty(EnmUmbracoPropertyAlias.template);
                if (!String.IsNullOrEmpty(template))
                    bodyContent = template.Replace(Constants.TEMPLATE_CONTENT_TAG, bodyContent);
                // Inline CSS?
                if (nTemplate.GetProperty(EnmUmbracoPropertyAlias.disableCSSInlining) != "1")
                    // We will inline the CCS!
                    CSS = nTemplate.GetProperty(EnmUmbracoPropertyAlias.css);
            }

            // Determine the ID of the email we are about to send.
            // This is tricky because the log ID is an identity column. Furthermore if two emails are sent at the same time, the ID might be lower then it should be.
            // For now we will make an assumption regarding the ID, but this should be done in a more reliable fashion in the future
            string newID = GetNextLogMailId();

            bodyContent = bodyContent.Replace("href=\"/umbraco/" + Constants.TAG_PREFIX, "href=\"" + Constants.TAG_PREFIX)
                                     .Replace("src=\"/umbraco/" + Constants.TAG_PREFIX, "src=\"" + Constants.TAG_PREFIX);

            // Parse e-mail body
            bodyContent = Helper.ParseText(bodyContent, _listOfTags);
            #endregion

            #region 2.We are done parsing the basic HTML template of the document. Now proces all links and images
            // Load the entire HTML body as an HTML document.
            var doc = new HtmlAgilityPack.HtmlDocument();
            doc.LoadHtml(bodyContent);

            // Process all hyperlinks
            ProcessHyperlinks(ref doc, newID);

            // Process all images
            ProcessImages(ref doc);

            // Inline all specified CSS styles
            if (!String.IsNullOrEmpty(CSS))
                InlineCSS(CSS, ref doc);
            #endregion

            // We are done performing all the required HTML magic
            bodyContent = doc.DocumentNode.OuterHtml;

            // Perform an extra check to make sure that browser-specific comment tags are also parsed (which unfortunately cannot be handled by the HTML agility pack)
            bodyContent = bodyContent.Replace("src=\"/", "src=\"" + Helper.WebsiteUrl + "/")
                                     .Replace("href=\"/", "href=\"" + Helper.WebsiteUrl + "/")
                                     .Replace("background=\"/", "background=\"" + Helper.WebsiteUrl + "/");

            // Determine of there are any "view online" hyperlinks in the document. These require a special webversion URL.
            if (bodyContent.Contains(Constants.TEMPLATE_WEBVERSIONURL_TAG))
            {
                // Generate a simple authentication hash based on the ID of the email
                String authenticationHash = HttpUtility.UrlEncode(Security.Hash(newID));
                // Replace the webversion tag with the real URL. The client may open the URL and can then see the webversion of the email.
                bodyContent = bodyContent.Replace(Constants.TEMPLATE_WEBVERSIONURL_TAG, Helper.GenerateWebversionUrl(newID));
            }

            #region 3. Place a tracking tag at the bottom of the email. When the image is loaded from the server it will trigger a "view" for the email
            if (Helper.IsStatisticsModuleEnabled && !IsLoggingDisabled) // Both the module and logging need to be enabled for this feature to work
            {
                //var tag = doc.CreateElement("img");
                //tag.Attributes.Add("src", Helper.WebsiteUrl + Constants.STATISTICS_IMAGE + "?&" + Constants.STATISTICS_QUERYSTRINGPARAMETER_MAILID + "=" + newID + "&" + Constants.STATISTICS_QUERYSTRINGPARAMETER_ACTION + "=" + EnmAction.view.ToString());
                //tag.Attributes.Add("style", "opacity:0"); // Make the tag not "visible", but it still needs to be rendered by the client (else the image won't get loaded) so make sure not to use display:none
                //doc.DocumentNode.LastChild.AppendChild(tag);

                string statTracker = "<img style=\"opacity:0;\" src=\"" + Helper.WebsiteUrl + Constants.STATISTICS_IMAGE + "?" + Constants.STATISTICS_QUERYSTRINGPARAMETER_MAILID + "=" + newID + "&" + Constants.STATISTICS_QUERYSTRINGPARAMETER_ACTION + "=" + EnmAction.view.ToString() + "\" />";
                bodyContent += statTracker; // Place the stat tracker image at the end
            }
            #endregion

            // Parsinc complete
            return bodyContent;
        }
        void ContentService_Publishing(IPublishingStrategy sender, PublishEventArgs<IContent> e)
        {
            // When content is renamed or 'umbracoUrlName' property value is added/updated
            foreach (IContent content in e.PublishedEntities)
            {
#if !DEBUG
                try
#endif
                {
                    Node node = new Node(content.Id);
                    if (node.Name != content.Name && !string.IsNullOrEmpty(node.Name)) // If name is null, it's a new document
                    {
                        // Rename occurred
                        UrlTrackerRepository.AddUrlMapping(content, node.GetDomainRootNode().Id, node.NiceUrl, AutoTrackingTypes.Renamed);

                        if (ClientTools != null)
                            ClientTools.ChangeContentFrameUrl(string.Concat("/umbraco/editContent.aspx?id=", content.Id));
                    }
                    if (content.HasProperty("umbracoUrlName"))
                    {
                        string contentUmbracoUrlNameValue = content.GetValue("umbracoUrlName") != null ? content.GetValue("umbracoUrlName").ToString() : string.Empty;
                        string nodeUmbracoUrlNameValue = node.GetProperty("umbracoUrlName") != null ? node.GetProperty("umbracoUrlName").Value : string.Empty;
                        if (contentUmbracoUrlNameValue != nodeUmbracoUrlNameValue)
                        {
                            // 'umbracoUrlName' property value added/changed
                            UrlTrackerRepository.AddUrlMapping(content, node.GetDomainRootNode().Id, node.NiceUrl, AutoTrackingTypes.UrlOverwritten);

                            if (ClientTools != null)
                                ClientTools.ChangeContentFrameUrl(string.Concat("/umbraco/editContent.aspx?id=", content.Id));
                        }
                    }
                }
#if !DEBUG
                catch (Exception ex)
                {
                    ex.LogException();
                }
#endif
            }
        }
Example #21
0
        public static bool HasVendorAccess(int pageId)
        {
            var page = new umbraco.NodeFactory.Node(pageId);

            if (page.GetProperty("vendorOnly") != null)
            {
                var memberProvider = (IMemberProvider)MarketplaceProviderManager.Providers["MemberProvider"];
                var member = memberProvider.GetCurrentMember();

                var vendorOnly = page.GetProperty("vendorOnly").Value == "1" ? true : false;
                if (vendorOnly)
                {
                    if (member.IsDeliVendor)
                        return true;
                    else
                        return false;
                }
                return true;
            }
            return true;
        }
Example #22
0
        /// <summary>
        /// Guesses the NiceUrl based on the node id.
        /// </summary>
        /// <param name="nodeId">The node id.</param>
        /// <returns>Returns a guestimate of the NiceUrl for a node id.</returns>
        /// <remarks>
        /// GuessNiceUrl is not very performant when attempting to guess the URL for unpublished nodes.
        /// Do not over-use this method. It makes many database calls and will be slow!
        /// </remarks>
        public static string GuessNiceUrl(int nodeId)
        {
            var node = new Node(nodeId);
            var niceUrl = node.NiceUrl;
            var published = node.Path != null;

            if (!niceUrl.StartsWith(Constants.Common.HTTP) || !published)
            {
                const string URLNAME = Constants.Umbraco.Content.UrlName; // "umbracoUrlName";
                var hasDomain = false;
                var domain = HttpContext.Current.Request.ServerVariables["SERVER_NAME"].ToLower();
                string nodeName;
                string nodePath;
                int nodeParentId;

                // if the node is published, get from the nodeFactory
                if (published)
                {
                    nodeName = node.GetProperty(URLNAME) != null && !string.IsNullOrEmpty(node.GetProperty(URLNAME).Value) ? node.GetProperty(URLNAME).Value : node.Name;
                    nodePath = node.Path;
                    nodeParentId = node.Parent != null ? node.Parent.Id : uQuery.RootNodeId;
                }
                else
                {
                    // otherwise, get from the Document object.
                    var doc = new umbraco.cms.businesslogic.web.Document(nodeId);
                    nodeName = doc.getProperty(URLNAME) != null && doc.getProperty(URLNAME).Value != null && !string.IsNullOrEmpty(doc.getProperty(URLNAME).Value.ToString()) ? doc.getProperty(URLNAME).Value.ToString() : doc.Text;
                    nodePath = doc.Path;
                    nodeParentId = doc.ParentId;
                }

                // check if the node has a domain associated.
                if (UmbracoSettings.UseDomainPrefixes)
                {
                    // get the path
                    var path = nodePath.Split(Constants.Common.SLASH);

                    // loop through each part of the path in reverse order
                    for (int i = path.Length - 1; i >= 0; i--)
                    {
                        int partId;
                        if (int.TryParse(path[i], out partId))
                        {
                            var domains = umbraco.cms.businesslogic.web.Domain.GetDomainsById(partId);
                            if (domains != null && domains.Length > 0)
                            {
                                hasDomain = true;
                                domain = domains[0].Name;
                                break;
                            }
                        }
                    }
                }

                // if the node is unpublished...
                if (!published)
                {
                    // get the published node for the parent node.
                    var parentNode = new Node(nodeParentId);
                    if (parentNode.Path != null || (nodeParentId == uQuery.RootNodeId && !hasDomain))
                    {
                        int level = parentNode.Path.Split(Constants.Common.COMMA).Length;
                        string parentUrl = nodeParentId > 0 && !(level == 2 && GlobalSettings.HideTopLevelNodeFromPath) ? parentNode.NiceUrl : string.Empty;
                        string urlName = string.Concat(Constants.Common.SLASH, url.FormatUrl(nodeName.ToLower()));
                        string fileExtension = GlobalSettings.UseDirectoryUrls ? string.Empty : Constants.Common.DOTASPX;

                        // construct the NiceUrl for the unpublished node.
                        niceUrl = string.Concat(parentUrl.Replace(Constants.Common.DOTASPX, string.Empty), urlName, fileExtension);
                    }
                }

                // if the node has a domain, and is unpublished, use the domain.
                if (niceUrl == Constants.Common.HASH && hasDomain)
                {
                    niceUrl = string.Concat(Constants.Common.HTTP, domain);
                }

                // if the NiceUrl doesn't start with 'http://' (and isn't '#') then prepend it.
                if (!niceUrl.StartsWith(Constants.Common.HTTP) && niceUrl != Constants.Common.HASH)
                {
                    niceUrl = string.Concat(Constants.Common.HTTP, domain, niceUrl);
                }
            }

            return niceUrl;
        }
Example #23
0
    public static List<int> GetRelated(int umbracoNodeId, string matchProperty, string nta)
    {
        var root = new Node(umbracoNodeId);
        var results = new List<int>();

        if (root != null)
        {
            string dta = root.NodeTypeAlias;
            var searcher = ExamineManager.Instance.SearchProviderCollection["RelatedContentSearcher"];
            var searchCriteria = searcher.CreateSearchCriteria(Examine.SearchCriteria.BooleanOperation.Or);

            string luceneString = "(__NodeTypeAlias: " + nta + " AND parentID: " + umbracoNodeId + ") ";

            var matchPropertyValue = root.GetProperty(matchProperty);
            if (matchPropertyValue != null)
            {
                luceneString = luceneString + " AND " + GetLuceneQuery(matchProperty, matchPropertyValue.Value);
            }

            if (!String.IsNullOrEmpty(luceneString))
            {
                var query = searchCriteria.RawQuery(luceneString);
                var searchResults = searcher.Search(query).ToList().OrderByDescending((sr => (sr.Fields.ContainsKey("publicationDate") ? sr.Fields["publicationDate"] : "")));

                foreach (var sr in searchResults)
                {
                    //weird date parsing stuff because examine seems to change the format it saves dates in for NO BLOODY REASON.
                    var dt = DateTime.MinValue;

                    if (sr.Fields.ContainsKey("publicationDate"))
                    {
                        if (!DateTime.TryParseExact(sr.Fields["publicationDate"].Substring(0, 8), "yyyyMMdd", CultureInfo.CurrentCulture, DateTimeStyles.None, out dt))
                        {
                            DateTime.TryParse(sr.Fields["publicationDate"], out dt);
                        }
                    }

                    if (GetFieldValue(sr, "id") != umbracoNodeId.ToString() && results.Count() < 6)
                    {
                        results.Add(Convert.ToInt32(GetFieldValue(sr, "id")));
                    }
                }
            }
        }

        return results;
    }