Jarrett's Tech Blog
-
New jQuery Rater Plugin for Star Ratings
The jQuery Star Rating widget is a neat control to add to your website. It has many options that allow you to easily customize it. However, it's usage is based on a fully degradable form submission model which means you must use markup containing an option list. Unfortunately, this means it becomes quite complex to support a rating model that fires off an ajax request to submit a new rating. Therefore, the developer is left to worry about:
- Writing code on the server to generate the option list only for users that have not already rated
- If the user has already rated, the server must generate different markup, or set the widget to disabled
- The developer must write javascript to handle the widget callback and build an ajax request
- No built in support for rating count and updated rating result
- No built in support for a failed rating
To make life easier, I wrote the jQuery Rater Plugin that should reduce the complexity of implementing an ajax rating scenario.
jQuery Rater Plugin DemoFeatures
- Auto Ajax posting
- Supports rating update and rating count
- Shows previous rating before user has rated
- Markup is same for rated and unrated
- Supports step ratings (partial stars)
View the Demo Page
First, lets take a look at the markup which is contained in an ASP.NET user control. However, you could write this in your server language of choice. There are three things being set below. The width of the stars, the current rating, and the count of ratings.
The only markup elements required by the plugin are the "ui-rater-starsOff" and "ui-rater-starsOn" spans. Also, they must be contained within an element that has an id you can reference.
We only need to activate the plugin when the user has not already rated the entry.
The only option I've set is the address to post the rating to. When the user performs a rating, the plugin will automatically build an ajax request to the postHref. It includes the id and chosen rating value in the form post data.
This plugin does more with less code than the existing jQuery Star Rating Widget because it foregoes the degrade-ability in favor of ajax.
- Previous Javascript size: ui.core.packed.js 4KB + ui.stars.pack.js 4KB + rate.js 2KB = 10KB
- New Javascript size: jquery.rater.js 3KB (unpacked)
To see a full server implementation, see the source code of AtomSite.
Download jQuery Rater Plugin (javascript + demo html + image + sample server page)
-
New BlogSvc Release 0.2
This release includes an implementation of Atom Publishing Protocol on WCF 3.5. In the words of Tim Bray:
An Atompub implementation lets you create, retrieve, update, and delete (CRUD) Web Resources. ... Atompub starts with a Service Document, which contains one or more named Workspaces, which contain Collections, which are what you actually POST to in order to start up the CRUD process. So the idea is simple; have a collection that when you POST to it, creates a new publication.
The object model is based off of the Atom Syndication Format and the AtomPub specs. All of the objects are based off of Xml or the new XElement. Propeties are used to support strongly typed access to the data.
Atom Syndication Format Atom Publishing Protocol AtomCategory AppCategories AtomContent AppCollection AtomEntry* AppControl AtomFeed AppService AtomGenerator AppWorkspace AtomLink* AtomPerson Atom Threading Extension AtomSource ThreadInReplyTo AtomText * Extended This release should work in IIS6 or IIS7 with .NET 3.5. Also the SVC handler must support all verbs. Since AtomPub is RESTful, you'll need PUT and DELETE to go along with the usual GET and POST verbs.
The WCF service is built using the new Web Programming Model available in 3.5. However, it is designed to support normal web services as well (more on this in a future post). A neat WCF feature with this release is the support of media entries allowing a user to post images to a collection. I found the trick to supporting raw data on Carlos' blog. However, there is a catch. Anytime you want to accept unknown content types and known content types, you must only deal with Stream objects. For example, although CreateEntry will always return an AtomEntry document you must specify a Stream because the input could be an AtomEntry or say a JPG image.
[ServiceContract] public interface IAtomPub { [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "{workspaceName}/{collectionName}/{entryName}/media")] Stream RetrieveMedia(string workspaceName, string collectionName, string entryName); [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "{workspaceName}/{collectionName}")] Stream CreateEntry(string workspaceName, string collectionName, Stream stream); [WebGet(UriTemplate = "{workspaceName}/{collectionName}/{entryName}")] Stream RetrieveEntry(string workspaceName, string collectionName, string entryName); [WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "{workspaceName}/{collectionName}/{entryName}", Method = "PUT")] Stream UpdateEntry(string workspaceName, string collectionName, string entryName, Stream stream); [WebInvoke(UriTemplate = "{workspaceName}/{collectionName}/{entryName}", Method = "DELETE")] void DeleteEntry(string workspaceName, string collectionName, string entryName); [OperationContract] [WebGet(UriTemplate = "service")] AppService RetrieveService(); [WebGet(UriTemplate = "{workspaceName}/{collectionName}/category?scheme={scheme}")] AppCategories RetrieveCategories(string workspaceName, string collectionName, string scheme); [WebGet(UriTemplate = "{workspaceName}/{collectionName}")] AtomFeed RetrieveFeed(string workspaceName, string collectionName); }
You can direct it to a strongly typed implementation by checking the content type.
public Stream CreateEntry(string workspaceName, string collectionName, Stream stream) { string contentType = WebOperationContext.Current.IncomingRequest.ContentType; AtomEntry entry; if (contentType == Atom.ContentType || contentType == Atom.ContentTypeEntry) { entry = new AtomEntry(); XmlReader reader = new XmlTextReader(stream); entry.Xml = XElement.Load(reader); entry = CreateEntry(workspaceName, collectionName, entry); } else entry = CreateMedia(workspaceName, collectionName, stream); return GetStream(entry); }
IDs and Hrefs
- Blog.svc WCF Service
- UriTemplates
- Handling Entry or Media Resources
- WebLinks
- Object Model over .Net 3.5 SP1 Object Model
Test AtomPub and Atom and Threading auto links.
-
WCF Adds Root Node on IXmlSerializable Object
Has anybody else had trouble with WCF adding a root node on their objects that implement IXmlSerializable?
Here is the setup:
- Create a class that implements IXmlSerializable
public class Entry : IXmlSerializable { public XElement Xml { get; set; } public void ReadXml(XmlReader reader) { Xml = XElement.Load(reader, LoadOptions.SetBaseUri); } public void WriteXml(XmlWriter writer) { Xml.WriteTo(writer); } }
- Create a WCF service that returns the object.
[ServiceContract] [XmlSerializerFormat] public interface IService { [OperationContract] [WebGet(BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "{a}/{b}/{c}")] Entry RetrieveEntry(string a, string b, string c); } public class Service: IService { public Entry RetrieveEntry(string a, string b, string c) { return new Entry { Xml = new XElement("test", a + "/" + b + "/" + c); } } }
When hitting the service located at http://localhost/EntryService.svc/one/two/three, I expect to get the following xml:<test>one/two/three</test>
Instead, I always get the above xml wrapped in a root node as shown below:<Entry xmlns="http://schemas.datacontract.org/2004/07/EntryTest"> <test>one/two/three</test> </Entry>
- I've set the BodyStyle to Bare
- I've set the [XmlSerializerFormat] attribute
- I've tried putting [XmlRoot(null)] on the Entry class
Update (7/27): It appears you must use the XmlRootAttribute to accomplish this. Your WriteXml(XmlWriter writer) method can check to see if the root node was already added by the serializer, and if not add it:
public void WriteXml(XmlWriter writer) { //only start document if needed bool start = false; if (writer.WriteState == WriteState.Start) { start = true; writer.WriteStartDocument(); writer.WriteStartElement("root", "http://example.com"); } //TODO: custom serialization here if (start) { writer.WriteEndElement(); writer.WriteEndDocument(); } }
This allows the WriteXml to be usable even when the object isn't being serialized by the WCF serializer.
-
BlogSvc - New Blogging Service for .NET 3.5
Update: BlogService now has it’s own website, see http://blogsvc.net
I've started a new project on CodePlex called BlogService. Eventually, it will have it's own website at blogsvc.net. The point of this project is to provide a robust back-end for a blog site. It uses the provider model design pattern for abstracting the data layer similar to ASP.NET providers. I've uploaded a design diagram of the major classes. It also contains a WCF service that will expose multiple endpoints (soap, rest, json).
To kick things off, I created a community preview release that includes the following functionality:
- BlogProvider
- XmlBlogProvider
- Business (Blog, BlogSite, BlogComment, etc.)
- Configuration
- Unit Tests
- WCF Service
- Multi-site support
This release provides most of the functionality needed to support a front-end blogging site. It does not include web pages yet.
-
Team System Quick Start Links
Here are some great links to jump-start your learning about VSTS.
Visual Studio 2008 Product Comparison - Use this to figure out which version you or your team members will need.
Patterns & Practices: Team Development with TFS Guide - Great guide for understanding best practices around TFS. This is a must read.
Rob Carbon's Blog : Provides Links to Team System Resources
TFS Event Subscriptions - Tool to create nice customized email subscriptions to TFS events.
Visual Studio Team System 2008 Team Foundation Server Power Tools - Build notification, process template editor, custom check-in policy pack, and more.
Team System Rocks: Provides Tutorial Videos and Other Info
Open Source Addins on CodePlex - Large amount of community support projects with plugins and customizations for Team System.
Vertigo Software Blog: Visual Studio Team System: tips, tricks, and techniques - A good blog that contains common error messages and tips for customizing or extending the usage of team system. It also has a good comparison between the different editions of team system (for 2005 version but still relevant for 2008).
When and how does my solution go "offline"? - This blog helps explain how and why a solution will go offline. I particularly found the the registry setting useful when I could not bind my solution / projects to the server. Team Explorer thought the server was offline when it really wasn't.
-
Comments Security Hole in BlogEngine.NET 1.4
I found a hole in BlogEngine.NET that allows anyone to delete and approve comments.
UPDATE 7/11: Fixed in 1.4.0.12Verify the Hole
- Add a test comment to your blog
- Refresh the blog posting to retrieve latest source
- View source of blog posting
- Find guid of comment to delete (see line 103 below)
<div id="id_9c2b8578-1dde-421e-94ff-5ea7e0d82012" class="comment"> <p class="date">7/10/2008 4:13:35 PM</p> <p class="gravatar"><img src="https://www.gravatar.com/avatar/b642b4217b34b1e8d3bd915fc65c4452.jpg?s=80&d=..." alt="Test3" /></p> <p class="content">asfasdfafdasd sa afsdfdsaas </p> <p class="author"> Test3 <img src="/blogengine/pics/flags/us.png" class="flag" alt="us" /> </p> </div>
- Request a POST to BlogPostUrl.aspx?deletecomment=guid
- Refresh the page and notice comment is deleted
Patch the Hole
You can patch the hole by updating the Page_Load event in the CommentView.ascx.cs file by checking for an authenticated user (lines 117,118, & 127)
protected void Page_Load(object sender, EventArgs e) { if (Post == null) Response.Redirect(Utils.RelativeWebRoot); if (!Page.IsPostBack && !Page.IsCallback) { if (Page.User.Identity.IsAuthenticated) { if (Request.QueryString["deletecomment"] != null) DeleteComment(); if (!string.IsNullOrEmpty(Request.QueryString["approvecomment"])) ApproveComment(); if (!string.IsNullOrEmpty(Request.QueryString["approveallcomments"])) ApproveAllComments(); } string path = Utils.RelativeWebRoot + "themes/" + BlogSettings.Instance.Theme + "/CommentView.ascx";
Repeat the steps given above to verify that the hole has been patched.
In the process of adding OpenID support to the comment system in BlogEngine.NET I found myself deep in a rabbit hole of refactoring. This comment security issue is just one of the things I've found during my journey. I've reported the issue on the BlogEngine.NET Issue Tracker. I think it is important to point out that the patch above is just a quick fix. The proper solution is to put authorization checks in the business layer (the BlogEngine.Core.Post business object in this case).
-
Blog Comments
Notifications Ajax Preview coComments Captcha FlagImage? CheckAuthorName BbCode Impersonation
-
Add OpenID to BlogEngine.NET 1.4 Part 1
Update : there is no Part 2 as I switched to AtomSite for my blog engine.
Here is a guide on how to add OpenID support to BlogEngine.NET 1.4. This first blog post will detail how to use an OpenID account to login as an existing blog user via impersonation. I've used Andrew's blog post How to add OpenID support to BlogEngine.NET as a starting place.
Pros
- Quick, minimum changes required
- Retains support of blogging tools (such as Live Writer)
- Easy to understand and backwards compatible
Cons
- Not "true" OpenID integration
- Accounts are maintained separately
- Impersonation file is required
Step 1: Download latest release of dotnetopenid library
Step 2: Place DotNetOpenId.dll into Bin folder (if compiling BlogEngine.Web then add reference to project)
Step 3: Update Login.aspx page
- Add
<%@ Register Assembly="DotNetOpenId" Namespace="DotNetOpenId.RelyingParty" TagPrefix="RP" %>
- Replace
<asp:Login ID="Login1" runat="server" class="loginbox" />
with
<RP:OpenIdLogin ID="OpenIdLogin1" runat="server" onloggedin="OpenIdLogin1_LoggedIn" />
Step 4: Update Login.aspx.cs code behind file
- Replace
protected void Page_Load(object sender, EventArgs e) { if (Page.User.Identity.IsAuthenticated) { changepassword1.Visible = true; changepassword1.ContinueButtonClick += new EventHandler(changepassword1_ContinueButtonClick); lsLogout.Visible = true; Login1.Visible = false; Page.Title += Resources.labels.changePassword; } else { Login1.LoggedIn += new EventHandler(Login1_LoggedIn); Login1.FindControl("username").Focus(); } }
with
protected void Page_Load(object sender, EventArgs e) { if (Page.User.Identity.IsAuthenticated) { changepassword1.Visible = true; changepassword1.ContinueButtonClick += new EventHandler(changepassword1_ContinueButtonClick); lsLogout.Visible = true; OpenIdLogin1.Visible = false; Page.Title += Resources.labels.changePassword; } }
- Replace
void Login1_LoggedIn(object sender, EventArgs e) { if (!Roles.IsUserInRole(Login1.UserName, BlogEngine.Core.BlogSettings.Instance.AdministratorRole)) Response.Redirect(BlogEngine.Core.Utils.RelativeWebRoot, true); }
with
protected void OpenIdLogin1_LoggedIn(object sender, DotNetOpenId.RelyingParty.OpenIdEventArgs e) { //don't allow login control to login, we will do that manually e.Cancel = true; //get impersonated user string user = Impersonation.Impersonate(e.ClaimedIdentifier); if (!Roles.IsUserInRole(user, BlogEngine.Core.BlogSettings.Instance.AdministratorRole)) Response.Redirect(BlogEngine.Core.Utils.RelativeWebRoot, true); else FormsAuthentication.RedirectFromLoginPage(user, OpenIdLogin1.RememberMe); }
Step 5: Add Impersonation.xml file to App_Data folder
<impersonation> <impersonate> <id>http://jarrettv.myopenid.com/</id> <user>Jarrett</user> </impersonate> </impersonation>
Step 6: Add Impersonation.cs to BlogEngineCore project and compile
using System; using System.Linq; using System.Xml.Linq; using System.Web; using System.Web.Hosting; namespace BlogEngine.Core { public class Impersonation { public static string Impersonate(string id) { string user = id; string path = BlogSettings.Instance.StorageLocation + "impersonation.xml"; if (!VirtualPathUtility.IsAppRelative(path)) throw new ArgumentException("xmlFileName must be app-relative"); string fullyQualifiedPath = VirtualPathUtility.Combine (VirtualPathUtility.AppendTrailingSlash (HttpRuntime.AppDomainAppVirtualPath), path); string actualPath = HostingEnvironment.MapPath(fullyQualifiedPath); XDocument xDoc = XDocument.Load(actualPath); user = xDoc.Element("impersonation").Elements("impersonate") .Where(x => x.Element("id").Value == id).Select(x => x.Element("user")).Single().Value; return user; } } }
Step 7: Deploy following changed files
- Login.aspx
- Login.aspx.cs
- \Bin\BlogEngine.Core.dll
- \Bin\DotNetOpenId.dll
- \App_Data\Impersonation.xml
In the next part, I will add OpenID support to the comment system.