Friday, February 4, 2011

Replacing Windows Explorer With Third Party Tool

How would I go about replacing Windows Explorer with a third party tool such as TotalCommander, explorer++, etc?

I would like to have one of those load instead of win explorer when I type "C:\directoryName" into the run window. Is this possible?

  • Thank you for the links but I don't see anywhere on the site that mentions how to setup windows so it will use the tool instead of explorer when typing into the run window.

  • From a comment on the first LifeHacker link,

    How to make x² your default folder application

    As part of the installation process, x² adds "open with xplorer2" in the context menu for filesystem folders.

    If you want to have this the default action (so that folders always open in x2 when you click on them) then make sure this is the default verb, either using Folder Options ("file folder" type) or editing the registry:

    [HKEY_CLASSES_ROOT\Directory\shell] @="open_x2"

    If you want some slightly different command line options, you can add any of the supported options by editing the following registry key:

    [HKEY_CLASSES_ROOT\Directory\shell\open\command] @="C:\Program files\zabkat\xplorer2\xplorer2_UC.exe" /T /1 "%1"

    Notes: 1. Please check your installation folder first: Your installation path may be different. Secondly, your executable may be called xplorer2.exe, if it is the non-Unicode version.

    1. Note that "%1" is required (including the quotation marks), and is replaced by the folder path you are trying to open.

    2. The /T switch causes no tabs to be restored and the /1 switch puts x2 in single pane mode. (You do not have to use these switches, but they make sense).

    (The above are from xplorer2 user manual)

    Ryan Lanciaux : Thanks Judah. I guess I thought the directions for the replacement were on the lifehacker article :)
  • If you go to Control Panel -> Folder Options And go to the File Types tab. You can go to the "Folder" file type (with "(NONE)" as the extension). Go to Advanced, create a new action that uses your program (I tried it with FreeCommander). Make sure you set it as default.

    That should do it.

    From Howler

Better way of opening a Document from Java?

I've been using the following code to open Office Documents, PDF, etc. on my windows machines using Java and it's working fine, except for some reason when a filename has embedded it within it multiple contiguous spaces like "File[SPACE][SPACE]Test.doc".

How can I make this work? I'm not averse to canning the whole piece of code... but I'd rather not replace it with a third party library that calls JNI.

public static void openDocument(String path) throws IOException {
    // Make forward slashes backslashes (for windows)
    // Double quote any path segments with spaces in them
    path = path.replace("/", "\\").replaceAll(
            "\\\\([^\\\\\\\\\"]* [^\\\\\\\\\"]*)", "\\\\\\\"$1\"");

    String command = "C:\\Windows\\System32\\cmd.exe /c start " + path + "";

    Runtime.getRuntime().exec(command);            
}

EDIT: When I run it with the errant file windows complains about finding the file. But... when I run the command line directly from the command line it runs just fine.

  • If you are using Java 6 you can just use the open method of java.awt.Desktop to launch the file using the default application for the current platform.

    Allain Lalonde : Works like a charm. Thanks.
    From Dan Dyer
  • Not sure if this will help you much... I use java 1.5+'s ProcessBuilder to launch external shell scripts in a java program. Basically I do the following: ( although this may not apply because you don't want to capture the commands output; you actually wanna fire up the document - but, maybe this will spark something that you can use )

    List<String> command = new ArrayList<String>();
    command.add(someExecutable);
    command.add(someArguemnt0);
    command.add(someArgument1);
    command.add(someArgument2);
    ProcessBuilder builder = new ProcessBuilder(command);
    try {
    final Process process = builder.start();
    ...    
    } catch (IOException ioe) {}
    
  • The issue may be the "start" command you are using, rather than your file name parsing. For example, this seems to work well on my WinXP machine (using JDK 1.5)

    import java.io.IOException;
    import java.io.File;
    
    public class test {
    
        public static void openDocument(String path) throws IOException {
         path = "\"" + path + "\"";
         File f = new File( path );
         String command = "C:\\Windows\\System32\\cmd.exe /c " + f.getPath() + "";
             Runtime.getRuntime().exec(command);          
        }
    
        public static void main( String[] argv ) {
         test thisApp = new test();
         try {
          thisApp.openDocument( "c:\\so\\My Doc.doc");
         }
         catch( IOException e ) {
          e.printStackTrace();
         }
        }
    }
    
    Allain Lalonde : Just to confirm you are using C:\\so\\My[space][space]Doc.doc right?
    From KeithL

What is a prepared statement?

I see a bunch of lines in the .log files in the postgres pg_log directory that say something like:

ERROR: prepared statement "pdo_pgsql_stmt_09e097f4" does not exist

What are prepared statements, and what kinds of things can cause these error messages to be displayed?

  • I think this would help you: http://jdbc.postgresql.org/documentation/81/server-prepare.html

    Basically looks like stored procedures that can be precompiled.

  • From the documentation:

    A prepared statement is a server-side object that can be used to optimize performance. When the PREPARE statement is executed, the specifie statement is parsed, rewritten, and planned. When an EXECUTE command is subsequently issued, the prepared statement need only be executed. Thus, the parsing, rewriting, and planning stages are only performed once, instead of every time the statement is executed.

    Searching the net, I found that the "pdo_pgsql_stmt" command is from some sort of PHP-connection to your database. Maybe this link can help you find a suiteable mailing-list or issue-tracker that you can send your error-messages to?


    EDIT: I think I found your bug here:

    http://bugs.php.net/bug.php?id=37870

    From Espo

A WYSIWYG Markdown control for Windows Forms?

[We have a Windows Forms database front-end application that, among other things, can be used as a CMS; clients create the structure, fill it, and then use a ASP.NET WebForms-based site to present the results to publicly on the Web. For added flexibility, they are sometimes forced to input actual HTML markup right into a text field, which then ends up as a varchar in the database. This works, but it's far from user-friendly.]

As such… some clients want a WYSIWYG editor for HTML. I'd like to convince them that they'd benefit from using simpler language (namely, Markdown). Ideally, what I'd like to have is a WYSIWYG editor for that. They don't need tables, or anything sophisticated like that.

A cursory search reveals a .NET Markdown to HTML converter, and then we have a Windows Forms-based text editor that outputs HTML, but apparently nothing that brings the two together. As a result, we'd still have our varchars with markup in there, but at least it would be both quite human-readable and still easily parseable.

Would this — a WYSIWYG editor that outputs Markdown, which is then later on parsed into HTML in ASP.NET — be feasible? Any alternative suggestions?

  • Can't you just use the same control I'm Stack Overflow uses (that we're all typing into)---WMD, and just store the Markdown in the VARCHAR. Then use the .NET Markdown to HTML converter, as you mentioned, to display the HTML as needed. Jeff talks about this in more detail in a StackOverflow podcast (don't know the episode number).

  • In addition to Jared: it was in Episode 11 at the middle part. You can download it here

    Ruben Bartelink : This would be fine as a comment (its my pet peeve, please dont take it personally!)
    From crono
  • Can't you just use the same control I'm Stack Overflow uses (that we're all typing into)---WMD, and just store the Markdown in the VARCHAR.

    That's a Web control. The input happens in Windows Forms, so that wouldn't work.

  • @Soeren,

    You can most definitely embed IE with the Javascript Markdown editor inside a Windows Forms application.

  • Sure, I could — but while that would work, it would feel quite alien inside the application (which otherwise doesn't embed a browser).

    The goal is to provide a relatively seamless experience, just like with, say, the RichTextBox control.

  • the RichTextBox control

    So you want to use Markdown but you want the user not to know it? This might not be an achievable goal. I think the point of Markdown is that it is geared toward writers that are willing to learn a little bit of fairly natural syntax and edit everything in plain text (like Wikipedia? are there pure WYSIWYG editors for that? probably... and probably some other Wikipedia editor person has to come and clean up the resulting markup and formatting...). If you want it to be transparent to the user (like MS Word) Markdown may not be what you want or give you the advantages it advertises in that situation.

    The input happens in Windows Forms

    Oops! Now I understand better your question. I guess it depends on how your Windows Forms app looks whether the embedded IE control sticks out like a sore thumb. If you try it you might find that you can get it to work.[1]

    In your position, I would try something like this [2]:

    If you don't think that sort of arrangement will go over well with your users, (especially all the editing in the text-only window) then once again I don't think Markdown is the answer for your specific application. If you think your users are keen on the idea of editing pure text, then I bet we can find a solution. Please clarify?

    Jared.

    [1] I had success dropping an IE HTML control into a project strictly to display some generated results as a PDF (using an IE Reader plugin like Adobe Reader or Foxit). The user has no idea that that part of the GUI is an IE control, it just shows the PDF, allows printing and saving, etc.

    [2] ...but remove the borders and make the two split controls touch all four edges of the embedded IE control, or get very close... keep it light grey or white, for example, and eliminate any borders of the IE control so it blends into the surrounding controls. Maybe put this on its own tab page and I challenge a non-technical user to tell/care if it's an HTML control or native.

    I could totally be wrong about all this (one would have to see this in action to determine if it would work) but it might be easier than writing your own interactive Markdown editor...

    ...actually to implement your own C# Markdown editor, you could just put a text edit box next to an embedded IE control and run the current Markdown through the .NET Markdown->HTML converter on a separate thread, and replace the HTML in the IE control (assuming the Markdown->HTML converter is very liberal and robust against throwing ANY exceptions).

  • "WYSIWYG Markdown" is really an oxymoron since the whole point of Markdown is to allow you to write markup syntax naturally and intuitively which is then post-processed into html, unless you mean actually taking for example **text** and rendering it as **text** for example. That would actually be kind of cool, but it would get very difficult for things like numbered and bulleted lists, since you would have to do all the positioning, yet keep everything based on actual textual characters (e.g. '*' instead of the bullet symbol) and support proper textual input positioning, backspace, etc.

    • For example,
    • in this bullet list,
    • the bullets would actually have to be asterisks,
    • and the spacing would not really be there.

    That would certainly be worth paying attention to, if someone did tackle it.

    From chaiguy

Count Xpaths in XmlSpy

I am using XmlSpy to analyze an xml file, and I want to get a quick count of the number of nodes that match a given xpath. I know how to enter the xpath and get the list of nodes, but I am really just interested in the count. Is it possible to get this?

I'm using XmlSpy Professional Edition version 2007 sp2, if it matters.

  • I just figureed it out. I just needed to put count() around my xpath, like so:

    count(//my/node)
    
    From pkaeding

How to get a list of current open windows/process with Java?

Does any one know how do I get the current open windows or process of a local machine using Java?

What I'm trying to do is: list the current open task, windows or process open, like in Windows Taskmanager, but using a multi-platform approach - using only Java if it's possible.

Thanks!

  • The only way I can think of doing it is by invoking a command line application that does the job for you and then screenscraping the output (like Linux's ps and Window's tasklist).

    Unfortunately, that'll mean you'll have to write some parsing routines to read the data from both.

    Process proc = Runtime.getRuntime().exec ("tasklist.exe");
    InputStream procOutput = proc.getInputStream ();
    if (0 == proc.waitFor ()) {
        // TODO scan the procOutput for your data
    }
    
    ramayac : Yep,I already thought about that too, but I tough it could be done with Java only. And I think I would be better to use "ps -aux" instead of top. Thanks for the quick answer!
    From jodonnell
  • This is another aproach to parse the the process list from the command "ps -e":

        try {
            String line;
            Process p = Runtime.getRuntime().exec("ps -e");
            BufferedReader input =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
                System.out.println(line); //<-- Parse data here.
            }
            input.close();
        } catch (Exception err) {
            err.printStackTrace();
        }
    

    If you are using Windows, then you sould change the line: "Process p = Runtime.getRun..." etc... (3rd line), for one that looks like this:

        Process p = Runtime.getRuntime().exec
            (System.getenv("windir") +"\\system32\\"+"tasklist.exe");
    

    Hope the info helps!

    From ramayac
  • There is no platform-neutral way of doing this. In the 1.6 release of Java, a "Desktop" class was added the allows portable ways of browsing, editing, mailing, opening, and printing URI's. It is possible this class may someday be extended to support processes, but I doubt it.

    If you are only curious in Java processes, you can use the java.lang.management api for getting thread/memory information on the JVM.

    From hazzen

What are some best practices for creating my own custom exception?

In a follow-up to a previous question regarding exceptions, what are best practices for creating a custom exception in .NET?

More specifically should you inherit from System.Exception, System.ApplicationException or some other base exception?

  • I think the single most important thing to remember when dealing with exceptions at any level (making custom, throwing, catching) is that exceptions are only for exceptional conditions.

  • Inherit from System.Exception. System.ApplicationException is useless and the design guidelines say "Do not throw or derive from System.ApplicationException."

    See http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx

  • See this question: http://stackoverflow.com/questions/52753/derive-from-exception-or-applicationexception-in-net

    From rp
  • The base exception from where all other exceptions inherit from is System.Exception, and that is what you should inherit, unless of course you have a use for things like, say, default messages of a more specific exception.

    From Jon Limjap
  • There is a code snippet for it. Use that. Plus, check your code analysis afterwards; the snippet leaves out one of the constructors you should implement.

    From Will
  • In the C# IDE, type 'exception' and hit TAB. This will expand to get you started in writing a new exception type. There are comments withs links to some discussion of exception practices.

    Personally, I'm a big fan of creating lots of small classes, at that extends to exception types. For example, in writing the Foo class, I can choose between:

    1. throw new Exception("Bar happened in Foo");
    2. throw new FooException("Bar happened");
    3. throw new FooBarException();

    where

    class FooException : Exception 
    {
        public FooException(string message) ... 
    }
    

    and

    class FooBarException : FooException 
    {
        public FooBarException() 
            : base ("Bar happened") 
        {
        }
    }
    

    I prefer the 3rd option, because I see it as being an OO solution.

    From Jay Bazuzi

Best way to parse Space Separated Text

I have string like this

 /c SomeText\MoreText "Some Text\More Text\Lol" SomeText

I want to tokenize it, however I can't just split on the spaces. I've come up with somewhat ugly parser that works, but I'm wondering if anyone has a more elegant design.

This is in C# btw.

EDIT: My ugly version, while ugly, is O(N) and may actually be faster than using a RegEx.

private string[] tokenize(string input)
        {
            string[] tokens = input.Split(' ');
            List<String> output = new List<String>();

            for (int i = 0; i < tokens.Length; i++)
            {
                if (tokens[i].StartsWith("\""))
                {
                    string temp = tokens[i];
                    int k = 0;
                    for (k = i + 1; k < tokens.Length; k++)
                    {
                        if (tokens[k].EndsWith("\""))
                        {
                            temp += " " + tokens[k];
                            break;
                        }
                        else
                        {
                            temp += " " + tokens[k];
                        }
                    }
                    output.Add(temp);
                    i = k + 1;
                }
                else
                {
                    output.Add(tokens[i]);
                }
            }

            return output.ToArray();            
        }
  • The Microsoft.VisualBasic.FileIO namespace (in Microsoft.VisualBasic.dll) has a TextFieldParser you can use to split on space delimeted text. It handles strings within quotes (i.e., "this is one token" thisistokentwo) well.

    Note, just because the DLL says VisualBasic doesn't mean you can only use it in a VB project. Its part of the entire Framework.

    From Will
  • You also might want to look into regular expressions. That might help you out. Here is a sample ripped off from MSDN...

    using System;
    using System.Text.RegularExpressions;
    
    public class Test
    {
    
        public static void Main ()
        {
    
            // Define a regular expression for repeated words.
            Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
              RegexOptions.Compiled | RegexOptions.IgnoreCase);
    
            // Define a test string.        
            string text = "The the quick brown fox  fox jumped over the lazy dog dog.";
    
            // Find matches.
            MatchCollection matches = rx.Matches(text);
    
            // Report the number of matches found.
            Console.WriteLine("{0} matches found in:\n   {1}", 
                              matches.Count, 
                              text);
    
            // Report on each match.
            foreach (Match match in matches)
            {
                GroupCollection groups = match.Groups;
                Console.WriteLine("'{0}' repeated at positions {1} and {2}",  
                                  groups["word"].Value, 
                                  groups[0].Index, 
                                  groups[1].Index);
            }
    
        }
    
    }
    // The example produces the following output to the console:
    //       3 matches found in:
    //          The the quick brown fox  fox jumped over the lazy dog dog.
    //       'The' repeated at positions 0 and 4
    //       'fox' repeated at positions 20 and 25
    //       'dog' repeated at positions 50 and 54
    
    From Craig
  • Craig is right — use regular expressions. Regex.Split may be more concise for your needs.

    From harpo
  • The computer term for what you're doing is lexical analysis; read that for a good summary of this common task.

    Based on your example, I'm guessing that you want whitespace to separate your words, but stuff in quotation marks should be treated as a "word" without the quotes.

    The simplest way to do this is to define a word as a regular expression:

    ([^"^\s]+)\s*|"([^"]+)"\s*
    

    This expression states that a "word" is either (1) non-quote, non-whitespace text surrounded by whitespace, or (2) non-quote text surrounded by quotes (followed by some whitespace). Note the use of capturing parentheses to highlight the desired text.

    Armed with that regex, your algorithm is simple: search your text for the next "word" as defined by the capturing parentheses, and return it. Repeat that until you run out of "words".

    Here's the simplest bit of working code I could come up with, in VB.NET. Note that we have to check both groups for data since there are two sets of capturing parentheses.

    Dim token As String
    Dim r As Regex = New Regex("([^""^\s]+)\s*|""([^""]+)""\s*")
    Dim m As Match = r.Match("this is a ""test string""")
    
    While m.Success
        token = m.Groups(1).ToString
        If token.length = 0 And m.Groups.Count > 1 Then
            token = m.Groups(2).ToString
        End If
        m = m.NextMatch
    End While
    

    Note 1: Will's answer, above, is the same idea as this one. Hopefully this answer explains the details behind the scene a little better :)

    From Todd Myhre
  • [^\t]+\t|"[^"]+"\t

    using the Regex definitely looks like the best bet, however this one just returns the whole string. I'm trying to tweak it, but not much luck so far.

    string[] tokens = System.Text.RegularExpressions.Regex.Split(this.BuildArgs, @"[^\t]+\t|""[^""]+""\t");
    
    Todd Myhre : This will not work because Regex.Split is designed to capture based on separators, not tokens. Use Regex.Match to get the desired effect.
    From FlySwat
  • There is the state machine approach.

        private enum State
        {
            None = 0,
            InTokin,
            InQuote
        }
    
        private static IEnumerable<string> Tokinize(string input)
        {
            input += ' '; // ensure we end on whitespace
            State state = State.None;
            State? next = null; // setting the next state implies that we have found a tokin
            StringBuilder sb = new StringBuilder();
            foreach (char c in input)
            {
                switch (state)
                {
                    default:
                    case State.None:
                        if (char.IsWhiteSpace(c))
                            continue;
                        else if (c == '"')
                        {
                            state = State.InQuote;
                            continue;
                        }
                        else
                            state = State.InTokin;
                        break;
                    case State.InTokin:
                        if (char.IsWhiteSpace(c))
                            next = State.None;
                        else if (c == '"')
                            next = State.InQuote;
                        break;
                    case State.InQuote:
                        if (c == '"')
                            next = State.None;
                        break;
                }
                if (next.HasValue)
                {
                    yield return sb.ToString();
                    sb = new StringBuilder();
                    state = next.Value;
                    next = null;
                }
                else
                    sb.Append(c);
            }
        }
    

    It can easily be extended for things like nested quotes and escaping. Returning as IEnumerable<string> allows your code to only parse as much as you need. There aren't any real downsides to that kind of lazy approach as strings are immutable so you know that input isn't going to change before you have parsed the whole thing.

    See: http://en.wikipedia.org/wiki/Automata-Based_Programming

    From fryguybob

As a ASP.NET programmer, do I need to be concerned about email injection attacks ?

There are lots of PHP articles about the subject so is this a PHP only problem. I am sending emails using System.Net.Mail after some regular expression checks of course. Similar to http://weblogs.asp.net/scottgu/archive/2005/12/10/432854.aspx

  • I've never heard of that issue in ASP.NET. However, you should trust user input about as much as you'd trust a hooker with your wallet.

    From Will
  • the PHP email injection attack works because of a weakness in the PHP Mail() function. As a .net developer you need not worry.

    From Danimal
  • As long as you are using the MailAddress object, I think you're fine, because injections will only manage to throw FormatExceptions for the specified address.

    Examples of how to properly use the System.Net.Mail components are included in that MSDN page; be sure to follow them and you will be fine.

    From Jon Limjap

Is there a good library for dealing with the Modbus protocol in .NET?

Does anyone know of a good (preferably open source) library for dealing with the Modbus protocol? I have seen a few libraries, but I am looking for some people's personal experiences, not just the top ten Google hits. I figure there has to be at least one other person who deals with PLCs and automation hardware like I do out there.

Open to any other materials that might have been a help to you as well...

  • I have done a lot of communication with devices for the past few years, since I work for a home automation company, but we don't use Modbus. We do communication in a standard and open way using Web Services for Devices(WSD) which is also know as Devices Profile for Web Services(DPWS).

    During this time at one point, I did hear of a project called NModbus. It is an open source library for working with modbus. I have not used it, but looking at the site and the changesets on Google Code, it looks pretty active. You may want to give it a look and even get involved in. This is the only library that I have heard of that targets .Net.

    Geoffrey Chetwood : Yeah, I saw nmodbus and it looked ok, but last time I tried it it was a bit rough around the edges. I will give it a try. Really, I am now interested in reading up on WSD. Thanks for the link!
    Dale Ragan : Sure thing. WSD is really the way to go. Modbus is a very old protocol, I know you may not have a choice, but devices of today are starting to target WSD.
    egapotz : Thumbs up for NModbus: works really well
    From Dale Ragan
  • Modbus is a very simple protocol to implement. All information you need can easily be found for free on the Internet.

    If you choose to implement it yourself, I will be happy to answer any questions you have along the way.

    If you choose to go for a modbus master library I would look for:

    • Modbust TCP support.
    • Modbus RTU over TCP/UDP and COM-port.
    • Configurable byte swapping, word swapping
    • Configurable "base" adress so you can choose adress 1 to actually be adress 0 (sounds stupid, but I prefere to always specify adresses the same way they are documented)
    • it must support reading several adresses as a block, but it need to be flexible, some modbus slaves will return error if any adress in the block is unused/reserved).
    From mliesen

jQuery "after" selector question

I can't seem to figure out a good way to do this, but it seems like it should be simple. I have an element that I want to append a div to. Then I have another element that I want to clone and shove into that intermediate div. Here's what I was hoping to do:

$("#somediv > ul").after("<div id='xxx'></div>").append($("#someotherdiv").clone());

This seems to be close, but not quite there. The problem with this is that the "append" seems to be operating on the original "#somediv > ul" selector. This sort of makes sense, but it's not what I wanted. How can I most efficiently select that intermediate div that I added with the "after" and put my "#someotherdiv" into it?

  • How can I most efficiently select that intermediate div that I added with the "after" and put my "#someotherdiv" into it?

    @Vincent's solution is probably the fastest way to get the same result. However if for whatever reason you need add the div with after() then need to select it and operate on it you can use

    .nextAll( [expr] )

    Find all sibling elements after the current element.
    Use an optional expression to filter the matched set.

    So your js becomes:

    $("#somediv > ul")
        .after("<div id='xxx'></div>")
        .nextAll('#xxx')
        .append($("#someotherdiv").clone());
    
    From Pat
  • use insertAfter():

    $("<div id='xxx'></div>").insertAfter("#somediv > ul").append($("#someotherdiv").clone())
    
    From Jimmy
  • Go the other way around and use insertAfter().

    $("<div id='xxx'></div>")
        .append($("#someotherdiv").clone())
        .insertAfter("#somediv > ul")
    

    Try to add your generated DOM nodes to the document only after finishing your work.

    Once the nodes are added to the displayed document, the browser starts listening to any change to refresh the view. Doing all the work before adding the nodes to the displayed document does improve browser performance.

What is the design pattern for processing command line arguments

If you are writing a program that is executable from the command line, you often want to offer the user several options or flags, along with possibly more than one argument. I have stumbled my way through this many times, but is there some sort of design pattern for looping through args and spinning off the appropriate functions?

Consider:

myprogram -f filename -d directory -r regex

How do you organize the code after you retrieve the arguments using whatever built-ins for your language? (language-specific answers welcomed, if that helps you articulate an answer)

  • I don't know of any documented "patterns" for processing.

    I believe one of the oldest libraries/APIs for handling arguments is getopt. Googling "getopt" shows lots of man pages and links to implementations.

    Generally, I have a preferences or settings service in my application that the argument processor knows how to communicate with. Arguments are then translated into something in this service that the application than then query. This could be as simple as a dictionary of settings (like a string setting named "filename").

  • I would recommend using a command line processor library. Some Russian guy created a decent one, but there are tons of them out there. Will save you some time so you can concentrate on the purpose of your app rather than parsing command line switches!

    From Kilhoffer
  • You didn't mention the language, but for Java we've loved Apache Commons CLI. For C/C++, getopt.

  • You don't mention a language for this but if you are looking for a really nice Objective-C wrapper around getopt then Dave Dribin's DDCLI framework is really nice.

    http://www.dribin.org/dave/blog/archives/2008/04/29/ddcli

  • I use the Getopts::std and Getopts::long in perl and also the Getopt function in C. This standardises the parsing and format of parameters. Other languages have different mechanisms for handling these.

    Hope this helps

    From Xetius
  • The standard design usually follows what getopt does, there are getopt libraries for many languages, .NET, python, C, Perl, PHP, etc.

    The basic design is to have a command line parser which returns part by part the arguments passed to be checked in a loop.

    This article discusses it in some more detail.

  • Getopt is the only way to go.

    http://sourceforge.net/projects/csharpoptparse

    From cfeduke
  • The boost::program_options library is nice if you're in C++ and have the luxury of using Boost.

    From argv0
  • I am not as much interested in the libraries, though that is definitely helpful. I was looking more for some "pseudo code" that illustrates the processing of say your average bunch of flags and a bunch of longer arguments, as an example.

    ragu.pattabi : You might want to update this in your question rather than here about clarification. It is only meant for answers.
    From Sam McAfee
  • Assuming you have a "config" object that you aim to setup with the flags and a suitable command line parser that takes care of parsing the command line and supply a constant stream of the options, here goes a block of pseudocode

    while (current_argument = cli_parser_next()) {
        switch(current_argument) {
            case "f": //Parser strips the dashes
            case "force":
                config->force = true;
                break;
            case "d":
            case "delete":
                config->delete = true;
                break;
            //So on and so forth
            default:
                printUsage();
                exit;
        }
    }
    
  • I prefer options like "-t text" and "-i 44"; I don't like "-fname" or "--very-long-argument=some_value".

    And "-?", "-h", and "/h" all produce a help screen.

    Here's how my code looks:

    int main (int argc, char *argv[])
       {  int i;
          char *Arg;
          int ParamX, ParamY;
          char *Text, *Primary;
    
       // Initialize...
       ParamX = 1;
       ParamY = 0;
       Text = NULL;
       Primary = NULL;
    
       // For each argument...
       for (i = 0; i < argc; i++)
          {
          // Get the next argument and see what it is
          Arg = argv[i];
          switch (Arg[0])
             {
             case '-':
             case '/':
                // It's an argument; which one?
                switch (Arg[1])
                   {
                   case '?':
                   case 'h':
                   case 'H':
                      // A cry for help
                      printf ("Usage:  whatever...\n\n");
                      return (0);
                      break;
    
                   case 't':
                   case 'T':
                      // Param T requires a value; is it there?
                      i++;
                      if (i >= argc)
                         {
                         printf ("Error:  missing value after '%s'.\n\n", Arg);
                         return (1);
                         }
    
                      // Just remember this
                      Text = Arg;
    
                      break;
    
                   case 'x':
                   case 'X':
                      // Param X requires a value; is it there?
                      i++;
                      if (i >= argc)
                         {
                         printf ("Error:  missing value after '%s'.\n\n", Arg);
                         return (1);
                         }
    
                      // The value is there; get it and convert it to an int (1..10)
                      Arg = argv[i];
                      ParamX = atoi (Arg);
                      if ((ParamX == 0) || (ParamX > 10))
                         {
                         printf ("Error:  invalid value for '%s'; must be between 1 and 10.\n\n", Arg);
                         return (1);
                         }
    
                      break;
    
                   case 'y':
                   case 'Y':
                      // Param Y doesn't expect a value after it
                      ParamY = 1;
                      break;
    
                   default:
                      // Unexpected argument
                      printf ("Error:  unexpected parameter '%s'; type 'command -?' for help.\n\n", Arg);
                      return (1);
                      break;
                   }
    
                break;
    
             default:
                // It's not a switch that begins with '-' or '/', so it's the primary option
                Primary = Arg;
    
                break;
             }
          }
    
       // Done
       return (0);
       }
    
  • A few comments on this...

    First, while there aren't any patterns per se, writing a parser is essentially a mechanical exercise, since given a grammar, a parser can be easily generated. Tools like Bison, and ANTLR come to mind.

    That said, parser generators are usually overkill for the command line. So the usual pattern is to write one yourself (as others have demonstrated) a few times until you get sick of dealing with the tedious detail and find a library to do it for you.

    I wrote one for C++ that saves a bunch of effort that getopt imparts and makes nice use of templates: TCLAP

    From mes5k
  • I'm riffing on the ANTLR answer by mes5k. This link to Codeproject is for an article that discusses ANLTR and using the visit pattern to implement the actions you want you app to take. It's well written and worth reviewing.

How to capture output of "pnputil.exe -e"

How do I capture the output of "%windir%/system32/pnputil.exe -e"? (assume windows vista 32-bit)

Bonus for technical explanation of why the app normally writes output to the cmd shell, but when stdout and/or stderr are redirected then the app writes nothing to the console or to stdout/stderr?

C:\Windows\System32>PnPutil.exe --help
Microsoft PnP Utility {...}

C:\Windows\System32>pnputil -e > c:\foo.txt

C:\Windows\System32>type c:\foo.txt

C:\Windows\System32>dir c:\foo.txt
 Volume in drive C has no label.
 Volume Serial Number is XXXX-XXXX

 Directory of c:\

09/10/2008  12:10 PM                 0 foo.txt
               1 File(s)              0 bytes
  • It could be that pnputil outputs to stderr instead of stdout.

    Try pnputil -e 2> c:\foo.txt

    ColinYounger : Nope - tried that myself.
  • Some applications are written so that it works in piping scenarios well e.g.

    svn status | find "? "
    

    is a command that pipes output of svn status into find "? " so it would filter subversion output down to unknown files (marked with a question mark) in my repos.

    Imagine if svn status would also output a header that says "Copyright ? 2009" That very specific header line would also show up. Which is not what I expect.

    So certain tools, like those of Sysinternals' will write any header information only if it is printed directly to the command window, if any kind of redirection is detected, then those header information will not be written as by the reason above.

    Header information becomes noise when used in piping/automation scenarios.

    I suppose if you can't use > to output to a file, its because the tool is hardwired not to do so. You'll need an indirect means to capture it.

    Hope this helps.

    From chakrit
  • As alluded to in the question, but not clearly stated, "pnputil -e 2> c:\foo.txt" does not have the intended result either. This one directs nothing into the file but it does send the output to the console.

    From JeffJ
  • There's only two output streams. If "> c:\foo.txt" doesn't work, and "2> C:\foo.txt" doesn't work then nothing is being output.

    You can merge the standard error into the standard output (2>&1) so all output is through standard output:

    pnputil -e 1>c:\foo.txt 2>&1

    If that doesn't output anything to foo.txt then pnputil must be detecting redirection and stopping output.

  • Out of curiousity, does piping to the clipboard put anything useful on the clipbioard?

    e.g. pnputil -e | clip

  • I think I found the technical answer for why it behaves this way. The MSDN page for WriteConsole says that redirecting standard output to a file causes WriteConsole to fail and that WriteFile should be used instead. The debugger confirms that pnputil.exe does call kernel32!WriteConsoleW and kernel32!WriteConsoleInputW.

    Hmm, I should have asked this as two separate questions.

    I'm still looking for an answer for how to scrape the output from this command. The accepted answer will be one that answers this part of the question.

    From JeffJ
  • @[Peter Ritchie]: Piping to clip has the effect of clearing the clipboard and writing nothing to the console. Good try.

    Peter Ritchie : If it's just clearing the clipboard then clearly pnputil is not outputting anything in these circumstances.
    From JeffJ
  • Doesn't seem like there is an easy way at all. You would have to start hooking the call to WriteConsole and dumping the string buffers. See this post for a similar discussion.

    Of course, if this is a one off for interactive use then just select all the output from the command window and copy it to the clipboard. (Make sure you cmd window buffer is big enough to store all the output).

    From Rob Walker
  • You could have tried Expect for Windows to do this kind of things, it would tell the tool that there was a console and hook the WriteConsole calls for you. Expect for Windows

    From schlenk
  • Hi,

    I am basically reopening this thread. I believe this is a practical problem to get the output of pnputil to a file for some other purpose but right now, it does not appear to work.

    Is there someone who can assist. Any help is appreciated.

    Regards, Naveen

    From
  • click on the system menu icon(upper left hand corner->properties->layout

    change the screen buffer size

    cls

    pnputil -e

    ;-P

Programmatically accessing Data in an ASP.net 2.0 Repeater

This is an ASP.Net 2.0 web app. The Item template looks like this, for reference:

<ItemTemplate>
 <tr>
  <td class="class1" align=center><a href='url'><img src="img.gif"></a></td>
  <td class="class1"><%# DataBinder.Eval(Container.DataItem,"field1") %></td>
  <td class="class1"><%# DataBinder.Eval(Container.DataItem,"field2") %></td>
  <td class="class1"><%# DataBinder.Eval(Container.DataItem,"field3") %></td>
  <td class="class1"><%# DataBinder.Eval(Container.DataItem,"field4") %></td>
 </tr>
</ItemTemplate>

Using this code in the bowels of the codebehind:

foreach (RepeaterItem item in rptrFollowupSummary.Items)
{
 string val = ((DataBoundLiteralControl)item.Controls[0]).Text;
 Trace.Write(val);
}

I produce this:

<tr>
<td class="class1" align=center><a href='url'><img src="img.gif"></a></td>
<td class="class1">23</td>
<td class="class1">1/1/2000</td>
<td class="class1">-2</td>
<td class="class1">11</td>
</tr>

What I need is the data from Field1 and Field4

I can't seem to get at the data the way I would in say a DataList or a GridView, and I can't seem to come up with anything else on Google or quickly leverage this one to do what I want. The only way I can see to get at the data is going to be using a regex to go and get it (Because a man takes what he wants. He takes it all. And I'm a man, aren't I? Aren't I?).

Am I on the right track (not looking for the specific regex to do this; forging that might be a followup question ;) ), or am I missing something?

  • Since you are working with tabular data, I'd recommend using the GridView control. Then you'll be able to access individual cells.

    Otherwise, you can set the td's for Field1 and Field4 to runat="server" and give them ID's. Then in the codebehind, access the InnerText property for each td.

    From ern
  • If you can afford a smidge more overhead in the generation, go for DataList and use the DataKeys property, which will save the data fields you need.

    You could also use labels in each of your table cells and be able to reference items with e.Item.FindControl("LabelID").

    From Dillie-O
  • Off the top of my head, you can try something like this:

    <ItemTemplate>
            <tr>
                <td "class1"><asp:Literal ID="litField1" runat="server" Text='<%# Bind("Field1") %>'/></td>
                <td "class1"><asp:Literal ID="litField2" runat="server" Text='<%# Bind("Field2") %>'/></td>
                <td "class1"><asp:Literal ID="litField3" runat="server" Text='<%# Bind("Field3") %>'/></td>
                <td "class1"><asp:Literal ID="litField4" runat="server" Text='<%# Bind("Field4") %>'/></td>
            </tr>
    </ItemTemplate>
    

    Then, in your code behind, you can access each Literal control as follows:

    foreach (RepeaterItem item in rptrFollowupSummary.Items)
    {   
        Literal lit1 = (Literal)item.FindControl("litField1");
        string value1 = lit1.Text;
        Literal lit4 = (Literal)item.FindControl("litField4");
        string value4 = lit4.Text;
    }
    

    This will add to your ViewState but it makes it easy to find your controls.

    From Alison
  • The <%#DataBinder.Eval(...) %> mechanism is not Data Binding in a "strict" sense. It is a one-way technique to put text in specific places in the template.

    If you need to get the data back out, you have to either:

    1. Get it from your source data
    2. Populate the repeater with a different mechanism

    Note that the Repeater doesn't save the DataSource between postbacks, You can't just ask it to give you the data later.

    The first method is usually easier to work with. Don't assume that it's too expensive to reacquire your data from the source, unless you prove it to yourself by measuring; it's usually pretty fast. The biggest problem with this technique is if the source data can change between calls.

    For the second method, a common technique is to use a Literal control. See Alison Zhou's post for an example of how to do it. I usually personally prefer to fill the Literal controls inside of the OnItemDataBound instead

  • The Repeater in this case is set in stone so I can't switch to something more elegant. Once upon a time I did something similar to what Alison Zhou suggested using DataLists, but it's been some time (2+ years) and I just completely forgot about doing it this way. Yeesh, talk about overlooking something obvious. . .

    So I did as Alison suggested and it works fine. I don't think the viewstate is an issue here, even though this repeater can get dozens of rows. I can't really speak to the question if doing it that way versus using the instead (but that seems like a fine solution to me otherwise). Obviously the latter is less of a viewstate footprint, but I'm not experienced enough to say when one approach might be preferrable to another without an extreme example in front of me. Alison, one question: why literals and not labels?

    Euro Micelli, I was trying to avoid a return trip to the database. Since I'm still a little green relative to the rest of the development world, I admit I don't necessarily have a good grasp of how many database trips is "just right". There wouldn't be a performance issue here (I know the app's load enough to know this), but I suppose I was trying to avoid it out of habit, since my boss tends to emphasize fewer trips where possible.

    From peacedog
  • @peacedog:

    Correct; Alison's method is perfectly acceptable.

    The trick with the database roundtrips: they are not free, obviously, but web servers tend to be very "close" (fast, low-latency connection) to the database, while your users are probably "far" (slow, high-latency connection).

    Because of that, sending data to/from the browser via cookies, ViewState, hidden fields or any other method can actually be "worse" than reading it again from your database. There are also security implications to keep in mind (Can an "evil" user fake the data coming back from the browser? Would it matter if they do?).

    But quite often it doesn't make any difference in performance. That's why you should do what works more naturally for your particular problem and worry about it only if performance starts to be a real-world issue.

    Good luck!