Search Results

Search found 36488 results on 1460 pages for 'extension method'.

Page 5/1460 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • developing browser extension for content filtering

    - by user272483
    i'm developing an application for content filtering. i'll use it as web service but my problem is that i hadn't developed any extension for firefox or ie before. i read some about firefox extensions and now i know a little about it. firstly can i use web service in a firefox/ie extension? if yes, can you give me a link of tutorial or sth like that? all suggestions are welcome. thx..

    Read the article

  • Detecting own posts on Facebook from a Chrome extension perspective

    - by Bane
    I want to create a Chrome extension that will automatically like every post I make on Facebook. My question is, how can I detect when I post something, and if that post if mine? Is there an event that occurs or something? (And just for the record, I know that these sorts of things are impossible when other apps post on my behalf, at least from an extension perspective. So I'm only concentrating on posts that I actually click the "post" button, or enter for, myself.)

    Read the article

  • recursively add file extension to all files

    - by seengee
    I have a few directories and sub-directories containing files with no file extension. I want to add .jpg to all the files contained within these directories. I have seen bash scripts for changing the file extension but not for just adding one. It also needs to be recursive, can someone help please?

    Read the article

  • Trigger events from Firefox browser extension?

    - by Alex
    Hello, I want to trigger events from a firefox extension, specifically click events. I've tried jQuery's .click() as well as the whole: var evt = document.createEvent("HTMLEvents"); evt.initEvent("click", true, false ); toClick[0].dispatchEvent(evt); This is not working for me, and I was wondering if this is even possible? (to trigger events from a firefox extension)? If so, how does one do it?

    Read the article

  • About extension methods

    - by Srinivas Reddy Thatiparthy
    Shall i always need to throw ArgumentNullException(well,extension methods in Enumerable throw ArgumentNullException) when an extension method is called on null?I would like to have a clarification on this?If the answer is an Yes and No please present both the cases.

    Read the article

  • Chrome extension - Localstorage not working

    - by Bjarki Jonasson
    I'm writing a Chrome extension that uses a content script to modify certain parts of a website. The content script worked fine until I tried to add an options page to my extension. Right now I'm using an options.html file to save user preferences to localstorage, as you can see here: <html> <head><title>Options</title></head> <script type="text/javascript"> function save_options() { var select = document.getElementById("width"); var width = select.children[select.selectedIndex].value; localStorage["site_width"] = width; } function restore_options() { var fwidth = localStorage["site_width"]; if (!fwidth) { return; } var select = document.getElementById("width"); for (var i = 0; i < select.children.length; i++) { var child = select.children[i]; if (child.value == fwidth) { child.selected = "true"; break; } } } </script> <body onload="restore_options()"> Width: <select id="width"> <option value="100%">100%</option> <option value="90%">90%</option> <option value="80%">80%</option> <option value="70%">70%</option> </select> <br> <button onclick="save_options()">Save</button> </body> </html> I also have a background.html file to handle the communication between the content script and the localstorage: <html> <script type="text/javascript"> chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if (request.method == "siteWidth") sendResponse({status: localStorage["site_width"]}); else sendResponse({}); }); </script> </html> Then there's the actual content script that looks like this: var Width; chrome.extension.sendRequest({method: "siteWidth"}, function(response) { width = response.status; }); None of that code actually works. It looks solid enough to me but I'm not a very experienced programmer so I might be wrong. Could someone explain localstorage to me in layman's terms?

    Read the article

  • Adding a custom option using an extension in Magento

    - by Tom
    I'm creating a custom extension and I would like to add a custom option when a certain item is purchased. For example, when the product "Name Tag" is purchased, the extension would detect that the specific product has been ordered and assign a custom option of "Year" to it. The user does not see this, but the attribute is added and displayed in the admin when viewing the order. Are there any specific listeners our there to accomplish this?

    Read the article

  • Localize WiX installer which uses the Firewall extension

    - by tronda
    I've got a WiX installer project which uses MSBuild to generate the MSI file. The WXS file includes the WiX firewall extension: xmlns:fire="http://schemas.microsoft.com/wix/FirewallExtension" I've defined two cultures in the MSBuild file with the following definition: <PropertyGroup> ... <Cultures>en-us;no-no</Cultures> </PropertyGroup> I've also added the translated resources: <ItemGroup> <EmbeddedResource Include="lang\Firewall_no-no.wxl" /> <EmbeddedResource Include="lang\WixUI_no-no.wxl" /> </ItemGroup> These represents translation to Norwegian for the Firewall extension and the WixUI extension. When I run the build it succeeds with the en-us part, but the no-no part fails with the following error messages: C:\delivery\Dev\wix30_public\src\ext\FirewallExtension\wixlib\FirewallExtension.wxs(19): error LGHT0102: The localization variable !(loc.WixSchedFirewallExceptionsInstall) is unknown. Please ensure the variable is defined. .... Couple of issues: I don't know where the C:\delivery directory comes from. I don't have such a directory. The localization variables referenced in the error message have been translated in the Firewall_no-no.wxl file. When I run MSBuild with more detailed information I see the following output right before the error message: Task "Light" Command: C:\Program Files (x86)\Windows Installer XML v3\bin\Light.exe -cultures:no-no -ext "C:\Program Files (x86)\Windows Installer XML v3\bin\WixUIExtension.dll" -ext "C:\Program Files (x86)\Windows I nstaller XML v3\bin\WixUtilExtension.dll" -ext "C:\Program Files (x86)\Windows Installer XML v3\bin\WixFirewallExtension.dll" -loc lang\Firewall_no-no.wxl -loc lang\WixUI_no-no.wxl -out F:\Projects\MyProd\MyProj\Installer\bin\Debug\no-no\MyInstaller.msi -pdbout F:\Projects\MyProd\MyProj\Installer\bin\Debug\no-no\MyInstaller.wixpdb obj\Debug\MyProj.wixobj As the details show, the MSBuild task results in having two -loc parameters to the Light executable. Not sure if that would be the reason for this problem. Any ideas on how to solve this?

    Read the article

  • Gmagick extension for php install -- how and where?

    - by Vivek Chandra
    Downloaded php-pear and tried installing gmagick extension by following the steps given in link "http://www.gerd-riesselmann.net/development/how-install-imagick-and-gmagick-ubuntu" The pecl gave an error -- gmagick-1.0.9b1$ pecl install gmagick Failed to download pecl/gmagick within preferred state "stable", latest release is version 1.0.9b1, stability "beta", use "channel://pecl.php.net/gmagick-1.0.9b1" to install install failed Tried adding the channel (no result)-- gmagick-1.0.9b1$ pecl channel-add http://pecl.php.net/package/gmagick/1.0.9b1 Error: No version number found in tag channel-add: invalid channel.xml file Found the link "http://pecl.php.net/package/gmagick" to download the php extension untar'd it to find the following files -- gmagick-1.0.9b1$ ls config.m4 gmagickdraw_methods.c gmagick_methods.c LICENSE php_gmagick_helpers.h README gmagick.c gmagick_helpers.c gmagickpixel_methods.c php_gmagick.h php_gmagick_macros.h Tried . / config.m4 only to find more errors gmagick-1.0.9b1$ . / config.m4 ./config.m4: line 1: syntax error near unexpected token `gmagick,' ./config.m4: line 1: `PHP_ARG_WITH(gmagick, whether to enable the gmagick extension,' Been at this since a day with no result.Read that gmagick is a swiss knife of image processing,sad that there isnt much documentation done on it or at least a proper how to install link anywhere. Badly need help. Thanks in advance.

    Read the article

  • Lambdas within Extension methods: Possible memory leak?

    - by Oliver
    I just gave an answer to a quite simple question by using an extension method. But after writing it down i remembered that you can't unsubscribe a lambda from an event handler. So far no big problem. But how does all this behave within an extension method?? Below is my code snipped again. So can anyone enlighten me, if this will lead to myriads of timers hanging around in memory if you call this extension method multiple times? I would say no, cause the scope of the timer is limited within this function. So after leaving it no one else has a reference to this object. I'm just a little unsure, cause we're here within a static function in a static class. public static class LabelExtensions { public static Label BlinkText(this Label label, int duration) { Timer timer = new Timer(); timer.Interval = duration; timer.Tick += (sender, e) => { timer.Stop(); label.Font = new Font(label.Font, label.Font.Style ^ FontStyle.Bold); }; label.Font = new Font(label.Font, label.Font.Style | FontStyle.Bold); timer.Start(); return label; } }

    Read the article

  • Having trouble with extension methods for byte arrays

    - by Dave
    I'm working with a device that sends back an image, and when I request an image, there is some undocumented information that comes before the image data. I was only able to realize this by looking through the binary data and identifying the image header information inside. I've been able to make everything work fine by writing a method that takes a byte[] and returns another byte[] with all of this preamble "stuff" removed. However, what I really want is an extension method so I can write image_buffer.RemoveUpToByteArray(new byte[] { 0x42, 0x4D }); instead of byte[] new_buffer = RemoveUpToByteArray( image_buffer, new byte[] { 0x42, 0x4D }); I first tried to write it like everywhere else I've seen online: public static class MyExtensionMethods { public static void RemoveUpToByteArray(this byte[] buffer, byte[] header) { ... } } but then I get an error complaining that there isn't an extension method where the first parameter is a System.Array. Weird, everyone else seems to do it this way, but okay: public static class MyExtensionMethods { public static void RemoveUpToByteArray(this Array buffer, byte[] header) { ... } } Great, that takes now, but still doesn't compile. It doesn't compile because Array is an abstract class and my existing code that gets called after calling RemoveUpToByteArray used to work on byte arrays. I could rewrite my subsequent code to work with Array, but I am curious -- what am I doing wrong that prevents me from just using byte[] as the first parameter in my extension method?

    Read the article

  • Safari Extension Questions

    - by Rob Wilkerson
    I'm in the process of building my first Safari extension--a very simple one--but I've run into a couple of problems. The extension boils down to a single, injected script that attempts to bypass the native feed handler and redirect to an http:// URI. My issues so far are twofold: The "whitelist" isn't working the way I'd expect. Since all feeds are shown under the "feed://" protocol, I've tried to capture that in the whitelist as "feed://*/*" (with nothing in the blacklist), but I end up in a request loop that I can't understand. If I set blacklist values of "http://*/*" and "https://*/*", everything works as expected. I can't figure out how to access my settings from my injected script. The script creates a beforeload event handler, but can't access my settings using the safari.extension.settings path indicated in the documentation. I haven't found anything in Apple's documentation to indicate that settings shouldn't be available from my script. Since extensions are such a new feature, even Google returns limited relevant results and most of those are from the official documentation. What am I missing? Thanks.

    Read the article

  • Automate the signature of the update.rdf manifest for my firefox extension

    - by streetpc
    Hello, I'm developing a firefox extension and I'd like to provide automatic update to my beta-testers (who are not tech-savvy). Unfortunately, the update server doesn't provide HTTPS. According to the Extension Developer Guide on signing updates, I have to sign my update.rdf and provide an encoded public key in the install.rdf. There is the McCoy tool to do all of this, but it is an interactive GUI tool and I'd like to automate the extension packaging using an Ant script (as this is part of a much bigger process). I can't find a more precise description of what's happening to sign the update.rdf manifest than below, and McCoy source is an awful lot of javascript. The doc says: The add-on author creates a public/private RSA cryptographic key pair. The public part of the key is DER encoded and then base 64 encoded and added to the add-on's install.rdf as an updateKey entry. (...) Roughly speaking the update information is converted to a string, then hashed using a sha512 hashing algorithm and this hash is signed using the private key. The resultant data is DER encoded then base 64 encoded for inclusion in the update.rdf as an signature entry. I don't know well about DER encoding, but it seems like it needs some parameters. So would anyone know either the full algortihm to sign the update.rdf and install.rdf using a predefined keypair, or a scriptable alternative to McCoy whether a command-line tool like asn1coding will suffise a good/simple developer tutorial on DER encoding

    Read the article

  • C# Thread-safe Extension Method

    - by Wonko the Sane
    Hello All, I may be waaaay off, or else really close. Either way, I'm currently SOL. :) I want to be able to use an extension method to set properties on a class, but that class may (or may not) be updated on a non-UI thread, and derives from a class the enforces updates to be on the UI thread (which implements INotifyPropertyChanged, etc). I have a class defined something like this: public class ClassToUpdate : UIObservableItem { private readonly Dispatcher mDispatcher = Dispatcher.CurrentDispatcher; private Boolean mPropertyToUpdate = false; public ClassToUpdate() : base() { } public Dispatcher Dispatcher { get { return mDispatcher; } } public Boolean PropertyToUpdate { get { return mPropertyToUpdate; } set { SetValue("PropertyToUpdate", ref mPropertyToUpdate, value; } } } I have an extension method class defined something like this: static class ExtensionMethods { public static IEnumerable<T> SetMyProperty<T>(this IEnumerable<T> sourceList, Boolean newValue) { ClassToUpdate firstClass = sourceList.FirstOrDefault() as ClassToUpdate; if (firstClass.Dispatcher.Thread.ManagedThreadId != System.Threading.Thread.CurrentThread.ManagedThreadId) { // WHAT GOES HERE? } else { foreach (var classToUpdate in sourceList) { (classToUpdate as ClassToUpdate ).PropertyToUpdate = newValue; yield return classToUpdate; } } } } Obviously, I'm looking for the "WHAT GOES HERE" in the extension method. Thanks, wTs

    Read the article

  • Extension method using Reflection to Sort

    - by Xavier
    I implemented an extension "MyExtensionSortMethod" to sort collections (IEnumerate). This allows me to replace code such as 'entities.OrderBy( ... ).ThenByDescending( ...)' by 'entities.MyExtensionSortMethod()' (no parameter as well). Here is a sample of implementation: //test function function Test(IEnumerable<ClassA> entitiesA,IEnumerable<ClassB> entitiesB ) { //Sort entitiesA , based on ClassA MySort method var aSorted = entitiesA.MyExtensionSortMethod(); //Sort entitiesB , based on ClassB MySort method var bSorted = entitiesB.MyExtensionSortMethod(); } //Class A definition public classA: IMySort<classA> { .... public IEnumerable<classA> MySort(IEnumerable<classA> entities) { return entities.OrderBy( ... ).ThenBy( ...); } } public classB: IMySort<classB> { .... public IEnumerable<classB> MySort(IEnumerable<classB> entities) { return entities.OrderByDescending( ... ).ThenBy( ...).ThenBy( ... ); } } //extension method public static IEnumerable<T> MyExtensionSortMethod<T>(this IEnumerable<T> e) where T : IMySort<T>, new() { //the extension should call MySort of T Type t = typeof(T); var methodInfo = t.GetMethod("MySort"); //invoke MySort var result = methodInfo.Invoke(new T(), new object[] {e}); //Return return (IEnumerable < T >)result; } public interface IMySort<TEntity> where TEntity : class { IEnumerable<TEntity> MySort(IEnumerable<TEntity> entities); } However, it seems a bit complicated compared to what it does so I was wondering if they were another way of doing it?

    Read the article

  • How to stop my firefox extension which interferes other extension?

    - by ccppjava
    Hi, I have tried very hard to make my extension as simple as possible, it now do not contain any skin/css, it just have 'statusbar' in one single 'overlay'. The issue is that when installed, it hides the top three icon of 'all-in-one toolbar' extension of my firefox 3.6.3. On other two machine which do not have 'all-in-one toolbar', it hide all the icons of the web-development toolbar! chrome.manifest content stackoverflow content/ content stackoverflow content/ contentaccessible=yes overlay chrome://browser/content/browser.xul chrome://stackoverflow/content/browser.xul locale stackoverflow en-US locale/en-US/ browser.xul <overlay id="dch-browser-overlay" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/x-javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"/> <script src="stackoverflow.js" /> <statusbar id="status-bar"> <statusbarpanel id="stackoverflow-status-bar-icon" class="statusbarpanel-iconic" src="chrome://stackoverflow/content/icon_small.png" tooltiptext="&runstackoverflow;" onclick="stackoverflow.run()" /> </statusbar> </overlay> I have tried very hard to simplify the extension to find the reason, but failed, any suggestion/ideas would be welcome. thx.

    Read the article

  • Objects in JavaScript defined and undefined at the same time (in a FireFox extension)

    - by Alexey Romanov
    I am chasing down a bug in a FireFox extension. I've finally managed to see it for myself (I've only had reports before) and I can't understand how what I saw is possible. One error message from my extension in the Error Console is "gBrowser is not defined". This by itself would be surprising enough, since the overlay is over browser.xul and navigator.xul, and I expect gBrowser to be available from both. Even worse is the actual place where it happens: line 101 of nextplease.js. That is, inside the function isTopLevelDocument, which is only called from onContentLoaded, which is only called from onLoad here: gBrowser.addEventListener(this.loadType, function (event) { nextplease.loadListener.onContentLoaded(event); }, true); So gBrowser is defined in onLoad, but somehow undefined in isTopLevelDocument. When I tried to actually use the extension, I got another error: "nextplease is not defined". The interesting thing is that it happened on lines 853 and 857. That is, inside the functions nextplease.getNextLink = function () { nextplease.getLink(window.content, nextplease.NextPhrasesMap, nextplease.NextImagesMap, nextplease.isNextRegExp, nextplease.NEXT_SEARCH_TYPE); } nextplease.getPrevLink = function () { nextplease.getLink(window.content, nextplease.PrevPhrasesMap, nextplease.PrevImagesMap, nextplease.isPrevRegExp, nextplease.PREV_SEARCH_TYPE); } So nextplease is somehow defined enough to call these functions, but isn't defined inside them. Finally, executing typeof(nextplease) in Execute JS returns "object". Same for gBrowser. How can this happen? Any ideas?

    Read the article

  • Extension methods conflict

    - by Yochai Timmer
    Lets say I have 2 extension methods to string, in 2 different namespaces: namespace test1 { public static class MyExtensions { public static int TestMethod(this String str) { return 1; } } } namespace test2 { public static class MyExtensions2 { public static int TestMethod(this String str) { return 2; } } } These methods are just for example, they don't really do anything. Now lets consider this piece of code: using System; using test1; using test2; namespace blah { public static class Blah { public Blah() { string a = "test"; int i = a.TestMethod(); //Which one is chosen ? } } } I know that only one of the extension methods will be chosen. Which one will it be ? and why ? How can I choose a certain method from a certain namespace ? Edit: Usually I'd use Namespace.ClassNAME.Method() ... But that just beats the whole idea of extension methods. And I don't think you can use Variable.Namespace.Method()

    Read the article

  • google chrome extension update text after response callback

    - by Jerome
    I am writing a Google Chrome extension. I have reached the stage where I can pass messages back and forth readily but I am running into trouble with using the response callback. My background page opens a message page and then the message page requests more information from background. When the message page receives the response I want to replace some of the standard text on the message page with custom text based on the response. Here is the code: chrome.extension.sendRequest({cmd: "sendKeyWords"}, function(response) { keyWordList=response.keyWordsFound; var keyWords=""; for (var i = 0; i FIRST QUESTION: This all seems to work fine but the text on the page doesn't change. I am almost certainly because the callback completes after the page is finished loading and the rest of the code finishes before the callback completes, too. How do I update the page with the new text? Can I listen for the callback to complete or something like that? SECOND QUESTION: The procedure I am pursuing first opens the message page and then the message page requests the keyword list from background. Since I always want the keyword list, it makes more sense to just send it when I create the tab. Can I do that? Here is the code from background that opens the message page: //when request from detail page to open message page chrome.extension.onRequest.addListener(function(request, sender, sendResponse) { if(request.cmd == "openMessage") { console.log("Received Request to Open Message, Profile Score: "+request.keyWordsFound.length); keyWordList=request.keyWordsFound; chrome.tabs.create({url: request.url}, function(tab){ msgTabId=tab.id; //needed to determine if message tab has later been closed chrome.tabs.executeScript(tab.id, {file: "message.js"}); }); console.log("Opening Message"); } });

    Read the article

  • Web scrapping from a Google Chrome extension

    - by limoragni
    I've started to develop a Chrome extension to navigate and prform actions on a website. Until now the extension is able to receive a couple of parameters and check a set of radio-buttons, fill in a few inputs of a form and then submit it. What I want to do now is to repeat the process, but I'm stuck when the page is reloaded. And I don't know how can I do to make the script reacts to the finish of the request. The workflow I want to achieve is the following (is for automaticly copying a certain object): Popup side Enter the number of the Master object to copy Enter the base name of the copies (example Mod, so the I can iterate and add mod1, mod2, modn) Enter the number of copies Background side Select master Select standard options Fill in inputs Submit form Wait for the page to complete the request and continue to the next copy. (here I need help) The problem is on the repetition, the rest is taking care of. I assume that must be a way of dealing with requests. Any ideas? By the way I'm doing it all with the extension and tabs methods of google chrome plus javascript and jquery.

    Read the article

  • 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

  • ASP.Net MVC view unable to see HtmlHelper extension method

    - by larryq
    Hi everyone, We're going through an ASP.Net MVC book and are having trouble with using an extenstion method within our view. The Extension method looks like this: using System; using System.Runtime.CompilerServices; using System.Web.Mvc; namespace MvcBookApplication { public static class HtmlHelperExtensions { public static string JQueryGenerator(this HtmlHelper htmlHelper, string formName, object model); } } We use the extension method in our view like this: <%=Html.JQueryGenerator("createmessage", ViewData.Model)%> The problem is, that line of code says JQueryGenerator isn't a recognized method of HtmlHelper. I believe we've got the correct references set in the web project, but are there other things we can check? There's no using statement for views, is there?

    Read the article

  • Extension method not working if I set controller property in Action, works in OnExecuting

    - by Blankman
    I have a class MyController that inherits from Controller, so all my controllers inherit from MyController. I have a property in MyController: public class MyController : Controller { public string SomeProperty {get;set;} } if I set this property in MyController's OnExecuting method, my HtmlHelper extension method works fine: public static string SomeExtension(this HtmlHelper htmlHelper) { StringBuilder sb = new StringBuilder(); string result = ""; var controller = htmlHelper.ViewContext.Controller as MyController; if (controller != null) { result = controller.SomeProperty; } return result; } it doesn't work if I set 'SomeProperty' in my controllers action method. I guess because I am doing 'as MyController' in the extension method? is there a way for it to work in both situations? I am using the value of SomeProperty to be outputted on my view pages.

    Read the article

  • [Visual Studio Extension Of The Day] Test Scribe for Visual Studio Ultimate 2010 and Test Professional 2010

    - by Hosam Kamel
      Test Scribe is a documentation power tool designed to construct documents directly from the TFS for test plan and test run artifacts for the purpose of discussion, reporting etc... . Known Issues/Limitations Customizing the generated report by changing the template, adding comments, including attachments etc… is not supported While opening a test plan summary document in  Office 2007, if you get the warning: “The file Test Plan Summary cannot be opened because there are problems with the contents” (with Details: ‘The file is corrupt and cannot be opened’), click ‘OK’. Then, click ‘Yes’ to recover the contents of the document. This will then open the document in Office 2007. The same problem is not found in Office 2010. Generated documents are stored by default in the “My documents” folder. The output path of the generated report cannot be modified. Exporting word documents for individual test suites or test cases in a test plan is not supported. Download it from Visual Studio Extension Manager Originally posted at "Hosam Kamel| Developer & Platform Evangelist" http://blogs.msdn.com/hkamel

    Read the article

  • C# Extension Methods - To Extend or Not To Extend...

    - by James Michael Hare
    I've been thinking a lot about extension methods lately, and I must admit I both love them and hate them. They are a lot like sugar, they taste so nice and sweet, but they'll rot your teeth if you eat them too much.   I can't deny that they aren't useful and very handy. One of the major components of the Shared Component library where I work is a set of useful extension methods. But, I also can't deny that they tend to be overused and abused to willy-nilly extend every living type.   So what constitutes a good extension method? Obviously, you can write an extension method for nearly anything whether it is a good idea or not. Many times, in fact, an idea seems like a good extension method but in retrospect really doesn't fit.   So what's the litmus test? To me, an extension method should be like in the movies when a person runs into their twin, separated at birth. You just know you're related. Obviously, that's hard to quantify, so let's try to put a few rules-of-thumb around them.   A good extension method should:     Apply to any possible instance of the type it extends.     Simplify logic and improve readability/maintainability.     Apply to the most specific type or interface applicable.     Be isolated in a namespace so that it does not pollute IntelliSense.     So let's look at a few examples in relation to these rules.   The first rule, to me, is the most important of all. Once again, it bears repeating, a good extension method should apply to all possible instances of the type it extends. It should feel like the long lost relative that should have been included in the original class but somehow was missing from the family tree.    Take this nifty little int extension, I saw this once in a blog and at first I really thought it was pretty cool, but then I started noticing a code smell I couldn't quite put my finger on. So let's look:       public static class IntExtensinos     {         public static int Seconds(int num)         {             return num * 1000;         }           public static int Minutes(int num)         {             return num * 60000;         }     }     This is so you could do things like:       ...     Thread.Sleep(5.Seconds());     ...     proxy.Timeout = 1.Minutes();     ...     Awww, you say, that's cute! Well, that's the problem, it's kitschy and it doesn't always apply (and incidentally you could achieve the same thing with TimeStamp.FromSeconds(5)). It's syntactical candy that looks cool, but tends to rot and pollute the code. It would allow things like:       total += numberOfTodaysOrders.Seconds();     which makes no sense and should never be allowed. The problem is you're applying an extension method to a logical domain, not a type domain. That is, the extension method Seconds() doesn't really apply to ALL ints, it applies to ints that are representative of time that you want to convert to milliseconds.    Do you see what I mean? The two problems, in a nutshell, are that a) Seconds() called off a non-time value makes no sense and b) calling Seconds() off something to pass to something that does not take milliseconds will be off by a factor of 1000 or worse.   Thus, in my mind, you should only ever have an extension method that applies to the whole domain of that type.   For example, this is one of my personal favorites:       public static bool IsBetween<T>(this T value, T low, T high)         where T : IComparable<T>     {         return value.CompareTo(low) >= 0 && value.CompareTo(high) <= 0;     }   This allows you to check if any IComparable<T> is within an upper and lower bound. Think of how many times you type something like:       if (response.Employee.Address.YearsAt >= 2         && response.Employee.Address.YearsAt <= 10)     {     ...     }     Now, you can instead type:       if(response.Employee.Address.YearsAt.IsBetween(2, 10))     {     ...     }     Note that this applies to all IComparable<T> -- that's ints, chars, strings, DateTime, etc -- and does not depend on any logical domain. In addition, it satisfies the second point and actually makes the code more readable and maintainable.   Let's look at the third point. In it we said that an extension method should fit the most specific interface or type possible. Now, I'm not saying if you have something that applies to enumerables, you create an extension for List, Array, Dictionary, etc (though you may have reasons for doing so), but that you should beware of making things TOO general.   For example, let's say we had an extension method like this:       public static T ConvertTo<T>(this object value)     {         return (T)Convert.ChangeType(value, typeof(T));     }         This lets you do more fluent conversions like:       double d = "5.0".ConvertTo<double>();     However, if you dig into Reflector (LOVE that tool) you will see that if the type you are calling on does not implement IConvertible, what you convert to MUST be the exact type or it will throw an InvalidCastException. Now this may or may not be what you want in this situation, and I leave that up to you. Things like this would fail:       object value = new Employee();     ...     // class cast exception because typeof(IEmployee) != typeof(Employee)     IEmployee emp = value.ConvertTo<IEmployee>();       Yes, that's a downfall of working with Convertible in general, but if you wanted your fluent interface to be more type-safe so that ConvertTo were only callable on IConvertibles (and let casting be a manual task), you could easily make it:         public static T ConvertTo<T>(this IConvertible value)     {         return (T)Convert.ChangeType(value, typeof(T));     }         This is what I mean by choosing the best type to extend. Consider that if we used the previous (object) version, every time we typed a dot ('.') on an instance we'd pull up ConvertTo() whether it was applicable or not. By filtering our extension method down to only valid types (those that implement IConvertible) we greatly reduce our IntelliSense pollution and apply a good level of compile-time correctness.   Now my fourth rule is just my general rule-of-thumb. Obviously, you can make extension methods as in-your-face as you want. I included all mine in my work libraries in its own sub-namespace, something akin to:       namespace Shared.Core.Extensions { ... }     This is in a library called Shared.Core, so just referencing the Core library doesn't pollute your IntelliSense, you have to actually do a using on Shared.Core.Extensions to bring the methods in. This is very similar to the way Microsoft puts its extension methods in System.Linq. This way, if you want 'em, you use the appropriate namespace. If you don't want 'em, they won't pollute your namespace.   To really make this work, however, that namespace should only include extension methods and subordinate types those extensions themselves may use. If you plant other useful classes in those namespaces, once a user includes it, they get all the extensions too.   Also, just as a personal preference, extension methods that aren't simply syntactical shortcuts, I like to put in a static utility class and then have extension methods for syntactical candy. For instance, I think it imaginable that any object could be converted to XML:       namespace Shared.Core     {         // A collection of XML Utility classes         public static class XmlUtility         {             ...             // Serialize an object into an xml string             public static string ToXml(object input)             {                 var xs = new XmlSerializer(input.GetType());                   // use new UTF8Encoding here, not Encoding.UTF8. The later includes                 // the BOM which screws up subsequent reads, the former does not.                 using (var memoryStream = new MemoryStream())                 using (var xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding()))                 {                     xs.Serialize(xmlTextWriter, input);                     return Encoding.UTF8.GetString(memoryStream.ToArray());                 }             }             ...         }     }   I also wanted to be able to call this from an object like:       value.ToXml();     But here's the problem, if i made this an extension method from the start with that one little keyword "this", it would pop into IntelliSense for all objects which could be very polluting. Instead, I put the logic into a utility class so that users have the choice of whether or not they want to use it as just a class and not pollute IntelliSense, then in my extensions namespace, I add the syntactical candy:       namespace Shared.Core.Extensions     {         public static class XmlExtensions         {             public static string ToXml(this object value)             {                 return XmlUtility.ToXml(value);             }         }     }   So now it's the best of both worlds. On one hand, they can use the utility class if they don't want to pollute IntelliSense, and on the other hand they can include the Extensions namespace and use as an extension if they want. The neat thing is it also adheres to the Single Responsibility Principle. The XmlUtility is responsible for converting objects to XML, and the XmlExtensions is responsible for extending object's interface for ToXml().

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >