Thursday, March 31, 2011

Are clusters discouraged in LabVIEW?

I found this comment in the LabVIEW instrument driver guidelines (section 6.2):

If you need more terminals than the recommended patterns, reconsider the grouping of the controls and indicators on the VI. Except for error in and error out, avoid using clusters to minimize the number of terminals. Clusters often require the user to unbundle and rebundle data from the cluster.

If National Instruments is discouraging clusters, what does "reconsider the grouping of the controls and indicators on the VI" mean?

I really like using clusters, and I think they've improved my VIs. Am I missing something?

From stackoverflow
  • Clusters as a data type are fine. What NI is discouraging is the bundling data into clusters for the sole purpose of passing data to a sub-vi. If you have data that must be shared between numerous vis ( or sub-vis) then you should consider using a functional global, or changing your architecture to normalize your data.

    Underflow : Functional globals, like globals in all languages, need some care when designing a solution. In particular, they tend to break the appearance of dataflow, which can lead to some peculiar debugging issues.
    nekomatic : Also I think NI driver guidelines would discourage using a functional global as part of the interface of your driver suite - see 2.6, 'Design configuration VIs so they do not rely on the status or setting of another VI'.
    nekomatic : Just to comment on my comment, this is not to say functional globals shouldn't be used - when they're appropriate, they're great.
  • Bundling and unbundling are relatively trivial processor and memory hits, so performance isn't a worry unless you're working in a tight loop.

    However, when the connector pane starts looking like a variegated porcupine, many people will start dropping everything into a "megacluster" input. While this does work (for a while), it eventually leads to a lot of unnecessary memory bloat and debugging pain, as things that aren't needed in a function still get copied around in the code.

    Even worse, one can end up with different megaclusters for different VI's, and then need to translate between structures.

    I usually find it best, when the inputs and outputs start getting excessive, to go back and refactor one VI into several, each with a smaller, more clearly defined function.

  • I think this is probably poor phrasing in NI's documentation. If it makes sense that a number of different values are written to or read from the instrument or its driver in one go then a cluster is the appropriate data type. You want to try and avoid the situation where the user has to read the data in the cluster out just so they can write it back in with one value changed. The other good general principles for using clusters, certainly in distributable/reusable code like an instrument driver, are:

    • Save the cluster as a strict typedef
    • Always bundle/unbundle cluster elements by name.

    That way you can change what's in the cluster without breaking existing code.

using string iterators over char* in boost regex

I am trying to search a char* to find matches and store each match as a struct using boost regex. I do not know how to use the std::string iterators over char*. So I created std::string from char* and using them. But now I want pointers in the original char* which can only be found using std::string I created. See the following code. The comments should clear your doubts.

typedef struct {
 void *pFind; // Pointer to begining of match   
 int lenFind; // Length of match
} IppRegExpFind;



bool regExSearch(int nStrLen /*Length of input string*/, 
    std::vector<IppRegExpFind>& vectResult /*vector of struct to store matches*/, 
    int &numMatches /* number of matches*/, 
    const char *sStrInput /*Input string to be searched*/,
    const char *sStrRegex /*Input regex string*/)
{
 bool bStatusOk = true;
 try{
  std::string regexStr(sStrRegex);
  std::string inputStr(sStrInput);
  static const boost::regex ex(regexStr);
  std::string::const_iterator start, end;
  start = inputStr.begin();
  end = inputStr.end();
  boost::match_results<std::string::const_iterator> what; 
  boost::match_flag_type flags = boost::match_default; 
  std::vector <std::string> matches;
  while(boost::regex_search(start, end, what, ex, flags))
  {
   matches.push_back(what.str());
   start = what[0].second;
  }
 //  convert boost:match_Results to a vector of IppRegExpFind
   }
   catch(...){
 bStatusOk = false;
    }
return bStatusOk;
}
From stackoverflow
  • You can get the original pointer by

    sStrInput+what.position(0)
    

    I'm not sure, however, why do you need all the tricks with std::string. According to the documentation, boost::regex_search can search any range specified by bidirectional iterators (ie. char* is a bidirectional iterator, so you pass (str, str+strlen(str)) as start and end), and there are even overloads for char* that treat it as C string.

What is the VB.NET select case statement logic with case OR-ing

When writing some vb code I tripped and I'm still left wondering why. I was ORing the case expectation yet a value lieing within this range didn't warrant a match; why not?

Example Code:

    Select Case 2
        Case 0
            ''// Some logic
        Case 1
            ''// Some other logic
        Case 2 Or 3
            Console.WriteLine("hit")
     End Select

With the above I would naturally assume that "hit" would be printed, but that's not the case.

From stackoverflow
  • This will allow you to perform "something" in the case of 0, "something else" in the case of 1, "hit" in the case of 2 or 3 or "hit else" otherwise.

    Select Case 2
        Case 0
            Console.WriteLine("something")
        Case 1
            Console.WriteLine("something else")
        Case Is 2 To 3
            Console.WriteLine("hit")
        Else
            Console.WriteLine("hit else")
     End Select
    
  • Edit: It appears I was wrong in assuming that VB.NET doesn't allow Case ORing. I was thinking in C# and IL and it appears I was wrong.

    However, as someone pointed out, the reason your code did not work was because Case 2 Or 3 was evaluating 2 Or 3 as a bitwise or and hence evaluating to Case 3.

    For clarification:

    
           2 binary = 0000 0010
           3 binary = 0000 0011
      2 Or 3 binary = 0000 0011 (= 3)
    
    
      Select Case 2
         Case 0            '--> no match
    
         Case 1            '--> no match
    
         Case 2 Or 3       '(equivalent to Case 3  --> no match)
       End Select
    

    However, I feel that I should point out that for the sake of performance, one should not use such constructs. When the compiler encounters Select statements (switch in C#) it will try to compile them using lookup tables and the switch MSIL instruction but in the case where you have something like Case 1,2,11,55 the compiler will not be able to convert that to a lookup table and it will have to use a series of compares (which is like using If.. Else).

    The point is that in order to really take advantage of the Select statement, the cases should be designed with that in mind. Otherwise, the only benefit is code readability.

    A well designed switch is an O(1) operation whereas an poorly designed one (which is equivalent to a series of If..Then..Else statements) is an O(n) operation.

    vanslly : Thanks, that allows my mind to rest now. Reading the code logically didn't give me any hints that I was doing something wrong.
    : I'm glad you were able to find the answer to the problem you were looking to solve and I hope the clarifications I added to my answer will help you craft better Select statements :)
  • Use the comma operator to delimit case statements

    Select Case 2
        Case 0,1,2,3
            Console.WriteLine("hit")
     End Select
    
    vanslly : my intent is not for case 0 and 1 to fall through. But the comma is what I was after.
    JaredPar : @downvoter, care to explain?
    Geoffrey Van Wyk : -1, because it does not answer the question as stated. It rather gives an alternative solution to the one attempted by the questioner. The question is: how does VB interpret the OR operator in a Select statement? Otherwise, the question must be edited to match the answer. But I would not suggest that, because @JohnT gave the correct answer.
    JaredPar : @Geoffrey, umm, the OP both accepted my answer and acknowledged it was what they were after.
    Geoffrey Van Wyk : @JaredPar, I know. @vanslly must restate the question, but then @JohnT, who answered correctly, loses the points.
  • JaredPar has it right but you can also use the To construct

    Select Case 2
        Case 0,1
        Case 2 To 3
            Console.WriteLine("Hit")
    End Select
    

    This would be 0 or 1 do nothing, 2 or 3 print Hit...The To construct is a range...

    Here's the MSDN

    vanslly : True, and I was using the To keyword, but it's slightly hacky because if say 2 and 3 were Enum vals and the enum gets refactored without taking this use into consideration - which if it's in some class deep in the bowels of a large system - then you have some unexpected breaks ;)
  • As Jared* said, you need to use the comma operator to delimit case statements.

    The or you were doing is a bitwise OR, resulting in it being "3". Amusingly, "2 AND 3" would probably have worked for your specific case.

    *Can't vote up with my puny rep, sorry!

How do I create / use a MembershipProvider?

How do you create a MembershipProvider for use in an ASP.NET/MVC website?

Doesn't it generate the tables it needs for you in your database?

From stackoverflow
  • Google is your friend:

    The vast majority of it depends on what you want to do. Maybe if you expand on why you want to create a custom one we could give a better answer.

    KingNestor : @Mcbeev, perhaps I don't want a custom one, I simply want to use a MembershipProvider with an asp.net mvc application.
    Chad Moran : You did ask how you create one.
    Simon_Weaver : stackoverflow is my bestest friend though :-)
  • Basically you have to make a class that inherits from the abstract MembershipProvider class in the .NET framework. Then you have to implement all of the abstract members of the base class. ValidateUser, GetUser and Initialize are probably the most important members to implement depending on how much of the interface you want to support.

    The default membership provider doesn't create anything in the database automagically. You have to run the aspnet_regsql.exe to create the necessary databases.

    To use the default asp.net SqlMembershipProvider. You just have to enable it and enter a proper connection string (see example configuration on MSDN). Then you have to create a login page that validates the user using the configured membership provider. The easiest way is to use the Login Control.

  • Default template for ASP.NET/MVC already have Membership registered within your web.config. At the end you just need to run:

    aspnet_regsql.exe -W
    

    This command will start wizard that will guide you accross database creation process.

    Zhaph - Ben Duguid : Note: You should run that from a VS 2008 command prompt - it's highly likely that the default paths won't have the .NET framework folders mapped.
    Mike Chaliy : Yep,typically this command located at c:\Windows\Microsoft.NET\Framework\v2.0.50727\

Javascript Namespacing, what am I doing wrong?

I'm taking an existing JS library I wrote up some time ago, and trying to organize it under a common namespace...Here is an example of the technique I am trying to use:

var NameSpace = new function ()
{
    var privateMember = [];

    function privateMethod() {};


    return 
    {  
     PublicMethod1 : function(arg, arg2)
     {
      // etc
     },
     PublicMethod2 : function ()
     {
      // etc
     },
     PublicMethod3 : function(arg, arg2)
     {
      // etc
     }
    }; 

}();

From what I can tell, this should work perfectly, however I get a Syntax Error on this line:

PublicMethod1 : function(arg, arg2)

Can anyone see some obvious problem with this technique?

From stackoverflow
  • var NameSpace= function ()
    {
        var privateMember = new Array();
    
        function privateMethod() { };
    
        return {           
            PublicMethod1 : function(arg, arg2)
            {
                    // etc
            },
            PublicMethod2 : function ()
            {
                    // etc
            },
            PublicMethod3 : function(arg, arg2)
            {
                    // etc
            }
        };  
    
    }();
    

    Problem was real tricky, return and { should be on the same line apparently. Also new [] was not valid, I fixed this for you too.

    FlySwat : It is somewhat ridiculous that JS is "whitespace agnostic" until it isn't.
    Matt Ephraim : JavaScript doesn't require a semicolon at the end of the line, so putting the opening bracket on the next line was making the function return before it could reach the bracket. I've been burned by that exact same gotcha.
  • just a quick note about the array assignment.

    This works: var privateMember = new Array();

    And this works, too: var privateMember = [];

    Of course, this doesn't: var privateMember = new [];

    Creating a singleton from the closure as in the original (correcting for the return positioning) is perfectly acceptable and doesn't need to be an instantiation of an object as in the second comment

FormView equivalent for a WinForms application?

Hi,

I'm trying to develop a small utility (a WinForms app) and I was hoping (to save time) to use a WinForms equivalent of an ASP.net FormView or DetailsView (to bind to) - i.e. for single objects (as opposed to multiple objects, which we could use a DataGridView for).

It's been about three years since I did anything meaningful in the world of WinForms (and I'm not in a position to do this in WPF) - can anyone suggest a control or container which supports databinding and works in a similar way to the ASP.net's FormView implementation?

The basic idea is to bind to either Plain Old CLR Objects (POCO) or DTO (Data Transfer Objects). However, I'm starting to feel like this is an exercise in diminished returns.. or perhaps I need a third party control..Infragistics?

/R

From stackoverflow
  • The WinForms uses somewhat another paradigm. It uses BindingSource and this not matter what control you use. For example it could be simple UserControl or even Panel.

    Following are steps to bind your class to form.

    1. Drop BindingSource on you form or panel or whatever...
    2. In DataSource poperty click Add Project Data Source.

    3. Select Object, select object you want to bind.

    4. Click Finish. At this stage we have datasource configured. Next steps will generate something similar to FormView.

    5. Open Data Sources docked window.

    6. With drop-down select Details.

    7. Drag and drop that to your form.

    Result should be the form similar to the FormView.

    Let me know if you have any questions.

    Henk Holterman : You may want to check the list of fields first and change some to Label or Combobox as appropriate.

Apache name based virtual hosting

Last time I tried setting up name based virtual hosting on my development machine I just gave up and mapped websites to different ports. This time, I'm trying to do it right :)!

I've properly registered DNS entries and sending two different headers to the server:

Host: dev.site1.com
Host: dev.site2.com

However, Apache is giving me a hard time with mapping dev.site2.com to dev.site1.com

Here's my slimmed down config:

Listen 80
ServerName localhost:80
NameVirtualHost *:80

<VirtualHost *>
    ServerName dev.site1.com
    DocumentRoot /www/site1
</VirtualHost>

<VirtualHost *>
    ServerName dev.site2.com
    DocumentRoot /www/site2
</VirtualHost>

I've tried combos such as (to no effect):

ServerName site1.com
ServerName site2.com

ServerName site1.com
ServerAlias *.site1.com site1
ServerName site2.com site2
ServerAlias *.site2.com site2

I'm happily running Apache 2.2 and hope there's some whose tackled with the same before and can help me out.

From stackoverflow
  • I note the following things:

    1. your ServerName is localhost:81 - shouldn't this be localhost:80?
    2. The DocumentRoot for both VirtualHosts are the same - /www/site1 - so will serve the same pages even if it works

    Try to create a separate DocumentRoot for the second virtual host.

    As a bit of a help, here's my (working, trimmed, URL's renamed) httpd.conf:

    NameVirtualHost *
    
    <VirtualHost *>
            DocumentRoot    /var/www/site1
            ServerName      my.website.co.nz
            ServerAlias     www.my.website.co.nz
    </VirtualHost>
    
    
    <VirtualHost *>
            DocumentRoot    /var/www/joker
            ServerName      another.site.co.nz
            ServerAlias     www.another.site.co.nz
    </VirtualHost>
    

    Happy hunting!

    EDIT: MrTopf has a good point. NameVirtualHost must exactly match the VirtualHost directive. Note how I have an asterisk only for each one of those, whereas you have a NameVirtualHost of *:80 and VirtualHosts with *.

    kRON : Oh sorry, I've misspelled the second document root. Yes, this is exactly what I'm doing, but everything seems to just point to the first VHost entry.
    Fritz H : Can you post your whole config, please?
    MrTopf : yeah, the missing :80 actually got me thinking and digging in the docs. Didn't know before that Apache is that picky ;-)
  • I usually also specify the port in the VirtualHost directives but not sure if this can be the problem:

    <VirtualHost *:80>
        ServerName dev.site2.com
        DocumentRoot /www/site2
    </VirtualHost>
    

    (I even specify the IP address usually in order to make sure it's really listening to the right one in case the server gets an additional one at some point).

    In fact I just noticed in the documentation this line:

    Note that the argument to the directive must exactly match the argument to the NameVirtualHost directive.

    So the problem can be that you specify your NameVirtualHost with a port but the VirtualHost directive without one which eventually does not make them match.

    kRON : Well, great catch! Who would have thought :)? It seemed to be the case. Quite frankly I was sure I got everything right when I read 'ServerName will match the Host parameter from incoming headers', but seems I should have done a better job. Thanks :)!
    MrTopf : Well, it's usually the little things you don't directly spot, isn't it? ;-) Glad it worked :-)

SPARC Assembly Tutorial

Any recommendations for a good tutorial on SPARC assembly online for free? Thanks

From stackoverflow
  • alt text

    They're few and far between for free, I would suggest trying to get a hold of (cheap, second-hand) Richard Paul's book called "SPARC Architecture Assembly Language Programming and C", ISBN 0138768897. It's well worth the money and available on Amazon, for one.

    The only online stuff I've seen is through www.sparc.com but I seem to recall that they require paid membership before you can access their documents (at least they did when we used them, but that was some time ago).

    The University of New Mexico has this which seems quite good. I'm not sure how easy it is to get your hands on ISEM (the emulator). I haven't been able to ftp-connect to the university but there's an email address you could try. Or, if you have an actual SPARC box, you won't need to worry about it.

    There are other SPARC emulators around such as Virtutech Simics, although cost may be a concern here - I'm not sure if you'd qualify for the academic license.

    Crashworks : +1 for Dr. Paul's book. It was the textbook back when I took the assembly class and got me from zero to proficient in RISC in about twelve weeks. I still have it under my desk as reference.
    Harvey : +1 I took Dr. Paul's class as well as graded assignments and can recommend that book highly.
    Crashworks : Moore Hall FTW. =)

Is it a good idea to retain/release method parameters in Objective-C?

Consider the following ObjC code example:

-(void) doStuffWithString: (String *) someParam {
    // Do stuff with someParam
}

If this code were being executed in a multi-threaded app, would it be a good idea to retain/release someParam? Specifically, I'm thinking of scenarios in which the passed-in parameter is a singleton object shared by many threads. Is the following safer, for example?

-(void) doStuffWithString: (String *) someParam {
    [stringParam retain];
    // Do stuff with someParam
    [stringParam release];
}
From stackoverflow
  • No, it's not the job of individual functions to try and provide thread-safety for parameters.

    Somewhere up the stack something passed down the object that is the parameter to "doStuffWithString". This is the code that should guarantee the that object will remain valid through the length of the function call.

    Two things to consider;

    1. In situations where you call a third-party or library function these will not do a retain/release for you.
    2. If there is a danger of the param being deleted this could occur before your call to 'retain' even happens!

    This thread may also be helpful.

How do I export to CSV file with table record value with comma in it properly?

I have a function that exports values into a CSV file, but the "comments" field has commas in it and it messes up the columns when you open it in a spreadsheet program.

Is there a way around exporting it properly?

//this exports only names and comments into a CSV file
function exportNamesCommentsCSV($table, $columns) {
    $file = "volunteer_comments";
    $csv_output = '';
    $table = 'volunteers_2009';
    $result = mysql_query("select * FROM ".$table."");
    $i = 0;
    if (mysql_num_rows($result) > 0) {
     while ($row = mysql_fetch_assoc($result)) {
      $csv_output .= $row['Field'].", ";
      $i++;
     }
    }
    $csv_output .= "\n";

    $values = mysql_query("SELECT lname, fname, email, comments FROM ".$table."");

    while ($rowr = mysql_fetch_row($values)) {
     for ($j=0;$j<$i;$j++) {
      $csv_output .= $rowr[$j].", ";
     }
     $csv_output .= "\n";
    }

    $filename = $file."_".date("Y-m-d_H-i",time());
    header("Content-type: application/vnd.ms-excel");
    header("Content-disposition: csv" . date("Y-m-d") . ".csv");
    header( "Content-disposition: filename=".$filename.".csv");
    print $csv_output;
    exit;
}

EDIT: This would be an example of a comment...

I would prefer to work the gates, but I can work anywhere really.

The , (comma) in the example comment above throws off the proper column structure.

From stackoverflow
  • You'll want to wrap the entry in a qualifier; typically quotes.

    "col1", "col2,,,", "col3"
    

    If the entry contains quotes, you'll need to double up on them.

    Here's the Wikipedia article

  • What you need to do is enclose values in quotes, like so:

    "value","value","value"
    

    This will correctly handle commas in the values, and numeric values will also still work fine.

    To put a quote in the value, however, you need to put two quotes together. E.g. representing this string:

    Bobby says, "Hi!"
    

    it will need to be represented as

    "some value","Bobby says, ""Hi!""","Some other value"
    

    You can do this with:

    $csv_value = "\"" . eregi_replace("\"", "\"\"", $orig_value) . "\"";
    
    Brad : Where do I add the $csv_value = ... line of code into my current function? I am unsure as to how to implement this into my current code.
  • One way to achieve what you want is to do a search and replace on your "comments" field, assuming you're sure that this is the only field than can contain embedded commas.

    You might also need to check that your memo field can't contain CRs or LFs, they too will mess with your csv file import.

  • PHP has functions for dealing with making comma separated files for you.

    Check out the fputcsv function. It lets you do something like this:

    <?php
    $list = array (
        array('this has, commas, in it','bbb','ccc','dddd'),
        array('123','456','789', 'this is "like this"'),
        array('1234','124','1242', 'yay, woo"!"')
    );
    
    $fp = fopen('file.csv', 'w');
    
    foreach ($list as $record) {
        fputcsv($fp, $record);
    }
    
    fclose($fp);
    ?>
    

    The file file.csv will have this in it:

    "this has, commas, in it",bbb,ccc,dddd
    123,456,789,"this is ""like this"""
    1234,124,1242,"yay, woo""!"""
    

    Later on when you need to read it, if you ever do, you can use fgetcsv.

    So in your situation, all you need to do is make an array of arrays that each have the name and the comment, and then put it through fputcsv and you're golden.

Where can I find a flexible logging library for Windows Mobile?

Can anyone suggest any open and free library for logging on Windows Mobile application written in C++?

It would be nice if it supports logging to files, syslog (would be nice) and logging level.

From stackoverflow
  • Perhaps you could see if the logging from http://pt-framework.sourceforge.net/ fits your needs. I don't know if syslog is supported.

  • None that I know of.

    You will most likely have to look for source code available logging libraries. Windows Mobile will pretty much compile most win32 code with no or little changes, so any win32 logging library should work.

    Generally I build my own as I like fine gained control over my logging code.

  • I'm currently using log4net in one of my compact framework projects. It's probably not ideal for production though, as the dll is 220k!

    ctacke : And way less than ideal for the requested C++

Python or Ruby for a .NET developer ?

I'm a C# .NET developer and I work on mostly ASP.NET projects.

I want to learn a new programming language,

  • to improve my programming skills by experiencing a new language,
  • to see something different then microsoft environment,
  • and maybe to think in a different way.

I focus on two languages for my goal. Python and Ruby.

  • Which one do you offer for me ?
  • Pros and cons of them on each other?
  • Is it worth learning them ?

EDIT : Sorry I editted my post but not inform here,

Ruby on Rails replaced with Ruby.

From stackoverflow
  • It's always valuable to learn a new programming language. And both Python and Ruby are good ones to know. It's important to note that while Python is a language, Ruby on Rails is a framework. IMHO, you should learn Ruby before you learn Rails.

    Go try ruby! to see if you like it. If you do, then try Rails. Otherwise, try Python. Both are similarly useful. To me, Ruby is more "fun". If you like Lisp, you'll probably like Ruby. If you like C, you might prefer Python. Try them both!

    Garrett : Ruby is a language on it's own, like you said it's a framework. Why not say Python => Django as Ruby => Ruby on Rails?
  • First... good for you for wanting to broaden your knowledge! Second, you are comparing a language (Python) with a web framework (Ruby on Rails).

    I think your best option is to try a few different frameworks in both Python and Ruby, do the same fairly simple task in each, and only then pick which one you'd like to learn more about. Rails is nice for Ruby, but it's not the only one out there. For Python I like Pylons and Django.

    Pros and cons: Ruby is a little cleaner, language-wise, than Python. Python has a much larger set of modules.

    Is it worth learning? Yes, to both Python and Ruby.

    ΤΖΩΤΖΙΟΥ : Please define "Ruby cleaner than Python". I would tend to say that the opposite is true, and that is why I would like to know what you mean exactly.
    dwc : Python has a few mixed paradigm things in it, while Ruby is more "pure" OO. For instance, why dir(foo) in Python for introspection? There have been a few times I've tried to remember a method in Python only to remember it's a function instead. It's little things like that, and mostly not important.
    Garrett : He did say Ruby, not Ruby on Rails.
    fuentesjr : Take note, his post was edited.
  • If you're looking to learn Ruby on Rails, the guides site has a great guide for getting started and the further guides for improving your rails-fu.

    Also, Tore Darell has written a Survivor's Guide for Ruby on Rails which could prove useful to you too.

  • I'd get in on Ruby. Seems to have a larger (or at least more active) community, the pace of new projects & continued development is second-to-none, and the learning resources seem to outnumber & outpace those of Python. I could be wrong, but these are my impressions.

    paprika : About 3 years ago I had the exact opposite impression, that's why I chose Python over Ruby. Probably Ruby caught up since then regarding learning resources, but back then I found a *lot* more Python stuff (books, articles, blogs etc.).
    fuentesjr : There is no indication that this is true.
  • If you're a beginner, I would recommend you try Django if you decide to start learning Python. Of course if you decide Ruby is your choice of flavor, Rails is the obvious way to go. Whichever language you choose, I can assure you it will be a good choice.

    Having said that, my personal choice is Python. I like the language, I like the community, and I use Python for almost every occasion. I use it for command-line apps, GUI apps, and I use it for web apps (Django). Oh and I use it for system administration scripts on Windows and Linux as well.

    Having said that as well, I would recommend you learn a language like Haskell or Lisp as well. That will really open your eyes to a new perspective to programming. Furthermore, since you say you are mostly familiar with the .Net framework, I would really recommend you start with F# since you'll already be familiar with the libraries and it will make the transition much more smoother. Either way, good luck.

    Canavar : F# is on my list :) I really want to learn it, but first I want to try a non-ms language. thanks, good for the answer. +1
  • Rule of thumb - Python if you like strict rules and Ruby if you hate them.

    Another one: if you adore JavaScript - Ruby is your choice :)

    Sarah Mei : I love Ruby, but will do almost anything to avoid writing JavaScript. Their ideas of objects may be similar, but JS syntax is plain old ugly.
    vava : I have completely opposite feelings about syntax, I love curly braces.
  • Both languages are powerful and fun. Either would be a useful addition to your tool box.

    Python has a larger community and probably more mature documentation and libraries. Its object-orientation is a little inconsistent and feels (to me, IMHO) like something that was bolted on to the language. You can alter class behaviour at runtime (monkey-patching) but not for the precompiled classes and it's generally frowned-upon.

    Ruby might be a little more different to your current experience: it has some flavour of Smalltalk (method-calling is more correctly message-sending for example). Its object-orientation is built-in from scratch, all classes are open to modification and it's an accepted - if slightly scary - practise. The community is smaller, the libraries less mature and documentation coverage is less.

    Both languages will have some level of broken backward compatibility in their next majopr releases, both have .Net implementations (IronPython is production, IronRuby getting there). Both have web frameworks that reflect their strengths (search SO for the Django/Rails debate).

    If I'd never seen Ruby, I'd be very happy working in Python, and have done so without suffering when necessary. I always found myself wishing I could do the work in Ruby. But that's my opinion, YMMV.

    Edit: Come to think of it, and even though it pains me, if you're seeking to leverage your knowledge of the .Net framework, you might be best off looking at IronPython, as it's more mature than the Ruby equivalent.

    Clinton Judy : I agree with Python (and I'm a Ruby user 100%). IronRuby will eventually mature, but IronPython is complete already and can access all of your usual .NET libraries, if you want to take it that direction.
  • What? No mention of IronPython?

    IronPython is the flagship language of the DLR. It allows you to use all the familiar .NET libraries, but through Python.

    I would definitely try Python and IronPython. You'll learn a lot and might even sneak it into your current projects (you can embed an IronPython engine in a .NET application).

Suggest a method for auto-updating my C# program

Hi,

I need to keep a program I've written up to date, this will happen frequently over the next year or so, this will need to be done over the Internet. Where would you suggest I start, are there any common techniques? Any suggestions welcome.

Thanks

From stackoverflow
  • ClickOnce is perfect for this sort of scenario.

  • ClickOnce works fairly well.

  • ClickOnce is a good solution, but if you wish to have total control then you can roll-your-own. I would suggest polling a webservice to find if there are later versions available, downloading required files to a side-by-side directory, and using a launcher (or updating a shortcut) to automatically launch the latest version.

    This is a little complicated, but caters for situations where the application may be running, and can therefore not be overwritten.

    Dour High Arch : After creating my own application updater, I strongly suggest using ClickOnce.

Outlook AppointmentItem - How do I programmatically add RTF to its Body?

I would like to set the Body of an AppointmentItem to a string of RTF that contains an embedded image. Setting Microsoft.Office.Interop.Outlook.AppointmentItem.Body results in the RTF appearing as-is in the appointment.

I have tried using Redemption which wraps the appointment and exposes an RTFBody property, but the RTF formatting (including the image) is lost.

In this example (which doesn't have an embedded image) the RTF appears in the document as-is. Has anyone managed to do this?

var appointment = (AppointmentItem)app.CreateItem(OlItemType.olAppointmentItem);
appointment.Subject = "test subject";
appointment.Start = DateTime.Now;
appointment.End = DateTime.Now.AddHours(1);
appointment.Body = @"{\rtf1\ansi\deff0{\fonttbl{\f0 Arial;}}{\colortbl ;\red0\green0\blue255;}\pard\cf1\f0\fs24 Test}";
appointment.Save();
From stackoverflow
  • Start setting BodyFormat property before setting the Body.

    "http://msdn.microsoft.com/en-us/library/aa211430(office.11).aspx"

    Stuart Harris : The BodyFormat property is not available on AppointmentItem. They are different to mailItems and don't support HTML (only text + RTF). Thanks for your help though.

How to read a pim.vol file

Is there any desktop-based way to read the pim.vol file that stores contacts, tasks and calendar information on a Windows Mobile device? Ideally I'd like to find an export tool that would allow me to extract the data from mine, but I'd also settle for a library that would allow me to interface with the file and pull data out of it.

I've googled this quite a bit and haven't come up with any good answers. I'd appreciate any pointers.

From stackoverflow
  • There is no desktop based way to read vol files.

    Vol files are CE database files which can be in one of two formats (CEDB, EDB). The pim.vol file is in EDB format. There is no desktop database libraries for these formats.

    You can write a Windows Mobile application to export any vol file (it's not that hard). The problems you will have is that the pim.vol database table format is different between the different versions of WM.

    If you want something to be WM version agnostic, you could use the POOM API, which is the WM native API for getting access to the PIM data. It's a lot slower than the direct database access tho.

    bigmattyh : Thanks for the detailed response. I appreciate it!

Embedding multipage documents in LaTeX documents

I am writing my dissertation and need to reproduce different short booklets (2-7 pages) that I have used in my studies.

Ideally, I would like to have each page of the booklet appear as a page in my dissertation, but enclosed within some frame and using my dissertation's page numbering, etc. I have the booklets in Word format but would rather embed them as PDFs so they would look exactly as they did to my subjects.

I can do this manually by splitting each PDF into multiple files and including them separately in my LaTeX.

However, is there some package or macro to achieve this without all this work?

From stackoverflow
  • Have a look at pdfpages - I've used it before and it has all the features you talk about as far as I remember.

VS addin: View markup. Does exists something like that?

While working with ASP.NET using Visual Studio (2008) I have discomfort issue: source code editor context menu has only item 'View Designer' but nothing about to view markup quickly!

To see it you need to open Designer and click Markup label in the bottom of a window. Or use Shift+F7 hot key (by default).

So I want to add an item menu 'View Markup' in additional to 'View Designer'. I guess I have to use a Visual Studio add-in if it already exists or write it by myself.

What do you think about that? Is it possible? Or is some solution already exists?

From stackoverflow
  • If you right click the file in "Solution Explorer" you get a "View Markup" option.

    abatishchev : Using Solution Explorer only isn't comfort. It's more quick to use a context menu in additional, imho of course.
    Micah : I agree, but without writing your own add-in or finding one already written, it's kind of the only option.
  • Generally, to add a command to the context menus you'd do the following:

    Tools | Customize

    On the "Toolbars" tab put a tick next to the "Context Menus" item - this will add a new toolbar to your IDE, with buttons for Editor Context Menus, Class View Context Menus, Debugger Context Menus, etc

    Then switch to the "Commands" tab, select the command you want, and drag it to the appropriate menu, and you're done - in this case in the left hand pane select "View", and then in the right hand pane, scroll down until you get to "View Markup".

    That being said, in this instance, I can add the button to the context menu for the code editor, but it's greyed out, and unusable - I guess it needs some context that it gets from the Solution Explorer that it doesn't get from the Code window - which is odd, because it's pulling the same details through for "View Designer" and "View Code".

    I guess I'd use Shift+F7 then, sorry about that.

  • When you are in code view and would like to see markup view there is no Keyboard shortcut for that. Here is what worked for me:

    http://www.karpach.com/Visual-Studio-F7-View-Source.htm

  • Tools > Options > Keyboard

    Search for View.ToggleDesigner in "Show Commands Containing".

    Add new shortcut to Global/Editor with F7.

    This works without needing a macro for VS2008/2010

    bbrown : That is great! I mapped CTRL+SHIFT+UP ARROW to this one and CTRL+SHIFT+DOWN ARROW to the OtherContextMenus.Context.ViewCode command. Now I can switch freely between the views.

Compare tool that can mask differences?

I do a lot of file comparisons (source, logs etc.) and need to mask certain sections e.g. dates / times / line numbers which cause every line to be different.

Beyond Compare allows you to pre-process the files but then you have to write pieces of code to do this.

Is there a GUI type tool that allows you to mask sections of the file via a filter e.g. skip columns 10 - 16, skip data between word x and word y etc.?

From stackoverflow
  • I don't know of any GUI tools, but if you're in a unix environment, you can pipe both files through sed or awk

    #Example: skip first word
    sed 's/^[^[:space:]]*//' yourfile1 >file1.tmp
    sed 's/^[^[:space:]]*//' yourfile2 >file2.tmp
    diff file1.tmp file2.tmp
    
  • Check out WinMerge. It has the ability to filter lines based on regular expressions.

    Kurt W. Leucht : I use WinMerge a lot and had no idea it had this filtering capability! Thanks for educating me!

How do I do this SELECT statement that uses column renaming (or column alias) with LINQ?

Apologies if this has been asked already, but I couldnt find it.

How do I get 'anotherColumnName' in LINQ?

SELECT thisColumnName as anotherColumnName FROM TableName

I have the following which obviously gives me 'thisColumnName' not 'anotherColumnName'

    var query = from names in _context.TableName
                select names;
    return query.ToList();

Solution

@Ian P - thanks to your answer.

For the finished solution I also needed a bit extra as below...

Old version.

public List<OldClassName> GetSomething()
{
    var query = from names in _context.OldClassNames
                select names;

    return query.ToList();
}

New version with column renaming.

public List<NewClassName> GetSomething()
{
    var query = from names in _context.OldClassNames
                select new NewClassName
                {
                    NewColumName = names.OldColumnName
                };
    return query.ToList();
}
From stackoverflow
  • Use an anonymous type:

    var query = (from name in _context.Table
                select new { anotherColumnName = name.ColumnName });
    

    Good luck!

    Paul Rowland : thanks. I just found this question as well. http://stackoverflow.com/questions/128277/linq-custom-column-names
  • @Ian P - thanks to your answer.

    For the finished solution I also needed a bit extra as below...

    Old version.

    public List<OldClassName> GetSomething()
    {
        var query = from names in _context.OldClassNames
                    select names;
    
        return query.ToList();
    }
    

    New version with column renaming.

    public List<NewClassName> GetSomething()
    {
        var query = from names in _context.OldClassNames
                    select new NewClassName
                    {
                        NewColumName = names.OldColumnName
                    };
        return query.ToList();
    }
    

Workaround for some WPF features that are missing in Silverlight

I’m porting a WPF app to silverlight 2, and have come across several WPF features which are presently missing from SL. Could anyone help me with equivalents or suggest workarounds.

  1. I want to handle clicks and double clicks on a textbox embedded in a list box. The WPF implementation uses PreviewMouseLeftButtonDown/Up on a listbox control. How can this be done in silverlight, it seems that PreviewMouseLeftButtonDown/Up are missing in silverlight.

  2. I want to handle button presses (F2/Delete) on a textbox embedded in a list box. The WPF implementation uses PreviewKeyDown on a textbox control which embedded as an item in a listbox. It seems that PreviewKeyDown is missing in silverlight. The KeyDown event handler does not seem to get invoked.

  3. I want to change some appearance properties of a textbox depending on the value of some custom attached properties. The WPF implementation uses a DataTrigger to do this. How can this be done in silverlight. It seems that DataTriggers are missing in silverlight.

  4. I want to change the width of a text box depending on the Actual Width of the listbox in which the text box is contained. The WPF implementation uses RelativeSource binding. What is the silverlight equivalent, or workaround for this.

From stackoverflow
  • I'm more familiar with Silverlight than the full WPF. Please considier my responses accordingly.

    For number 2. For many keys, I check on KeyUp and KeyDown. I use KeyDown while trying to watch the entire time that the key is held down and KeyUp when it was used just once. You should know this was for a game without an individual text box.

  • For item 4, you can bind both the listbox width and the textbox width to a static resource's property so that it acts as a router for the binding. You could also use a value converter that you initialize with a reference to the listbox, then use the converter for your textbox width.

    For item 3, you could use a similar approach.

  • For item 1 and 2, the best way to get access to these input events is to create a custom TextBox deriving from the built in TextBox. Then you can override the OnKeyDown and OnMouseLeftButton down. From there you can either call the necessary code, or fire a new event. e.g.:

    public class MyTextBox : TextBox
    {
        public event MouseButtonEventHandler MySpecialMouseLeftButtonDown;
    
        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            if (MySpecialMouseLeftButtonDown != null)
            {
                MySpecialMouseLeftButtonDown(this, e);
            }
            base.OnMouseLeftButtonDown(e);
        }
    }
    

    Similarly with OnKeyDown.

    Isak Savo : This is not how the Preview events works in WPF. As WPF has routed events, the preview events are tunneled from the root element (e.g. Window) down to the final receiver (e.g. Textbox) which gives higher elements the option to intercept the event before it reaches the textbox.
    KeithMahoney : Yes. Calling the event PreviewMouseLeftButtonDown was not a good idea. But it would work to solve the problem that the thread starter had. I will edit the answer to remove the source of possible confusion.

How can I get my user control to know when the parent hears the user controls OnHide event?

I have an asp.net page with a task bar on the side. Clicking a task opens up a user control for that task with some controls and a close button.

How do I run some C# code when that user control is hidden by clicking the close button?

Much of the stuff on the control is surrounded by an update panel and I'll just say right now that I have to use it. Anyway, I would just use the page_unload event but this is called in many other instances than the one single instance I want it to be called in (window is closing) partly because of the updatepanel.

The close button is not something I've implemented, it's just part of the framework being used for these controls, so it doesn't have any code behind.

All I really want to accomplish is to have some C# code run only when the control is closed, which in effect just hides it. Is there something analogous to Page_Closing/Hiding? I can't seem to find it if there is.

Is there any way to achieve this?

EDIT: I should note that I did find the OnHide event for the control, but the code behind for this logic should really be in the controls, not the pages. Mainly because what needs to happen is when the control is hidden, set some text in the control so when it is loaded up later it will display the correct info.

EDIT: Thanks for all the insights. I'm still not really able to solve the problem, what teedyay suggested...

"If you don't want to handle that code on the page, make your own version of the control, inheriting from the original. You can handle the OnHide event in a more self-contained way in there."

Is probably the closest to what I need. I'm wondering if it is at all possible to bubble events from the parent to the user controls? Logically in my head it seems like it wouldn't be possible and I haven't found any info on it but I thought I'd ask.


Update: I think stepping back and stating a little more clearly what I want to accomplish may clear up some confusion.

I have a user control that is a floating panel that hovers over my main page. It inherits from a control that I do not have the code for. This control generates URL's (upon user request) and displays them within the control it also shows a history of the last 3 URLS generated.

When the page recognizes the controls OnHide event being fired, I need the code within the user control to disable some buttons and store the url in a history queue. How can I get my user control to know when the parent hears an OnHide event?

Also, am I thinking about this wrong, if so is there a smarter way to do this?

From stackoverflow
  • The Page_Unload event will be no good to you: this happens at the end of the page's lifecycle on the server - i.e. before the page content has even been sent to the client.

    Remember that the web is stateless, so the server has no recollection of what page it has served up to whom, unless you go out of your way to remember.

    If the user control you're using has a close button and you want to hook up to that being clicked then you can only really use whatever interface the developer of that control has given you. In this case it sounds like the OnHide event is your way in.

    If you don't want to handle that code on the page, make your own version of the control, inheriting from the original. You can handle the OnHide event in a more self-contained way in there.

    Carter : Thanks for the input. It seems like the OnHide is exactly what I want, but that is an event that the control itself throws so code for it would go in my pages codebehind (which is what I don't want). If I had access to the close button I could achieve what I want by hooking into it's onclick.
  • You can just put an event into your custom control that fires when the user hits a button to close it. when this happens you can handle it via the page that has the control on it and make any changes that you need to the rest of the page or the app. If the control isn't a custom control where you can access the code-behind then you might want to just test for it's visibility, that may work in some cases.

    Carter : Well, I have an event that fires when the close is clicked, onhide. The problem is I need to check for the window being hidden from the code behind for the control, not the page containing the control.
    Middletone : if you use me.visible from the code behind this may work. A control can see it's own status this way. I'm not sure if it works if the parent control is hidden, I'll have to test this for you.
  • In the custom control, there are several methods you can override - particularly:

    protected override void OnUnload(EventArgs e) {
    
        // Insert custom code here
    
        base.OnUnload(e);
    }
    
    Carter : I appreciate the input. I at first thought about overriding the unload event raiser, but the problem is that it will still raise at times when I don't want it to. Also, if I changed this it would change for all of the other user controls I use in the app.
    Fritz H : You could then try deriving a custom UserControl from the original one with OnUnload overridden to perform the tasks you want, in additional with perhaps setting or checking flags elsewhere to see if it should perform the tasks?
  • I'm not sure if I understand you correctly, you have a usercontrol, that contains a "close" button. When this button is clicked, you hide the control, and want something beeing done?

    If you wan't it inside the control you could add it to the buttons click event, just after the hiding (as the button should effektively hide the control right?).

    If you wan't to handle your actions outside the usercontrol on the page itself you can simply add a custom event (like Middletone suggested). Here's how it would work, in codebehind:

    /// <summary>
    /// This is the Event Delegate
    /// </summary>
    public delegate void MyEventHandler(object sender, EventArgs e);
    
    /// <summary>
    /// This event is thrown when <...>
    /// </summary>
    public event MyEventHandler NewMyEvent;
    
    /// <summary>
    /// Internal event that triggers the external events
    /// </summary>
    /// <param name="e"></param>
    private void OnNewMyEvent(EventArgs e)
    {
        if (NewMyEvent != null)
            NewMyEvent(this, e);
    }
    

    Now, whenever you want the Event to be trown (e.g. when the handling of the close button is finished) Just call

    NewMyEvent(new EventArgs());
    

    and you're all set. In that case you would call that after setting the hide command.

    Hope it helps :)

    Carter : unfortunately I do not have access to the close button. This button comes from an inherited control. If you wouldn't mind, maybe take a look at my most recent update and give some insight if you have any.