NewsLetter

Topics: Controls
Feb 5, 2009 at 1:56 PM
Hi,
I made an upgrade for the newletter widget

When the the mail exists in the system the user get option the unregister or go back...
 ascx & ascx.cs are attached

Enjoy,
Or Shnaider

The ascx code:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="widget.ascx.cs" Inherits="widgets_Newsletter_widget" %>

<div id="newsletterform" style="padding-right:5px;height:95px!important">
    <asp:Label ID="lblInstruction"  Text="<%$Resources:labels, newLetterInstruction %>" runat="server" ></asp:Label>
    <br />
 
  <asp:TextBox runat="server" ID="txtEmail" Width="160px" onfocus="CleanMsg();" />
  <asp:RequiredFieldValidator
    runat="server"
    ControlToValidate="txtEmail"
    ErrorMessage="<%$Resources:labels, enterEmail %>"
    Display="dynamic"
    ValidationGroup="newsletter" />
    
  <asp:RegularExpressionValidator
    runat="server"
    ControlToValidate="txtEmail"
    ErrorMessage="<%$Resources:labels, enterValidEmail %>"
    ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
    Display="dynamic"
    ValidationGroup="newsletter" />   
    
    
  <div style="text-align:center;vertical-align:bottom">
  <span style="height:10px;">&nbsp;</span><br />
    <asp:Button runat="server" ID="btnSave" Text="<%$Resources:labels, updateMe %>" ValidationGroup="newsletter"  OnClientClick="return beginAddEmail()" />
    <asp:Button runat="server" ID="btnUnregister" Text="<%$Resources:labels, newletterUnregister %>" ValidationGroup="newsletter"  OnClientClick="return beginUnregister()" style="display:none;text-align:center" />
    <asp:Button runat="server" ID="btnBack" Text="<%$Resources:labels, back %>" ValidationGroup="newsletter" OnClientClick="reload();return false;"  UseSubmitBehavior="true" style="display:none;text-align:center" />
 
  </div>
    
  <div id="newsletterthanks" style="display:none;text-align:center">
  <span style="height:10px;">&nbsp;</span><br />
  <h2 id="newsletteraction"><%=Resources.labels.newletterThanks%></h2>
</div>
</div>



<script type="text/javascript">

function CleanMsg()
{
     $('newsletterthanks').style.display = 'none';
}

function beginUnregister()
  {
    if(!Page_ClientValidate())
      return false;
      
    var arg = $('<%=txtEmail.ClientID %>').value + '_' + 'unreg';
    var context = 'newsletter';
    <%=Page.ClientScript.GetCallbackEventReference(this, "arg", "endUnregister", "context") %>;
    
    return false;
  }
 
  function reload()
  {
 
      
    $('<%=txtEmail.ClientID %>').value = "";
    $('<%=lblInstruction.ClientID %>').innerHTML = "<%=Resources.labels.newLetterInstruction %>";   
    $('<%=btnUnregister.ClientID %>').style.display="none";    
    $('<%=btnSave.ClientID %>').style.display="inline";
    $('<%=btnBack.ClientID %>').style.display="none";
     $('newsletterthanks').style.display = 'none';
    
    return false;
  }
 
  function endUnregister(arg, context)
  {
   
    if (arg == "true")
    {
        
        $('newsletterthanks').style.display = 'block';
       $('newsletterthanks').innerHTML = "<%=Resources.labels.newslettrerUnregister %>";
    }
    $('<%=lblInstruction.ClientID %>').innerHTML = "<%=Resources.labels.newLetterInstruction %>";       
    $('<%=txtEmail.ClientID %>').value = "";
     $('<%=btnUnregister.ClientID %>').style.display="none";    
    $('<%=btnSave.ClientID %>').style.display="inline";
    $('<%=btnBack.ClientID %>').style.display="none";
  }

  function beginAddEmail()
  {
    if(!Page_ClientValidate())
      return false;
      
     $('newsletterthanks').style.display = 'none';
    var arg = $('<%=txtEmail.ClientID %>').value + '_' + 'addmail';
    var context = 'newsletter';
    <%=Page.ClientScript.GetCallbackEventReference(this, "arg", "endAddEmail", "context") %>;
    
    return false;
  }
 
  function endAddEmail(arg, context)
  {
   
    if (arg == "false")
    {
      $('<%=lblInstruction.ClientID %>').innerHTML = "<%=Resources.labels.newslettrerEmailExists %>";
      $('<%=btnUnregister.ClientID %>').style.display="inline";      
       $('<%=btnSave.ClientID %>').style.display="none";
    }
    else
    {
         $('<%=btnUnregister.ClientID %>').style.display="none";
        $('newsletterthanks').style.display = 'block';
        $('newsletterthanks').innerHTML = "<%=Resources.labels.newletterThanks %>";
         $('<%=txtEmail.ClientID %>').value = "";
    }
   
    $('<%=btnBack.ClientID %>').style.display="inline";
  }
</script>

the cs:

#region using

using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Xml;
using BlogEngine.Core;
using System.Net.Mail;

#endregion

public partial class widgets_Newsletter_widget : WidgetBase, ICallbackEventHandler
{

   

    public override string Name
    {
        get { return "Newsletter"; }
    }

    public override bool IsEditable
    {
        get { return true; }
    }

    public override void LoadWidget()
    {

    }

    #region Event handling

    static widgets_Newsletter_widget()
    {
        Post.Saved += new EventHandler<SavedEventArgs>(Post_Saved);
    }

    static void Post_Saved(object sender, SavedEventArgs e)
    {
        Post post = (Post)sender;
        if (e.Action == SaveAction.Insert && post.IsPublished)
        {
            LoadEmails();                        
            foreach (XmlNode node in _Doc.SelectNodes("emails/email"))
            {
                MailMessage mail = CreateEmail(post);
                mail.To.Add(node.InnerText);                
                // Utils.SendMailMessageAsync(mail);
                Utils.SendMailMessage(mail);

            }
        }
    }

    private static MailMessage CreateEmail(Post post)
    {
        MailMessage mail = new MailMessage();
        mail.Subject = post.Title;        
        mail.Body = "<div dir=\"rtl\"> כתבה חדשה זמינה באתר<br /> <a href=\"" + post.AbsoluteLink + "\">" + post.Title + "</a><br />";
        mail.Body += post.Description;
        mail.Body += "<hr />";
        mail.Body += "הודעה זו התקבלה משום שנרשמת באתר  ";
        mail.Body += "<a href=\"" + Utils.AbsoluteWebRoot + "\">" + Utils.AbsoluteWebRoot + "</a>";
        mail.Body += "</div>";
        mail.From = new MailAddress(BlogSettings.Instance.Email, BlogSettings.Instance.Name);
        return mail;
    }

    #endregion

    #region Save and retrieve e-mails

    private static XmlDocument _Doc;
    private static string _FileName;

    private void AddEmail(string email)
    {
        try
        {
            LoadEmails();

            if (!DoesEmailExist(email))
            {
                XmlNode node = _Doc.CreateElement("email");
                node.InnerText = email;
                _Doc.FirstChild.AppendChild(node);

                _Callback = "true";
                SaveEmails();
            }
            else
            {
                //_Doc.FirstChild.RemoveChild(_Doc.SelectSingleNode("emails/email[text()='" + email + "']"));
                _Callback = "false";
                //SaveEmails();
            }
        }
        catch
        {
            _Callback = "false";
        }
    }

    private void RemoveEmail(string email)
    {
        try
        {
            LoadEmails();

            if (DoesEmailExist(email))
            {
                _Doc.FirstChild.RemoveChild(_Doc.SelectSingleNode("emails/email[text()='" + email + "']"));
                _Callback = "true";
                SaveEmails();
               
            }
            else
            {  
                _Callback = "false";
            }
        }
        catch
        {
            _Callback = "false";
        }
    }

    private bool DoesEmailExist(string email)
    {
        return _Doc.SelectSingleNode("emails/email[text()='" + email + "']") != null;
    }

    private static void LoadEmails()
    {
        if (_Doc == null || _FileName == null)
        {
            _FileName = Path.Combine(BlogSettings.Instance.StorageLocation, "newsletter.xml");
            _FileName = System.Web.Hosting.HostingEnvironment.MapPath(_FileName);

            if (File.Exists(_FileName))
            {
                _Doc = new XmlDocument();
                _Doc.Load(_FileName);
            }
            else
            {
                _Doc = new XmlDocument();
                _Doc.LoadXml("<emails></emails>");
            }
        }
    }

    private void SaveEmails()
    {
        using (MemoryStream ms = new MemoryStream())
        using (FileStream fs = File.Open(_FileName, FileMode.Create, FileAccess.Write))
        {
            _Doc.Save(ms);
            ms.WriteTo(fs);
        }
    }

    #endregion

    #region ICallbackEventHandler Members

    private string _Callback;

    /// <summary>
    /// Returns the results of a callback event that targets a control.
    /// </summary>
    /// <returns>The result of the callback.</returns>
    public string GetCallbackResult()
    {
        return _Callback;
    }

    /// <summary>
    /// Processes a callback event that targets a control.
    /// </summary>
    /// <param name="eventArgument">A string that represents an event argument to pass to the event handler.</param>
    public void RaiseCallbackEvent(string eventArgument)
    {
        _Callback = eventArgument;


        String email = _Callback.Split('_')[0];
        String action = _Callback.Split('_')[1];
        switch(action)
        {
            case "addmail":
                AddEmail(email);
                break;
            case "unreg":
                RemoveEmail(email);
                break;
           
        }
        
    }

    #endregion
}




Feb 8, 2009 at 1:23 PM
Edited Feb 8, 2009 at 1:34 PM
Hello,

Thank you for this widget. Not many people know how to utilize RSS feeds or are willing to learn, so this is a great solution.

I'm assuming this method should be something like:

private static MailMessage CreateEmail(Post post) { 
     MailMessage mail = new MailMessage(); 
     mail.Subject = post.Title; 
mail.Body = "There's a new post available. <a href=\"">" + post.Title + "</a>"; mail.Body += post.Description; mail.Body += ""; mail.Body += "You are receiving this e-mail because you have signed up for e-mail notifications at "; mail.Body += "<a href=\"">" + Utils.AbsoluteWebRoot + "</a>"; mail.From = new MailAddress(BlogSettings.Instance.Email, BlogSettings.Instance.Name); return mail; }


Also, I think this widget would be even better if the user had options on how to receive e-mails. Not everyone wants an e-mail every time a blog is post and would rather opt to receive a digest of them either daily, weekly or monthly.