Wednesday, April 6, 2011

Inheriting ThreadStatic values to implement dynamic scoping in C#/.NET in multithreaded context

Is there a way to make newly-spawned threads inherit the values of ThreadStatic state (or something like it) on their parent threads? I would like to use this (or something like it) to implement "dynamically scoped" special variables that contain operation/task context information to use for tracking/logging, etc. Is this a reasonable approach, and can it be made to work?

From stackoverflow
  • You can't "inherit" values. However, the new ThreadLocal<T> class for .NET 4 allows you to provide a Func<T> in the constructor, which can initialize the thread based on the parent's state. This would provide a reasonable workaround.

    Max Strini : Thanks, this is certainly interesting. But how would I allow the child to access the parent's state?
    Reed Copsey : You could use a lambda in the parent that provides access to the variable(s) in question that are required to initalize the ThreadLocal. This uses a form of lazy initialization, so on first use, you'd get the current parent's state.
    Max Strini : this didn't do what I needed at the time for some reason I've forgotten, but it was nice to know about this anyway.

Does the Jquery validation plugin require a form tag?

I want to validate some asp.net textboxes with the jQuery Validation plugin found at http://docs.jquery.com/Plugins/Validation, but it appears that the elements must be between a form tag. If I have just a couple elements, I would hardly call that a form, so I would rather not have them wrapped inside a form element. Is there a way around this? Also, if I have two buttons on the form, a cancel and a submit button and I want the form only to validate when the submit button is clicked, but not the cancel button, how is this accomplished?

From stackoverflow
  • The jquery validate plugin requires a form element to function, so you should have your form fields (no matter how few) contained inside a form.

    You can tell the validation plugin not to operate on form submission, then manually validate the form when the correct submit button is clicked.

    For example, using a class to identify the correct submit button:

    
    $(document).ready(function() {
      var form = $("form");
    
      form.validate({
        onsubmit: false,
      });
    
      //Validate form only if validation submit button is clicked
      //Allows cancel submit buttons to function properly
      $('.validate', form).click(function() {
        if (form.valid()) {
          form.submit();
        }
        else {
          form.validate().form();
        }
      });
    
    });
    
  • I have just a couple elements, I would hardly call that a form, so I would rather not have them wrapped inside a form element.

    If the elements are not within a form tag, then it is not a valid HTML document, so behavior within script might get wonky depending on how the browser deals with the malformed HTML.

    Most browsers will create a form implicitly, but now you have no control over the form's behavior. The defaults are usually be a post action form targeted at the requested page's URL.

    The problem is, you probably have no idea what selector to use in the JQuery to get a reference to the form... but I suppose $(form) would do the trick.

    validate when the submit button is clicked, but not the cancel button

    The plug-in intercepts and runs on the submit event of a form. Generally cancel buttons are html input elements with the type attribute set to "reset":

    <input type="reset" value="cancel" />
    

    A reset type button will not cause the form to submit, and this will not trigger the validation.

    If you use another button type, make sure the onclick even returns false. This cancels the form's submit action but still allows you to run javasctipt of your own when the button is clicked.

    Xaisoft : I am using an asp:Button for the Cancel and Submit.
    Xaisoft : I actually figured out the second part. I set the UseSubmitBehavior property to false for the cancel button and it made it a regular input type=button instead of a type=submit and that solved the issue. I decided to use the LiveValidation script. It works pretty well. Thanks for the help.

Write a cmd line script to parse an xml file

What would be the best solution to check (from the command line with a script), if a certain xml file contains this line:

<endpoint uri="endpoint.php" class="flex.messaging.endpoints.AMFEndpoint"/>

or this line

<!-- <endpoint uri="endpoint.php" class="flex.messaging.endpoints.AMFEndpoint"/> -->

and stop execution if the second one (commented out) is found?

Thx, martin

From stackoverflow
  • Single line or across multiple lines? If the former, you can use grep.

    Update: There seem to be some XML aware variants like xgrep, xmltwig and xmlstarlet.

    Maxim Veksler : +1 for xmlstarlet
  • assuming pattern occurs at single line

    #!/bin/bash
    awk '
    /<endpoint uri=.*endpoint.php.*class.*flex.messaging.endpoints.AMFEndpoint/ && /<!--/{
        exit
    }
    /<endpoint uri=.*endpoint.php.*class.*flex.messaging.endpoints.AMFEndpoint/{
        # to execute external script inside awk, uncomment below
        #cmd = "myscript.sh"
        #system(cmd)
    } 
    ' file
    

    OR you can return a code back to shell

    #!/bin/bash
    var=$(awk '
    /<endpoint uri=.*endpoint.php.*class.*flex.messaging.endpoints.AMFEndpoint/ && /<!--/{
        print 1
    }
    /<endpoint uri=.*endpoint.php.*class.*flex.messaging.endpoints.AMFEndpoint/{
        print 0
    } 
    ' file)
    [ "$var" -eq 1 ] && exit
    [ "$var" -eq 0 ] && ./myscript.sh
    
    Noufal Ibrahim : These are not totally reliable. A node called
    ghostdog74 : its OP's sample, not mine. If there is possibility of "s" in endpoint, then matching it exactly will do.
    martin : this looks good! It is sufficient how it is checked. I am trying to execute a script in the second case... just putting a command in there does not work for me e.g. (./doSomething.sh) do I need to use exec()?

what is the latest version of WinForms? And how does this relate the version of .NET?

What is the latest version of WinForms? And how does this relate the version of .NET?

For example in VS2008 with .NET 3.5 is there Windows Forms 3.5 under the bonnet?

From stackoverflow
  • I don't believe there's a separate version number for Windows Forms. Why would there be?

    Greg : I just wasn't sure as a newbie - I'm looking for a good book (ideally available in PDF) for Windows Forms programming in VS2008 with .NET 3.5. All I seem to be able to see so far is "windows forms 2.0" type books...
    Paul Sasik : 2.0 will be fine for forms programming for you. Little has changed there. The biggies are LINQ, WCF, WPF... ah. There you go. WPF. Windows Presentation Foundation. That's the "new" forms engine. You might want to take a look at that before diving into the "older" forms technology.
  • Windows Forms is just a subset of the Framework Class Library and yes, the current version is 3.5.

    WPF Update

    A new presentation technology has been added to .Net since 2.0 called WPF (Windows Presentation Foundation) It is the newer way to create .Net UIs and which is also used by Silverlight.

    WPF described on Wikipedia

    Greg : ok - so I should really look for a programming Windows Forms 3.5 text then...thanks
    Paul Sasik : Copied from below: 2.0 will be fine for forms programming for you. Little has changed there. The biggies are LINQ, WCF, WPF... ah. There you go. WPF. Windows Presentation Foundation. That's the "new" forms engine. You might want to take a look at that before diving into the "older" forms technology.
    Ash : Microsoft call it the 'Framework' Class Library. 'Foundation' can be confused with WPF etc.
    Paul Sasik : @Ash: Thanks... post midnight brain mush mixed with years of MFC coding...
    TrueWill : Note that you do want .NET 3.5 SP1.
  • .Net provide a bouquet of different technologies to do your job. Winforms is a technology that lets you create desktop applications, and so does WPF. ASP.net allows you to create web applications and WPF is for creating workflow foundation programming etc. etc.

  • On my PC with .NET 3.5 SP1 installed, System.Windows.Forms is version: 1.0.5000.0 in the Global assembly cache. The actual file version (and Product version) of 'System.Windows.Forms.dll' is 1.1.4322.2032.

    It is unrelated to the overall .NET version, there is no Windows Forms 3.5 although Microsoft would say there is, ie Windows Presentation Foundation (WPF).

    If you need to build classic Windows desktop applications you would use Windows Forms.

    If you need to build more modern looking desktop applications that support text flow layouts, richer formatting and styling and graphical animation then Windows Presentation Foundation is the better choice.

How to exclude specific fields from a Rails XML output

I am working on a RoR project which outputs XML to RESTful requests. The problem is it includes the "updated-at" and "created-at" fields in the output.

I have tried using:

:exclude -> [ :created_at, :updated_at ] 

and

:exclude -> [ 'created-at', 'updated-at' ]

but the output still renders them. How do I exclude them from the rendering without these?

From stackoverflow
  • The option you want is called :except, not :exclude. For example:

    obj.to_xml(:except => [ :created_at, :updated_at ])
    

    For more info, see the Rails API docs for this method.

    Ash : This worked perfectly. What's more, I has discovered that it applies the `:except` to the entire xml, including any `:include`'s. Cool. Exactly what I needed.

Django/Python: How do you start a new process in Python?

After a customer uploads an image I want to re-size an image to 8 different sizes and then send them up to S3 and save them to the file system. Obviously this could take a long time (seconds) and I would want to do it in a "multithreaded" way (I quote that because I don't care if it's actually multithreaded or if it's some other functionality). My understanding is that because of the GIL in Python you cannot successfully use multithreading for things like this because it uses the same process and therefore works exactly the same as if you did it in your code's normal flow (vs multithreading). Is there some other, better way of opening a new process in Python for this sort of task?

From stackoverflow
  • If you want to call an external process, use the subprocess module.

    If on the other hand you want to side-step the GIL and spin of some Python task, use the multiprocessing module. It provides an interface very much like the threading package's but utilizes subprocesses so you are not bound by the constraints of the GIL.

    orokusaki : What would be the reason for using subprocess (ie, what would be an external process)?
    jkp : @orokusaki: say you want to process some file with some external utility, EG, you are processing video and you want ffmpeg to transcode it for you: in this case you'd use the subprocess module to fire up ffmpeg, pipe your input data to it and read it's output to get the processed data. If what you want is to run some long-running Python routine without being affected by the GIL however, the multiprocessing package is what you want.

Redirecting Wordpress's Login/Register page to a custom login/registration page

I have a website, with a user system. I want to integrate wordpress's user system into that website's, but I still want to use the website's register/login pages. I don't want anybody to be able to login or register using Wordpress's login or registration forms. Instead, when they're try to access the login/registration pages in Wordpress, I want those pages to redirect them to my own login/registration pages.

Is there any way of doing this? I've tried Google, but all I could find was redirection AFTER the user logs in or registers, which is not what I want.

Thank you in advance.

From stackoverflow
  • You might be able to latch onto the login_head hook and issue a redirect there.

  • add_action('init','possibly_redirect');
    
    function possibly_redirect(){
     global $pagenow;
     if( 'wp-login.php' == $pagenow ) {
      wp_redirect('http://google.com/');
      exit();
     }
    }
    
    Bruno De Barros : This worked for me, thank you :)
    this. __curious_geek : Where shall I register add_action call? where do I call this ? excuse me for I'm a .Net developer.
    nickohrn : You have two options. Either throw the above code in a plugin or create a functions.php in your themes' folder and add the above.