Thursday, April 14, 2011

Viewing all event handlers associated with a Button?

I have a number of Inherited User Controls, for each User Control I sometimes have overridden event Handlers for the Buttons on the Control. (To allow for Child specific behaviours to occur)

Is there a way of viewing all the Event Handlers associated with a particular component?

The problem being that on one of the Buttons, the event handler wass being called twice. I believe this was due to the fact that I had assigned the Click Event Handler twice, once in the parent and once in the child User Control. I remove the assignment in the child control and now nothing happens when I click the button (within the VS2008 designer)!

Any and all help will be gratefully received!

EDIT

The reason nothing happened is down to a verion control issue .... the child's overidden event handler was incorrect!

But the main point still remains... Im not the only contributer to the codebase, and If I need to see which events are attributed to a component I cant explicitly at the moment. Especially with regards to Timers as we dynamically add and remove events that need t obe 'synchronised' to a single timer. It would be good to see which Events are tagged onto the Tick event?!

From stackoverflow
  • The only way to view all event handlers on a component (that I know of) is to write code to do it for you, probably using Reflection.

    The VS 2008 designer won't do this for you; despite the fact that most events on Controls are multicast, the designer only supports assigning a single handler per event. If you're doing anything more complex than this, you'll only get accurate results if you actually debug your program.

  • Could maybe try look at the source code to see if it is assigned twice? Either in the .cs file or in the .designer.cs file.

  • You could do a text search on entire solution or current project source code based on what you're looking for.
    Search for example: "controlName.EventName +=". You'll directly see what has subscribed to this control event.

  • Using Resharper, I do this using Shift-F12, which shows a tree view of all usages (including usages via an interface). Without Resharper, it is probably simplest to use text search as Tyalis suggests.

What are good code deployment strategies?

I am working on a Django project. And our team follows agile practices(TDD,very short launch times etc..)

When it comes to deployment stage of a feature, we follow manual procedures to get the code deployed on to our production machine. Manual procedures in the sense, run the testcases(of the entire project) manually and run the syncdb(or any latest db changes) manually and other stuff.

This manual stuff is taking about half and hour per day,everyday. So I wanted to automate this. So is there any automatic deployer or something that takes the commands I give and do what I want or it should be done only MANUALLY??(using a simple shell file which has got all my commands. In which case, I need to learn shell programming a bit because I dont want to uupdate my latest code in my production machine if any test case fails. So such a sort of conditions exist for deploying, which may involve a bit of shell programming. I guess!)

From stackoverflow
  • So in Agile terms, you've identified duplication in your deployment process, now you're looking for ways to refactor it. ;-)

    In the Ruby/Rails world, you'd turn first to Capistrano or Vlad The Deployer, and in the Python/Django world you'd turn to the equivalent, except AFAIK there isn't one.

    It seems from this post that Capistrano has been used successfully to handle Django deployment, so that's an option worth exploring.

    Beyond that, why would you need shell programming? You have a super-powerful scripting language in Python - why not automate your manual process in that?

  • I just started researching this myself and it looks like the Python-equivalent of Capistrano is Fabric, although maybe not as mature. There seem to be a growing number of people wanting to switch over simply because Capistrano is too ruby/rails centric, although I haven't seen anyone complain about Capistrano being incapable or lacking. YMMV. More info here and here.

    EDIT: Looks like Fabric is undergoing a lot of changes. They're moving their homepage to http://docs.fabfile.org/

    hughdbrown : More detail on fabric: http://stackoverflow.com/questions/1233655/what-is-the-simplest-way-to-ssh-using-python
    Maddy : One of my collegues wrote a python script for handling 'svn update', run testcases and othercases(based on the conditions mentioned in the question, also). It falls on the same lines as Fabric

C++ compiler that supports C++0x features?

Is where any C++ compiler that supports C++0x features already?

From stackoverflow
  • Both the 2008 Visual C++ 'Feature Pack' and g++ support some features.

    The list of C++0x features supported by g++.


    The Visual C++ 2008 Feature Pack ... includes an implementation of TR1. Portions of TR1 are scheduled for adoption in the upcoming C++0x standard as the first major addition to the ISO 2003 standard C++ library. Our implementation includes a number of important features such as:

    • Smart pointers
    • Regular expression parsing
    • New containers (tuple, array, unordered set, etc)
    • Sophisticated random number generators
    • Polymorphic function wrappers
    • Type traits
    • And more!
    shoosh : I'm pretty sure VS2008 doesn't support any C++0x features. do you have any references for that?
    Pete Kirkham : You made that comment the same minute I added the link.
  • GCC has some of it supported. See here.

  • There are compilers that partially support C++0x, but there can't be full support yet because the final C++0x has not yet been standardized.

    • GCC 4.4 (not released yet) would support some features like auto.
    • GCC 4.3 has not bad tr1 support and some feature like Variadic templates.
    • Latest Intel compiler supports quite well some C++0x features: it already has support of auto and lambda function.
    caspin : 4.2 has complete tr1 support, I believe the 4.1 and 4.0 do as well.
    Artyom : Not really, even 4.3 has "regex" support and you can even compile but regex_match always returns false... it is in GCC to do list. I think in 4.4 dev. branch this should be ok.
  • Microsoft's Visual Studio 2010 CTP (Community Technology Preview) contains support for four C++0x features namely lambdas, auto, static_assert, and rvalue references.

    You can download the VPC image here, make sure to read the bit about accounting for the January 1 2009 expiry date (this blog post is referenced).

    Peter McGrattan : If possible please explain downvote thanks
    Pete Kirkham : Anyone mentioning anything other than g++ gets downvoted by fanboys. Compare my post vs Andy's - both have same link, but also mention VC++, so get down votes.
    Peter McGrattan : @Pete: Thanks I wasn't sure if I had got something incorrect. I thought I'd add a reference to VS2010 since no one else had yet mentioned it. Irrelevantly I do also use g++ as when on linux - surely there is enough room for both especially when answering questions.
  • Scott Meyers has a nice detailed summary of C++0x support across some common compilers here:

    http://www.aristeia.com/C++0x/C++0xFeatureAvailability.htm

how to find host name from IP with out login to the host

i need to find the host name of a UNIX host whose IP is known with out login to that UNIX host

From stackoverflow
  • Use nslookup

    nslookup 208.77.188.166 
    ...
    Non-authoritative answer:
    166.188.77.208.in-addr.arpa     name = www.example.com.
    
  • You can use traceroute command as well.

    http://linux.die.net/man/8/traceroute

    just use the traceroute it will show you the routing path with host names (IPs resolved)

  • You can do a reverse DNS lookup with host, too. Just give it the IP address as an argument:

    $ host 192.168.0.10
    server10 has address 192.168.0.10
    
  • The other answers here are correct - use reverse DNS lookups. If you want to do it via a scripting language (Python, Perl) you could use the gethostbyaddr API.

Execute a statement after thread gets over.

Hi,

I am having a function where I have used a thread in c#.net.

I am having a another function on the next line of that thread. But this function has to be called only after the thread gets executed.

How can i do it ?

Example..

Somefunction()
{
    // thread        //(thread started)
    add()            (another function but need to be executed only tha above thread gets over)
}
From stackoverflow
  • Why start a separate thread if you want execution to be single threaded?

    Dave Van den Eynde : It's a common example of starting an operation in the background, do something else in the mean while and then wait for that background operation to complete before proceeding.
    ck : That makes sense, but its not what the OP is asking for
    Dave Van den Eynde : Are you sure about that?
    ck : I think so, he says he starts a thread, then runs something else when that thread is done.
    Dave Van den Eynde : Well exactly, he probably starts up a second thread to do some background processing, and now wants to make sure it's over before stepping onto the add() call.
    Cerebrus : @CK: I think @Dave is right on this point. The question did sound peculiarly put to me, but I think it means the same thing.
  • Use a BackgroundWorker and include the function call in the worker completeted event handler.

    var worker = new BackgroundWorker();
    _worker.DoWork += delegate { DoStuff(); };    
    _worker.RunWorkerCompleted += worker_RunWorkerCompleted;
    _worker.RunWorkerAsync();
    
    
    [...]
    
    private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
       /// Do post-thread stuff
    }
    
  • by "after the thread gets executed", do you mean it must have started? or it must have finished?

    If you mean finished, then you would typically Join() the thread - but there is no point Join()ing a thread you have stared in the line before (just execute the code directly). The other approach is to use a "callback" at the end of the threaded method.

    If you mean started, then you can do things like:

    object lockObj = new object();
    lock(lockObj) {
        ThreadPool.QueueUserWorkItem(delegate {
            lock(lockObj) {
                Monitor.Pulse(lockObj);
            }
            // do things (we're on the second thread...)
        });
        Monitor.Wait(lockObj);
    }
    // thread has definitely started here
    
  • You can use , for instance, a ManualResetEvent. When you start the processing on the other thread, you call the reset method. When processing on the other thread has finished, you call set. Then, the method that must be executed on the 'main thread', needs to wait until the ManualResetEvent has been set before it can execute.

    For more info, you can have a look at the ManualResetEvent at MSDN.

  • Use Thread.Join to block the current thread until the specified thread has finished execution.

  • If add() is thread safe, just call it at the end of the function you pass to create thread.

  • You could try the following, it may not work for your scenario: I can't tell given the amount of detail you provided:

    First create a delegate:

    public delegate int MyThreadSignature(Something arg);
    

    Then use the Begin/End Invoke pattern:

    var thread = new MyThreadSignature(WorkerMethod);
    thread.BeginInvoke(theArg, 
                       MyThreadEnded, /*Method to call when done*/, 
                       thread /*AsyncState*/);
    

    Create the MyThreadEnded method:

    void MyThreadEnded(IAsyncResult result)
    {
        var thread = (MyThreadSignature)result.AsyncState;
        var result = thread.EndInvoke(result);
        // Call your next worker here.
    }
    

    The method to call MUST have the signature in the example: Name(IAsyncResult result).

Locales and ResourceBundles in a plugin-based program

We need to start adding internationalisation to our program. Thankfully not the whole thing yet, just a few bits, but I want the way we do it to scale up to potentially cover the whole program. The thing is, our program is based on plugins, so not all strings belong in the same place.

As far as I understand it, Java's ResourceBundle work like this. You create a class that extends ResourceBundle, called something like MyProgramStrings, and also language-specific classes called MyProgramStrings_fr, MyProgramStrings_es etc. Each of these classes maps keys (strings) to values (any object). It's up to each of these classes where to get its data from, but a common place for them is a properties file.

You look up values in two stages: first you get the correct bundle, then you query it for the string you want.

Locale locale = Locale.getDefault(); // or = new Locale("en", "GB");
ResourceBundle rb = ResourceBundle.getBundle("MyProgramStrings", locale);
String wotsitName = rb.getString("wotsit.name");

However, what we need is to combine the results of several locales into a single resource space. For example, a plugin needs to be able to override a string that's already defined, and have that new value returned whenever code looks up the string.

I'm a little lost in all this. Can anybody help?


Update: David Waters asked:

I have put my answer at the bottom but I would be interested in hearing how you solved this problem.

Well, we haven't got very far yet - long term WIBNIs always fall victim to the latest crisis - but we're basing it on the interface that a plugin implements, with the convention that resources have the same fully qualified name as the interface.

So an interface UsersAPI may have various different implementations. A method getBundle() on that interface by default returns the equivalent of ResourceBundle.get("...UsersAPI", locale). That file can be replaced, or implementations of UsersAPI can override the method if they need something more complicated.

So far that does what we need, but we're still looking at more flexible solutions based on the plugins.

From stackoverflow
  • You don't have to implement ResourceBundles as a series of classes, with one class per locale (i.e. a class named MyProgramStrings, MyProgramStrings_fr, MyProgramStrings_de). The ResourceBundle class will fall back to using properties files if need be:

    public static void main(String[] args) {
    
     ResourceBundle bundle = ResourceBundle.getBundle("MyResources");
     System.out.println("got bundle: " + bundle);
    
     String valueInBundle = bundle.getString("someKey");
     System.out.println("Value in bundle is: " + valueInBundle);
    }
    

    If I have a file named MyResources.properties on the classpath, then this method will result in:

    got bundle: java.util.PropertyResourceBundle@42e816  
    Value in bundle is: someValue
    

    As for setting up a hierarchy of bundles, or "merging" them together, I'm afraid I can't help much there, except that I know that Spring does have a concept of hierchical MessageSources (link to API) which are implemented on top of java.util.ResourceBundle, so perhaps you can use Spring's functionality to achieve what you want?

    BTW, here is the relevant part of the ResourceBundle.getBundle() javadoc that explains it's "search and instantiation strategy":

    http://java.sun.com/j2se/1.5.0/docs/api/java/util/ResourceBundle.html#getBundle(java.lang.String, java.util.Locale, java.lang.ClassLoader)

    • First, it attempts to load a class using the candidate bundle name. If such a class can be found and loaded using the specified class loader, is assignment compatible with ResourceBundle, is accessible from ResourceBundle, and can be instantiated, getBundle creates a new instance of this class and uses it as the result resource bundle.
    • Otherwise, getBundle attempts to locate a property resource file. It generates a path name from the candidate bundle name by replacing all "." characters with "/" and appending the string ".properties". It attempts to find a "resource" with this name using ClassLoader.getResource. (Note that a "resource" in the sense of getResource has nothing to do with the contents of a resource bundle, it is just a container of data, such as a file.) If it finds a "resource", it attempts to create a new PropertyResourceBundle instance from its contents. If successful, this instance becomes the result resource bundle.
    Marcus Downing : So they properties file is actually mixed in among the sources, and therefore among the classes, and looked up by fully-qualified path name? I just tried that and it worked. Thanks, that makes it clearer and may be the beginnings of a solution...
    matt b : Yep, that's one way you could do it - and probably the simplest.
    Chris Morley : For internationalization, we have found it easier to use external properties files so we don't have to send out sources to the translators.
  • I know Struts and Spring have something for that. But let's say you can't use Struts or Spring then what I would do is to create a subclass of ResourceBundle and load the *.properties (one per plugin) in this ResourceBundle. Then you can use

    ResourceBundle bundle = ResourceBundle.getBundle("MyResources");

    Like you would normally do with a property file.

    Of course, you should cached the result so you don't have to search each Properties every time.

    Marcus Downing : I'm going to need some clarification. When do I instanciate the subclass? How does ResourceBundle.getBundle know of its existence?
    matt b : ResourceBundle.getBundle() searches the classpath for a class whose name matches "the candidate bundle name" ... take a look at the ResourceBundle javadoc link I posted above for a full and more complete explanation
  • getBundle loads a set of candidate bundle files generated using the specified locale (if any) and the default locale.

    Typically, a resource file with no locale info has the "default" values (eg, perhaps en_US values are in MyResources.properties), then over riding resource values are created for different locales (eg ja strings are in MyResources_ja.properties) Any resource in the more specific file overrides the less specific file properties.

    Now you want to add in the ability for each plug-in to provide it's own set of properties files. It isn't clear whether the plug-in would be able to modify the resources of the main app or other plug-ins, but it sounds like you want to have a singleton class where each plug-in can register its base resource file name. All requests for property values go through that singleton, which would then look through the resource bundles of each plug in (in some order ...) and finally the app itself for the property value.

    The Netbeans NbBundle class does similar stuff.

  • I have had a slightly similar problem see question 653682 . The solution I found was to have a class that extends ResourceBundle and, checks if we are overriding the value if not delegate to the PropertyResourceBundle generated from files.

    So if you wanted to store Labels for the UI you would have a class com.example.UILabels and a properties file com.example.UILabelsFiles.

    package com.example;
    
    public class UILabels extends ResourceBundle{
        // plugins call this method to register there own resource bundles to override
        public static void addPluginResourceBundle(String bundleName){
            extensionBundles.add(bundleName);
        }
    
        // Find the base Resources via standard Resource loading
        private ResourceBundle getFileResources(){
            return ResourceBundle.getBundle("com.example.UILabelsFile", this.getLocale());
        }
        private ResourceBundle getExtensionResources(String bundleName){
            return ResourceBundle.getBundle(bundleName, this.getLocale());
        }
    
        ...
        protected Object handleGetObject(String key){
            // If there is an extension value use that
            Object extensionValue = getValueFromExtensionBundles(key);
            if(extensionValues != null)
                return extensionValues;
            // otherwise use the one defined in the property files
            return getFileResources().getObject(key);
        }
    
        //Returns the first extension value found for this key, 
        //will return null if not found    
        //will return the first added if there are multiple.
        private Object getValueFromExtensionBundles(String key){
            for(String bundleName : extensionBundles){
                ResourceBundle rb = getExtensionResources(bundleName);
                Object o = rb.getObject(key);
                if(o != null) return o;
            }
            return null;
        }    
    
    }
    

restrict user input using javascript

Hi there,

Can someone show me some example for restricting user input (on input tag) in Javascript?

Something that when we set the input (type="text") to only accept numeric, so it will ignore any other input except for numeric...

I think it's handy for number input (such as zip, credit card, money, value, score, date etc...), and if you can please show me how to create input with pattern, something like:

Please Input Date:
|-----------------|
|     /     /     |
|-----------------|

PS: I heard WebForms 2.0 will support this in the future... (Acid 3 compliant browser?)

input type="date"
input type="time"
input type="number"
input type="money"

But it was only news from future :D

From stackoverflow
  • You can use specific libs like jQuery Validate (or whatever your JS framework offers) on form submit. The other solution is to control the value on the keyUp & blur events but it can become quite messy to decide what to do with ill-formated entry (especially when the format is a bit complex -- ie not just undesired characters). So, all in all, I'd recommend client-side control on submit.

    Dels : i already have form submit validation method :D
  • This might help you.

    http://www.w3schools.com/jsref/event_onkeydown.asp

    <html>
    <body>
    
    <script type="text/javascript">
    function noNumbers(e)
    {
    var keynum;
    var keychar;
    var numcheck;
    
    if(window.event) // IE
    {
    keynum = e.keyCode;
    }
    else if(e.which) // Netscape/Firefox/Opera
    {
    keynum = e.which;
    }
    keychar = String.fromCharCode(keynum);
    numcheck = /\d/;
    return !numcheck.test(keychar);
    }
    </script>
    
    <form>
    <input type="text" onkeydown="return noNumbers(event)" />
    </form>
    
    </body>
    </html>
    
    Julian Aubourg : Yes, that works for simple character filtering... but what about full-fledged formats like a date ("mm/dd/yy"). You cannot just return false if it's not the proper format or else you won't ever be able to enter the first digits.
    Eibx : No that's true, but it gives a certain idea on how it could be made. Fx. you would only be able to type 0 and 1 in the first charecter of the date string. If the user would type a number above that, the number wouldn't be registered. But yes this specific codes does not do the whole magic.
    Julian Aubourg : yeah, I just commented for clarity ;)
  • This question has already an accepted answer, but I think there is a better solution to this. You don't have to implement that yourself on keydown etc., there are libraries for that. They call the technique you describe "input masks". Check out this jQuery plugin it does exactly what you want.