Creating a Dynamic Dictionary with C# 4 dynamic

In C# 4 there’s a new keyword introduced which is dynamic.

Here’s what msdn say about it

The dynamic type enables the operations in which it occurs to bypass

compile-time type checking. Instead, these operations are resolved at

run time.

combined with the var keyword.. anonymous method, and don’t forget anonymous object. I couldn’t help get the feeling that coding in C# is getting similar in a way coding in javascript Smile.

Right, let’s get back to the topic,  so I want to create a dynamic dictionary which enable me from doing this

 

to this

1 dynamic dynamicDictionary = new DynamicDictionary<string>(); 2 dynamicDictionary.cat = "Tom"; 3 4 System.Console.WriteLine(dynamicDictionary.cat);//also prints out "Tom"

This is surprisingly quite easy to implement, as all we need to is extend our class from DynamicObject that reside in System.Dynamic and override couple of methods..two actually.

1 public class DynamicDictionary<TValue> : DynamicObject 2 { 3 private Dictionary<string, TValue> _dictionary; 4 5 public DynamicDictionary() 6 { 7 _dictionary = new Dictionary<string, TValue>(); 8 } 9 10 public override bool TryGetMember(GetMemberBinder binder, out object result) 11 { 12 TValue data; 13 if (!_dictionary.TryGetValue(binder.Name, out data)) 14 { 15 throw new KeyNotFoundException("There's no key by that name"); 16 } 17 18 result = (TValue)data; 19 20 return true; 21 } 22 23 public override bool TrySetMember(SetMemberBinder binder, object value) 24 { 25 if (_dictionary.ContainsKey(binder.Name)) 26 { 27 _dictionary[binder.Name] = (TValue)value; 28 } 29 else 30 { 31 _dictionary.Add(binder.Name, (TValue)value); 32 } 33 34 return true; 35 } 36 }

The trick is in the TryGetMember and TrySetMember method which set and get the property for dynamic object. There’s other method in DynamicObject that you can override such TryGetIndex and TrySetIndex which try to access the dynamic object by index.

You can read more about it in Aaron’s blog

Nuget uninstall package with dependencies

Thought i share a nice command of using nuget.

Let’s say you installed a package with a whole bunch of dependencies, but to found out later that that’s not the package that you want… how do we get rid of the package dependencies altogether without running uninstall-package command one by one.

for example, we’re installing jquery.ui.all package

PM> Install-Package jquery.ui.all Attempting to resolve dependency 'jQuery.UI.Core.All (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Core (= 1.8.9)'. Attempting to resolve dependency 'jQuery (= 1.4.4 && < 1.6)'. Attempting to resolve dependency 'jQuery.UI.Core.Mouse (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Core.Widget (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Core.Position (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Interactions.All (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Interactions.Draggable (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Interactions.Droppable (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Interactions.Resizable (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Interactions.Selectable (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Interactions.Sortable (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Widgets.All (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Widgets.Accordion (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Widgets.Autocomplete (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Widgets.Button (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Widgets.Dialog (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Widgets.Slider (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Widgets.Tabs (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Widgets.Datepicker (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Widgets.Progressbar (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.All (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Core (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Blind (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Bounce (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Clip (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Drop (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Explode (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Fade (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Highlight (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Pulsate (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Scale (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Shake (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Slide (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Effects.Transfer (= 1.8.9)'. Attempting to resolve dependency 'jQuery.UI.Themes.base (= 1.8.9)'. Successfully installed 'jQuery 1.4.4'. Successfully installed 'jQuery.UI.Core 1.8.9'. Successfully installed 'jQuery.UI.Core.Widget 1.8.9'. Successfully installed 'jQuery.UI.Core.Mouse 1.8.9'. Successfully installed 'jQuery.UI.Core.Position 1.8.9'. Successfully installed 'jQuery.UI.Core.All 1.8.9'. Successfully installed 'jQuery.UI.Interactions.Draggable 1.8.9'. Successfully installed 'jQuery.UI.Interactions.Droppable 1.8.9'. Successfully installed 'jQuery.UI.Interactions.Resizable 1.8.9'. Successfully installed 'jQuery.UI.Interactions.Selectable 1.8.9'. Successfully installed 'jQuery.UI.Interactions.Sortable 1.8.9'. Successfully installed 'jQuery.UI.Interactions.All 1.8.9'. Successfully installed 'jQuery.UI.Widgets.Accordion 1.8.9'. Successfully installed 'jQuery.UI.Widgets.Autocomplete 1.8.9'. Successfully installed 'jQuery.UI.Widgets.Button 1.8.9'. Successfully installed 'jQuery.UI.Widgets.Dialog 1.8.9'. Successfully installed 'jQuery.UI.Widgets.Slider 1.8.9'. Successfully installed 'jQuery.UI.Widgets.Tabs 1.8.9'. Successfully installed 'jQuery.UI.Widgets.Datepicker 1.8.9'. Successfully installed 'jQuery.UI.Widgets.Progressbar 1.8.9'. Successfully installed 'jQuery.UI.Widgets.All 1.8.9'. Successfully installed 'jQuery.UI.Effects.Core 1.8.9'. Successfully installed 'jQuery.UI.Effects.Blind 1.8.9'. Successfully installed 'jQuery.UI.Effects.Bounce 1.8.9'. Successfully installed 'jQuery.UI.Effects.Clip 1.8.9'. Successfully installed 'jQuery.UI.Effects.Drop 1.8.9'. Successfully installed 'jQuery.UI.Effects.Explode 1.8.9'. Successfully installed 'jQuery.UI.Effects.Fade 1.8.9'. Successfully installed 'jQuery.UI.Effects.Highlight 1.8.9'. Successfully installed 'jQuery.UI.Effects.Pulsate 1.8.9'. Successfully installed 'jQuery.UI.Effects.Scale 1.8.9'. Successfully installed 'jQuery.UI.Effects.Shake 1.8.9'. Successfully installed 'jQuery.UI.Effects.Slide 1.8.9'. Successfully installed 'jQuery.UI.Effects.Transfer 1.8.9'. Successfully installed 'jQuery.UI.Effects.All 1.8.9'. Successfully installed 'jQuery.UI.Themes.base 1.8.9'. Successfully installed 'jQuery.UI.All 1.8.9'. Successfully added 'jQuery 1.4.4' to MvcApplication1. Successfully added 'jQuery.UI.Core 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Core.Widget 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Core.Mouse 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Core.Position 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Core.All 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Interactions.Draggable 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Interactions.Droppable 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Interactions.Resizable 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Interactions.Selectable 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Interactions.Sortable 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Interactions.All 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Widgets.Accordion 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Widgets.Autocomplete 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Widgets.Button 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Widgets.Dialog 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Widgets.Slider 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Widgets.Tabs 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Widgets.Datepicker 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Widgets.Progressbar 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Widgets.All 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Core 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Blind 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Bounce 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Clip 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Drop 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Explode 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Fade 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Highlight 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Pulsate 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Scale 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Shake 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Slide 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.Transfer 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Effects.All 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.Themes.base 1.8.9' to MvcApplication1. Successfully added 'jQuery.UI.All 1.8.9' to MvcApplication1.

look at that dependencies, after the painful wait due to my poor internet connection, i found out that i just need the jquery.ui.core package Sad smile

And i got all this packages installed

PM> Get-Package Id Version Description/Release Notes -- ------- ------------------------- jQuery 1.4.4 jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development jQuery.UI.All 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Core 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Core.All 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Core.Mouse 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Core.Position 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Core.Widget 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.All 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Blind 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Bounce 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Clip 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Core 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Drop 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Explode 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Fade 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Highlight 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Pulsate 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Scale 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Shake 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Slide 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Effects.Transfer 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Interactions.All 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Interactions.Drag... 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Interactions.Drop... 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Interactions.Resi... 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Interactions.Sele... 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Interactions.Sort... 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Themes.base 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Widgets.Accordion 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Widgets.All 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Widgets.Autocomplete 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Widgets.Button 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Widgets.Datepicker 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Widgets.Dialog 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Widgets.Progressbar 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Widgets.Slider 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ... jQuery.UI.Widgets.Tabs 1.8.9 jQuery UI is an open source library of interface components — interactions, full-featured widgets, and animation effects — based on the stellar jQuery javascript library . Each component is built according ...

 

now, instead of running uninstall-package to each of dependencies

we could instead run

PM> Uninstall-Package jquery.ui.all -RemoveDependencies Successfully removed 'jQuery.UI.All 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Themes.base 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.All 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Transfer 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Slide 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Shake 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Scale 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Pulsate 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Highlight 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Fade 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Explode 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Drop 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Clip 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Bounce 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Blind 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Effects.Core 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Widgets.All 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Widgets.Progressbar 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Widgets.Datepicker 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Widgets.Tabs 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Widgets.Slider 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Widgets.Dialog 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Widgets.Button 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Widgets.Autocomplete 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Widgets.Accordion 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Interactions.All 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Interactions.Sortable 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Interactions.Selectable 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Interactions.Resizable 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Interactions.Droppable 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Interactions.Draggable 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Core.All 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Core.Position 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Core.Mouse 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Core.Widget 1.8.9' from MvcApplication1. Successfully removed 'jQuery.UI.Core 1.8.9' from MvcApplication1. Successfully removed 'jQuery 1.4.4' from MvcApplication1. Successfully uninstalled 'jQuery.UI.All 1.8.9'. Successfully uninstalled 'jQuery.UI.Themes.base 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.All 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Transfer 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Slide 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Shake 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Scale 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Pulsate 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Highlight 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Fade 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Explode 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Drop 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Clip 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Bounce 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Blind 1.8.9'. Successfully uninstalled 'jQuery.UI.Effects.Core 1.8.9'. Successfully uninstalled 'jQuery.UI.Widgets.All 1.8.9'. Successfully uninstalled 'jQuery.UI.Widgets.Progressbar 1.8.9'. Successfully uninstalled 'jQuery.UI.Widgets.Datepicker 1.8.9'. Successfully uninstalled 'jQuery.UI.Widgets.Tabs 1.8.9'. Successfully uninstalled 'jQuery.UI.Widgets.Slider 1.8.9'. Successfully uninstalled 'jQuery.UI.Widgets.Dialog 1.8.9'. Successfully uninstalled 'jQuery.UI.Widgets.Button 1.8.9'. Successfully uninstalled 'jQuery.UI.Widgets.Autocomplete 1.8.9'. Successfully uninstalled 'jQuery.UI.Widgets.Accordion 1.8.9'. Successfully uninstalled 'jQuery.UI.Interactions.All 1.8.9'. Successfully uninstalled 'jQuery.UI.Interactions.Sortable 1.8.9'. Successfully uninstalled 'jQuery.UI.Interactions.Selectable 1.8.9'. Successfully uninstalled 'jQuery.UI.Interactions.Resizable 1.8.9'. Successfully uninstalled 'jQuery.UI.Interactions.Droppable 1.8.9'. Successfully uninstalled 'jQuery.UI.Interactions.Draggable 1.8.9'. Successfully uninstalled 'jQuery.UI.Core.All 1.8.9'. Successfully uninstalled 'jQuery.UI.Core.Position 1.8.9'. Successfully uninstalled 'jQuery.UI.Core.Mouse 1.8.9'. Successfully uninstalled 'jQuery.UI.Core.Widget 1.8.9'. Successfully uninstalled 'jQuery.UI.Core 1.8.9'. Successfully uninstalled 'jQuery 1.4.4'.

and that nice command take care it all

Change context device based on user agent with Sitecore Rule Engine

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 using System; 2 using Sitecore.Data.Fields; 3 using Sitecore.Data.Items; 4 using Sitecore.Pipelines.HttpRequest; 5 using Sitecore.Rules; 6 using Sitecore.RoyalBorough.SharedSource.Rules; 7 8 namespace Sitecore.RoyalBorough.SharedSource.Pipelines.HttpRequest 9 { 10 public class RulesEngineDeviceResolver : HttpRequestProcessor 11 { 12 public override void Process(HttpRequestArgs args) 13 { 14 if (Sitecore.Context.Database == null 15 || Sitecore.Context.Item == null 16 || String.Compare(Sitecore.Context.Database.Name, "core", true) == 0) 17 { 18 return; 19 } 20 21 if (this.InvokeGlobalRules()) 22 { 23 return; 24 } 25 } 26 27 /// <summary> 28 /// Invoke global device resolution rules. 29 /// </summary> 30 /// <returns>True if a global device resolution rule applied.</returns> 31 protected bool InvokeGlobalRules() 32 { 33 Sitecore.Data.Items.Item ruleRoot = Sitecore.Context.Database.GetItem("/sitecore/system/Settings/Rules/Determine Context Device/Rules"); 34 35 if (ruleRoot == null) 36 { 37 return false; 38 } 39 40 // TODO: use descendants instead of children 41 // for each possible global rule definition item 42 foreach (Sitecore.Data.Items.Item child in ruleRoot.Children) 43 { 44 string ruleXml = child["Rule"]; 45 46 if (String.IsNullOrEmpty(ruleXml) || child["Disabled"] == "1") 47 { 48 continue; 49 } 50 51 // parse the rule XML 52 RuleList<RuleContext> rules = new RuleList<RuleContext>(); 53 rules.Name = child.Paths.Path; 54 RuleList<RuleContext> parsed = RuleFactory.ParseRules<RuleContext>( 55 Sitecore.Context.Database, 56 ruleXml); 57 rules.AddRange(parsed.Rules); 58 59 if (rules == null || rules.Count < 1) 60 { 61 continue; 62 } 63 64 // invoke the rule 65 RuleContext ruleContext = new RuleContext(); 66 ruleContext.Item = Sitecore.Context.Item; 67 rules.Run(ruleContext); 68 69 // rule applied 70 if (ruleContext.IsAborted) 71 { 72 return true; 73 } 74 } 75 76 return false; 77 } 78 } 79 80 public class SetContextDeviceRuleContext : Sitecore.Rules.RuleContext 81 { 82 private DeviceItem _evaluateDevice; 83 84 public SetContextDeviceRuleContext(DeviceItem deviceItem) 85 { 86 this.EvaluateDevice = deviceItem; 87 this.Item = this.EvaluateDevice.InnerItem; 88 } 89 90 public Item ContextItem 91 { 92 get { return Sitecore.Context.Item; } 93 } 94 95 public DeviceItem ContextDevice 96 { 97 get { return Sitecore.Context.Device; } 98 set 99 { 100 Sitecore.Context.Device = value; 101 this.Abort(); 102 } 103 } 104 105 public Database ContextDatabase 106 { 107 get { return Sitecore.Context.Database; } 108 } 109 110 public DeviceItem EvaluateDevice 111 { 112 get { return _evaluateDevice; } 113 set { _evaluateDevice = value; } 114 } 115 116 public Language ContextLanguage 117 { 118 get { return Sitecore.Context.Language; } 119 } 120 } 121 }

We need to create a new template for our rule, so in /sitecore/Templates/User Defined/Rules create a new template called SetContextDeviceRule

sitecore_contextdevice_createtemplate_setcontextdevicerule

which has the following structure

sitecore_contextdevice_template_setcontextdevicerule

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

sitecore_contextdevice_createdeterminecontextdevicefolder

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

sitecore_contextdevice_create3newfolders

Next we need to configure the insert options for those folders, do the following :

  • Set the Actions folder insert options to templates/system/rules/Actionsitecore_contextdevice_insertoptions_setaction
  • 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

sitecore_contextdevice_condition_createuseragentismobile

Next set the Text and Type field

sitecore_contextdevice_condition_edituseragentismobile

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 using System; 2 using System.Web; 3 using Sitecore.Rules; 4 using Sitecore.Rules.Conditions; 5 6 namespace Sitecore.RoyalBorough.SharedSource.Rules.Conditions 7 { 8 public class UserAgentIsMobile<T> : OperatorCondition<T> where T : RuleContext 9 { 10 /// <summary> 11 /// Determines whether [is mobile mobdification]. 12 /// Get from http://www.codeproject.com/KB/aspnet/mobiledetect.aspx 13 /// </summary> 14 /// <value> 15 /// <c>true</c> if this instance is mobile browser; otherwise, <c>false</c>. 16 /// </value> 17 private bool IsMobileBrowser 18 { 19 get 20 { 21 //GETS THE CURRENT USER CONTEXT 22 HttpContext context = HttpContext.Current; 23 24 //FIRST TRY BUILT IN ASP.NT CHECK 25 if (context.Request.Browser.IsMobileDevice) 26 { 27 return true; 28 } 29 //THEN TRY CHECKING FOR THE HTTP_X_WAP_PROFILE HEADER 30 if (context.Request.ServerVariables["HTTP_X_WAP_PROFILE"] != null) 31 { 32 return true; 33 } 34 //THEN TRY CHECKING THAT HTTP_ACCEPT EXISTS AND CONTAINS WAP 35 if (context.Request.ServerVariables["HTTP_ACCEPT"] != null && 36 context.Request.ServerVariables["HTTP_ACCEPT"].ToLower().Contains("wap")) 37 { 38 return true; 39 } 40 //AND FINALLY CHECK THE HTTP_USER_AGENT 41 //HEADER VARIABLE FOR ANY ONE OF THE FOLLOWING 42 if (context.Request.ServerVariables["HTTP_USER_AGENT"] != null) 43 { 44 //Create a list of all mobile types 45 string[] mobiles = new[] 46 { 47 "midp", "j2me", "avant", "docomo", 48 "novarra", "palmos", "palmsource", 49 "240x320", "opwv", "chtml", 50 "pda", "windows ce", "mmp/", 51 "blackberry", "mib/", "symbian", 52 "wireless", "nokia", "hand", "mobi", 53 "phone", "cdm", "up.b", "audio", 54 "SIE-", "SEC-", "samsung", "HTC", 55 "mot-", "mitsu", "sagem", "sony" 56 , "alcatel", "lg", "eric", "vx", 57 "NEC", "philips", "mmm", "xx", 58 "panasonic", "sharp", "wap", "sch", 59 "rover", "pocket", "benq", "java", 60 "pt", "pg", "vox", "amoi", 61 "bird", "compal", "kg", "voda", 62 "sany", "kdd", "dbt", "sendo", 63 "sgh", "gradi", "jb", "dddi", 64 "moto", "iphone" 65 }; 66 67 //Loop through each item in the list created above 68 //and check if the header contains that text 69 foreach (string s in mobiles) 70 { 71 if (context.Request.ServerVariables["HTTP_USER_AGENT"].ToLower().Contains(s.ToLower())) 72 { 73 return true; 74 } 75 } 76 } 77 78 return false; 79 } 80 } 81 82 protected override bool Execute(T ruleContext) 83 { 84 if (HttpContext.Current == null 85 || String.IsNullOrEmpty(HttpContext.Current.Request.UserAgent)) 86 { 87 return false; 88 } 89 90 return IsMobileBrowser; 91 } 92 } 93 }

Next we need to setup the Action, create a new action under the Actions folder and call it “Set Context Device to This Device”

sitecore_contextdevice_action_editsetcontextdevicetospecificdevice

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 using Sitecore.Data.Items; 2 3 namespace Sitecore.RoyalBorough.SharedSource.Rules.Actions 4 { 5 public class SetContextDeviceToSpecificDevice<T> : Sitecore.Rules.Actions.RuleAction<T> where T : Sitecore.Rules.RuleContext 6 { 7 public string DeviceID 8 { 9 get; 10 set; 11 } 12 13 public override void Apply(T ruleContext) 14 { 15 Sitecore.Context.Device = new DeviceItem(ruleContext.Item.Database.GetItem(this.DeviceID)); 16 ruleContext.Abort(); 17 } 18 } 19 }

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”

sitecore_contextdevice_rule_editsetcontextdevicetomobileformobiledevices

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 namespace Sitecore.Royalborough.SharedSource.Pipelines.HttpRequest 2 { 3 public class LayoutResolver : Sitecore.Pipelines.HttpRequest.LayoutResolver 4 { 5 public override void Process(Sitecore.Pipelines.HttpRequest.HttpRequestArgs args) 6 { 7 if (Sitecore.Context.Item != null 8 && Sitecore.Context.Device != null 9 && Sitecore.Context.Item.Visualization.GetLayout(Sitecore.Context.Device) != null) 10 { 11 Sitecore.Data.Items.LayoutItem layout = 12 Sitecore.Context.Item.Visualization.GetLayout(Sitecore.Context.Device); 13 Sitecore.Context.Page.FilePath = layout.FilePath; 14 return; 15 } 16 17 base.Process(args); 18 } 19 } 20 }

Edit the web.config and replace Sitecore LayoutResolver with our own

1 <!--<processor type="Sitecore.Pipelines.HttpRequest.LayoutResolver, Sitecore.Kernel" />--> 2 <processor type="Sitecore.RoyalBorough.Pipeline.HttpRequest.LayoutResolver, Sitecore.RoyalBorough.SharedSource" />

Now things should work as expected in Sitecore 6.1

Learning Sitecore CMS

Have to study Sitecore CMS for a couple of weeks, absolutely clueless with it so i ask Google to find some tutorials on it.To my surprise i found very little tutorial on Sitecore outside the Sitecore Developer Network (SDN),  i do however found some nice tutorials by Jens Mikkelsen and John West.

So what’s Sitecore CMS ?, it’s a commercial CMS that uses ASP .NET technology at the core. It’s actually an old player, the company founded at 2001 and has many offices in different countries, so i can conclude that it’s well established company. And here at my company most of our big clients are using this beast  as their CMS solution, so i need to understand how to use it.

Well, I’ll be learning Sitecore for a few more couple of days before actually using it in a project, I’ll post some more if i found something interesting.

Happy new year 2012

Happy new year everyone!, this post arrive late Sad smile, well can’t help it since I got internet issues lately..

A lot of things happened for me in 2011, I got my first MCTS certification on web application using .NET 4, moved to a new boarding house with my wife, got a new job.. still in Bali though.

While some people on new years night go out partying or just hang out with friends, my wife and I decide to spend the night at Sanur beach. So we drove around 30 minutes away from home to get there, it was so crowded, a lot of people seems to had the same idea Smile. But we finally found a nice spot, where we spend an hour there watching the fireworks, to bad we didn’t bring any camera though, it was so beautiful.

Usually people make their new year’s resolution, well I got mine too.. one of them is to be able to post in this blog more frequently, looking back I only have around 6 post total in 2011 which probably because I think I should make a post related programming. Well.. that didn’t work too well for me, cause I didn’t know what to write, so hopefully I can post more frequently from now on even though is not about C# or ASP.NET.

Realtime web application with SignalR

A couple of weeks back i got a task to develop a chat application for an existing application that we have. The idea was so that the existing members could chat with each other without requiring any external IM services such as YM, Skype or MSN messenger. Seems quite simple.. well let’s see about that.

I did some research on how would be the best way to do this, there are a couple of ways that I found:

  1. AJAXpolling
  2. Comet/ AJAX long polling
  3. HTML 5 Web Socket

AJAX Polling

Before AJAX, websites page where not as interactive as of now, imagine that you open your favorite news site and then you got a list of news up until that time displayed on the page, left the tab open for an hour, and if you go back to that tab and need to see if there’s any new news since you left you need to refresh the page. Well with AJAX, a JavaScript could run in the background firing every n minutes to check if there’s any new data and display, this approach is called AJAX polling.

Using this idea of AJAX polling, people start to experiment on creating a real-time apps for web application such as chat application. The drawback of it is because it check to the server every n seconds/minutes it will put the server under heavy load, and imagine that if you have hundreds or even thousand users using the chat application and each of them do a check on the server to see if there’s any new data.. it will be a nightmare.

Not to mention the bandwidth consumption that this approach uses, people that see the weakness of this approach then seek a better approach

Comet / AJAX long polling

It’s a method, improvement if you like, from learning the weakness of AJAX polling, the idea of Comet is the client browser maintain a persistent connection to the server, and instead of the client checks every n second/minutes to the server to check new data, the server itself will tell the clients if there any new data and sent it to them.

HTML 5 Web Socket

This is a new feature in HTML 5 to provide a real two way communication between server and client, we don’t need to any workaround such as AJAX polling or Comet to create real-time apps it will natively provided by the browser as a feature of HTML 5. So as long the client’s browser support it and the server also support it we all set to go.

Back to the chat application, after taking a look at the available approach it seems that Web Socket would be the way to do it.. however currently –at the time of writing- it’s not supported by IE 9, even though FF7 and Chrome 15 does support it the IIS doesn’t support the Web Socket protocol yet.. bummer. So it seems i at this point i could only use Comet to develop my chat application.

Here’s where SignalR come to action, SignalR is async signaling library for .NET to help build real time web application. It’s an open source library under MIT license that’s developed by Damian Edwards and David Fowler, folks from Microsoft. It’s very easy to use, here an example taken straight from the documentation page.

Setup

Go to NuGet and install the SignalR package into a WebApplication:

Install-Package SignalR

Server

Create a class the derives from Hub:

public class Chat : Hub { public void Send(string message) { // Call the addMessage method on all clients Clients.addMessage(message); } }

Client

Javascript + HTML
1 <script src="Scripts/jquery-1.6.2.min.js" type="text/javascript"></script> 2 <script src="Scripts/jquery.signalR.min.js" type="text/javascript"></script> 3 <script src="/signalr/hubs" type="text/javascript"></script> 4 <script type="text/javascript"> 5 $(function () { 6 // Proxy created on the fly 7 var chat = $.connection.chat; 8 9 // Declare a function on the chat hub so the server can invoke it 10 chat.addMessage = function(message) { 11 $('#messages').append('<li>' + message + '</li>'); 12 }; 13 14 $("#broadcast").click(function () { 15 // Call the chat method on the server 16 chat.send($('#msg').val()) 17 .done(function() { 18 console.log('Success!') 19 }) 20 .fail(function(e) { 21 console.warn(e); 22 }) 23 }); 24 25 // Start the connection 26 $.connection.hub.start(); 27 }); 28 </script> 29 30 <input type="text" id="msg" /> 31 <input type="button" id="broadcast" value="broadcast" /> 32 33 <ul id="messages"> 34 </ul>

If you didn’t notice, in the JavaScript code above it assign a click event handler to button with id broadcast which call a server method Send in Chat class.. and if we take a look at the Send method it will trigger the JavaScript addMessage() function for all connected clients. Pretty awesome isn’t it, this approach make it easy for client and server to communicate since they can call each other methods.If you run this code in multiple browsers and try it you will notice that if you press the broadcast button in one browser, then all the browser will all get the “Success!” message, a simple example of SignalR broadcast capability.

The other awesome thing about SignalR is that it will support Web Socket when IIS supports it, so at the moment i could just develop my chat application, and when IIS does support Web Socket, presumably on IIS 8 and .NET 4.5 i could just update the transport mechanism from Comet to Web Socket, and from what i read on the documentation page this could be done by just setting a single property, awesome !

Edit: Paul Batum has made a nice article of using Web Socket in Windows 8 developer preview with some example including chat.

The SignalR team hang out on http://jabbr.net/, you’ll notice that it’s a chat application Smile, previously this chat app is meant to be an example for SignalR,  however with people keep adding new features into it, it slowly becomes a rich chat application, another good thing about open source. So if you want to know more about SignalR, download the source code at https://github.com/SignalR/SignalR,  got any question or suggestion just go to their chat room, the nice folks there will help you.

Failed to load viewstate. The control tree into which viewstate is..

I got this error message when i was working with dynamic control earlier. It seems this exception is thrown when some control in the control tree can not successfully load it’s viewstate.

Let’s take a look at the code,

1 var lvQuestions = new ListView(); 2 lvQuestions.ID = "lvQuestions"; 3 lvQuestions.LayoutTemplate = new QuestionsLayoutTemplate(); 4 lvQuestions.ItemTemplate = new QuestionsItemTemplate(); 5 lvQuestions.EditItemTemplate = new QuestionsEditTemplate(); 6 lvQuestions.InsertItemTemplate = new QuestionsInsertTemplate(); 7 lvQuestions.InsertItemPosition = InsertItemPosition.LastItem; 8 lvQuestions.ItemInserting += new EventHandler(lvQuestions_ItemInserting); 9 lvQuestions.ItemDataBound += new EventHandler(lvQuestions_ItemDataBound); 10 lvQuestions.ItemEditing += new EventHandler(lvQuestions_ItemEditing); 11 lvQuestions.ItemDeleting += new EventHandler(lvQuestions_ItemDeleting); 12 lvQuestions.ItemCanceling += new EventHandler(lvQuestions_ItemCanceling); 13 lvQuestions.ItemUpdating += new EventHandler(lvQuestions_ItemUpdating); 14 lvQuestions.ItemCommand += new EventHandler(listView_ItemCommand); 15

i created a dynamic list view, set the templates and add the listview to a placeholder control. So far everything works fine, i can add a data and it display it, delete also works but the problem arise when i tried to edit the item. Let’s take a look at the item template and edit template

1 private class QuestionsItemTemplate : ITemplate 2 { 3 4 #region ITemplate Members 5 6 public void InstantiateIn(Control container) 7 { 8 var tr = new TableRow(); 9 var td = new TableCell(); 10 var literal = new System.Web.UI.WebControls.Literal(); 11 literal.ID = "ltQuestion"; 12 td.Controls.Add(literal); 13 tr.Controls.Add(td); 14 15 td = new TableCell(); 16 spanTag = new HtmlGenericControl("span"); 17 spanTag.Attributes.Add("class", "ico edit"); 18 button = new LinkButton(); 19 button.ID = "btnEdit"; 20 button.CommandName = "Edit"; 21 button.Text = "Edit"; 22 button.CausesValidation = false; 23 spanTag.Controls.Add(button); 24 td.Controls.Add(spanTag); 25 tr.Controls.Add(td); 26 27 spanTag = new HtmlGenericControl("span"); 28 spanTag.Attributes.Add("class", "ico remove"); 29 td = new TableCell(); 30 button = new LinkButton(); 31 button.ID = "btnDelete"; 32 button.CommandName = "Delete"; 33 button.Text = "Delete"; 34 button.CausesValidation = false; 35 spanTag.Controls.Add(button); 36 td.Controls.Add(spanTag); 37 tr.Controls.Add(td); 38 39 container.Controls.Add(tr); 40 } 41 42 #endregion 43 } 44 45 private class QuestionsEditTemplate : ITemplate 46 { 47 48 #region ITemplate Members 49 50 public void InstantiateIn(Control container) 51 { 52 var tr = new TableRow(); 53 var td = new TableCell(); 54 var textField = new System.Web.UI.WebControls.TextBox(); 55 textField.ID = "txtQuestion"; 56 td.Controls.Add(textField); 57 58 var requiredValidator = new RequiredFieldValidator(); 59 requiredValidator.ID = "regValTxtQuestion"; 60 requiredValidator.ControlToValidate = textField.ID; 61 requiredValidator.Text = "*"; 62 requiredValidator.ErrorMessage = "Please fill the question"; 63 requiredValidator.ValidationGroup = "regValTxtQuestion_Edit"; 64 td.Controls.Add(requiredValidator); 65 tr.Controls.Add(td); 66 67 spanTag = new HtmlGenericControl("span"); 68 spanTag.Attributes.Add("class", "ico cancel"); 69 button = new LinkButton(); 70 button.ID = "btnCancel"; 71 button.CommandName = "Cancel"; 72 button.Text = "Cancel"; 73 button.CausesValidation = false; 74 spanTag.Controls.Add(button); 75 td.Controls.Add(spanTag); 76 tr.Controls.Add(td); 77 78 spanTag = new HtmlGenericControl("span"); 79 spanTag.Attributes.Add("class", "ico save"); 80 button = new LinkButton(); 81 button.ID = "btnUpdate"; 82 button.CommandName = "Update"; 83 button.Text = "Update"; 84 spanTag.Controls.Add(button); 85 td.Controls.Add(spanTag); 86 tr.Controls.Add(td); 87 88 container.Controls.Add(tr); 89 } 90 91 #endregion 92 } 93

It’s pretty straight forward, i have a literal control that display the value in view mode and a texbox control to display the value in edit mode. But everytime i try to edit it i got the same error again and again. And then a thought cross my mind.. what if i set all the controls in the item template and edit template but control their visibility property. Will that do the trick, let’s see..

1 private class QuestionsItemTemplate : ITemplate 2 { 3 4 #region ITemplate Members 5 6 public void InstantiateIn(Control container) 7 { 8 var tr = new TableRow(); 9 var td = new TableCell(); 10 var literal = new System.Web.UI.WebControls.Literal(); 11 literal.ID = "ltQuestion"; 12 td.Controls.Add(literal); 13 var textField = new System.Web.UI.WebControls.TextBox(); 14 textField.Visible = false; 15 textField.ID = "txtQuestion"; 16 td.Controls.Add(textField); 17 tr.Controls.Add(td); 18 19 td = new TableCell(); 20 spanTag = new HtmlGenericControl("span"); 21 spanTag.Attributes.Add("class", "ico edit"); 22 button = new LinkButton(); 23 button.ID = "btnEdit"; 24 button.CommandName = "Edit"; 25 button.Text = "Edit"; 26 button.CausesValidation = false; 27 spanTag.Controls.Add(button); 28 td.Controls.Add(spanTag); 29 30 spanTag = new HtmlGenericControl("span"); 31 spanTag.Attributes.Add("class", "ico cancel"); 32 spanTag.Style.Add("display", "none"); 33 button = new LinkButton(); 34 button.Visible = false; 35 button.ID = "btnCancel"; 36 button.CommandName = "Cancel"; 37 button.Text = "Cancel"; 38 button.CausesValidation = false; 39 spanTag.Controls.Add(button); 40 td.Controls.Add(spanTag); 41 tr.Controls.Add(td); 42 43 spanTag = new HtmlGenericControl("span"); 44 spanTag.Attributes.Add("class", "ico remove"); 45 td = new TableCell(); 46 button = new LinkButton(); 47 button.ID = "btnDelete"; 48 button.CommandName = "Delete"; 49 button.Text = "Delete"; 50 button.CausesValidation = false; 51 spanTag.Controls.Add(button); 52 td.Controls.Add(spanTag); 53 54 spanTag = new HtmlGenericControl("span"); 55 spanTag.Attributes.Add("class", "ico save"); 56 spanTag.Style.Add("display", "none"); 57 button = new LinkButton(); 58 button.Visible = false; 59 button.ID = "btnUpdate"; 60 button.CommandName = "Update"; 61 button.Text = "Update"; 62 spanTag.Controls.Add(button); 63 td.Controls.Add(spanTag); 64 tr.Controls.Add(td); 65 66 container.Controls.Add(tr); 67 } 68 69 #endregion 70 } 71

Above is the modified item template, i include all controls that are used in both item template and edit template and basically just handle their visibility property. The edit template has simillar contruct but with different controls being hidden, you get the idea. And so.. compile, run the code.. fingers crossed.. and it works!. It has the same control hierarchy when on view mode and edit mode but display different controls, i guess using dynamic controls can be quite tricky. Hope this helps.

Using Sql Compact 4 in WPF Application project

Earlier today, i’m having trouble generating database model using Entity Framework and SQL CE 4 in WPF Application project.

after googling around, it seems there’s quite a few people that’s having the same problem, it’s a different story if you’re using it in a web application project, there’s a selection for SQL CE 4 when you’re trying to generate database like shown below.

here’s the workaround on getting the EF play nice on WPF app project:

    1. create a new WPF app project
    2. right click the project and select add new item
    3. choose sql compact 4
    4. right click the project and select add new item
    5. choose ADO.NET Entity Data Model
    6. on the EF Visual Designer, right click and choose Update Model from Database


notice that it doesn’t have SQL CE 4 as a data source

here’s what we’ll do

  1. right click the project and select add new item
  2. choose Application Configuration File
  3. open the configuration file, and add in this line below inside the configuration tag
<connectionStrings>
        <add name="{EdmxContainerName}" connectionString="metadata=res://*/{EdmxFileName}.csdl|res://*/{EdmxFileName}.ssdl|res://*/{EdmxFileName}.msl;provider=System.Data.SqlServerCe.4.0;provider connection string=&quot;Data Source=EzWorklog.sdf&quot;" providerName="System.Data.EntityClient" />
    </connectionStrings>

notice the {EdmxFileName} and {EdmxContainerName} that i put on the connection string, fill it with the appropriate value.
now go back to the EF visual designer and choose Update model from database
now it will know the database that we specified in our application configuration file

Happy coding

 

 

How to deal with boredom in long term project

As an employee in an outsourcing company, we do not have the luxury to choose which project that we want to join.

Sometimes the project will run for a month, a couple of month or even years. the latter is especially true when handling a software that’s mature enough causing most of the developers involved in the project only have to maintain the software.

after a few month, reaching a year, boredom will surely creeps in the developer’s mind. this is understandable of course, having to deal with the same thing every day for the last x month/years everyone at some point will have that sense boredom.

as a developer there’s a couple of things that we can do to take our boredom away while keep upgrading our skills.

make a simple project, you determine the deadline, you determine the features, you determine the technologies to be used, make it fun, challenge yourself.

some project may not be accomplished, but that’s ok. learn from it, why you can’t finished it on time, or why you left it partway. is it because the design flaw, poor judgment on the technologies or just don’t have time to work on it.

every thing that you get from your simple project can benefit yourself in your professional life, it’s a valuable experience.

so get out there, and start making your simple project :)

Using Jquery UI Autocomplete to consume WCF Service

I had some problem when trying to use jQuery UI autocomplete to get the data from a WCF service, after browsing around i finally found a way to resolve it

In the jQueryUI autocomplete file:

  1. Change the code for jQuery UI autocomplete , by default it execute an ajax call with GET method, we need to change this to POST
  2. We need to change the default content type to “application/json”  or else there will be an exception when trying to access the WCF service
  3. The WCF service will try to deserialize the data that we sent and it expect the data that we sent is sent in JSON string format
    1. eq: {‘term’:'human’} and not ‘term=human’ to do this we can use JSON.stringify method that we can get from http://www.json.org/js.html
In the WCF service file:

We need to decorate  our method with this attribute

[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]

The javascript code

$('#<%= txtTitle.ClientID %>').autocomplete({ source: "/WebPages/Transaction/WebServices/TransactionService.svc/SearchPayeeByName" });

The jQuery UI that i use is version v1.8.14

Follow

Get every new post delivered to your Inbox.