BlogEngine.Net Extensions How-To part 02, Enhancing Post View Count Extension

by mosessaur| 04 March 2008| 7 Comments

Couple of days ago, I've walked through how to build simple BlogEngine Extension. Today I'll explore an advanced feature of BlogEngine Extensions which is provided settings your own extensions.

What is Extension Settings:
Settings are parameters user can provide to an extension to manage its behaviour. For example in my PostViews Extension, I'll provide settings that will allow user to exclude rage of IP addresses from accumulating any post view count. This setting is provided by the extension, and defined/filled by user.

Extension Setting Types:
I was able to categorize extension settings into 2 types:

  1. Scalar Extension Settings:
    Only single value per parameter will be added. This will be reflected on the settings web form as one text box per parameter which will only accept single value. To enable this feature you should set ExtensionSettings.IsScalar=true
  2. Multi Valued Extension Settings:
    Will allow multi value per parameter to be added. Just as Tabular settings. This will be reflected on the settings web form as list of values displayed on GridView. You can add new settings, edit or delete existing ones. To enable this feature you should set ExtensionSettings.IsScalar=false which is currently the default value.

PostViews Extension we are exploring now, has Scalar Extension Settings. The final results of your settings will be displayed as web from with simple text box entry fields:
PostViewsExtensionSettingsForm

Defining Extension Settings:
BlogEngine provide set of simple APIs to enable you define your extension settings easly. I'll explore few of these APIs that I used to define PostViews Extension Settings:

  1. ExtensionSettings.AddParameter: This is an overloaded method. Basically adds a parameter to extenssion which will be displayed in the entry form as a text box. Through variations of overloads, you can define parameter name which is mandatory, parameter label (label of the field), maximum length of the parameter, is it mandatory (required) and if it is a key field.
  2. ExtensionSettings.AddValue & ExtensionSettings.AddValues: These methods are used to define default values to extension parameters. If the Extension is scalar, then just one and only record is saved. If the extension is multivalued, then everytime you call any of these methods you add a new row to the parameter list.
  3. Help property: This is a free text property can be HTML. This will display help box on the right. You can use it to describe briefly how is the extension can be configured using your settings.
    extensionsettingshelpbox

Coding Time:
Extension Settings should be defined uopn Extension instantiation, which make Constructor best place for such thing.

   1: public PostViewes()
   2: {
   3:     Post.Serving += new EventHandler<ServingEventArgs>(OnPostServing);
   4:  
   5:     //Init Extension Settings
   6:     BuildSettings();
   7: }
   8: private void BuildSettings()
   9: {
  10:     //Create ExtensionSettings with this Type Name
  11:     ExtensionSettings settings = new ExtensionSettings(this.GetType().Name);
  12:     //Define settings as Scalar
  13:     settings.IsScalar = true;
  14:     //Define 1st Parameter Name="AuthenticatedOnly", Label="Authenticated only", Maxlength=5 characters, Required=Yes
  15:     settings.AddParameter("AuthenticatedOnly", "Authenticated only", 5, true);
  16:     //Define 2nd Parameter Name="ExecludedIPs", Label="Execlude IPs" as link to external tool, Maxlength=255 characters, Required=No
  17:     settings.AddParameter("ExecludedIPs", "<a href=\"https://www.google.com/support/googleanalytics/bin/answer.py?answer=55572\" target=\"_blank\">Execlude IPs</a>", 255, false);
  18:     //Adding default values
  19:     settings.AddValues(new string[] {"True",""});
  20:     //Build Help Text
  21:     settings.Help = "<p>Set <strong>Authenticated Only</strong> field to <strong>True</strong> if you wish " +
  22:         "<strong>only authenticated users</strong> to view total number of views of each post.<br/>" +
  23:          "Set <strong>Execlude IPs(regex)</strong> field if you wish to execlude range of IP addresses "+
  24:          "from accumulating post view count. This is Regular Expression field.</p>" +
  25:          "You can use <a href=\"https://www.google.com/support/googleanalytics/bin/answer.py?answer=55572\" target=\"_blank\">this tool</a> "+
  26:          "to generate your range of IPs ";
  27:  
  28:     //Import Settings into BlogEngine
  29:     ExtensionManager.ImportSettings(settings);
  30:  
  31:     //Retrieve Settings From BlogEngine int local static field to be used later in event handlers
  32:     _settings = ExtensionManager.GetSettings(this.GetType().Name);
  33: }

Of course you defined extension settings to be used to control your extension behavior. So I've modified the event handler to apply the use of extension settings, bellow is the code of the modifed OnPostServing Event Handler:

   1: private void OnPostServing(object sender, ServingEventArgs e)
   2: {
   3:     IPublishable ipub = ((IPublishable)sender);
   4:  
   5:     string body = String.Empty; 
   6:  
   7:     //Check For Single Post View, When viewing Specific Post, basically through post.aspx
   8:     if (e.Location == ServingLocation.SinglePost)
   9:     {
  10:         if (File.Exists(_FileName))
  11:         {
  12:             string pattern = _settings.GetSingleValue("ExecludedIPs");
  13:             string ip = HttpContext.Current.Request.UserHostAddress;
  14:             bool matchedIp = (!string.IsNullOrEmpty(pattern) && Regex.IsMatch(ip, pattern));
  15:             
  16:             //Do not count view of authenticated users and users who have IPs match execluded IPs pattern
  17:             if (!matchedIp && !HttpContext.Current.Request.IsAuthenticated)
  18:             {
  19:                 int viewCount;
  20:                 //Fetch out total views of current viewing post.
  21:                 Dictionary<string, int> posts = IncrementPostViewCount(ipub.Id.ToString(), out viewCount);
  22:  
  23:                 //Save list of posts in Xml File with new counted post.
  24:                 WriteToXml(posts);
  25:  
  26:                 //Override the body of the post (temporary) to display total views
  27:                 body = String.Format("<br/> Views({0})", viewCount);
  28:             }
  29:             else
  30:             {
  31:                 int viewCount = GetPostViewCount(ipub.Id.ToString());
  32:  
  33:                 //Override the body of the post (temporary) to display total views
  34:                 body = String.Format("<br/> Views({0})", viewCount);
  35:             }
  36:         }
  37:     }
  38:     //Check For Post List View, basically through main default.aspx or using postlist.ascx usercontrol
  39:     else if (e.Location == ServingLocation.PostList)
  40:     {
  41:         int viewCount = GetPostViewCount(ipub.Id.ToString());
  42:         
  43:         //Override the body of the post (temporary) to display total views
  44:         body = String.Format("<br/> Views({0})", viewCount);
  45:     }
  46:     
  47:     if (bool.Parse(_settings.GetSingleValue("AuthenticatedOnly")) && !HttpContext.Current.Request.IsAuthenticated)
  48:         return;
  49:         
  50:     e.Body += body;
  51: }

That was all for this post. If I got a chance later, I'll explore the non scalar extensions demonistrating that using an outof the box extension that is provided by BlogEngine like BBCode extension.

You can download the code here (2.61 kb) and explore the full solution.

kick it on DotNetKicks.com

Comments

mitru
mitru Romania on 5/29/2008 11:34 PM Hi,
how do I use your extension? I don't have the edit link in extensions manager, what's the problem?
mosessaur
mosessaur Egypt on 5/30/2008 2:05 AM Well, make sure you are logged in as Administrator when you browse extension page. Because it should work normally, I have it working normally.
mitru
mitru Romania on 6/5/2008 2:23 PM It doesn't work, I'm an admin, no edit link, and then which tag should i use within my posts?
Daniel
Daniel Mexico on 6/8/2008 1:20 PM gracias por su valiosa información
Busby SEO Test
Busby SEO Test United States on 11/22/2008 1:57 PM ty for the information about blog engine.net....
prasenjit
prasenjit India on 11/23/2008 6:11 AM Good Work! Can u tell me as to how can i save the number of view in database. Please Help!
cariaja
cariaja United States on 6/30/2009 8:38 AM Hello, this is my first time i visit here. I found so many interesting in your blog especially on how to determine the topic. keep up the good work.

Add comment


(Will show your Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading