I pick this up from one of the John West blog post, i want to able to change the Sitecore context device based on the user agent that it detected, so if the device that access my application is a mobile devices then give them the mobile view, if not give them the standard view.
What we’re going to use here are the Sitecore Rule Engine, so we define a certain rule which trigger an action when the condition is fulfilled.In John’s blog he explained that this can be achieved by creating global rules where the rule set the context device if condition is met, or by running rules that is associated with each device.In this post i’m only interested in the global rule approach.
First add this code in the web.config
note: my assembly is Sitecore.RoyalBorough.SharedSource, if you use something else, you need to replace that
1 |
<processor type="Sitecore.RoyalBorough.SharedSource.Pipelines.HttpRequest.RulesEngineDeviceResolver, Sitecore.RoyalBorough.SharedSource"/> |
Which is used to register the RulesEngineDeviceResolver class below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 |
using System; using Sitecore.Data.Fields; using Sitecore.Data.Items; using Sitecore.Pipelines.HttpRequest; using Sitecore.Rules; using Sitecore.RoyalBorough.SharedSource.Rules; namespace Sitecore.RoyalBorough.SharedSource.Pipelines.HttpRequest { public class RulesEngineDeviceResolver : HttpRequestProcessor { public override void Process(HttpRequestArgs args) { if (Sitecore.Context.Database == null || Sitecore.Context.Item == null || String.Compare(Sitecore.Context.Database.Name, "core", true) == 0) { return; } if (this.InvokeGlobalRules()) { return; } } /// /// Invoke global device resolution rules. /// /// True if a global device resolution rule applied. protected bool InvokeGlobalRules() { Sitecore.Data.Items.Item ruleRoot = Sitecore.Context.Database.GetItem("/sitecore/system/Settings/Rules/Determine Context Device/Rules"); if (ruleRoot == null) { return false; } // TODO: use descendants instead of children // for each possible global rule definition item foreach (Sitecore.Data.Items.Item child in ruleRoot.Children) { string ruleXml = child["Rule"]; if (String.IsNullOrEmpty(ruleXml) || child["Disabled"] == "1") { continue; } // parse the rule XML RuleList<RuleContext> rules = new RuleList<RuleContext>(); rules.Name = child.Paths.Path; RuleList<RuleContext> parsed = RuleFactory.ParseRules<RuleContext>( Sitecore.Context.Database, ruleXml); rules.AddRange(parsed.Rules); if (rules == null || rules.Count < 1) { continue; } // invoke the rule RuleContext ruleContext = new RuleContext(); ruleContext.Item = Sitecore.Context.Item; rules.Run(ruleContext); // rule applied if (ruleContext.IsAborted) { return true; } } return false; } } public class SetContextDeviceRuleContext : Sitecore.Rules.RuleContext { private DeviceItem _evaluateDevice; public SetContextDeviceRuleContext(DeviceItem deviceItem) { this.EvaluateDevice = deviceItem; this.Item = this.EvaluateDevice.InnerItem; } public Item ContextItem { get { return Sitecore.Context.Item; } } public DeviceItem ContextDevice { get { return Sitecore.Context.Device; } set { Sitecore.Context.Device = value; this.Abort(); } } public Database ContextDatabase { get { return Sitecore.Context.Database; } } public DeviceItem EvaluateDevice { get { return _evaluateDevice; } set { _evaluateDevice = value; } } public Language ContextLanguage { get { return Sitecore.Context.Language; } } } } |
We need to create a new template for our rule, so in /sitecore/Templates/User Defined/Rules create a new template called SetContextDeviceRule
which has the following structure
Notice that we set the source for “Rule” to /sitecore/System/Settings/Rules/ Then in Sitecore Content Editor create new folder called Determine Context Device under /sitecore/System/Settings/Rules
The rule that we are going to defined works by specifying a condition, and if the condition is passed then run a certain action(s), so under that new folder create folders called Actions,Conditions, and Rules
Next we need to configure the insert options for those folders, do the following :
- Set the Actions folder insert options to templates/system/rules/Action
- Do the same for Conditions folder, but instead pointing to Action template point it to Condition Template
- For the Rules folder, point it to templates/User Defined/Rules/SetContextDeviceRule
Now that we have configured the insert options for those folders, it’s time to add some item to it. Start by adding a new condition under Conditions folder and call it User Agent Is Mobile
Next set the Text and Type field
Note that the Type field refers to UserAgentIsMobile class in Sitecore.RoyalBorough.SharedSource assembly, which is responsible to figure out if the accessing device is a mobile device or not based on the incoming user agent, code below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
using System; using System.Web; using Sitecore.Rules; using Sitecore.Rules.Conditions; namespace Sitecore.RoyalBorough.SharedSource.Rules.Conditions { public class UserAgentIsMobile<T> : OperatorCondition<T> where T : RuleContext { /// /// Determines whether [is mobile mobdification]. /// Get from http://www.codeproject.com/KB/aspnet/mobiledetect.aspx /// /// /// true if this instance is mobile browser; otherwise, false. /// private bool IsMobileBrowser { get { //GETS THE CURRENT USER CONTEXT HttpContext context = HttpContext.Current; //FIRST TRY BUILT IN ASP.NT CHECK if (context.Request.Browser.IsMobileDevice) { return true; } //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null) { return true; } //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP if (context.Request.ServerVariables["HTTP_ACCEPT"] != null && context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap")) { return true; } //AND FINALLY CHECK THE HTTP_USER_AGENT //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null) { //Create a list of all mobile types string[] mobiles = new[] { "midp", "j2me", "avant", "docomo", "novarra", "palmos", "palmsource", "240x320", "opwv", "chtml", "pda", "windows ce", "mmp/", "blackberry", "mib/", "symbian", "wireless", "nokia", "hand", "mobi", "phone", "cdm", "up.b", "audio", "SIE-", "SEC-", "samsung", "HTC", "mot-", "mitsu", "sagem", "sony" , "alcatel", "lg", "eric", "vx", "NEC", "philips", "mmm", "xx", "panasonic", "sharp", "wap", "sch", "rover", "pocket", "benq", "java", "pt", "pg", "vox", "amoi", "bird", "compal", "kg", "voda", "sany", "kdd", "dbt", "sendo", "sgh", "gradi", "jb", "dddi", "moto", "iphone" }; //Loop through each item in the list created above //and check if the header contains that text foreach (string s in mobiles) { if (context.Request.ServerVariables["HTTP_USER_AGENT"].ToLower().Contains(s.ToLower())) { return true; } } } return false; } } protected override bool Execute(T ruleContext) { if (HttpContext.Current == null || String.IsNullOrEmpty(HttpContext.Current.Request.UserAgent)) { return false; } return IsMobileBrowser; } } } |
Next we need to setup the Action, create a new action under the Actions folder and call it “Set Context Device to This Device”
It refer to SetContextDeviceToSpecificDevice class which will be triggered when the condition is true, this class is responsible to change the sitecore context device, code below
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
using Sitecore.Data.Items; namespace Sitecore.RoyalBorough.SharedSource.Rules.Actions { public class SetContextDeviceToSpecificDevice<T> : Sitecore.Rules.Actions.RuleAction<T> where T : Sitecore.Rules.RuleContext { public string DeviceID { get; set; } public override void Apply(T ruleContext) { Sitecore.Context.Device = new DeviceItem(ruleContext.Item.Database.GetItem(this.DeviceID)); ruleContext.Abort(); } } } |
Now we need to setup the rule, under the Rules folder create a new item and call it “Set Context Device To Mobile for Mobile Devices”
That’s it, make sure the assembly –for me it’s Sitecore.RoyalBorough.SharedSource.dll- is in the sitecore bin folder, and you can start test it right away. If all goes well, you should see different view rendered when you access the site through Mobile devices and from PC
update Jan 17, 2012
If we’re to use Sitecore 6.1, we have a problem when we try to change the context device, the layout does not get updated it’s still uses the old layout and not the mobile layout, as a result when the mobile device access our page the rendered layout is all messed up. This is fixed on Sitecore 6.4, for 6.1 here’s the workaround
Create a new LayoutResolver class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
namespace Sitecore.Royalborough.SharedSource.Pipelines.HttpRequest { public class LayoutResolver : Sitecore.Pipelines.HttpRequest.LayoutResolver { public override void Process(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args) { if (Sitecore.Context.Item != null && Sitecore.Context.Device != null && Sitecore.Context.Item.Visualization.GetLayout(Sitecore.Context.Device) != null) { Sitecore.Data.Items.LayoutItem layout = Sitecore.Context.Item.Visualization.GetLayout(Sitecore.Context.Device); Sitecore.Context.Page.FilePath = layout.FilePath; return; } base.Process(args); } } } |
Edit the web.config and replace Sitecore LayoutResolver with our own
1 |
<processor type="Sitecore.RoyalBorough.Pipeline.HttpRequest.LayoutResolver, Sitecore.RoyalBorough.SharedSource" /> |
Now things should work as expected in Sitecore 6.1
Thought You’d find this interesting
http://sitecoresnippets.blogspot.com/2011/03/wurfl-based-mobile-detection-solution.html?m=1
🙂
hey, that is interesting!
thanks for sharing Michael