q:
What is the best way to transparently rewrite a URL over an SSL connection with Apache 2.2?

Apache 2 does not natively support multiple name-based virtual hosts for an SSL connection and I have heard that mod_rewrite can help with this. I would like to do something like this:

I have set up the server so that the sites can be accessed by

https://secure.example.com/dbadmin

but I would like to have this as https://dbadmin.example.com

How do I set it up so that the Rewrite rule will rewrite dbadmin.example.com to secure.example.com/dbadmin, but without displaying the rewrite on the client's address bar (i.e. the client will still just see dbadmin.example.com), all over https?

[A]
There is apaches mod_rewrite, or you could setup apache to direct
https://dbadmin.example.com
to path/to/example.com/dbadmin on the server
```
```
<VirtualHost *>
ServerName subdomain.domain.com
DocumentRoot /home/httpd/htdocs/subdomain/
</VirtualHost>
```
```


q:
I'm using .htaccess and mod_rewrite to point to files that reside behind the DocumentRoot. My folder structure looks like this:

home/
    webroot/
    other_files/

I have a .htaccess file in webroot with the following content:

RewriteEngine on
RewriteRule ^(.*)$ /home/other_files/$1

If I try to access http://example.com/file.html I receive the following error:

The requested URL /home/other_files/file.html was not found on this server.

Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction?

[A]
I believe you need to add a section with
```
```
<Directory "/home/other_files">
  (options)
</Directory>
```
```
to your server configuration before apache will be able to serve anything from it.  For an example, my DocumentRoot is /var/www but there is this section in the default available site:
```
```
Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
```
```
You could then rewrite a URL to go to /doc/ and the server would know where to get the files from.

s: huggingface

c: devops

d: intermediate


q:
From time to time I see an enum like the following:

[Flags]
public enum Options
{
    None    = 0,
    Option1 = 1,
    Option2 = 2,
    Option3 = 4,
    Option4 = 8
}

I don't understand what exactly the [Flags] attribute does.

Anyone have a good explanation or example they could post?

[A]
Flags allow you to use bitmasking inside your enumeration.  This allows you to combine enumeration values, while retaining which ones are specified.
```
```
[Flags]
public enum DashboardItemPresentationProperties : long
{
    None = 0,
    HideCollapse = 1,
    HideDelete = 2,
    HideEdit = 4,
    HideOpenInNewWindow = 8,
    HideResetSource = 16,
    HideMenu = 32
}
```
```


q: Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept?

[A]
It's a fairly simple process. Take a function, bind one of its arguments and return a new function. For example:
```
```
let concatStrings left right = left + right
let makeCommandPrompt= appendString "c:\> "
```
```
Now by currying the simple concatStrings function, you can easily add a DOS style command prompt to the front of any string! Really useful!
Okay, not really. A more useful case I find is when I want to have a make a function that returns me data in a stream like manner.
```
```
let readDWORD array i = array[i] | array[i + 1] << 8 | array[i + 2] << 16 |
    array[i + 3] << 24 //I've actually used this function in Python.
```
```
The convenient part about it is that rather than creating an entire class for this sort of thing, calling the constructor, calling obj.readDWORD(), you just have a function that can't be mutated out from under you.


q: I've done some WPF programing and one thing I never got was the command pattern.  Every example seems to be for built in ones, edit, cut, paste.  Anyone have an example or suggestion of best practice for custom commands?

[A]
Ah ha! A question I can answer! Firstly, I should mention that I have personally found it easier to define and hook up commands in code rather than in XAML. It allows me to hook up the handlers for the commands a little more flexibly than an all XAML approach does.
You should work out what commands you want to have and what they relate to. In my application, I currently have a class for defining important application commands like so:
```
```
public static class CommandBank
{
  /// Command definition for Closing a window
  public static RoutedUICommand CloseWindow { get; private set; }

  /// Static private constructor, sets up all application wide commands.
  static CommandBank()
  {
    CloseWindow = new RoutedUICommand();
    CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));
    // ...
  }
```
```
Now, because I wanted to keep the code all together, using a code only approach to Commands lets me put the following methods in the class above:
```
```
/// Closes the window provided as a parameter
public static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)
{
  ((Window)e.Parameter).Close();
}

/// Allows a Command to execute if the CommandParameter is not a null value
public static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e)
{
  e.CanExecute = e.Parameter != null;
  e.Handled = true;
}
```
```
The second method there can even be shared with other Commands without me having to repeat it all over the place.
Once you have defined the commands like this, you can add them to any piece of UI. In the following, once the Window has Loaded, I add command bindings to both the Window and MenuItem and then add an input binding to the Window using a loop to do this for all command bindings. The parameter that is passed is the Window its self so the code above knows what Window to try and close.
```
```
public partial class SimpleWindow : Window
{
  private void WindowLoaded(object sender, RoutedEventArgs e)
  {
    // ...
    this.CommandBindings.Add(
      new CommandBinding(
        CommandBank.CloseWindow,
        CommandBank.CloseWindowExecute,
        CommandBank.CanExecuteIfParameterIsNotNull));

    foreach (CommandBinding binding in this.CommandBindings)
    {
       RoutedCommand command = (RoutedCommand)binding.Command;
       if (command.InputGestures.Count > 0)
       {
         foreach (InputGesture gesture in command.InputGestures)
         {
           var iBind = new InputBinding(command, gesture);
           iBind.CommandParameter = this;
           this.InputBindings.Add(iBind);
         }
       }
    }

    // menuItemExit is defined in XAML
    menuItemExit.Command = CommandBank.CloseWindow;
    menuItemExit.CommandParameter = this;
    // ...
  }

  // ....
}
```
```
I then also later have event handlers for the WindowClosing and WindowClosed events, I do recommend you make the actual implementation of commands as small and generic as possible. As in this case, I didn't try to put code that tries to stop the Window closing if there is unsaved data, I kept that code firmly inside the WindowClosing event.
Let me know if you have any follow up questions. :)


q: Are there any handy general items you put in your .procmailrc file?

[A]
Just simple things - move messages to appropriate folders, forward some stuff to an email2sms address, move spam to spam folder. One thing I'm kind of proud of is how to mark your spam as "read" (this is for Courier IMAP and Maildir, where "read" means "move to different folder and change the filename"):
```
```
:0
* ^X-Spam                       # the header our filter inserts for spam
{
    :0
    .Junk\ E-mail/              # stores in .Junk E-mail/new/

    :0
    * LASTFOLDER ?? /\/[^/]+$   # get the stored message's filename
    { tail=$MATCH }             # and put it into $tail
    # now move the message
    TRAP="mv .Junk\ E-mail/new/$tail .Junk\ E-mail/cur/$tail:2,S"
}
```
```


q:
I've moved from TFS to SVN (TortoiseSVN) with my current company. I really miss the "Shelve" feature of TFS. I've read various articles on how to "Shelve" with SVN, but I've read nothing that gives a very simple experience to "shelve" work.

Ideally, I'd like extra items added to the TortoiseSVN context menu - "Shelve" & "Unshelve".
"Shelve" would remove the current shelve-set, and upload the working directory under a suitable path defined by user options. "Unshelve" would merge the set with the working copy.

Does something like this exist? Can anyone suggest any ways to "hack" this feature in the GUI?

Note: The following link doesn't really achieve the user experience I was looking for:

Shelving Subversion

One of the greatest things about TFS Shelve is how easy it is to use...

[A]
I don't believe that SVN has this feature built into the server product. I also don't believe anything like this emulated in any clients that I have used, including TortoiseSVN.
To get around this problem, I have resorted to using a DVCS such as
Git
or
Mercurial
, to allow me to branch/merge/shelve locally before pushing the content back to SVN. It's arguably a bit of a kludge, but it works really well.


q:
I've had this long term issue in not quite understanding how to implement a decent Lucene sort or ranking.  Say I have a list of cities and their populations. If someone searches "new" or "london" I want the list of prefix matches ordered by population, and I have that working with a prefix search and an sort by field reversed, where there is a population field, IE New Mexico, New York; or London, Londonderry.

However I also always want the exact matching name to be at the top.  So in the case of "London" the list should show "London, London, Londonderry" where the first London is in the UK and the second London is in Connecticut, even if Londonderry has a higher population than London CT.

Does anyone have a single query solution?

[A]
My current solution is to create an exact searcher and a prefix searcher, both sorted by reverse population, and then copy out all my hits starting from the exact hits, moving to the prefix hits.  It makes paging my results slightly more annoying than I think it should be.
Also I used a hash to eliminate duplicates but later changed the prefix searcher into a boolean query of a prefix search (MUST) with an exact search (MUST NOT), to have Lucene remove the duplicates. Though this seemed even more wasteful.
Edit
: Moved to a comment (since the feature now exists):
Yuval F
Thank you for your blog post ... How would the sort comparator know that the name field "london" exactly matches the search term "london" if it cannot access the search term?


q:
I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle.  It kept throwing me a Too Many Clauses error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query.

Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries?

[A]
I've hit this before.  It has to do with the fact that lucene, under the covers, turns many (all?) things into boolean queries when you call Query.rewrite()
From:
http://web.archive.org/web/20110915061619/http://lucene.apache.org:80/java/2_2_0/api/org/apache/lucene/search/Query.html
```
```
public Query rewrite(IndexReader reader)
              throws IOException

    Expert: called to re-write queries into primitive queries.
            For example, a PrefixQuery will be rewritten into a
            BooleanQuery that consists of TermQuerys.

    Throws:
        IOException
```
```


q:
I need to try to lock on an object, and if its already locked just continue (after time out, or without it).

The C# lock statement is blocking.

[A]
I believe that you can use
```
Monitor.TryEnter()
```
.
The lock statement just translates to a
```
Monitor.Enter()
```
call and a
```
try catch
```
block.


q:
Can anyone recommend a good binary XML format? It's for a JavaME application, so it needs to be a) Easy to implement on the server, and b) Easy to write a low-footprint parser for on a low-end JavaME client device.

And it goes without saying that it needs to be smaller than XML, and faster to parse.

The data would be something akin to SVG.

[A]
What kind of data are you planning to use? I would say, that if the server is also done in Java, easiest way for small footprint is to send/receive binary data in predefined format. Just write everything in known order into
```
DataOutputStream
```
.
But it would really depend, what what kind of data are you working on and can you define the format.
Actually you should evaluate, if this kind of optimization is even needed. Maybe you target devices are not
so
limited.


q:
I am trying to load Linq on my .Net 3.5 enabled web server by adding the following to my .aspx page:

<%@ Import Namespace="System.Query" %>

However, this fails and tells me it cannot find the namespace.

The type or namespace name 'Query' does not exist in the namespace 'System'

I have also tried with no luck:

System.Data.Linq

System.Linq

System.Xml.Linq

I believe that .Net 3.5 is working because var hello = "Hello World" seems to work.

Can anyone help please?

PS: I just want to clarify that I don't use Visual Studio, I simply have a Text Editor and write my code directly into .aspx files.

[A]
The
```
var hello
```
stuff is compiler magic and will work without Linq.
Try adding a reference to
```
System.Core
```
Sorry, I wasn't clear. I meant add
```
System.Core
```
to the web project's references, not to the page.
The
```
Import
```
on the page are basically just using statements, allowing you to skip the namespace on the page.


q: Are there any codes that allow for numerical formatting of data when using string.format?

[A]
Loads, stick
```
string.Format
```
into Google :-)
A quite good tutorial is at
iduno


q:
Now that .NET v3.5 SP1 has been released (along with VS2008 SP1), we now have access to the .NET entity framework.

My question is this.  When trying to decide between using the Entity Framework and LINQ to SQL as an ORM, what's the difference?

The way I understand it, the Entity Framework (when used with LINQ to Entities) is a 'big brother' to LINQ to SQL?  If this is the case - what advantages does it have?  What can it do that LINQ to SQL can't do on its own?

[A]
There are a number of obvious differences outlined in that article @lars posted, but short answer is:
L2S is tightly coupled - object property to specific field of database or more correctly object mapping to a specific database schema
L2S will only work with SQL Server (as far as I know)
EF allows mapping a single class to multiple tables
EF will handle M-M relationships
EF will have ability to target any ADO.NET data provider
The original premise was L2S is for Rapid Development, and EF for more "enterprisey" n-tier applications, but that is selling L2S a little short.


q: What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website?

[A]
The
lxml package
supports xpath.  It seems to work pretty well, although I've had some trouble with the self:: axis.  There's also
Amara
, but I haven't used it personally.


q:
I have a script that checks responses from HTTP servers using the PEAR HTTP classes. However, I've recently found that the script fails on FTP servers (and probably anything that's not HTTP or HTTPS). I tried Google, but didn't see any scripts or code that returned the server status code from servers other than HTTP servers.

How can I find out the status of a newsgroup or FTP server using PHP?

EDIT: I should clarify that I am interested only in the ability to read from an FTP server and the directory that I specify. I need to know if the server is dead/gone, I'm not authorized to read, etc.

Please note that, although most of the time I'm language agnostic, the entire website is PHP-driven, so a PHP solution would be the best for easy of maintainability and extensibility in the future.

[A]
Wouldn't it be simpler to use the built-in PHP FTP* functionality than trying to roll your own?  If the URI is coming from a source outside your control, you would need to check the protocal definition (http:// or ftp://, etc) in order to determine which functionality to use, but that is fairly trivial.  If there is now protocal specified (there really should be!) then you could try to default to http.
see
here


q:
I've got an MDI application written in Delphi 2006 which runs XP with the default theme.

Is there a way of controlling the appearance of the MDI Children to avoid the large XP-style title bar on each window?

I've tried setting the BorderStyle of the MDIChildren to bsSizeToolWin but they are still rendered as normal Forms.

[A]
I don't think there is; in my experience, MDI in Delphi is very strictly limited and controlled by its implementation in the VCL (and perhaps also by the Windows API?). For example, don't try hiding an MDI child (you'll get an exception if you try, and you'll have to jump through a couple of API hoops to work around that), or changing the way an MDI child's main menu is merged with the host form's.
Given these limitations, perhaps you should reconsider why you'd like to have special title bars in the first place? I guess there are also good reasons why this MDI stuff is standardized --- your users might appreciate it :)
(PS: nice to see a Delphi question around here!)


q:
I'm trying to rebuild an old metronome application that was originally written using MFC in C++ to be written in .NET using C#.  One of the issues I'm running into is getting the timer to "tick" accurately enough.

For example, assuming an easy BPM (beats per minute) of 120, the timer should tick every .5 seconds (or 500 milliseconds).  Using this as the basis for the ticks, however, isn't entirely accurate as .NET only guarantees that your timer will not tick before the elapsed time has passed.

Currently, to get around this for the same 120 BPM example used above, I am setting the ticks to something like 100 milliseconds and only playing the click sound on every 5th timer tick.  This does improve the accuracy quite a bit, but if feels like a bit of a hack.

So, what is the best way to get accurate ticks?  I know there are more timers available than the windows forms timer that is readily available in Visual Studio, but I'm not really familiar with them.

[A]
There are three timer classes called 'Timer' in .NET.   It sounds like you're using the Windows Forms one, but actually you might find the System.Threading.Timer class more useful - but be careful because it calls back on a pool thread, so you can't directly interact with your form from the callback.
Another approach might be to p/invoke to the Win32 multimedia timers - timeGetTime, timeSetPeriod, etc.
A quick google found this, which might be useful
http://www.codeproject.com/KB/miscctrl/lescsmultimediatimer.aspx
'Multimedia' (timer) is the buzz-word to search for in this context.


q:
I would like to create a stored procedure in MySQL that took a list as argument. For example, say that I would like to be able to set multiple tags for an item in one call, then what I want to do is to define a procedure that takes the ID of the item and a list of tags to set. However, I can't seem to find any way to do this, there is no list datatype, as far as I'm aware, but can it be emulated somehow? Could the list of tags be a comma-separated string, which can somehow be split and looped over?

How do you usually work with lists in MySQL stored procedures?

[A]
Not sure if these will work specifically in a SP, but there are ENUM and SET datatypes in MySQL 5 which may do what you need.
http://dev.mysql.com/doc/refman/5.0/en/enum.html
http://dev.mysql.com/doc/refman/5.0/en/set.html


q:
So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable?

public class TokenTree
{
    public TokenTree()
    {
        /* I must admit to not fully understanding this,
         * I got it from msdn. As far as I can tell, IDictionary is an
         * interface, and Dictionary is the default implementation of
         * that interface, right?
         */
        SubPairs = new Dictionary<string, string>();
    }

    public string Key;
    public string Value;
    public IDictionary<string, string> SubPairs;
}

It's only really a simple shunt for passing around data.

[A]
There is an actual Data Type called KeyValuePair, use like this
```
```
KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>("defaultkey", "defaultvalue");
```
```


q:
Does anyone know if it is possible to display a prompt to a user/administrator when activating or installing a sharepoint feature?

I am writing a custom webpart and it is connecting to a separate database, I would like to allow the administrator to select or type in a connection string when installing the .wsp file or activating the feature.

I am looking inside the FeatureActivated event and thinking of using the SPWebConfigModification class to actually write the connection string to the web.config files in the farm.

I do not want to hand edit the web.configs or hard code the string into the DLL.

If you have other methods for handling connection strings inside sharepoint I would be interested in them as well.

[A]
Unfortunately there is no way to swap to a screen where you can get user via the feature activation process. Couple of comments for you:
I'm assuming the connection string is going to be different for every installation, so there is no way you can include it directly in the Solution.
I'm assuming that you couldn't programmatically construct this during installation.
Therefore, you need some way to get user input. Here are a couple of options:
It could be a web part property, though this would mean setting it each and every time the web part was added, and you would need to then maitain those settings individually.
You could build out your own _layouts settings screen (good post:
http://community.zevenseas.com/Blogs/Robin/archive/2008/03/17/lcm-creating-custom-application-page-and-using-the-propertybag-more-detailed.aspx
), and from there users can maintain the property, storing it in either the Web Property bag, or inside the Web.Config. I try to avoid using the Web.Config where I can, but if you do wish to go this route then MAKE SURE you use the SPWebConfigModification class (Read this great blog:
http://www.crsw.com/mark/Lists/Posts/Post.aspx?ID=32
)
Finally, a technique I often use is storing configuration information in a SharePoint List. Chris O'Brien has a great framework for that here:
http://www.codeplex.com/SPConfigStore
Hope that helps,
Daniel


q: Using the Windows API, how can I get a list of domains on my network?

[A]
Answered my own question:
Use the
NetServerEnum
function, passing in the
```
SV_TYPE_DOMAIN_ENUM
```
constant for the "servertype" argument.
In Delphi, the code looks like this:
```
```
<snip>
type
  NET_API_STATUS = DWORD;
  PSERVER_INFO_100 = ^SERVER_INFO_100;
  SERVER_INFO_100 = packed record
    sv100_platform_id : DWORD;
    sv100_name        : PWideChar;
end;

function NetServerEnum(  //get a list of pcs on the network (same as DOS cmd "net view")
  const servername    : PWideChar;
  const level         : DWORD;
  const bufptr        : Pointer;
  const prefmaxlen    : DWORD;
  const entriesread   : PDWORD;
  const totalentries  : PDWORD;
  const servertype    : DWORD;
  const domain        : PWideChar;
  const resume_handle : PDWORD
) : NET_API_STATUS; stdcall; external 'netapi32.dll';

function NetApiBufferFree(  //memory mgmt routine
  const Buffer : Pointer
) : NET_API_STATUS; stdcall; external 'netapi32.dll';

const
  MAX_PREFERRED_LENGTH = DWORD(-1);
  NERR_Success = 0;
  SV_TYPE_ALL  = $FFFFFFFF;
  SV_TYPE_DOMAIN_ENUM = $80000000;

function TNetwork.ComputersInDomain: TStringList;
var
  pBuffer        : PSERVER_INFO_100;
  pWork          : PSERVER_INFO_100;
  dwEntriesRead  : DWORD;
  dwTotalEntries : DWORD;
  i              : integer;
  dwResult       : NET_API_STATUS;
begin
  Result := TStringList.Create;
  Result.Clear;

  dwResult := NetServerEnum(nil,100,@pBuffer,MAX_PREFERRED_LENGTH,
                            @dwEntriesRead,@dwTotalEntries,SV_TYPE_DOMAIN_ENUM,
                            PWideChar(FDomainName),nil);

  if dwResult = NERR_SUCCESS then begin
    try
      pWork := pBuffer;
      for i := 1 to dwEntriesRead do begin
        Result.Add(pWork.sv100_name);
        inc(pWork);
      end;  //for i
    finally
      NetApiBufferFree(pBuffer);
    end;  //try-finally
  end  //if no error
  else begin
    raise Exception.Create('Error while retrieving computer list from domain ' +
                           FDomainName + #13#10 +
                           SysErrorMessage(dwResult));
  end;
end;
<snip>
```
```


q:
I wrote an application that currently runs against a local instance of MySql.  I would like to centralize the DB somewhere on the Net, and share my application.

But, I'm cheap, and don't want to pay for it.  Does anyone know of a free on-line relational DB service that I could connect to via C#?

[A]
I've never heard of such a thing. A few years ago, many hosts (Brinkster, etc) offered some minimal database capacity with their free web hosting accounts, but I think you'd find it difficult to find something like that now. Even if you could, most hosts no longer allow you to connect to a database (even on an account you're paying for) outside of a web application running on their server.
My advice would be to cobble together an old computer and use that as a database server that you run out of your house (coupled with no-ip or some similar service, probably). If you're going to need more horsepower/bandwidth than that, you'll probably just have to suck it up and pay for something.


q: Is there a maintained package I can use to retrieve and set MP3 ID3 metadata using Python?

[A]
A simple example from the book Dive Into Python works ok for me,
this
is the download link, the example is fileinfo.py. Don't know if it's the best, but it can do the basic job.
The entire book is available online
here
.


q:
I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem.

In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0.

Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different.

Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there?

[A]
It doesn't
need
to be WIA. I was mostly looking at the WIA setup because it offers the same basic interface for different scanners. I've got 3 scanners on this machine and the TWAIN drivers/software for all of them suck (like blocking the screen during scanning).
For document management, I'm really looking for simple 200dpi grayscale scans, so most of the stuff in the TWAIN drivers is overkill.
That said, asking here was part of my last attempt to figure out how to do it in WIA before moving on to TWAIN.


q: We need to add WorkFlow to our Spring managed application. Does anyone have any useful experience in using any of the myriad of OSS Work Flow solutions? Which one is best? Which one integrates with Spring best? Which ones should we avoid?

[A]
If you only need some simple process orchestration, Spring's own
Web Flow
, despite its name can serve as a orchestration task manager.   If you need to preserve state for several days then you will need to become an 'early adopter' of one of the open-source projects.  You may want to look at
Eclipse's BPEL project
.
My hunch is that once a clearer picture of the BPEL/BPM/Workflow space emerges you will see Spring provide an abstraction layer the same way they have for JDBC, Transactions, ORM frameworks etc...


q: Is it possible to access the iSight camera on a macbook programmatically? By this I mean I would like to be able to just grab still frames from the iSight camera on command and then do something with them. If so, is it only accessible using objective c, or could other languages be used as well?

[A]
I don't have a Mac here, but there is some Documentation up here:
http://developer.apple.com/documentation/Hardware/Conceptual/iSightProgGuide/01introduction/chapter_1_section_1.html
It looks like you have to go through the QuickTime API. There is supposed to be a Sample Project called "MungGrab" which could be worth a look according to
this thread
.


q:
When I use the sp_send_dbmail stored procedure, I get a message saying that my mail was queued. However, it never seems to get delivered. I can see them in the queue if I run this SQL:

SELECT * FROM msdb..sysmail_allitems WHERE sent_status = 'unsent'

This SQL returns a 1:

SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb'

This stored procedure returns STARTED:

msdb.dbo.sysmail_help_status_sp

The appropriate accounts and profiles have been set up and the mail was functioning at one point. There are no errors in msdb.dbo.sysmail_event_log.

[A]
Have you tried
```
```
sysmail_stop_sp
```
```
then
```
```
sysmail_start_sp
```
```


q:
This snippet of Perl code in my program is giving the wrong result.

$condition ? $a = 2 : $a = 3 ;
print $a;

No matter what the value of $condition is, the output is always 3, how come?

[A]
This is explained in the Perl
documentation
.
Because of Perl operator precedence the statement is being parsed as
```
```
($condition ? $a= 2 : $a ) = 3 ;
```
```
Because the ?: operator  produces an assignable result, 3 is assigned to the result of the condition.
When $condition is true this means ($a=2)=3 giving $a=3
When $condition is false this means ($a)=3 giving $a=3
The correct way to write this is
```
```
$a = ( $condition ? 2 : 3 );
print $a;
```
```
We got bitten by this at work, so I am posting here hoping others will find it useful.


q:
I am working at a client site where there is a proxy server (HTTP) in place. If I do a hard reset of the emulator it forgets network connection settings for the emulator and settings in the hosted Windows Mobile OS. If I 'save state and exit' it will lose all of these settings. I need to do hard resets regularly which means that I lose this information and spend a lot of time setting:

The emulators associated network card

DNS servers for network card in the WM OS.

Proxy servers in connection settings of WM OS.

How can I make my life easier? Can I save this as defaults in the emulator, or create an installer easily?


q:
I have a stored procedure which takes as its parameter a varchar which needs to be cast as a datetime for later use:

SET @the_date = CAST(@date_string AS DATETIME)

I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL?

NB: using Sybase ASE 12.5.3, there is no ISDATE function

[A]
Found
this in the second result
in Google when searching for "validate date string sql".
```
```
----Invalid date
SELECT ISDATE('30/2/2007')
RETURNS : 0 (Zero)
----Valid date
SELECT ISDATE('12/12/20007')
RETURNS : 1 (ONE)
----Invalid DataType
SELECT ISDATE('SQL')
RETURNS : 0 (Zero)
```
```


q:
Inside an asp.net page, should I use

<html><title>My page's title from México</title></html>

Or

<html><title>My page&rsquo;s title from M&eacute;xico</title></html>

Both examples have the same output. Since asp.net encodes all my pages to utf-8, there is no need to use html entities, is that right?


q:
I'm using IIS 5.1 in Windows XP on my development computer. I'm going to set up HTTPS on my company's web server, but I want to try doing it locally before doing it on a production system.

But when I go into the Directory Security tab of my web site's configuration section, the "Secure communication" groupbox is disabled. Is there something I need to do to make this groupbox enabled?


q:
I'm working on a spec for a piece of software for my company and as part of the auditing system I think it would be neat if there was a way to grab the current Active Directory user.

Hopefully something like:

Dim strUser as String
strUser = ActiveDirectory.User()
MsgBox "Welcome back, " & strUser

[A]
Try this article
- I have some code at work that will erm, work if this doesn't...
Relevant quote:
```
```
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" _
                    (ByVal IpBuffer As String, nSize As Long) As Long
Private Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" _
                    (ByVal lpBuffer As String, nSize As Long) As Long

Function ThisUserName() As String
    Dim LngBufLen As Long
    Dim strUser As String

    strUser = String$(15, " ")
    LngBufLen = 15

    If GetUserName(strUser, LngBufLen) = 1 Then
        ThisUserName = Left(strUser, LngBufLen - 1)
    Else
        ThisUserName = "Unknown"
    End If
End Function

Function ThisComputerID() As String
    Dim LngBufLen As Long
    Dim strUser As String

    strUser = String$(15, " ")
    LngBufLen = 15

    If GetComputerName(strUser, LngBufLen) = 1 Then
        ThisComputerID = Left(strUser, LngBufLen)
    Else
        ThisComputerID = 0
    End If
End Function
```
```


q: How do I grep and show the preceding and following 5 lines surrounding each matched line?

[A]
For
BSD
or
GNU
```
grep
```
you can use
```
-B num
```
to set how many lines before the match and
```
-A num
```
for the number of lines after the match.
```
```
grep -B 3 -A 2 foo README.txt
```
```
If you want the same number of lines before and after you can use
```
-C num
```
.
```
```
grep -C 3 foo README.txt
```
```
This will show 3 lines before and 3 lines after.


q:
I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes...

I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code.  It would merely construct a URL based on the current date and then do a window.location = on that URL.

I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript.  I could have sworn that this was possible years ago, but I can't find anything that tells me either way now.

[A]
What you want is a
bookmarklet
they are easy to create and should work in most major browsers.
Edit: Stack overflow seems not to allow creating bookmarklets in the context of the site, basically you can create a new bookmark and type the following in the location field
```
javascript:window.location='http://www.google.com/search?q='+Date()
```
to get a bookmarklet that searches google for the current date.


q:
I'm trying to use a select statement to get all of the columns from a certain MySQL table except one. Is there a simple way to do this?

EDIT: There are 53 columns in this table (NOT MY DESIGN)

[A]
To the best of my knowledge, there isn't. You can do something like:
```
```
SELECT col1, col2, col3, col4 FROM tbl
```
```
and manually choose the columns you want. However, if you want a lot of columns, then you might just want to do a:
```
```
SELECT * FROM tbl
```
```
and just ignore what you don't want.
In your particular case, I would suggest:
```
```
SELECT * FROM tbl
```
```
unless you only want a few columns. If you only want four columns, then:
```
```
SELECT col3, col6, col45, col 52 FROM tbl
```
```
would be fine, but if you want 50 columns, then any code that makes the query would become (too?) difficult to read.


q:
Is there any IL level debugger in form of a VS plugin or standalone application?

Visual studio’s debugger is great, but it allows you to debug on either HLL code level or assembly language, you can’t debug IL.
It seems that in some situations it would be useful to have an opportunity to debug at IL level.

In particular it might be helpful when debugging a problem in the code that you don't have the source of.

It is arguable if it is actually useful to debug IL when you don't have the source, but anyway.

[A]
The best way to do this is to use ILDASM to disassemble the managed binary, which will generate the IL instructions. Then recompile that IL source code in debug mode using ILASM, when you fire up the Visual Studio debugger you will be able to step through the raw IL.
```
ildasm foo.exe /OUT=foo.exe.il /SOURCE
```
```
ilasm foo.exe.il /DEBUG
```
I've written a blog post about this topic at:
How to debug Compiler Generated code
.


q:
What is it?

How do I implement connection pooling with MS SQL?

What are the performance ramifications when

Executing many queries one-after-the other (i.e. using a loop with 30K+ iterations calling a stored procedure)?

Executing a few queries that take a long time (10+ min)?

Are there any best practices?

[A]
Connection pooling is a mechanism to re-use connections, as establishing a new connection is slow.
If you use an MSSQL connection string and System.Data.SqlClient then you're already using it - in .Net this stuff is under the hood most of the time.
A loop of 30k iterations might be better as a server side cursor (look up T-SQL cursor statements), depending on what you're doing with each step outside of the sproc.
Long queries are fine - but be careful calling them from web pages as Asp.Net isn't really optimised for long waits and some connections will cut out.


q:
I was recently tasked with coming up with an offsite backup strategy. We have about 2TB of data that would need to be backed up so our needs are a little out of the norm.

I looked into Iron Mountain and they wanted $12,000 a month!

Does anyone have any suggestions on how best to handle backing up this much data on a budget (like a tenth of Iron Mountain)? How do other companies afford to do this?

Thanks!

UPDATE :: UPDATE

Ironically enough, I just had the sort of devastating failure we're all talking about. I had my BES server fail and than 2 days later 2 drives in my Exchange server's RAID5 died (2!!!??!). I'm currently in the process of rebuilding my network and the backup integrity is an definitely an issue.

At least now my bosses are paying attention :)

[A]
2TB is chump change nowadays.
Look into hard-drive based hot-swappable backup machines, and rent a box at your local bank:
http://www.high-rely.com/
(there are many more products such as this, but my Google-time is limited).


q:
Thanks to FireFox's buggy implementation of ActiveX components (it really should take an image of them when printing) Flex components (in our case charts) don't print in FX.

They print fine in IE7, even IE6.

We need these charts to print, but they also have dynamic content.  I don't really want to draw them again as images when the user prints - the Flex component should do it.

We've found a potential workaround, but unfortunately it doesn't work in FireFox3 (in FireFox2 it sort-of works, but not well enough).

Anyone know a workaround?

[A]
Using the ACPrintManager I was able to get firefox 3 to print perfectly!
The one thing I had to add to the example was to check if stage was null, and callLater if the stage was null.
```
```
private function initPrint():void {
    //if we don't have a stage, wait until the next frame and try again
    if ( stage ==  null ) {
        callLater(initPrint);
        return;
    }

    PrintManager.init(stage);

    var data:BitmapData = new BitmapData(stage.stageWidth, stage.stageHeight);
    data.draw(myDataGrid);

    PrintManager.setPrintableContent(data);
}
```
```


q:
Anybody have a script or alias to find untracked (really: unadded) files in a Perforce tree?

EDIT: I updated the accepted answer on this one since it looks like P4V added support for this in the January 2009 release.

[A]
Ahh, one of the Perforce classics :) Yes, it really sucks that there is STILL no easy way for this built into the default commands.
The easiest way is to run a command to find all files under your clients root, and then attempt to add them to the depot. You'll end up with a changelist of all new files and existing files are ignored.
E.g dir /s /b /A-D | p4 -x - add
(use 'find . -type f -print' from a nix command line).
If you want a physical list (in the console or file) then you can pipe on the results of a diff (or add if you also want them in a changelist).
If you're running this within P4Win you can use $r to substitute the client root of the current workspace.


q:
I writing a report in Visual Studio that takes a user input parameter and runs against an ODBC datasource. I would like to write the query manually and have reporting services replace part of the where clause with the parameter value before sending it to the database. What seems to be happening is that the @parmName I am assuming will be replaced is actually being sent as part of the SQL statement. Am I missing a configuration setting somewhere or is this simply not possible?

I am not using the filter option in the tool because this appears to bring back the full dataset from the database and do the filtering on the SQL Server.

[A]
It sounds like you'll need to treat the SQL Statement as an expression. For example:
```
```
="Select col1, col2 from table 1 Where col3 = " & Parameters!Param1.Value
```
```
If the where clause is a string you would need to do the following:
```
```
="Select col1, col2 from table 1 Where col3 = '" & Parameters!Param1.Value & "'"
```
```
Important: Do not use line breaks in your SQL expression. If you do you will get an error.
Holla back if you need any more assistance.


q:
I would like to filter an array of items by using the map() function. Here is a code snippet:

var filteredItems = items.map(function(item)
{
    if( ...some condition... )
    {
        return item;
    }
});

The problem is that filtered out items still uses space in the array and I would like to completely wipe them out.

Any idea?

EDIT: Thanks, I forgot about filter(), what I wanted is actually a filter() then a map().

EDIT2: Thanks for pointing that map() and filter() are not implemented in all browsers, although my specific code was not intended to run in a browser.

[A]
That's not what map does. You really want
```
Array.filter
```
. Or if you really want to remove the elements from the original list, you're going to need to do it imperatively with a for loop.


q:
How do you retrieve selected text using Regex in C#?

I am looking for C# code that is equivalent to this Perl code:

$indexVal = 0;
if($string =~ /Index: (\d*)/){$indexVal = $1;}

[A]
```
```
int indexVal = 0;
Regex re = new Regex(@"Index: (\d*)")
Match m = re.Match(s)

if(m.Success)
  indexVal = int.TryParse(m.Groups[1].toString());
```
```
I might  have the group number wrong, but you should be able to figure it out from here.


q:
How do you create a static class in C++? I should be able to do something like:

cout << "bit 5 is " << BitParser::getBitAt(buffer, 5) << endl;

Assuming I created the BitParser class. What would the BitParser class definition look like?

[A]
In C++ you want to create a static function of a class (not a static class).
```
```
class BitParser {
public:
  ...
  static ... getBitAt(...) {
  }
};
```
```
You should then be able to call the function using BitParser::getBitAt() without instantiating an object which I presume is the desired result.


q: Has anyone been able to get xinc to run correctly under OpenBSD's chrooted default Apache? I'd like to keep our development server running fully chrooted just like our Production server so that we make sure our code runs just fine chrooted.

[A]
Having never used xinc myself, I can only hint as to how I usually get to chrooting apps.
First step would be to gather information on everything the app needs to run; this I usually accomplish by running
systrace(1)
and
ldd(1)
to find out what is needed to run the software.
Go through the output of
```
```
systrace -A -d. <app>
ldd <app>
```
```
and make sure that everything the app touches and needs (quite a lot of apps touch stuff it doesn't actually need) is available in the chroot environment. You might need to tweak configs and environment variables a bit. Also, if there is an option to have the app log to syslog, I usually do that and create a syslog socket (see the -a option of
syslogd(8)
) in order to decrease the places the app needs write access to.
What I just described is a generic way to make just about any program run in a chroot environment (however, if you need to import half the userland and some suid commands, you might want to just not do chroot :). For apps running under Apache (I'm sure you're aware that the OpenBSD
httpd(8)
is slightly different) you have the option (once the program has started; any dynamic libraries still needs to be present in the jail) of using apache to access the files, allowing  the use of
httpd.conf
to import resources in the chroot environment without actually copying them.
Also useful (if slightly outdated) is
this
link, outlining some gotchas in chrooted PHP on OpenBSD.


q:
This should be fine seeing as the CLR hasn't actually changed?

The boxes running the C# 2.0 code have had .NET 3.5 rolled out.

The background is that we have a windows service (.NET 2.0 exe built with VS2005, deployed to ~150 servers) that dynamically loads assemblies (almost like plug-ins) to complete various work items asked of it. Whenever we roll out a new version of the bus logic, we just drop the assemblies on an FTP server and the windows service knows how to check for, grab and store the latest versions. New assemblies are now built using VS2008 and targetting .NET 2.0, we know that works ok. However we'd like to start taking advantage of C# 3.0 language features such as LINQ and targetting the assemblies against .NET 3.5 without having to build and deploy a new version of the windows service.

[A]
C#3 and .Net 3.5 adds new assemblies, but the IL is unchanged.
This means that with .Net 2 assemblies you can compile and use C#3, as long as you don't use Linq or anything else that references System.Linq or System.Core
```
yield
```
,
```
var
```
, lambda syntax, anon types and initialisers are all compiler cleverness. The IL they produce is cross-compatible.
If you can reference the new assemblies for 3.5 it should all just work.
There is no new version of ASP.Net - it should still be 2.0.50727 - but you should still compile for 3.5


q:
I'm integrating .NET support into our C++ application.

It's an old-school MFC application, with 1 extra file compiled with the "/clr" option that references a CWinFormsControl.

I'm not allowed to remove the linker flag "/NODEFAULTLIB".

(We have our own build management system, not Visual Studio's.)

This means I have to specify all necessary libraries: VC runtime and MFC.

Other compiler options include "/MD"

Next to that: I can't use the linker flag "/FORCE:MULTIPLE" and just add everything:

I'm looking for a non-overlapping set of libraries.

[A]
We have a BizTalk 2006 with Web Application and Several WebServices that need to go from Dev to UAT to Live.
We use MSBuild right from within VS to build, run tests, dependent on test result, complie, zip and ship to servers.
Small MSBuild script on server to unzip, move the files, install clean web app, unlist biztalk bits, install new biztalk bits, re enlist and then start the stuff.
MSBuild is hugh and more people need to use it as it there now right in the platform =>
Use
MSBuild


q: I'm looking for a tool which can generate a Makefile for a C/C++ project for different compilers (GCC, Microsoft Visual C++, C++Builder, etc.) and different platforms (Windows, Linux, and Mac).

[A]
Try
Automatic Makefile Generator
.
It has support for the following compilers:
Borland 3.1
Borland 5.0
Borland 5.0, 16 bit
Borland 5.5
Borland 5.6
Borland 5.8
CC
GNU g++
GNU g++, dynamic library
Intel 5, 6, 7 for Linux
Intel 5, 6, 7 for Linux, dynamic library
Intel 5, 6, 7 for Windows
Intel 8,9,10 for Linux
Intel 8,9,10 for Linux, dynamic library
Intel 8,9 for Windows
Intel 10 for Windows
Visual C++ 5
Visual C++ 6, 7, 7.1
Visual C++ 8
Open Watcom
Watcom 10A
Watcom 10A, 16 bit


q:
I'm trying to set the group type for a new Active Directory Entry via VB.NET and DirectoryServices to create a distribution list.

How do I access the ADS_GROUP_TYPE enumerations?

Specifically I'm after ADS_GROUP_TYPE_GLOBAL_GROUP.

[A]
I don't think I can access the enumerations via .NET so instead I created the specific constant I needed. For what it's worth here's my code:
```
```
Const ADS_GROUP_TYPE_GLOBAL_GROUP As Object = &H2
        adNewGroup.Properties("groupType").Value = ADS_GROUP_TYPE_GLOBAL_GROUP
```
```
Refactoring welcome!


q:
Suppose we have a table A:

itemid mark
1      5
2      3

and table B:

itemid mark
1      3
3      5

I want to join A*B on A.itemid=B.itemid both right and left ways. i.e. result:

itemid A.mark B.mark
1      5      3
2      3      NULL
3      NULL   5

Is there a way to do it in one query in MySQL?

[A]
Could do with some work but here is some sql
```
```
select distinct T.itemid, A.mark as "A.mark", B.mark as "B.mark"
    from (select * from A union select * from B) T
    left join A on T.itemid = A.itemid
    left join B on T.itemid = B.itemid;
```
```
This relies on the left join, which returns all the rows in the original table (in this case this is the subselect table T). If there are no matches in the joined table, then it will set the column to NULL.


q:
Apparantly when users right-click in our WPF application, and they use the Windows Classic theme, the default ContextMenu of the TextBox (which contains Copy, Cut and Paste) has a black background.

I know this works well:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

  <TextBox ContextMenu="{x:Null}"/>

</Page>

But this doesn't work:

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

<Page.Resources>

 <Style x:Key="{x:Type TextBox}" TargetType="{x:Type TextBox}">
   <Setter Property="ContextMenu" Value="{x:Null}"/>
</Style>
</Page.Resources>

  <TextBox/>
</Page>

Does anyone know how to style or disable the default ContextMenu for all TextBoxes in WPF?

[A]
Try removing the x:Key attribute from the Style resource, leaving TargetType.  I know, you're supposed to have that x:Key for a resource, but if you have it along with your TargetType the Key prevails.
Here's a sample style that I use in a project to skin all tooltips in one of my apps (this is in App.Resources--notice, no Key)
```
```
<Style
    TargetType="{x:Type ToolTip}">
    <Setter
      Property="Template">
      <Setter.Value>
        <ControlTemplate
          TargetType="{x:Type ToolTip}">
          <Grid
            Width="{TemplateBinding Width}"
            Height="{TemplateBinding Height}">
            <Rectangle
              RadiusX="9"
              RadiusY="9"
              Stroke="LightGray"
              StrokeThickness="2">
              <Rectangle.Fill>
                <RadialGradientBrush>
                  <GradientStop />
                  <GradientStop
                    Color="FloralWhite"
                    Offset="0" />
                  <GradientStop
                    Color="Cornsilk"
                    Offset="2" />
                </RadialGradientBrush>
              </Rectangle.Fill>
            </Rectangle>
            <ContentPresenter
              Margin="6 4 6 4" />
          </Grid>
        </ControlTemplate>
      </Setter.Value>
    </Setter>
  </Style>
```
```


q: Given a handle of type HWND is it possible to confirm that the handle represents a real window?

[A]
There is a function
```
IsWindow
```
which does exactly what you asked for.
```
```
BOOL isRealHandle = IsWindow(unknwodnHandle);
```
```
Look at
this link
for more information.


q:
I wonder what type of servers for internal usage you virtualize in the last -say- 6 months. Here's what we got virtual so far:

mediawiki

bugtracker (mantis)

subversion

We didn't virtualize spezialized desktop PCs which are running a certain software product, that is only used once in a while. Do you plan to get rid of those old machines any time soon?

And which server products do you use? Vmware ESX, Vmware Server, Xen installations...?

[A]
Our build machine running FinalBuilder runs on a Windows XP Virtual Machine running in VMWare Server on Linux.
It is very practical to move it and also to backup, we just stop the Virtual Machine and copy the disk image.
Some days ago we needed to change the host pc, it took less than 2 hours to have our builder up and running on another pc.


q:
I was reading Joel's book where he was suggesting as interview question:

Write a program to reverse the "ON" bits in a given byte.

I only can think of a solution using C.

Asking here so you can show me how to do in a Non C way (if possible)

[A]
What specifically does that question mean?
Does
reverse
mean setting 1's to 0's and vice versa?
Or does it mean
00001100
-->
00110000
where you reverse their order in the byte? Or perhaps just reversing the part that is from the first 1 to the last 1? ie.
00110101
-->
00101011
?
Assuming it means reversing the bit order in the whole byte, here's an x86 assembler version:
```
```
; al is input register
; bl is output register

xor bl, bl      ; clear output

; first bit
rcl al, 1       ; rotate al through carry
rcr bl, 1       ; rotate carry into bl

; duplicate above 2-line statements 7 more times for the other bits
```
```
not the most optimal solution, a table lookup is faster.


q: Is there a way to check to see if an Microsoft Office process (i.e. Word, Excel) has hung when using Office Automation? Additionally, if the process is hung, is there a way to terminate it?

[A]
I can answer the latter half; if you have a reference to the application object in your code, you can simply call "Quit" on it:
```
```
private Microsoft.Office.Interop.Excel.Application _excel;
// ... do some stuff ...
_excel.Quit();
```
```
For checking for a hung process, I'd guess you'd want to try to get some data from the application and see if you get results in a reasonable time frame (check in a timer or other thread or something). There's probably a better way though.


q:
I am working on a small webapp and I want to use Groovy to write some unit testing for my app. Most of my coding is done on Eclipse and I really want to run all the unit testing with the graphical test runner within Eclipse (I really like the green bar :) )

Sadly, after 4 hours of try-and-error, I'm still not able to setup properly. I tried to use the Eclipse Junit4 test runner to run a Groovy file with method annotated for testing using @Test. But it keeps complaining NoClassDefFoundException

Anyone can help?

Here is content of my groovy file, named simpleTest.groovy

import org.junit.Test
import static org.junit.Assert.assertEquals

class simpleTest{
  @Test
  void trial(){
    assertEquals 6, 3+3
  }
}

Anyone can help?

[A]
Unfortunately, the Groovy Eclipse plugin is pretty horrible at giving actual helpful information to let you know what is going wrong with your setup. I'm going to assume you  already did the verification to make sure the plugin is actually building your Groovy files (i.e. doing a sample with no dependencies, checking the properly output directory, etc...) After that, it's a lot of really small configuration verification...I've run into problems where the particular "runner" I'm using in Eclipse (i.e. in the Run menu) doesn't have the write class name defined there or for some reason my project didn't get the JUnit library dependency properly inserted into it.
Ultimately, it can be a configuration headache, but long term you'll end up saving some time and gaining some cool functionality if you can knock it out...


q:
I have an application deployed into multiple zones and there are some issues with opening larger documents (20-50MB) across the WAN.

Currently the documents are stored in Zone 1 (Americas) and a link stored in the database to the docs.

I have heard some things about blobs in oracle and store binary in MS SQL Server 2005 and then perhaps copying the database to other zones.

Any other suggestions or good results with one of the described options?

[A]
Your best option here may be caching the document in the requested zone the first time it is requested, and pinging the source document's last modified each time the cached document is requested in order to determine if it needs refreshed. In this case you're only requesting a small piece of information (a date) across the WAN most of the times the document is accessed. This works best for a subset of documents that are frequently requested.
If you have a large set of documents, each infrequently requested by a disparate group, then you may want to look into replicating the documents in each of your zones each time the master is updated. This may best be accomplished by storing the document as binary data in your master database and having the slaves pull from the master.


q:
This is a question I asked on another forum which received some decent answers, but I wanted to see if anyone here has more insight.

The problem is that you have one of your pages in a web application timing out when it gets to a stored procedure call, so you use Sql Profiler, or your application trace logs, to find the query and you paste it into management studio to figure our why it's running slow.  But you run it from there and it just blazes along, returning in less than a second each time.

My particular case was using ASP.NET 2.0 and Sql Server 2005, but I think the problem could apply to any RDBMS system.

[A]
Try changing the SelectCommand timeout value:
```
```
DataAdapter.SelectCommand.CommandTimeout = 120;
```
```


q:
I understand how JS is run and I think I understand most of the DOM but I've no idea about animation. Does anybody here know of a good guide that can explain to me how it's done in Javascript?

In addition, should I even consider Javascript for animation? Should I instead be looking to learn flash?

[A] if your animation is simple, change colors over time, move from x to y in 3 seconds. Javascript is fine. If you want all kinds of wizbang buttons and coordinated rotation of the screen, straight up js + dhtml will be clunky at best. Silverlight vs Flash are you questions at that point. Interestingly enough, you program Silverlight with javascript, and that would be the major benefit to simply upgrading to a faster and more dynamic DOM that is implemented in Silverlight but still writing the same code. Flash programmability is very limited in my experience, you can do anything, but it will be slow and take thousands of lines of code to get there. For simple JS animations look at jQuery or Scriptaculous.


q: What's the best way to make a linked list in Java?

[A]
Java has a
LinkedList
implementation, that you might wanna check out. You can download the JDK and it's sources at
java.sun.com
.


q: How do I write code where a company icon appears on the left side next to the URL address in the browser's address bar?

[A]
it loads www.whateveryouron.com/favicon.ico
if your domain is robermyers.com, just put a favicon.ico 16px icon thats accessible, and you're in like flint.
just try this
googles
or
stackoverflows


q:
I'm getting into more of a TDD workflow, and have a mix of MVC and asp.net Web Forms apps.

MOQ is recommended for MVC.

I've used Rhino for Web Forms.

Does anyone have a best practice for having 1 framework mock for both?

[A]
I would just go ahead and use my favourite framework for both. I don't think there's any reason that I would choose one framework for web forms and another for MVC. A far bigger problem is how I would unit test my web forms pages at all, since it's notoriously hard to seperate the page from the rest of the HttpRequest stack.
My favourite is Moq. I've also used TypeMock. It costs money, but it's really powerful - it lets you mock concrete classes and constructors, so you could potentially mock things like HttpContext or HttpRequest.


q:
I'm trying to decode the result of the Python os.wait() function. This returns, according to the Python docs:

a tuple containing its pid and exit status indication: a 16-bit number, whose low byte is the signal number that killed the process, and whose high byte is the exit status (if the signal number is zero); the high bit of the low byte is set if a core file was produced.

How do I decode the exit status indication (which is an integer) to obtain the high and low byte? To be specific, how do I implement the decode function used in the following code snippet:

(pid,status) = os.wait()
(exitstatus, signum) = decode(status)

[A]
This will do what you want:
```
```
signum = status & 0xff
exitstatus = (status & 0xff00) >> 8
```
```


q:
What's the easiest way to do an "instring" type function with a regex? For example, how could I reject a whole string because of the presence of a single character such as :? For example:

this - okay

there:is - not okay because of :

More practically, how can I match the following string:

//foo/bar/baz[1]/ns:foo2/@attr/text()

For any node test on the xpath that doesn't include a namespace?

(/)?(/)([^:/]+)

Will match the node tests but includes the namespace prefix which makes it faulty.

[A]
I dont know regex syntax very well but could you not do:
```
[any alpha numeric]\*:[any alphanumeric]\*
```
I think something like that should work no?


q:
Many applications have grids that display data from a database table one page at a time. Many of them also let the user pick the number of records per page, sort by any column, and navigate back and forth through the results.

What's a good algorithm to implement this pattern without bringing the entire table to the client and then filtering the data on the client. How do you bring just the records you want to display to the user?

Does LINQ simplify the solution?

[A]
On MS SQL Server 2005 and above,
ROW_NUMBER()
seems to work:
T-SQL: Paging with ROW_NUMBER()
```
```
DECLARE @PageNum AS INT;
DECLARE @PageSize AS INT;
SET @PageNum = 2;
SET @PageSize = 10;

WITH OrdersRN AS
(
    SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum
          ,OrderID
          ,OrderDate
          ,CustomerID
          ,EmployeeID
      FROM dbo.Orders
)

SELECT *
  FROM OrdersRN
 WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1
                  AND @PageNum * @PageSize
 ORDER BY OrderDate
         ,OrderID;
```
```


q:
Consider this problem: I have a program which should fetch (let's say) 100 records from a database, and then for each one it should get updated information from a web service. There are two ways to introduce parallelism in this scenario:

I start each request to the web service on a new Thread. The number of simultaneous threads is controlled by some external parameter (or dynamically adjusted somehow).

I create smaller batches (let's say of 10 records each) and launch each batch on a separate thread (so taking our example, 10 threads).

Which is a better approach, and why do you think so?

[A]
Two things to consider.
1. How long will it take to process a record?
If record processing is very quick, the overhead of handing off records to threads can become a bottleneck.  In this case, you would want to bundle records so that you don't have to hand them off so often.
If record processing is reasonably long-running, the difference will be negligible, so the simpler approach (1 record per thread) is probably the best.
2. How many threads are you planning on starting?
If you aren't using a threadpool, I think you either need to manually limit the number of threads, or you need to break the data into big chunks.  Starting a new thread for every record will leave your system thrashing if the number of records get large.


q:
Which is more efficient for the compiler and the best practice for checking whether a string is blank?

Checking whether the length of the string == 0

Checking whether the string is empty (strVar == "")

Also, does the answer depend on language?

[A]
Yes, it depends on language, since string storage differs between languages.
Pascal-type strings:
```
Length = 0
```
.
C-style strings:
```
[0] == 0
```
.
.NET:
```
.IsNullOrEmpty
```
.
Etc.


q: I've kept up to date with new features in the C# language as it's moved from version 1 through version 3.  I haven't done such a good job keeping up to date with ASP.NET.  I feel like some of the post version 1 features are not so good (e.g. the AJAX framework) or are just not that useful to me (e.g. the membership framework).  Can anyone recommend any new killer ASP.NET features that might have gone unnoticed?

[A]
I'm still learning ASP.net so I can't tell you exactly, but if you look through
http://www.asp.net/learn/
you'll probably find a few new gems, there's even a 3.5 section.


q: I've been playing around with the ASP.NET MVC Framework and the one thing that's really confusing me is how I'm meant to do server side validation of posted form data.  I presume I don't post back to the same URL, but if I don't, how do I redisplay the form with the entered data and error messages?  Also, where should the validation logic go?  In the model or the controller?  This seems to be one of the few areas where web forms are much stronger (I miss the validation controls).

[A]
Have you taken a look at this?
http://www.codeplex.com/MvcValidatorToolkit
Quoted from the page
The Validator Toolkit provides a set
  of validators for the new ASP.NET MVC
  framework to validate HTML forms on
  the client and server-side using
  validation sets.
I'm afraid that someone more MVC-savvy than me would have to speak to where in the architecture you should put things.


q:
Are you aware of any tool that creates diagrams showing the branch/merge activity in a SVN repository?

We've all seen these diagrams in various tutorials. Some good, some not so good. Can they be created automatically (or maybe with a little prodding -- you might have to tell it what if your branching philosophy is dev-test-prod, branch-per-release, etc.)

I'm looking at the TortoiseSVN Revision Graph right now, but it has more detail than I want and the wrong layout.

Orion, thanks for the response. I guess since branching and merging are more a convention for managing files in a repository than a "built in feature of SVN, it would be pretty tough. I'll stick with the poorly-drawn diagram at the top of the whiteboard in our team's office.

[A] prior to SVN 1.5 (which has been out all of a month or so), it didn't track merges at all, so the bits where branches 'reconnect' to the trunk are impossible for it to do anyway


q:
Being new to Objective-C (but a long term C/++) programmer I'm looking for advice/recommendations on naming conventions for variables.

My personal preference would be to utilize a prefix for instance variables both for clarity within functions and to prevent shadowing of function parameters. However I'm a fan of properties which rules out prefixes (unless you also prefix your property names, which doesn't work too well and looks daft). Similarly I could use the "self.variable" convention, but only if I make EVERYTHING a property.

So given the code below what's your preferred naming style for instance/function variables? And if you don't bother, how do you deal with shadowing on function params?

@interface GridItem : NSObject
{
    CGRect _rect;
    ...
}
@end

-(void) initFromRect:(CGRect)rect
{
    _rect = rect;
    ...
}

Cheers!

[A]
I don't like using underscores as prefixes for any identifiers, because C and C++ both reserve certain underscore prefixes for use by the implementation.
I think using "self.variable" is ugly.
In general, I use unadorned identifiers (that is, no prefixes nor suffixes) for instance variables.  If your class is so complicated that you can't remember the instance variables, you're in trouble.  So for your example, I'd use "rect" as the name of the instance variable and "newRect" or "aRect" as the parameter name.


q: I'm sure there is a good (or at least decent) reason for this.  What is it?

[A]
It is so that you don't have two things trying to update the control at the same time. (This could happen if the CPU switches to the other thread in the middle of a write/read)
Same reason you need to use mutexes (or some other synchronization) when accessing shared variables between multiple threads.
Edit:
In other languages such as C++ you are
  free to try and do this (without an
  exception being thrown as in
  WinForms), but you'll end up learning
  the hard way!
Ahh yes...I switch between C/C++ and C# and therefore was a little more generic then I should've been, sorry... He is correct, you
can
do this in C/C++, but it will come back to bite you!


q: I have a project where I would like to generate a report export in MS Word format.  The report will include images/graphs, tables, and text.  What is the best way to do this?  Third party tools?  What are your experiences?

[A]
The answer is going to depend slightly upon if the application is running on a server or if it is running on the client machine. If you are running on a server then you are going to want to use one of the XML based office generation formats as there are know issues when
using Office Automation on a server
.
However, if you are working on the client machine then you have a choice of either
using Office Automation
or using the Office Open XML format (see links below), which is supported by Microsoft Office 2000 and up either natively or through service packs. One draw back to this though is that you might not be able to embed some kinds of graphs or images that you wish to show.
The best way to go about things will all depend sightly upon how much time you have to invest in development. If you go the route of Office Automation there are quite a few good tutorials out there that can be found via Google and is fairly simple to learn. However, the Open Office XML format is fairly new so you might find the learning curve to be a bit higher.
Office Open XML Iinformation
Office Open XML -
http://en.wikipedia.org/wiki/Office_Open_XML
OpenXML Developer -
http://openxmldeveloper.org/default.aspx
Introducing the Office (2007) Open XML File Formats -
http://msdn.microsoft.com/en-us/library/aa338205.aspx


q:
I have a website that works correctly under IIS 6.0: It authenticates users with windows credentials, and then when talking to the service that hits the DB, it passes the credentials.

In IIS 7.0, the same config settings do not pass the credentials, and the DB gets hit with NT AUTHORITY\ANONYMOUS.

Is there something I'm missing? I've turned ANONYMOUS access off in my IIS 7.0 website, but I can't get the thing to work.

These are the settings that I'm using on both IIS 6.0 and 7.0:

<authentication mode="Windows">
<identity impersonate="true">

What changed from 6.0 to 7.0?

[A]
Interesting... I have the opposite problem -
Not being able
to get the authentication to be passed from the client browser, through the webserver and onto the database within a large corporate network over firewalls.
I also feel that "end to end user" authentication to the database is a bad idea and a potential security risk.  There is nothing to stop the end user from loading up SQL Query and connecting directly to your database, so you'd better have your schema locked down!
@Esteban - Clarified my
not very useful in helping you
answer.


q:
I have this program, we'll call it Host. Host does all kinds of good stuff, but it needs to be able to accept input through the command line while it's running. This means it has to somehow send its other process data and then quit. For example, I need to be able to do this:

./Host --blahblah 3 6 3 5

This should somehow end up calling some function in Host called

handleBlahBlah(int x1, int y1, int x2, int y2){
  //do some more sweet stuff
}

Host is a C program, and does not need to support multiple instances.

An example of this is Amarok music player. With Amarok running and playing, you can type "amarok --pause" and it will pause the music.

I need to be able to do this in Linux or Windows. Preferably Linux.

What is the cleanest way to implement this?

[A]
So, I may be missing the point here, but by deafult a C program's main function takes two arguments; argc, a count of the number of arguments (at least one), and argv (or arg vector), the argument list.  You could just parse through the arguments and call the correct method.
For example:
```
```
int main(int argc, *argv[])
 {
     /*loop through each argument and take action*/
      while (--argc > 0)
      {
           printf(%s%s, *++argv, (argc > 1) ? " " : "");
      }
 }
```
```
would print all of the arguments to screen.  I am no C guru, so I hope I haven't made any mistakes.
EDIT:  Ok, he was after something else, but it wasn't really clear before the question was edited.  Don't have to jump on my rep...


q:
Ideally, I'm looking for a templated logical Set class.  It would have all of the standard set operations such as Union, Intersection, Etc., and collapse duplicated items.

I ended up creating my own set class based on the C# Dictionary<>- just using the Keys.

[A]
```
HashSet<T>
```
is about the closest you'll get, I think.


q: Currently, I'm attempting to make multiple beziers have equidistant points.  I'm currently using cubic interpolation to find the points, but because the way beziers work some areas are more dense than others and proving gross for texture mapping because of the variable distance.  Is there a way to find points on a bezier by distance rather than by percentage?  Furthermore, is it possible to extend this to multiple connected curves?

[A]
distance between P_0 and P_3 (in cubic form), yes, but I think you knew that, is straight forward.
Distance on a curve is just arc length:
fig 1 http://www.codecogs.com/eq.latex?%5Cint_%7Bt_0%7D%5E%7Bt_1%7D%20%7B%20|P'(t)|%20dt
where:
fig 2 http://www.codecogs.com/eq.latex?P%27(t)%20=%20[%7Bx%27,y%27,z%27%7D]%20=%20[%7B%5Cfrac%7Bdx(t)%7D%7Bdt%7D,%5Cfrac%7Bdy(t)%7D%7Bdt%7D,%5Cfrac%7Bdz(t)%7D%7Bdt%7D%7D]
(see the rest)
Probably, you'd have t_0 = 0, t_1 = 1.0, and dz(t) = 0 (2d plane).


q: Having been a PHP developer on LAMP servers for quite a while, is there anything that I will need to take into consideration while preparing an application for IIS on windows.

[A]
Make sure you get the FastCGI extension for IIS 6.0 or IIS 7.0.  It is the single most important thing you can have when running PHP under IIS.  Also this article should get you setup:
http://learn.iis.net/page.aspx/247/using-fastcgi-to-host-php-applications-on-iis-60/
Everything beyond this is simple, MySQL and what not.


q:
I've been using PHP & MySQL for ages and am about to start using PostgreSQL instead.

What's the preferred method?

Is it via the PDO objects or is there something better?

[A]
PDO objects are the new hotness.  I'd recommend that as long as you can ensure that your target platform will always be running PHP 5.2+.
There are many other database abstraction layers that support PostgreSQL that are compatible with older versions of PHP; I'd recommend
ADODB
.
You should really be using PDO or a different abstraction layer even for your MySQL work; that way you won't have this problem again!


q: What is the difference between early and late binding?

[A]
Taken directly from
http://word.mvps.org/fAQs/InterDev/EarlyvsLateBinding.htm
There are two ways to use Automation (or OLE Automation) to
  programmatically control another application.
Late binding uses CreateObject to create and instance of the
  application object, which you can then control. For example, to create
  a new instance of Excel using late binding:
```
```
Dim oXL As Object
 Set oXL = CreateObject("Excel.Application")
```
```
On the other hand, to manipulate an existing instance of Excel (if
  Excel is already open) you would use GetObject (regardless whether
  you're using early or late binding):
```
```
Dim oXL As Object
 Set oXL = GetObject(, "Excel.Application")
```
```
To use early binding, you first need to set a reference in your
  project to the application you want to manipulate. In the VB Editor of
  any Office application, or in VB itself, you do this by selecting
  Tools + References, and selecting the application you want from the
  list (e.g. “Microsoft Excel 8.0 Object Library”).
To create a new instance of Excel using early binding:
```
```
Dim oXL As Excel.Application
 Set oXL = New Excel.Application
```
```
In either case, incidentally, you can first try to get an existing
  instance of Excel, and if that returns an error, you can create a new
  instance in your error handler.


q: I've grokked the code for all the aforementioned apps and I still can't find a straightforward way to create a static directory structure from a single command.

[A]
So what you want is to able to issue a command that will generate an entire directory tree?
```
```
cp -r <template> <destination>
```
```
Or am I misunderstanding?  If you want to generate a consistent directory structure, your best bet is to simply copy it from a template.  Fast, easy, done.


q: Does anyone use have a good regex library that they like to use? Most of the regexes that you find online either contain bugs or are so focused on the edge cases that it turns into a competition to validate whatever spec 100%. Of course you can write your own, but when you are billing by the hour its handy to have a library around.

[A]
Besides being pretty much the best Regex tool on the market (seriously), RegexBuddy is about the only tool I know of that lets you switch amongst different Regex rendering engines.
http://www.regexbuddy.com/
See info here:
http://en.wikipedia.org/wiki/RegexBuddy
RegexBuddy's proprietary regular expression engine allows the software to emulate the rules and limitations of numerous popular regular expression flavors.


q:
I'm an ASP.NET developer who has used Microsoft SQL Server for all my database needs (both at work and for personal projects).

I am considering trying out the LAMP stack for some of my personal projects.

What are some of the main differences between MySQL and SQL Server? Is using stored procedures a common practice in MySQL?

Any advice or resources you'd recommend to help me with the switch?

To those who have experience with both, are there any missing features from MySQL?

[A]
One thing you have to watch out for is the fairly severe differences in the way SQL Server and MySQL implement the SQL syntax.
Here's a nice
Comparison of Different SQL Implementations
.
For example, take a look at the top-n section. In MySQL:
```
```
SELECT age
FROM person
ORDER BY age ASC
LIMIT 1 OFFSET 2
```
```
In SQL Server (T-SQL):
```
```
SELECT TOP 3 WITH TIES *
FROM person
ORDER BY age ASC
```
```


q:
I currently use nant, ccnet (cruise control), svn, mbunit. I use msbuild to do my sln build just because it was simpler to shell out.

Are there any merits to switching my whole build script to MSBuild? I need to be able to run tests, watir style tests, xcopy deploy. Is this easier?

Update: Any compelling features that would cause me to shift from nant to msbuild?

[A]
I feel that MSBuild and Nant are fairly comparable. If you are using one of these, I generally wouldn't switch between them unless there was a compelling feature that was missing in the product you had selected.
I personally use MSBuild for any new project, but your mileage may vary.
Hope that helps!
Edit:
@ChanChan  - @Jon mentions that Nant doesn't build .NET 3.5 applications. This may be enough of a reason to either change, or at least use them in parallel. As I've moved more towards MSBuild, I am probably not the most informed person to highlight any other showstoppers with either technology.
Edit:
It appears Nant now builds .NET 3.5 Applications.


q:
I'm looking for a good method of generating an iCalendar file (*.ics) in c# (asp.net).  I've found a couple resources, but one thing that has been lacking is their support for quoted-printable fields - fields that have carriage returns and line feeds.

For example, if the description field isn't encoded properly, only the first line will display and possibly corrupting the rest of the information in the *.ics file.

I'm looking for existing classes that can generate *.ics files and/or a class that can generate quoted-printable fields.

[A]
I use
DDay.Ical
, its good stuff.
Has the ability to open up an ical file and get its data in a nice object model. It says beta, but it works great for us.
Edit Nov 2016
This library has been deprecated, but was picked up and re-released as iCal.NET by another dev.
Notes about the release:
rianjs.net/2016/07/dday-ical-is-now-ical-net
Source on GitHub:
github.com/rianjs/ical.net


q:
We deployed a live, fresh, swanky site using preview 3 including rigorous stress testing.

Page Output caching was our saviour and afforded us the ability to meet our performance contractual requirements.

My question is, is there a difference between action OutputCacheFilter and page output caching?

Is the action output caching faster than page output caching?

[A]
Internally, the OutputCacheAttribute (aka output cache filter) uses the same internal mechanism as
page output caching
(aka the @OutputCache directive).
Therefore, it's not any faster than page output caching. However, with MVC, you really can't use page output caching via the @OutputCache directive in MVC because we render the view (aka page)
after
the action runs. So you would gain very little benefit.
With the output cache filter, it does the correct thing and does not execute the action code if the result is in the output cache. Hope that helps. :)


q:
I've been trying to understand how to read the memory of other processes on Mac OS X, but I'm not having much luck. I've seen many examples online using ptrace with PEEKDATA and such, however it doesn't have that option on BSD [man ptrace].

int pid = fork();
if (pid > 0) {
    // mess around with child-process's memory
}

How is it possible to read from and write to the memory of another process on Mac OS X?

[A]
Matasano Chargen had a good post a while back on porting some debugging code to OS X, which included learning how to read and write memory in another process (among other things).
It has to work, otherwise GDB wouldn't
:
It turns out Apple, in their infinite wisdom, had gutted
```
ptrace()
```
. The OS X man page lists the following request codes:
```
PT_ATTACH
```
— to pick a process to debug
```
PT_DENY_ATTACH
```
— so processes can stop themselves from being debugged
[...]
No mention of reading or writing memory or registers. Which would have been discouraging if the man page had not also mentioned
```
PT_GETREGS
```
,
```
PT_SETREGS
```
,
```
PT_GETFPREGS
```
, and
```
PT_SETFPREGS
```
in the error codes section. So, I checked
```
ptrace.h
```
. There I found:
```
PT_READ_I
```
— to read instruction words
```
PT_READ_D
```
— to read data words
```
PT_READ_U
```
— to read U area data if you’re old enough to remember what the U area is
[...]
There’s one problem solved. I can read and write memory for breakpoints. But I still can’t get access to registers, and I need to be able to mess with EIP.


q:
Is there any difference between

   int on_exit(void (*function)(int , void *), void *arg);

and

   int atexit(void (*function)(void));

other than the fact that the function used by on_exit gets the exit status?

That is, if I don't care about the exit status, is there any reason to use one or the other?

Edit: Many of the answers warned against on_exit because it's non-standard. If I'm developing an app that is for internal corporate use and guaranteed to run on specific configurations, should I worry about this?

[A]
You should use
```
atexit()
```
if possible.
```
on_exit()
```
is nonstandard and less common.  For example, it's not available on OS X.
Kernel.org -
```
on_exit()
```
:
This function comes from SunOS 4, but is also present in libc4, libc5 and
  glibc.  It no longer occurs in Solaris (SunOS 5).  Avoid this function, and
  use the standard atexit(3) instead.


q:
In your applications, what's a "long time" to keep a transaction open before committing or rolling back?  Minutes?  Seconds?  Hours?

and on which database?

[A]
transactions: minutes.
Cursors: 0seconds maximum, if you use a cursor we fire you.
This is not ridiculous when you consider we are in a high availability web environment, that has to run sql server, and we don't even allow stored procs because of inability to accurately version and maintain them. If we were using oracle maybe.


q:
I'm dynamically loading user controls adding them to the Controls collection of the web form.

I'd like to hide user controls if they cause a unhandled exception while rendering.

So, I tried hooking to the Error event of each UserControl but it seems that this event never fires for the UserControls as it does for Page class.

Did some googling around and it doesn't seem promising. Any ideas here?

[A]
Global.asax and Application_Error?
http://www.15seconds.com/issue/030102.htm
Or the Page_Error Event on an individual Page only:
http://support.microsoft.com/kb/306355
```
```
void Page_Load(object sender, System.EventArgs e)
{
    throw(new ArgumentNullException());
}

public void Page_Error(object sender,EventArgs e)
{
    Exception objErr = Server.GetLastError().GetBaseException();
    string err =    "Error Caught in Page_Error event

" +
                    "
Error in: " + Request.Url.ToString() +
                    "
Error Message: " + objErr.Message.ToString()+
                    "
Stack Trace:
" +
                      objErr.StackTrace.ToString();
    Response.Write(err.ToString());
    Server.ClearError();
}
```
```
Also, Karl Seguin (Hi Karl!) had a Post on using HttpHandler instead:
http://codebetter.com/blogs/karlseguin/archive/2006/06/12/146356.aspx
(Not sure what the permission to reproduce it, but if you want to write up an answer, you got my Upvote ☺)


q:
When creating a new ASP.NET project in Visual Studio should I chose create: website or project?

I understand that web application project was the way to do it back in the day with VS 2003 but is it still applicable today? What are some of the caveats using one over the other?

[A]
There's a
pretty good comparison chart on MSDN
.
Website projects are simple, in that all files added to the project folders are automatically compiled and included, which was supposedly added to make it more palatable to classic ASP and PHP developers. Once benefit is that it includes build providers, which allow for certain actions to be associated with a filetype - that's how the first release of SubSonic would rebuild the data access layer when you added a .abp file to the site.
Web Application Projects are a lot more flexible, though. For instance, all class libraries in a Website Project need to be in the App_Code folder, which is frustrating in a complex application. There are a lot of scenarios which just don't work for a Website Project.
You can convert from one to another, although if you're unsure I'd recommend just starting with a Web Application.


q: Does anybody know if it's possible, and how, to programmatically send a SMS from the iPhone, with the official SDK / Cocoa Touch?

[A]
You can use a
```
sms:[target phone number]
```
URL to open the SMS application, but there are no indications on how to prefill a SMS body with text.


q:
How can I left-align the numbers in an ordered list?

1.  an item
// skip some items for brevity
9.  another item
10. notice the 1 is under the 9, and the item contents also line up

Change the character after the number in an ordered list?

1) an item

Also is there a CSS solution to change from numbers to alphabetic/roman lists instead of using the type attribute on the ol element.

I am mostly interested in answers that work on Firefox 3.

[A]
The CSS for styling lists is
here
, but is basically:
```
```
li {
    list-style-type: decimal;
    list-style-position: inside;
}
```
```
However, the specific layout you're after can probably only be achieved by delving into the innards of the layout with something like
this
(note that I haven't actually tried it):
```
```
ol { counter-reset: item }
li { display: block }
li:before { content: counter(item) ") "; counter-increment: item }
```
```


q:
I'm looking for a good article on using emacs as C/C++ IDE.

Something like Steve Yegge's "Effective emacs".

[A]
No specific article, really, but I've found
EmacsWiki
to be full of useful information. Consider checking out these entries:
CPlusPlus
as a starting point for many C++-related articles, and
CppTemplate
to define a template that can give you a good skeleton when you start new files


q:
You should be able to create a generic form:

public partial class MyGenericForm<T> :
    Form where T : class
{
    /* form code */
    public List<T> TypedList { get; set; }
}

Is valid C#, and compiles.  However the designer won't work and the form will throw a runtime exception if you have any images stating that it cannot find the resource.

I think this is because the windows forms designer assumes that the resources will be stored under the simple type's name.

[A]
I have a hack to workaround this, which works but isn't ideal:
Add a new class to the project that inherits the form with its simple name.
```
```
internal class MyGenericForm:
    MyGenericForm<object> { }
```
```
This means that although the designer is still wrong the expected simple type (i.e without
```
<>
```
) is still found.


q:
Usually when I'm creating indexes on tables, I generally guess what the Fill Factor should be based on an educated guess of how the table will be used (many reads or many writes).

Is there a more scientific way to determine a more accurate Fill Factor value?

[A]
You could try running a big list of realistic operations and looking at IO queues for the different actions.
There are a lot of variables that govern it, such as the size of each row and the number of writes vs reads.
Basically: high fill factor = quicker read, low = quicker write.
However it's not quite that simple, as almost all writes will be to a subset of rows that need to be looked up first.
For instance: set a fill factor to 10% and each single-row update will take 10 times as long to find the row it's changing, even though a page split would then be very unlikely.
Generally you see fill factors 70% (very high write) to 95% (very high read).
It's a bit of an art form.
I find that a good way of thinking of fill factors is as pages in an address book - the more tightly you pack the addresses the harder it is to change them, but the slimmer the book. I think I explained it better on
my blog
.


q:
We have an SVN repository running on a Windows server, and I want to link internal documentation, feature changes, bugs and so on to code changes.

We've found WebSVN to be amazingly slow - the repository is too large for it (I think).

The team using it is primarily coding in C#, and while some have experience with other languages I'd really like a tool anyone on the team can maintain.

Most of the tools I've seen are based on PHP, Java, Python, etc. All languages the team could learn, but I'd rather something that uses the skills we already have.

Can you recommend a good web-based repository browser for SVN, ideally one that uses ASP.NET, SQL Server and that runs on IIS?

[A]
Have a look at
http://warehouseapp.com
It's Mongrel/Ruby/MySQL stack (should work on Windows though)
but I'm looking to avoid installing
  MySQL and Ruby on the server.
I know (also using C# stack myself), but self-hosted web-based SVN client market is such a small niche that even offering in different language could be considered good enough. MySQL doesn't bite and installation of Ruby is pretty much x-copy command. I understand why you don't want to spoil your server with additional software though, but if are OK to host your SVN repositories with third-party, you get a nice web-based interface without maintenance hassles.
I'm using
http://unfuddled.com
(they also have some basic API to hook up on if needed).
Not to promote reinventing the wheel,
  but I originally wrote my own web SVN
  browser by using the
svn log --xml
command
This is actually good idea. I'm also parsing some XML formatted output during my automated build process, but creating our own full-blown SVN browser is kind of overkill because now you have to maintain not one primary project, but also the tool. But then again, we, programmers, love to create tools that will make working on our primary projects easier.
ASP.NET SVN browser sounds like promising open-source idea, anybody willing to start work on it? I would contribute.


q: What are the pros and cons of using table aliases in SQL?  I personally try to avoid them, as I think they make the code less readable (especially when reading through large where/and statements), but I'd be interested in hearing any counter-points to this.  When is it generally a good idea to use table aliases, and do you have any preferred formats?

[A]
Well, there are some cases you
must
use them, like when you need to join to the same table twice in one query.
It also depends on wether you have unique column names across tables. In our legacy database we have 3-letter prefixes for all columns, stemming from an abbreviated form from the table, simply because one ancient database system we were once compatible with didn't support table aliases all that well.
If you have column names that occur in more than one table, specifying the table name as part of the column reference is a must, and thus a table alias will allow for a shorter syntax.


q:
In Perl, an object is just a reference to any of the basic Perl data types that has been blessed into a particular class.  When you use the ref() function on an unblessed reference, you are told what data type the reference points to.  However, when you call ref() on a blessed reference, you are returned the name of the package that reference has been blessed into.

I want to know the actual underlying type of the blessed reference.  How can I determine this?

[A]
And my first thought on this was: "Objects in Perl are always hash refs, so what the hack?"
But, Scalar::Util::reftype is the answer. Thanks for putting the question here.
Here is a code snippet to prove this.. (in case it is of any use to anyone).
```
$> perl -e 'use strict; use warnings "all";
            my $x = [1]; bless ($x, "ABC::Def");
            use Data::Dumper; print Dumper $x;
            print ref($x) . "\n";
            use Scalar::Util "reftype"; print reftype($x) . "\n"'`
```
Output:
```
$VAR1 = bless( [
                 1
               ], 'ABC::Def' );
ABC::Def
ARRAY
```


q:
I am trying to code a flowchart generator for a language using Ruby.

I wanted to know if there were any libraries that I could use to draw various shapes for the various flowchart elements and write out text to those shapes.

I would really prefer not having to write code for drawing basic shapes, if I can help it.

Can someone could point me to some reference documentation with examples of using that library?

[A]
It sounds like you're going to be limited mainly by the capabilities of whatever user agent you're building for; if this is a web project, drawing capabilities are going to be dependent on the browser. Since Ruby is running server-side, you would at minimum need some JavaScript to allow dragging/zooming, etc. There's plenty of examples of JavaScript being used for vector drawing (just google "javascript graphics library"), but all require coding, and I haven't seen any library that abstracts this elegantly.
ImageMagick has a Ruby binding called RMagick (sometimes known by other names, depending on the repository). (
Link
)
I haven't used it myself, but I believe it will do what you're looking for. You will need to do some coding, but it's along the lines of
```
```
draw.rectangle(x1, y1, x2, y2)
draw.polygon(x1, y1,...,xN, yN)
```
```


q: We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses?

[A]
Just use C#'s && operator:
```
```
var items = dc.Users.Where(l => l.Date == DateTime.Today && l.Severity == "Critical")
```
```
Edit: Ah, need to read more carefully. You wanted to know how to
conditionally
add additional clauses. In that case, I have no idea. :) What I'd probably do is just prepare several queries, and execute the right one, depending on what I ended up needing.


q:
I'd like to start moving our application business layers into a collection of REST web services. However, most of our Intranet has been built using Classic ASP and most of the developers where I work keep programming in Classic ASP. Ideally, then, for them to benefit from the advantages of a unique set of web APIs, it would have to be called from Classic ASP pages.

I haven't the slightest idea how to do that.

[A]
Here are a few articles describing how to call a web service from a class ASP page:
Integrating ASP.NET XML Web Services with 'Classic' ASP Applications
Consuming XML Web Services in Classic ASP
Consuming a WSDL Webservice from ASP