Moses' Blog

Living {.net} lifestyle

Muhammad Mosa

Moses' profile picture
Logo
Software Engineer.
MCT, MCSD.NET,
MCTS: .Net 2.0 Web, Windows, Distributed Applications
MCTS: .Net 3.5 WF Application Development
MCTS: WSS 3.0, MOSS 2007 Configuration & App Dev
MCPD: Enterprise Application Developer

Send mail My Live Space Moses on Facebook Twitter Moses on Technorati

Sponsors



Calendar

<<  November 2008  >>
MoTuWeThFrSaSu
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

View posts in large calendar

Recent Comments

Comment RSS

Community Credit

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

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

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

Posted: Mar 04 2008, 10:02 by mosessaur | Comments (4) RSS comment feed |
  • Currently 4.428571/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Filed under: ASP.NET | BlogEngine.Net
Social Bookmarks: E-mail | Kick it! | DZone it! | del.icio.us

Comments

Add comment


(For Gravatar icon)

  Country flag

biuquote
  • Comment
  • Preview
Loading