Search Results

Search found 202 results on 9 pages for 'anders rask'.

Page 9/9 | < Previous Page | 5 6 7 8 9 

  • A ToDynamic() Extension Method For Fluent Reflection

    - by Dixin
    Recently I needed to demonstrate some code with reflection, but I felt it inconvenient and tedious. To simplify the reflection coding, I created a ToDynamic() extension method. The source code can be downloaded from here. Problem One example for complex reflection is in LINQ to SQL. The DataContext class has a property Privider, and this Provider has an Execute() method, which executes the query expression and returns the result. Assume this Execute() needs to be invoked to query SQL Server database, then the following code will be expected: using (NorthwindDataContext database = new NorthwindDataContext()) { // Constructs the query. IQueryable<Product> query = database.Products.Where(product => product.ProductID > 0) .OrderBy(product => product.ProductName) .Take(2); // Executes the query. Here reflection is required, // because Provider, Execute(), and ReturnValue are not public members. IEnumerable<Product> results = database.Provider.Execute(query.Expression).ReturnValue; // Processes the results. foreach (Product product in results) { Console.WriteLine("{0}, {1}", product.ProductID, product.ProductName); } } Of course, this code cannot compile. And, no one wants to write code like this. Again, this is just an example of complex reflection. using (NorthwindDataContext database = new NorthwindDataContext()) { // Constructs the query. IQueryable<Product> query = database.Products.Where(product => product.ProductID > 0) .OrderBy(product => product.ProductName) .Take(2); // database.Provider PropertyInfo providerProperty = database.GetType().GetProperty( "Provider", BindingFlags.NonPublic | BindingFlags.GetProperty | BindingFlags.Instance); object provider = providerProperty.GetValue(database, null); // database.Provider.Execute(query.Expression) // Here GetMethod() cannot be directly used, // because Execute() is a explicitly implemented interface method. Assembly assembly = Assembly.Load("System.Data.Linq"); Type providerType = assembly.GetTypes().SingleOrDefault( type => type.FullName == "System.Data.Linq.Provider.IProvider"); InterfaceMapping mapping = provider.GetType().GetInterfaceMap(providerType); MethodInfo executeMethod = mapping.InterfaceMethods.Single(method => method.Name == "Execute"); IExecuteResult executeResult = executeMethod.Invoke(provider, new object[] { query.Expression }) as IExecuteResult; // database.Provider.Execute(query.Expression).ReturnValue IEnumerable<Product> results = executeResult.ReturnValue as IEnumerable<Product>; // Processes the results. foreach (Product product in results) { Console.WriteLine("{0}, {1}", product.ProductID, product.ProductName); } } This may be not straight forward enough. So here a solution will implement fluent reflection with a ToDynamic() extension method: IEnumerable<Product> results = database.ToDynamic() // Starts fluent reflection. .Provider.Execute(query.Expression).ReturnValue; C# 4.0 dynamic In this kind of scenarios, it is easy to have dynamic in mind, which enables developer to write whatever code after a dot: using (NorthwindDataContext database = new NorthwindDataContext()) { // Constructs the query. IQueryable<Product> query = database.Products.Where(product => product.ProductID > 0) .OrderBy(product => product.ProductName) .Take(2); // database.Provider dynamic dynamicDatabase = database; dynamic results = dynamicDatabase.Provider.Execute(query).ReturnValue; } This throws a RuntimeBinderException at runtime: 'System.Data.Linq.DataContext.Provider' is inaccessible due to its protection level. Here dynamic is able find the specified member. So the next thing is just writing some custom code to access the found member. .NET 4.0 DynamicObject, and DynamicWrapper<T> Where to put the custom code for dynamic? The answer is DynamicObject’s derived class. I first heard of DynamicObject from Anders Hejlsberg's video in PDC2008. It is very powerful, providing useful virtual methods to be overridden, like: TryGetMember() TrySetMember() TryInvokeMember() etc.  (In 2008 they are called GetMember, SetMember, etc., with different signature.) For example, if dynamicDatabase is a DynamicObject, then the following code: dynamicDatabase.Provider will invoke dynamicDatabase.TryGetMember() to do the actual work, where custom code can be put into. Now create a type to inherit DynamicObject: public class DynamicWrapper<T> : DynamicObject { private readonly bool _isValueType; private readonly Type _type; private T _value; // Not readonly, for value type scenarios. public DynamicWrapper(ref T value) // Uses ref in case of value type. { if (value == null) { throw new ArgumentNullException("value"); } this._value = value; this._type = value.GetType(); this._isValueType = this._type.IsValueType; } public override bool TryGetMember(GetMemberBinder binder, out object result) { // Searches in current type's public and non-public properties. PropertyInfo property = this._type.GetTypeProperty(binder.Name); if (property != null) { result = property.GetValue(this._value, null).ToDynamic(); return true; } // Searches in explicitly implemented properties for interface. MethodInfo method = this._type.GetInterfaceMethod(string.Concat("get_", binder.Name), null); if (method != null) { result = method.Invoke(this._value, null).ToDynamic(); return true; } // Searches in current type's public and non-public fields. FieldInfo field = this._type.GetTypeField(binder.Name); if (field != null) { result = field.GetValue(this._value).ToDynamic(); return true; } // Searches in base type's public and non-public properties. property = this._type.GetBaseProperty(binder.Name); if (property != null) { result = property.GetValue(this._value, null).ToDynamic(); return true; } // Searches in base type's public and non-public fields. field = this._type.GetBaseField(binder.Name); if (field != null) { result = field.GetValue(this._value).ToDynamic(); return true; } // The specified member is not found. result = null; return false; } // Other overridden methods are not listed. } In the above code, GetTypeProperty(), GetInterfaceMethod(), GetTypeField(), GetBaseProperty(), and GetBaseField() are extension methods for Type class. For example: internal static class TypeExtensions { internal static FieldInfo GetBaseField(this Type type, string name) { Type @base = type.BaseType; if (@base == null) { return null; } return @base.GetTypeField(name) ?? @base.GetBaseField(name); } internal static PropertyInfo GetBaseProperty(this Type type, string name) { Type @base = type.BaseType; if (@base == null) { return null; } return @base.GetTypeProperty(name) ?? @base.GetBaseProperty(name); } internal static MethodInfo GetInterfaceMethod(this Type type, string name, params object[] args) { return type.GetInterfaces().Select(type.GetInterfaceMap).SelectMany(mapping => mapping.TargetMethods) .FirstOrDefault( method => method.Name.Split('.').Last().Equals(name, StringComparison.Ordinal) && method.GetParameters().Count() == args.Length && method.GetParameters().Select( (parameter, index) => parameter.ParameterType.IsAssignableFrom(args[index].GetType())).Aggregate( true, (a, b) => a && b)); } internal static FieldInfo GetTypeField(this Type type, string name) { return type.GetFields( BindingFlags.GetField | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault( field => field.Name.Equals(name, StringComparison.Ordinal)); } internal static PropertyInfo GetTypeProperty(this Type type, string name) { return type.GetProperties( BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault( property => property.Name.Equals(name, StringComparison.Ordinal)); } // Other extension methods are not listed. } So now, when invoked, TryGetMember() searches the specified member and invoke it. The code can be written like this: dynamic dynamicDatabase = new DynamicWrapper<NorthwindDataContext>(ref database); dynamic dynamicReturnValue = dynamicDatabase.Provider.Execute(query.Expression).ReturnValue; This greatly simplified reflection. ToDynamic() and fluent reflection To make it even more straight forward, A ToDynamic() method is provided: public static class DynamicWrapperExtensions { public static dynamic ToDynamic<T>(this T value) { return new DynamicWrapper<T>(ref value); } } and a ToStatic() method is provided to unwrap the value: public class DynamicWrapper<T> : DynamicObject { public T ToStatic() { return this._value; } } In the above TryGetMember() method, please notice it does not output the member’s value, but output a wrapped member value (that is, memberValue.ToDynamic()). This is very important to make the reflection fluent. Now the code becomes: IEnumerable<Product> results = database.ToDynamic() // Here starts fluent reflection. .Provider.Execute(query.Expression).ReturnValue .ToStatic(); // Unwraps to get the static value. With the help of TryConvert(): public class DynamicWrapper<T> : DynamicObject { public override bool TryConvert(ConvertBinder binder, out object result) { result = this._value; return true; } } ToStatic() can be omitted: IEnumerable<Product> results = database.ToDynamic() .Provider.Execute(query.Expression).ReturnValue; // Automatically converts to expected static value. Take a look at the reflection code at the beginning of this post again. Now it is much much simplified! Special scenarios In 90% of the scenarios ToDynamic() is enough. But there are some special scenarios. Access static members Using extension method ToDynamic() for accessing static members does not make sense. Instead, DynamicWrapper<T> has a parameterless constructor to handle these scenarios: public class DynamicWrapper<T> : DynamicObject { public DynamicWrapper() // For static. { this._type = typeof(T); this._isValueType = this._type.IsValueType; } } The reflection code should be like this: dynamic wrapper = new DynamicWrapper<StaticClass>(); int value = wrapper._value; int result = wrapper.PrivateMethod(); So accessing static member is also simple, and fluent of course. Change instances of value types Value type is much more complex. The main problem is, value type is copied when passing to a method as a parameter. This is why ref keyword is used for the constructor. That is, if a value type instance is passed to DynamicWrapper<T>, the instance itself will be stored in this._value of DynamicWrapper<T>. Without the ref keyword, when this._value is changed, the value type instance itself does not change. Consider FieldInfo.SetValue(). In the value type scenarios, invoking FieldInfo.SetValue(this._value, value) does not change this._value, because it changes the copy of this._value. I searched the Web and found a solution for setting the value of field: internal static class FieldInfoExtensions { internal static void SetValue<T>(this FieldInfo field, ref T obj, object value) { if (typeof(T).IsValueType) { field.SetValueDirect(__makeref(obj), value); // For value type. } else { field.SetValue(obj, value); // For reference type. } } } Here __makeref is a undocumented keyword of C#. But method invocation has problem. This is the source code of TryInvokeMember(): public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result) { if (binder == null) { throw new ArgumentNullException("binder"); } MethodInfo method = this._type.GetTypeMethod(binder.Name, args) ?? this._type.GetInterfaceMethod(binder.Name, args) ?? this._type.GetBaseMethod(binder.Name, args); if (method != null) { // Oops! // If the returnValue is a struct, it is copied to heap. object resultValue = method.Invoke(this._value, args); // And result is a wrapper of that copied struct. result = new DynamicWrapper<object>(ref resultValue); return true; } result = null; return false; } If the returned value is of value type, it will definitely copied, because MethodInfo.Invoke() does return object. If changing the value of the result, the copied struct is changed instead of the original struct. And so is the property and index accessing. They are both actually method invocation. For less confusion, setting property and index are not allowed on struct. Conclusions The DynamicWrapper<T> provides a simplified solution for reflection programming. It works for normal classes (reference types), accessing both instance and static members. In most of the scenarios, just remember to invoke ToDynamic() method, and access whatever you want: StaticType result = someValue.ToDynamic()._field.Method().Property[index]; In some special scenarios which requires changing the value of a struct (value type), this DynamicWrapper<T> does not work perfectly. Only changing struct’s field value is supported. The source code can be downloaded from here, including a few unit test code.

    Read the article

  • jQuery - Why editable-select list plugin doesn't work with latest jQuery?

    - by Binyamin
    Why editable-select list plugin<select><option>value</option>doesn't work with latest jQuery? editable-select code: /** * Copyright (c) 2009 Anders Ekdahl (http://coffeescripter.com/) * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * * Version: 1.3.1 * * Demo and documentation: http://coffeescripter.com/code/editable-select/ */ (function($) { var instances = []; $.fn.editableSelect = function(options) { var defaults = { bg_iframe: false, onSelect: false, items_then_scroll: 10, case_sensitive: false }; var settings = $.extend(defaults, options); // Only do bg_iframe for browsers that need it if(settings.bg_iframe && !$.browser.msie) { settings.bg_iframe = false; }; var instance = false; $(this).each(function() { var i = instances.length; if(typeof $(this).data('editable-selecter') == 'undefined') { instances[i] = new EditableSelect(this, settings); $(this).data('editable-selecter', i); }; }); return $(this); }; $.fn.editableSelectInstances = function() { var ret = []; $(this).each(function() { if(typeof $(this).data('editable-selecter') != 'undefined') { ret[ret.length] = instances[$(this).data('editable-selecter')]; }; }); return ret; }; var EditableSelect = function(select, settings) { this.init(select, settings); }; EditableSelect.prototype = { settings: false, text: false, select: false, wrapper: false, list_item_height: 20, list_height: 0, list_is_visible: false, hide_on_blur_timeout: false, bg_iframe: false, current_value: '', init: function(select, settings) { this.settings = settings; this.select = $(select); this.text = $('<input type="text">'); this.text.attr('name', this.select.attr('name')); this.text.data('editable-selecter', this.select.data('editable-selecter')); // Because we don't want the value of the select when the form // is submitted this.select.attr('disabled', 'disabled'); var id = this.select.attr('id'); if(!id) { id = 'editable-select'+ instances.length; }; this.text.attr('id', id); this.text.attr('autocomplete', 'off'); this.text.addClass('editable-select'); this.select.attr('id', id +'_hidden_select'); this.initInputEvents(this.text); this.duplicateOptions(); this.positionElements(); this.setWidths(); if(this.settings.bg_iframe) { this.createBackgroundIframe(); }; }, duplicateOptions: function() { var context = this; var wrapper = $(document.createElement('div')); wrapper.addClass('editable-select-options'); var option_list = $(document.createElement('ul')); wrapper.append(option_list); var options = this.select.find('option'); options.each(function() { if($(this).attr('selected')) { context.text.val($(this).val()); context.current_value = $(this).val(); }; var li = $('<li>'+ $(this).val() +'</li>'); context.initListItemEvents(li); option_list.append(li); }); this.wrapper = wrapper; this.checkScroll(); }, checkScroll: function() { var options = this.wrapper.find('li'); if(options.length > this.settings.items_then_scroll) { this.list_height = this.list_item_height * this.settings.items_then_scroll; this.wrapper.css('height', this.list_height +'px'); this.wrapper.css('overflow', 'auto'); } else { this.wrapper.css('height', 'auto'); this.wrapper.css('overflow', 'visible'); }; }, addOption: function(value) { var li = $('<li>'+ value +'</li>'); var option = $('<option>'+ value +'</option>'); this.select.append(option); this.initListItemEvents(li); this.wrapper.find('ul').append(li); this.setWidths(); this.checkScroll(); }, initInputEvents: function(text) { var context = this; var timer = false; $(document.body).click( function() { context.clearSelectedListItem(); context.hideList(); } ); text.focus( function() { // Can't use the blur event to hide the list, because the blur event // is fired in some browsers when you scroll the list context.showList(); context.highlightSelected(); } ).click( function(e) { e.stopPropagation(); context.showList(); context.highlightSelected(); } ).keydown( // Capture key events so the user can navigate through the list function(e) { switch(e.keyCode) { // Down case 40: if(!context.listIsVisible()) { context.showList(); context.highlightSelected(); } else { e.preventDefault(); context.selectNewListItem('down'); }; break; // Up case 38: e.preventDefault(); context.selectNewListItem('up'); break; // Tab case 9: context.pickListItem(context.selectedListItem()); break; // Esc case 27: e.preventDefault(); context.hideList(); return false; break; // Enter, prevent form submission case 13: e.preventDefault(); context.pickListItem(context.selectedListItem()); return false; }; } ).keyup( function(e) { // Prevent lots of calls if it's a fast typer if(timer !== false) { clearTimeout(timer); timer = false; }; timer = setTimeout( function() { // If the user types in a value, select it if it's in the list if(context.text.val() != context.current_value) { context.current_value = context.text.val(); context.highlightSelected(); }; }, 200 ); } ).keypress( function(e) { if(e.keyCode == 13) { // Enter, prevent form submission e.preventDefault(); return false; }; } ); }, initListItemEvents: function(list_item) { var context = this; list_item.mouseover( function() { context.clearSelectedListItem(); context.selectListItem(list_item); } ).mousedown( // Needs to be mousedown and not click, since the inputs blur events // fires before the list items click event function(e) { e.stopPropagation(); context.pickListItem(context.selectedListItem()); } ); }, selectNewListItem: function(direction) { var li = this.selectedListItem(); if(!li.length) { li = this.selectFirstListItem(); }; if(direction == 'down') { var sib = li.next(); } else { var sib = li.prev(); }; if(sib.length) { this.selectListItem(sib); this.scrollToListItem(sib); this.unselectListItem(li); }; }, selectListItem: function(list_item) { this.clearSelectedListItem(); list_item.addClass('selected'); }, selectFirstListItem: function() { this.clearSelectedListItem(); var first = this.wrapper.find('li:first'); first.addClass('selected'); return first; }, unselectListItem: function(list_item) { list_item.removeClass('selected'); }, selectedListItem: function() { return this.wrapper.find('li.selected'); }, clearSelectedListItem: function() { this.wrapper.find('li.selected').removeClass('selected'); }, pickListItem: function(list_item) { if(list_item.length) { this.text.val(list_item.text()); this.current_value = this.text.val(); }; if(typeof this.settings.onSelect == 'function') { this.settings.onSelect.call(this, list_item); }; this.hideList(); }, listIsVisible: function() { return this.list_is_visible; }, showList: function() { this.wrapper.show(); this.hideOtherLists(); this.list_is_visible = true; if(this.settings.bg_iframe) { this.bg_iframe.show(); }; }, highlightSelected: function() { var context = this; var current_value = this.text.val(); if(current_value.length < 0) { if(highlight_first) { this.selectFirstListItem(); }; return; }; if(!context.settings.case_sensitive) { current_value = current_value.toLowerCase(); }; var best_candiate = false; var value_found = false; var list_items = this.wrapper.find('li'); list_items.each( function() { if(!value_found) { var text = $(this).text(); if(!context.settings.case_sensitive) { text = text.toLowerCase(); }; if(text == current_value) { value_found = true; context.clearSelectedListItem(); context.selectListItem($(this)); context.scrollToListItem($(this)); return false; } else if(text.indexOf(current_value) === 0 && !best_candiate) { // Can't do return false here, since we still need to iterate over // all list items to see if there is an exact match best_candiate = $(this); }; }; } ); if(best_candiate && !value_found) { context.clearSelectedListItem(); context.selectListItem(best_candiate); context.scrollToListItem(best_candiate); } else if(!best_candiate && !value_found) { this.selectFirstListItem(); }; }, scrollToListItem: function(list_item) { if(this.list_height) { this.wrapper.scrollTop(list_item[0].offsetTop - (this.list_height / 2)); }; }, hideList: function() { this.wrapper.hide(); this.list_is_visible = false; if(this.settings.bg_iframe) { this.bg_iframe.hide(); }; }, hideOtherLists: function() { for(var i = 0; i < instances.length; i++) { if(i != this.select.data('editable-selecter')) { instances[i].hideList(); }; }; }, positionElements: function() { var offset = this.select.offset(); offset.top += this.select[0].offsetHeight; this.select.after(this.text); this.select.hide(); this.wrapper.css({top: offset.top +'px', left: offset.left +'px'}); $(document.body).append(this.wrapper); // Need to do this in order to get the list item height this.wrapper.css('visibility', 'hidden'); this.wrapper.show(); this.list_item_height = this.wrapper.find('li')[0].offsetHeight; this.wrapper.css('visibility', 'visible'); this.wrapper.hide(); }, setWidths: function() { // The text input has a right margin because of the background arrow image // so we need to remove that from the width var width = this.select.width() + 2; var padding_right = parseInt(this.text.css('padding-right').replace(/px/, ''), 10); this.text.width(width - padding_right); this.wrapper.width(width + 2); if(this.bg_iframe) { this.bg_iframe.width(width + 4); }; }, createBackgroundIframe: function() { var bg_iframe = $('<iframe frameborder="0" class="editable-select-iframe" src="about:blank;"></iframe>'); $(document.body).append(bg_iframe); bg_iframe.width(this.select.width() + 2); bg_iframe.height(this.wrapper.height()); bg_iframe.css({top: this.wrapper.css('top'), left: this.wrapper.css('left')}); this.bg_iframe = bg_iframe; } }; })(jQuery); $(function() { $('.editable-select').editableSelect( { bg_iframe: true, onSelect: function(list_item) { alert('List item text: '+ list_item.text()); // 'this' is a reference to the instance of EditableSelect // object, so you have full access to everything there // alert('Input value: '+ this.text.val()); }, case_sensitive: false, // If set to true, the user has to type in an exact // match for the item to get highlighted items_then_scroll: 10 // If there are more than 10 items, display a scrollbar } ); var select = $('.editable-select:first'); var instances = select.editableSelectInstances(); // instances[0].addOption('Germany, value added programmatically'); });

    Read the article

< Previous Page | 5 6 7 8 9