Question:
I have a small VB.NET application that I'm working on using the full version of Visual Studio 2005. In the Publish properties of the project, I have it set to Automatically increment revision with each publish.

The issue is that it's only incrementing the revision in the Setup files. It doesn't seem to be updating the version number in the About Box (which is the generic, built-in, About Box template). That version number seems to be coming from My.Application.Info.Version.

What should I be using instead so that my automatically incrementing revision number shows up in the about box?

Answer:
I'm no VB.NET expert, but have you tried to set the value to for example 1.0.0.*?
This should increase the revision number (at least it does in the AssemblyInfo.cs in C#).


Question: I'm slowly learning Objective-C and Cocoa, and the only way I see so far to capture key events in Text Views is to use delegation, but I'm having trouble finding useful documentation and examples on how to implement such a solution. Can anyone point me in the right direction or supply some first-hand help?

Answer:
Generally, the way you implement it is simply to add the required function to your view's controller, and set its delegate. For example, if you want code to run when the view loads, you just delegate your view to the controller, and implement the awakeFromNib function.
So, to detect a key press in a text view, make sure your controller is the text view's delegate, and then implement this:
```
```
- (void)keyUp:(NSEvent *)theEvent
```
```
Note that this is an inherited NSResponder method, not a NSTextView method.


Question:
I work in VBA, and want to parse a string eg

<PointN xsi:type='typens:PointN'
xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
xmlns:xs='http://www.w3.org/2001/XMLSchema'>
    <X>24.365</X>
    <Y>78.63</Y>
</PointN>

and get the X & Y values into two separate integer variables.

I'm a newbie when it comes to XML, since I'm stuck in VB6 and VBA, because of the field I work in.

How do I do this?

Answer:
This is a bit of a complicated question, but it seems like the most direct route would be to load the XML document or XML string via MSXML2.DOMDocument which will then allow you to access the XML nodes.
You can find more on MSXML2.DOMDocument at the following sites:
Manipulating XML files with Excel VBA & Xpath
MSXML -
http://msdn.microsoft.com/en-us/library/ms763742(VS.85).aspx
An Overview of MSXML 4.0


Question:
Imagine you want to animate some object on a WinForm. You setup a timer to update the state or model, and override the paint event of the Form. But from there, what's the best way to continually repaint the Form for the animation?

Invalidate the Form as soon as you are done drawing?

Setup a second timer and invalidate the form on a regular interval?

Perhaps there is a common pattern for this thing?

Are there any useful .NET classes to help out?

Each time I need to do this I discover a new method with a new drawback. What are the experiences and recommendations from the SO community?

Answer:
What you're doing is the only solution I've ever used in WinForms (a timer with constant redrawings). There are a bunch of techniques that you can use to make the user's experience with it smoother (such as double-buffering).
You might want to give WPF a try. There are built-in facilities for doing animations in WPF, and they're much smoother (and require less code and no synchronization on your part) than a timer-based solution.
Note that you do not need to use WPF throughout your whole app for that solution; it's possible to pack this functionality into a WPF control and embed the control in a WinForms application (or an unmanaged app, for that matter):
http://www.codeproject.com/KB/WPF/WPF_UserControls.aspx


Question:
The following code doesn't compile with gcc, but does with Visual Studio:

template <typename T> class A {
public:
    T foo;
};

template <typename T> class B: public A <T> {
public:
    void bar() { cout << foo << endl; }
};

I get the error:

test.cpp: In member function ‘void B::bar()’:

test.cpp:11: error: ‘foo’ was not declared in this scope

But it should be! If I change bar to

void bar() { cout << this->foo << endl; }

then it does compile, but I don't think I have to do this. Is there something in the official specs of C++ that GCC is following here, or is it just a quirk?

Answer:
This changed in
gcc-3.4
.  The C++ parser got much more strict in that release -- per the spec but still kinda annoying for people with legacy or multi-platform code bases.


Question: Does SQL Server 2008 ship with the .NET 3.5 CLR, so that stored procedures written in CLR can use 3.5 features?

Answer: Actually it ships with .NET 3.5 SP1.  So yes, the stored procs can use 3.5 features and libraries.


Question:
I have created a custom dialog for Visual Studio Setup Project using the steps described
here

Now I have a combobox in one of my dialogs. I want to populate the combobox with a list of all SQL Server instances running on the local network. It's trivial to get the server list ... but I'm completely lost on how to make them display in the combobox. I would appreciate your help and some code might also be nice as I'm beginner :).

Answer:
I've always found the custom dialogs in visual studio setup projects to be woefully limited and barely functional.
By contrast, I normally create custom actions that display winforms gui's for any remotely difficult tasks during setup.  Works really well and you can do just about anything you want by creating a custom action and passing a few parameters across.
In the dayjob we built a collection of common custom actions for tasks like application config and database creation / script execution to get around custom dialog limitations.


Question:
Let me try to explain what I need. I have a server that is visible from the internet. What I need is to create a ASP.NET application that get the request of a web Site and send to a internal server, then it gets the response and publish the the info. For the client this should be totally transparent.

For different reasons I cannot redirect the port to the internal server. What I can do but no know how - maybe the answer is there - is to create a new Web Site that its host in the other server.

Answer:
Why won't any old proxy software work for this?  Why does it need to be an ASP.NET application?  There are TONS of tools out there (both Windows and *nix) that will get the job done quite easily.  Check
Squid
or
NetProxy
for starters.
If you need to integrate with IIS,
IISProxy
looks like it would do the trick too.


Question:
Ok, I've seen a few posts that mention a few other posts about not using SP wikis because they suck.

Since we are looking at doing our wiki in SP, I need to know why we shouldn't do it for a group of 6 automation-developers to document the steps in various automated processes and the changes that have to be made from time to time.

Answer:
The default wiki included with Sharepoint doesn't support common wiki features well at all.  There is no way to edit a single section of a page, and no way to link directly to a particular section on another page.  The backend is in HTML so you lose the ability to edit in plaintext using simple syntax.  The diff feature can't span multiple versions.  Poor cross browser support of WYSIWYG editing.  No way to auto-insert a table of contents...
There are, however, other wiki add-ins for Sharepoint which I can't categorically dismiss, for instance
Confluence
makes an
add-in for Sharepoint
.  I haven't evaluated this software myself, and Confluence is somewhat expensive ($1,200 for 25 user license) although if you are already on Sharepoint I sense large corporate coffers :P. There also appear to be some free add-ins like
CKS Enhanced Wiki
but that appears to have a lot of the same problems mentioned above.


Question:
What is the best way people have found to do String to Lower case / Upper case in C++?

The issue is complicated by the fact that C++ isn't an English only programming language. Is there a good multilingual method?

Answer:
```
```
#include <algorithm>
std::string data = "Abc";
std::transform(data.begin(), data.end(), data.begin(), ::toupper);
```
```
http://notfaq.wordpress.com/2007/08/04/cc-convert-string-to-upperlower-case/
Also, CodeProject article for common string methods:
http://www.codeproject.com/KB/stl/STL_string_util.aspx


Question:
std::swap() is used by many std containers (such as std::list and std::vector) during sorting and even assignment.

But the std implementation of swap() is very generalized and rather inefficient for custom types.

Thus efficiency can be gained by overloading std::swap() with a custom type specific implementation. But how can you implement it so it will be used by the std containers?

Answer:
You're not allowed (by the C++ standard) to overload std::swap, however you are specifically allowed to add template specializations for your own types to the std namespace. E.g.
```
```
namespace std
{
    template<>
    void swap(my_type& lhs, my_type& rhs)
    {
       // ... blah
    }
}
```
```
then the usages in the std containers (and anywhere else) will pick your specialization  instead of the general one.
Also note that providing a base class implementation of swap isn't good enough for your derived types. E.g. if you have
```
```
class Base
{
    // ... stuff ...
}
class Derived : public Base
{
    // ... stuff ...
}

namespace std
{
    template<>
    void swap(Base& lha, Base& rhs)
    {
       // ...
    }
}
```
```
this will work for Base classes, but if you try to swap two Derived objects it will use the generic version from std because the templated swap is an exact match (and it avoids the problem of only swapping the 'base' parts of your derived objects).
NOTE: I've updated this to remove the wrong bits from my last answer. D'oh! (thanks puetzk and j_random_hacker for pointing it out)


Question:
For my blog I am wanting to use the Output Cache to save a cached version of a perticular post for around 10 minutes, and thats fine...

<%@OutputCache Duration="600" VaryByParam="*" %>

However, if someone posts a comment, I want to clear the cache so that the page is refreshed and the comment can be seen.

How do I do this in ASP.Net C#?

Answer:
Hmm. You can specify a VaryByCustom attribute on the OutputCache item. The value of this is passed as a parameter to the GetVaryByCustomString method that you can implement in global.asax. The value returned by this method is used as an index into the cached items - if you return the number of comments on the page, for instance, each time a comment is added a new page will be cached.
The caveat to this is that this does not actually clear the cache. If a blog entry gets heavy comment usage, your cache could explode in size with this method.
Alternatively, you could implement the non-changeable bits of the page (the navigation, ads, the actual blog entry) as user controls and implement partial page caching on each of those user controls.


Question: Certainly there's the difference in general syntax, but what other critical distinctions exist?  There are some differences, right?

Answer:
This topic has had a lot of face time since .Net 2.0 was released. See this
Wikipedia
article for a readable summary.


Question:
What is the best way of doing case-insensitive string comparison in C++ without transforming a string to all uppercase or all lowercase?

Please indicate whether the methods are Unicode-friendly and how portable they are.

Answer:
Assuming you are looking for a method and not a magic function that already exists, there is frankly no better way. We could all write code snippets with clever tricks for limited character sets, but at the end of the day at somepoint you have to convert the characters.
The best approach for this conversion is to do so prior to the comparison. This allows you a good deal of flexibility when it comes to encoding schemes, which your actual comparison operator should be ignorant of.
You can of course 'hide' this conversion behind your own string function or class, but you still need to convert the strings prior to comparison.


Question: I haven't touched sharepoint in years.  If I want to setup a development environment to get up to speed, what options do I have?  I don't have an MSDN license, is there anyway I can get up and running for free? (for development only)

Answer:
There is no way you can have a MOSS 2007/WSS 3.0 development for free but a
Microsoft Action Pact
is so cheap to get. :)
There is a nice blog to read to get the requirements and the steps to get a full MOSS 2007 image up and running here :
How to Create a MOSS 2007 VPC Image: The Whole 9 Yards
.


Question:
On my Windows XP machine Visual Studio 2003 2005 and 2008 all complain that I cannot start debugging my web application because I must either be a member of the Debug Users group or of the Administrators group. So, I am an Administrator and I added Debug Users just in case, and it still complains.

Short of reformatting my machine and starting over, has anyone encountered this and fixed it [with some undocumented command]?

Answer:
You could try running "
```
VsJITDebugger.exe -p <PID>
```
" on the command line. I've had a simalar situation and been able to debug the application using the above.
"
```
VsJITDebugger.exe /?
```
" will show you all the options.
The PID can be found either in the task manager (view->Select Columns...) or Visual Studio's Attach to Process.


Question:
I am developing an application to install a large number of data files from multiple DVDs.  The application will prompt the user to insert the next disk, however Windows will automatically try to open that disk either in an explorer window or ask the user what to do with the new disk.

How can I intercept and cancel auto play messages from my application?

Answer:
There are two approaches that I know of.  The first and simplest is to register the special Windows message "QueryCancelAutoPlay" and simply return 1 when the message is handled.  This only works for the current window, and not a background application.
The second approach requires inserting an object that implements the COM interface
```
IQueryCancelAutoPlay
```
COM interface into the Running Object Table.


Question:
I'm not new to web publishing, BUT I am new to publishing against a web site that is frequently used.  Previously, the apps on this server were not hit very often, but we're rolling out a high demand application.  So, what is the best practice for publishing to a live web server?

Is it best to wait until the middle
of the night when people won't be on
it (Yes, I can pretty much rely on
that -- it's an intranet and
therefore will have times of
non-use)

Publish when new updates are made to
the trunk (dependent on build
success of course)

If 2 is true, then that seems bad if someone is using that specific page or DLL and it gets overwritten.

...I'm sure there are lots of great places for this kind of thing, but I didn't use the right google search terms.

Answer:
@Nick DeVore wrote:
If 2 is true, then that seems bad if
someone is using that specific page or
DLL and it gets overwritten.
It's not really an issue if you're using ASP.NET stack (Webforms, MVC or rolling your own) because all your aspx files get compiled and therefore not touched by webserver. /bin/ folder is completely shadowed somewhere else, so libraries inside are not used by webserver either.
IIS will wait until all requests are done (however there is some timeout though) and then will proceed with compilation (if needed) and restart of AppDomain. If only a few files have changed, there won't even be AppDomain restart. IIS will load new assemblies (or compiled aspx/asmx/ascx files) into existing AppDomain.
@Nick DeVore wrote:
Help me understand this a little bit
more. Point me to the place where this
is explained from Microsoft. Thanks!
Try google for "IIS AppDomain" keywords. I found
What ASP.NET Programmers Should Know About Application Domains
.


Question: Is it possible to upload a file from a client's computer to the server through a web service? The client can be running anything from a native desktop app to a thin ajax client.

Answer:
I'm not a master in "webservice", but if you develop the webservice (and the client), you always can convert the binary file to
BASE64
in the client (can do in java... and i soupose in ajax too) and transfer as "string", in the other side, in the webservice encode to binary from BASE64...
It's one idea, that's work, but maybe not "correct" in all enviroment.


Question:
I'm working on a web service at the moment and there is the potential that the returned results could be quite large ( > 5mb).

It's perfectly valid for this set of data to be this large and the web service can be called either sync or async, but I'm wondering what people's thoughts are on the following:

If the connection is lost, the
entire resultset will have to be
regenerated and sent again. Is there
any way I can do any sort of
"resume" if the connection is lost
or reset?

Is sending a result set this large even appropriate? Would it be better to implement some sort of "paging" where the resultset is generated and stored on the server and the client can then download chunks of the resultset in smaller amounts and re-assemble the set at their end?

Answer:
There's no hard law against 5 Mb as a result set size. Over 400 Mb can be
hard to send
.
You'll automatically get async handlers (since you're using .net)
implement some sort of "paging" where
  the resultset is generated and stored
  on the server and the client can then
  download chunks of the resultset in
  smaller amounts and re-assemble the
  set at their end
That's already happening for you -- it's called tcp/ip ;-) Re-implementing that could be overkill.
Similarly --
entire resultset will have to be
  regenerated and sent again
If it's MS-SQL, for example that is generating most of the resultset -- then re-generating it will take advantage of some implicit cacheing in SQL Server and the subsequent generations will be quicker.
To some extent you can get away with not worrying about these problems, until they surface as 'real' problems -- because the platform(s) you're using take care of a lot of the performance bottlenecks for you.


Question:
The only thing I've found has been;

.hang {
    text-indent: -3em;
    margin-left: 3em;
}

The only way for this to work is putting text in a paragraph, which causes those horribly unsightly extra lines. I'd much rather just have them in a <span class="hang"></span> type of thing.

I'm also looking for a way to further indent than just a single-level of hanging. Using paragraphs to stack the indentions doesn't work.

Answer:
```
<span>
```
is an inline element. The term
hanging indent
is meaningless unless you're talking about a paragraph (which generally means a block element). You can, of course, change the margins on
```
<p>
```
or
```
<div>
```
or any other block element to get rid of extra vertical space between paragraphs.
You may want something like
```
display: run-in
```
, where the tag will become either block or inline depending on context... sadly, this is
not yet universally supported by browsers
.


Question:
I am currently architecting a small CRUD applicaton. Their database is a huge mess and will be changing frequently over the course of the next 6 months to a year. What would you recommend for my data layer:

1) ORM (if so, which one?)

2) Linq2Sql

3) Stored Procedures

4) Parametrized Queries

I really need a solution that will be dynamic enough (both fast and easy) where I can replace tables and add/delete columns frequently.

Note: I do not have much experience with ORM (only a little SubSonic) and generally tend to use stored procedures so maybe that would be the way to go. I would love to learn Ling2Sql or NHibernate if either would allow for the situation I've described above.

Answer:
NHibernate
, but only if you would be amenable to having an object-first approach wherein you define your classes, and then define your desired table structure in the mapping files, and then create a database schema using NHibernate's built in schema generation classes.
For doing it the other way around (e.g., you have a bunch of tables and then you base your object design on that) I've found
MyGeneration
+ NHibernate to work, although I'm not too happy with the resulting classes (mainly because I'm such a stickler for true Object Oriented Programming).


Question: How would you reccommend handling RSS Feeds in ASP.NET MVC?  Using a third party library?  Using the RSS stuff in the BCL?  Just making an RSS view that renders the XML?  Or something completely different?

Answer:
Here is what I recommend:
Create a class called RssResult that
inherits off the abstract base class
ActionResult.
Override the ExecuteResult method.
ExecuteResult has the ControllerContext passed to it by the caller and with this you can get the data and content type.
Once you change the content type to rss, you will want to serialize the data to RSS (using your own code or another library) and write to the response.
Create an action on a controller that you want to return rss and set the return type as RssResult.  Grab the data from your model based on what you want to return.
Then any request to this action will receive rss of whatever data you choose.
That is probably the quickest and reusable way of returning rss has a response to a request in ASP.NET MVC.


Question:
I'm new to MVC (and ASP.Net routing).  I'm trying to map *.aspx to a controller called PageController.

routes.MapRoute(
   "Page",
   "{name}.aspx",
   new { controller = "Page", action = "Index", id = "" }
);

Wouldn't the code above map *.aspx to PageController?  When I run this and type in any .aspx page I get the following error:

The controller for path '/Page.aspx' could not be found or it does not implement the IController interface.
  Parameter name: controllerType

Is there something I'm not doing here?

Answer:
Not sure how your controller looks, the error seems to be pointing to the fact that it can't find the controller.  Did you inherit off of Controller after creating the PageController class?  Is the PageController located in the Controllers directory?
Here is my route in the Global.asax.cs
```
```
routes.MapRoute(
    "Page",
    "{Page}.aspx",
    new { controller = "Page", action = "Index", id = "" }
);
```
```
Here is my controller, which is located in the Controllers folder:
```
```
using System.Web.Mvc;

namespace MvcApplication1.Controllers
{
    public class PageController : Controller
    {
        public void Index()
        {
            Response.Write("Page.aspx content.");
        }
    }
}
```
```


Question:
How can I determine the IP of my router/gateway in Java? I can get my IP easily enough. I can get my internet IP using a service on a website. But how can I determine my gateway's IP?

This is somewhat easy in .NET if you know your way around. But how do you do it in Java?

Answer:
That is not as easy as it sounds.  Java is platform independent, so I am not sure how to do it in Java.  I am
guessing
that .NET contacts some web site which reports it back.  There are a couple ways to go.  First, a deeper look into the ICMP protocol may give you the information you need.  You can also trace the IP you go through (your route).  When you encounter an IP that is not in the following ranges:
10.0.0.0 – 10.255.255.255
172.16.0.0 – 172.31.255.255
192.168.0.0 – 192.168.255.255
it is the IP one hop away from yours, and probably shares a few octets of information with your IP.
Best of luck.  I'll be curious to hear a definitive answer to this question.


Question:
I curious to how different people solve integration of systems. I have a feeling that the last years more and more work has gone into integrating systems and that this kind of work need will increase as well.

I wondering if you solve it developing your own small services that are then connected or if you use some sort of product (WebSphere, BizTalk, Mule etc). I'd also think it'd be interesting to know how these kind of solutions are managed and maintained (how do you solve security, instrumentation etc, etc), what kind of problems have you experienced with your solution and so on.

Answer:
wow - Ok - will get a post on this but will be big.
Intergration needs to be backed up with a big understanding by the business on the benefits - Get an opertating model sorted out - as the business may acutally need to standardise instead of intergrate, as this can be costly - its why most SOA fail!
Enterprise Architecture: Driving Business Benefits from IT
Author(s): Jeanne W. Ross
If intergration is needed you then need to settle on type of integration.
What are the speed and performance metrics?
We have a .NET SOA with a Composite Application that uses BizTalk 2006 and webservices with Line of Business Applications. Performance of the application at the composite end (consuming) - is limited to the speed of the webservices (and their implementation) in the line of business application!  We need sub <3 second return on results - list of cases. Could not be acheived in the webservices so we need to get go to the database directly for initial search.  Then over the webservices for case creation.  Cost implications and maintance becomes an issue here.
The point here is to look at the performance criteria in the specs and business requirements this will help in look at the type of integration that you need to do - WebServices (HTTP), File Drop/ EDI etc
Functionally for intergration you need to then look at the points of failure in the proposed architecture - as this will lead to a chain of responisblity in SLA/OLA.  You may need to wrapper the intergration/faliure points into things that you control.
On similar point about integration with Line of Business is with how much do you need to know about the other product before you can integrate?  Yeah Webservices are supposed to be design by contract but the implementation is often leaky and you need to understand alot about what is happening - and if this is a product that you dont control the abstraction even with webservices leaks into your intergation technology aka BizTalk.
Couple these two points together and you the best advise is to get a intergration hub type like BizTalk - wrapper the line of business applications in webservices you create - so the BizTalk side can be free from leaky abstractions then you also can reduce the points of failure as the you have decoupled the line of business application from the intergration hub and the point of failure to a single source rather than inside an orchestration.
Instrumentation and diagnosics in SOA and Intergation Porjects are hard to acheive! - Dont let any shiney sales person try and tell you differently!  Yeah MOM with MOM Ent can do this UniCenter can do blah.
The main problem is understand what the error aka burps in the intergation mean and how to recover from them...  You end up with messages stuck and you need to understand what that means to that busienss process.  You can get an alert to say - processers are 100% Ram 100% orchestrations have failed - but no real meaning.   You have to engineer this stuff in to the solution from the outset - and hopefully into you points of failure.
Types of intergration patterns and how to do them do need to be considered too.
The above is a real world view of a .NET SOA with BizTalk in a LIVE implementation.  But it is also due to the architectural limitations of this - BizTalk mainly is a HUB and SPOKE pattern.
Check out
Enterprise Application Patterns by Martin Fowler
There are many ways to skin the task!
Other considerations...  Platform/Developer Languages etc.
One of the big factors for us was the skills needed to start this stuff. We had OO devs with Java and C# understanding, but mainly C#.  So we went for the MS stack.  But when you choose the intergration type and the product to manage this they will need more skills in understanding that technology.  But hey this is normall for us Devs right?  Wrong many developers regardless of there expereince can come unstuck with the likes of BizTalk!  Big shift in paradigm - which in part is due to messaging shift rather than code.
Best bit for last!
Numbers of transactions that are likely to be faced in the integration is probable the single biggest factor in all of this.  As this will guide what pattern, points of failure and tolarance for such things.
You need to select best on anticpated volumes the right one.  Something that can scale up and scale out!  We selected BizTalk since it can scale up and scale out correctly and with better understanding than some others.
If you dont have volumes then look at not getting something to manage them and go for a webservice to webservice type style with no management - performance and failure understanding will need to be coded into them.
If your on windows platform with .net 3 take look at WWF/WCF as this can help in webservice to webservice - lots more in the acutal platform now for all these concerns without the overhead of BizTalk and others.
Hope this helps.


Question: How can I pipe the new password to smbpasswd so I can automate my installation process.

Answer:
using either
pipelines
or
redirection
.


Question:
I am currently writing a simple, timer based mini app in C# that performs an action n times every k seconds.

I am trying to adopt a test driven development style, so my goal is to unit test all parts of the app.

So, my question is: Is there a good way to unit test a timer based class?

The problem, as I see it, is that there is a big risk that the tests will take uncomfortably long to execute, since they must wait so and so long for the desired actions to happen.

Especially if one wants realistic data (seconds), instead of using the minimal time resolution allowed by the framework (1 ms?).

I am using a mock object for the action, to register the number of times the action was called, and so that the action takes practically no time.

Answer:
I think what I would do in this case is test the code that actually executes when the timer ticks, rather than the entire sequence. What you really need to decide is whether it is worthwhile for you to test the actual behaviour of the application (for example, if what happens after every tick changes drastically from one tick to another), or whether it is sufficient (that is to say, the action is the same every time) to just test your logic.
Since the timer's behaviour is guaranteed never to change, it's either going to work properly (ie, you've configured it right) or not; it seems to be to be wasted effort to include that in your test if you don't actually need to.


Question:
If I inherit from a base class and want to pass something from the constructor of the inherited class to the constructor of the base class, how do I do that?

For example, if I inherit from the Exception class I want to do something like this:

class MyExceptionClass : Exception
{
     public MyExceptionClass(string message, string extraInfo)
     {
         //This is where it's all falling apart
         base(message);
     }
}

Basically what I want is to be able to pass the string message to the base Exception class.

Answer:
Modify your constructor to the following so that it calls the base class constructor properly:
```
```
public class MyExceptionClass : Exception
{
    public MyExceptionClass(string message, string extrainfo) : base(message)
    {
        //other stuff here
    }
}
```
```
Note that a constructor is not something that you can call anytime within a method. That's the reason you're getting errors in your call in the constructor body.


Question:
When I am running the following statement:

@filtered = map {s/&nbsp;//g} @outdata;

it is returning an empty list instead of the filtered list that I expected.  What I am trying to do is remove every occurrence of &nbsp; from an array of string (which is an XML file).

Obviously, I am not understanding something.  Can anyone tell me the correct way to do this might be, and why this isn't working for me as is?

Answer:
Try this:
```
```
@filtered = map {s/ //g; $_} @outdata;
```
```
The problem is the s operator in perl modifies $_ but actually returns the number of changes it made. So, the extra $_ at the end causes perl to return the modified string for each element of @outdata.


Question:
I installed VS SP1 and played around with Entity Framework.

I created a schema from an existing database and tried some basic operations.

Most of it went well, except the database schema update.

I changed the database in every basic way:

added a new table

deleted a table

added a new column to an existing table

deleted a column from an existing table

changed the type of an existing column

The first three went well, but the type change and the column deletion did not followed the database changes.

Is there any way to make is work from the designer? Or is it not supported at the moment? I didn't find any related material yet, but still searching.

Answer:
I would guess that possibly those don't happen because they would break the build for existing code, but that's just a guess on my part.
Here's my logic:
First, EF is supposed to be more than 1:1 table mapping, so it's quite possible that just because you are deleting a column from table A doesn't mean that for that entity, there shouldn't be a property Description. You might just map that property to another table.
Second, changing a type could just break builds. that's the only rationale there.


Question:
I have thus far avoided the nightmare that is testing multi-threaded code since it just seems like too much of a minefield.  I'd like to ask how people have gone about testing code that relies on threads for successful execution, or just how people have gone about testing those kinds of issues that only show up when two threads interact in a given manner?

This seems like a really key problem for programmers today, it would be useful to pool our knowledge on this one imho.

Answer:
I have had the unfortunate task of testing threaded code and they are definitely the hardest tests I have ever written.
When writing my tests, I used a combination of delegates and events.  Basically it is all about using
```
PropertyNotifyChanged
```
events with a
```
WaitCallback
```
or some kind of
```
ConditionalWaiter
```
that polls.
I am not sure if this was the best approach, but it has worked out for me.


Question:
I've got a Repeater that lists all the web.sitemap child pages on an ASP.NET page.  Its DataSource is a SiteMapNodeCollection.  But, I don't want my registration form page to show up there.

Dim Children As SiteMapNodeCollection = SiteMap.CurrentNode.ChildNodes

'remove registration page from collection
For Each n As SiteMapNode In SiteMap.CurrentNode.ChildNodes
If n.Url = "/Registration.aspx" Then
    Children.Remove(n)
End If
Next

RepeaterSubordinatePages.DataSource = Children

The SiteMapNodeCollection.Remove() method throws a

NotSupportedException: "Collection is read-only".

How can I remove the node from the collection before DataBinding the Repeater?

Answer:
Using Linq and .Net 3.5:
```
```
//this will now be an enumeration, rather than a read only collection
Dim children = SiteMap.CurrentNode.ChildNodes.Where( _
    Function (x) x.Url <> "/Registration.aspx" )

RepeaterSubordinatePages.DataSource = children
```
```
Without Linq, but using .Net 2:
```
```
Function IsShown( n as SiteMapNode ) as Boolean
    Return n.Url <> "/Registration.aspx"
End Function

...

//get a generic list
Dim children as List(Of SiteMapNode) = _
    New List(Of SiteMapNode) ( SiteMap.CurrentNode.ChildNodes )

//use the generic list's FindAll method
RepeaterSubordinatePages.DataSource = children.FindAll( IsShown )
```
```
Avoid removing items from collections as that's always slow. Unless you're going to be looping through multiple times you're better off filtering.


Question:
I'm trying to serialize a Type object in the following way:

Type myType = typeof (StringBuilder);
var serializer = new XmlSerializer(typeof(Type));
TextWriter writer = new StringWriter();
serializer.Serialize(writer, myType);

When I do this, the call to Serialize throws the following exception:

"The type System.Text.StringBuilder was not expected. Use the
  XmlInclude or SoapInclude attribute to specify types that are not
  known statically."

Is there a way for me to serialize the Type object?  Note that I am not trying to serialize the StringBuilder itself, but the Type object containing the metadata about the StringBuilder class.

Answer:
Just looked at its definition, it is not marked as Serializable. If you really need this data to be serialize, then you may have to convert it to a custom class that is marked as such.
```
```
public abstract class Type : System.Reflection.MemberInfo
    Member of System

Summary:
Represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.

Attributes:
[System.Runtime.InteropServices.ClassInterfaceAttribute(0),
System.Runtime.InteropServices.ComDefaultInterfaceAttribute(System.Runtime.InteropServices._Type),
System.Runtime.InteropServices.ComVisibleAttribute(true)]
```
```


Question:
Is there any known way of listing the WMI classes and their properties available for a particular system? Im interested in a vbscript approach, but please suggest anything really :)

P.S. Great site.

Answer:
I believe this is what you want.
WMI Code Creator
A part of this nifty utility allows you to browse namespaces/classes/properties on the local and remote PCs, not to mention generating WMI code in VBScript/C#/VB on the fly.  Very useful.
Also, the source code used to create the utility is included in the download, which could provide a reference if you wanted to create your own browser like interface.


Question:
I'm running PHP 5.2.3 on Windows 2000 Server with IIS 5.  I'm trying
to get cURL working, so in my php.ini file, I have this line:

extension_dir ="F:\PHP\ext"

And later, I have:

extension=php_curl.dll

The file F:\PHP\ext\php_curl.dll exists, but when I try to run any PHP
script, I get this in the error log:

PHP Warning:  PHP Startup: Unable to load dynamic library 'F:\PHP\ext
  \php_curl.dll' - The specified module could not be found.
   in Unknown on line 0

Answer:
Problem solved!
Although the error message said
The specified module could not be found
, this is a little misleading -- it's not that it couldn't find
```
php_curl.dll
```
, but rather it couldn't find a module that
```
php_curl.dll
```
required.  The 2 DLLs it requires are
```
libeay32.dll
```
and
```
SSLeay32.dll
```
.
So, you have to put those 2 DLLs somewhere in your PATH (e.g.,
```
C:\Windows\system32
```
).  That's all there is to it.
However, even that did not work for me initially.  So I downloaded the Windows zip of the latest version of PHP, which includes all the necessary DLLs.  I didn't reinstall PHP, I just copied all of the DLLs in the "ext" folder to my PHP extensions folder (as specified in the
```
extension_dir
```
variable in
```
php.ini
```
), and I copied the versions of
```
libeay32.dll
```
and
```
SSLeay32.dll
```
from the PHP download into my System32 directory.
I also did an iisreset, but I don't know if that was necessary.


Question:
The .NET garbage collector will eventually free up memory, but what if you want that memory back immediately? What code do you need to use in a class MyClass to call

MyClass.Dispose()

and free up all the used space by variables and objects in MyClass?

Answer:
This article
has a pretty straightforward walkthrough.  However,
having
to call the GC instead of letting it take its natural course is generally a sign of bad design/memory management,
especially
if no limited resources are being consumed (connections, handles, anything else that typically leads to implementing IDisposable).
What's causing you to need to do this?


Question:
From what I've read, VS 2008 SP1 and Team Foundation Server SP1 packages are traditional service packs that require you to first install the original versions before you will be able to install the SP.

Is there a way, supported or not, to slipstream the install?

Answer:
Here's an
MSDN forum post
in which an MSFTie indicates it will be possible and that details are forthcoming.  Another poster is relaying results of her almost-successful attempt.  Looks like this will be doable soon.
Related:
how to slipstream Team Foundation Server 2008 SP1 (TFS 2008 SP1)


Question:
Once I have my renamed files I need to add them to my project's wiki page. This is a fairly repetitive manual task, so I guess I could script it but I don't know where to start.

The process is:

Got to appropriate page on the wiki

for each team member (DeveloperA, DeveloperB, DeveloperC)
{
    for each of two files ('*_current.jpg', '*_lastweek.jpg')
    {
        Select 'Attach' link on page
        Select the 'manage' link next to the file to be updated
        Click 'Browse' button
        Browse to the relevant file (which has the same name as the previous version)
        Click 'Upload file' button
    }
}

Not necessarily looking for the full solution as I'd like to give it a go myself.

Where to begin? What language could I use to do this and how difficult would it be?

Answer:
If you're writing in C#, the WebClient classes might be a good place to start.  I bet people could give more specific advice if you mentioned which wiki platform you are using, and whether it requires authentication, though.
I'd probably start by downloading fiddler and watching the http requests from doing it manually.  Then you could use some simple scripts and regexes to build your http requests for automating the process.
Of course, if your wildly lucky, your wiki would have a backend simple enough that you could just plug them into its db directly. :)


Question: How do you scan a directory for folders and files in C? It needs to be cross-platform.

Answer:
opendir/readdir are POSIX. If POSIX is not enough for the portability you want to achieve, check
Apache Portable Runtime


Question:
In Ruby, what's the difference between {} and []?

{} seems to be used for both code blocks and hashes.

Are [] only for arrays?

The documention isn't very clear.

Answer:
Broadly speaking, you're correct. As well as hashes, the general style is that curly braces
```
{}
```
are often used for blocks that can fit all onto one line, instead of using
```
do
```
/
```
end
```
across several lines.
Square brackets
```
[]
```
are used as class methods in lots of Ruby classes, including String, BigNum, Dir and confusingly enough, Hash. So:
```
```
Hash["key" => "value"]
```
```
is just as valid as:
```
```
{ "key" => "value" }
```
```


Question:
Let's say we have a simple function defined in a pseudo language.

List<Numbers> SortNumbers(List<Numbers> unsorted, bool ascending);

We pass in an unsorted list of numbers and a boolean specifying ascending or descending sort order. In return, we get a sorted list of numbers.

In my experience, some people are better at capturing boundary conditions than others. The question is, "How do you know when you are 'done' capturing test cases"?

We can start listing cases now and some clever person will undoubtedly think of 'one more' case that isn't covered by any of the previous.

Answer:
Don't waste too much time trying to think of
every
boundry condition.  Your tests won't be able to catch
every
bug first time around.  The idea is to have tests that are
pretty good
, and then each time a bug
does
surface, write a new test specifically for that bug so that you never hear from it again.
Another note I want to make about code coverage tools.  In a language like C# or Java where your have many get/set and similar methods, you should
not
be shooting for 100% coverage.  That means you are wasting too much time writing tests for trivial code.  You
only
want 100% coverage on your complex business logic.  If your full codebase is closer to 70-80% coverage, you are doing a good job.  If your code coverage tool allows multiple coverage metrics, the best one is 'block coverage' which measures coverage of 'basic blocks'.  Other types are class and method coverage (which don't give you as much information) and line coverage (which is too fine grain).


Question: What can I do to increase the performance/speed of my PHP scripts without installing software on my servers?

Answer:
There is no magic solution, and attempting to provide generic solutions could well just be a waste of time.
Where are your bottlenecks? For example are your scripts processor/database/memory intensive?
Have you performed any profiling?


Question: Is there a way, when I parse an XML document using lxml, to validate that document against its DTD using an external catalog file?   I need to be able to work the fixed attributes defined in a document’s DTD.

Answer:
Can you give an example? According to the
lxml validation docs
, lxml can handle DTD validation (specified in the XML doc or externally in code) and system catalogs, which covers most cases I can think of.
```
```
f = StringIO("<!ELEMENT b EMPTY>")
dtd = etree.DTD(f)
dtd = etree.DTD(external_id = "-//OASIS//DTD DocBook XML V4.2//EN")
```
```


Question:
Is it possible to write a doctest unit test that will check that an exception is raised?

For example, if I have a function foo(x) that is supposed to raise an exception if x < 0, how would I write the doctest for that?

Answer:
Yes. You can do it. The
doctest module documentation
and Wikipedia has an
example
of it.
```
```
>>> x
   Traceback (most recent call last):
     ...
   NameError: name 'x' is not defined
```
```


Question:
I'm developing a C# application that uses a handful of XML files and some classes in System.Xml.  A coworker insists on adding the MSXML6 redistributable to our install, along with the .NET framework but I don't think the .NET framework uses or needs MSXML in anyway.  I am well aware that using MSXML from .NET is not supported but I suppose its theoretically possible for System.Xml itself to wrap MSXML at a low level.  I haven't found anything definitive that .NET has its own implementation but neither can I find anything to suggest it needs MSXML.

Help me settle the debate.  Does System.Xml use MSXML?

Answer:
System.Xml doesn't use MSXML6. They are seperate xml processing engines. See post here:
MSXML 6.0 vs. System.Xml: Schema handling differences


Question:
If you create an ASP.NET web file project you have direct access to the Profile information in the web.config file. If you convert that to a Web App and have been using ProfileCommon etc. then you have to jump through a whole bunch of hoops to get your web app to work.

Why wasn't the Profile provider built into the ASP.NET web app projects like it was with the web file projects?

Answer:
The profile provider uses the ASP.NET Build Provider system, which doesn't work with Web Application Projects.
Adding a customized BuildProvider
  class to the Web.config file works in
  an ASP.NET Web site but does not work
  in an ASP.NET Web application project.
  In a Web application project, the code
  that is generated by the BuildProvider
  class cannot be included in the
  application.
source:
MSDN Build Provider documentation


Question:
we're developing a web app to cover all aspects of a printing company from finances, to payroll, to job costing.  Its important to be able to control who can access what parts of these applications.  Don't want a line employee giving himself a raise, etc...

I've heard of the concept of ACL & ACO, but haven't found a good example that we could adapt to our project.

Anyone know where I can find good information to work from?

Answer:
I've had to implement that type of security a couple of times.  Unfortunately I don't know of any really good articles that provide examples.  My implementations were mainly piecing together the parts through trial and error.
However, I did come across this link on MSDN:
http://msdn.microsoft.com/en-us/library/52kd59t0(VS.71).aspx
It has some of the concepts.
After my original post, I did some more research.  I found this article:
http://www.aspfree.com/c/a/C-Sharp/Implementing-Role-Based-Security-using-CSharp/
it seems pretty promising, I didn't go through all the details, but it at least guides you through the high-level topics.


Question:
I've been using Emacs's sql interactive mode to talk to the MySQL db server and gotten to enjoy it. A developer has set up another db on a new non-default port number but I don't know how to access it using sql-mysql.

How do I specify a port number when I'm trying to connect to a database?

It would be even better if Emacs can prompt me for a port number and just use the default if I don't specify. Any chances of that?

Answer:
```
```
(setq sql-mysql-options (list "-P <port number>"))
```
```


Question: I'm trying to parse an INI file using C++. Any tips on what is the best way to achieve this? Should I use the Windows API tools for INI file processing (with which I am totally unfamiliar), an open-source solution or attempt to parse it manually?

Answer:
I have never parsed ini files, so I can't be too specific on this issue.
But i have one advice:
Don't reinvent the wheel as long as an existing one meets your requirements
http://en.wikipedia.org/wiki/INI_file#Accessing_INI_files
http://sdl-cfg.sourceforge.net/
http://sourceforge.net/projects/libini/
http://www.codeproject.com/KB/files/config-file-parser.aspx
Good luck :)


Question:
Is there a simple way in Perl that will allow me to determine if a given variable is numeric?  Something along the lines of:

if (is_number($x))
{ ... }

would be ideal.  A technique that won't throw warnings when the -w switch is being used is certainly preferred.

Answer:
Not perfect, but you can use a regex:
```
```
sub isnumber
{
    shift =~ /^-?\d+\.?\d*$/;
}
```
```


Question:
I'm using the new ASP.Net ListView control to list database items that will be grouped together in sections based on one of their columns like so:

region1
    store1
    store2
    store3
region2
    store4
region3
    store5
    store6

Is this possible to do with the ListView's GroupItemTemplate? Every example I have seen uses a static number of items per group, which won't work for me. Am I misunderstanding the purpose of the GroupItem?

Answer:
I haven't used GroupItemCount, but I have taken this example written up by
Matt Berseth
titled
Building a Grouping Grid with the ASP.NET 3.5 LinqDataSource and ListView Controls
and have grouped items by a key just like you want.
It involves using an outer and inner ListView control.  Works great, give it a try.


Question:
Let's say I woke up today and wanted to create a clone of StackOverflow.com, and reap the financial windfall of millions $0.02 ad clicks. Where do I start?

My understanding of web technologies are:

HTML is what is ultimately displayed

CSS is a mechanism for making HTML look pleasing

ASP.NET lets you add functionality using .NET(?)

JavaScript does stuff

AJAX does asyncronous stuff

... and the list goes on!

To write a good website to I just need to buy seven books and read them all? Are Web 2.0 sites really the synergy of all these technologies?

Where does someone go to get started down the path to creating professional-looking web sites, and what steps are there along the way.

Answer:
I would recommend this book:
http://www.amazon.com/MCTS-Self-Paced-Training-Exam-70-528/dp/0735623341/ref=sr_1_1?ie=UTF8&s=books&qid=1218830714&sr=8-1
I have just read it to take the exam, and although I knew the web theory part, I found it to be of great value.
This of course is a ASP.NET specific book, but that is what I would recommend learning anyways.
After you learn all the ASP.NET stuff, I would suggest reading up on
JQuery
.
Happy coding :)


Question: Has anyone built a website with IronPython and ASP.NET.  What were your experiences and is the combination ready for prime-time?

Answer:
The current version of ASP.NET integration for IronPython is not very up-to-date and is more of a "proof-of-concept." I don't think I'd build a production website based on it.
Edit:
: I have a very high level of expectation for how things like this should work, and might setting the bar a little high.  Maybe you should take what's in "ASP.NET Futures", write a test application for it and see how it works for you.  If you're successful, I'd like to hear about it.  Otherwise, I think there should be a newer CTP of this in the next six months.
(I'm a developer on IronPython and IronRuby.)
Edit 2:
Since I originally posted this, a
newer version
has been released.


Question:
I'm coming from a Rails background and doing some work on a ASP.NET project (not ASP MVC). Newbie question: what's the easiest way to make a custom editor for a table of records?

For example: I have a bunch of data rows and want to change the "category" field on each -- maybe a dropdown, maybe a link, maybe the user types it in.

In Rails, I'd iterate over the rows to build a table, and would have a form for each row. The form would have an input box or dropdown, and submit the data to a controller like "/item/edit/15?category=foo" where 15 was the itemID and the new category was "foo".

I'm new to the ASP.NET model and am not sure of the "right" way to do this -- just the simplest way to get back the new data & save it off. Would I make a custom control and append it to each row? Any help appreciated.

Answer:
There are a few controls that will do this for you, with varying levels of complexity depending on their relative flexibility.
The traditional way to do this would be the DataGrid control, which gives you a table layout. If you want something with more flexibility in appearance, the DataList and ListView controls also have built-in support for editing, inserting or deleting fields as well.
Check out
Matt Berseth's blog
for some excellent examples of asp.net controls in action.


Question:
I have two separate mercurial repositories. At this point it makes sense that they "become one" because I want to work on the two projects simultaneously.

I'd really like the two projects to each be a subdirectory in the new repository.

How do I merge the two projects?

Is this a good idea, or should I
keep them separate?

It seems I ought to be able to push from one repository to the other... Maybe this is really straight forward?

Answer:
If you aren't using the same code across the projects, keep them separate. You can set
your
personal repository of each of those projects to be just a directory apart. Why mix all the branches, merges, and commit comments when you don't have to.
About your edit:
Pushing from One repository to Another. You can always use the
```
transplant
```
command. Although, all this is really side stepping your
desire
to combine the two, so you might feel uncomfortable using my suggestions. Then you can use the forest extension, or something.
```
```
hg transplant -s REPOSITORY lower_rev:high_rev
```
```


Question:
Got a bluescreen in windows while cloning a mercurial repository.

After reboot, I now get this message for almost all hg commands:

c:\src\>hg commit
waiting for lock on repository c:\src\McVrsServer held by '\x00\x00\x00\x00\x00\
x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
interrupted!

Google is no help.

Any tips?

Answer:
When "waiting for lock on repository", delete the repository file:
```
.hg/wlock
```
(or it may be in
```
```
.hg/store/lock
```
```
)
When  deleting the lock file, you must make sure nothing else is accessing the repository. (If the lock is a string of zeros or blank, this is almost certainly true).


Question:
I have a large database of normalized order data that is becoming very slow to query for reporting.  Many of the queries that I use in reports join five or six tables and are having to examine tens or hundreds of thousands of lines.

There are lots of queries and most have been optimized as much as possible to reduce server load and increase speed.  I think it's time to start keeping a copy of the data in a denormalized format.

Any ideas on an approach?  Should I start with a couple of my worst queries and go from there?

Answer:
I know this is a bit tangential, but have you tried seeing if there are more indexes you can add?
I don't have a lot of DB background, but I am working with databases a lot recently, and I've been finding that a lot of the queries can be improved just by adding indexes.
We are using DB2, and there is a command called db2expln and db2advis, the first will indicate whether table scans vs index scans are being used, and the second will recommend indexes you can add to improve performance.  I'm sure MySQL has similar tools...
Anyways, if this is something you haven't considered yet, it has been helping a lot with me... but if you've already gone this route, then I guess it's not what you are looking for.
Another possibility is a "materialized view" (or as they call it in DB2), which lets you specify a table that is essentially built of parts from multiple tables.  Thus, rather than normalizing the actual columns, you could provide this view to access the data... but I don't know if this has severe performance impacts on inserts/updates/deletes (but if it is "materialized", then it should help with selects since the values are physically stored separately).


Question:
I'm looking for good/working/simple to use PHP code for parsing raw email into parts.

I've written a couple of brute force solutions, but every time, one small change/header/space/something comes along and my whole parser fails and the project falls apart.

And before I get pointed at PEAR/PECL, I need actual code. My host has some screwy config or something, I can never seem to get the .so's to build right. If I do get the .so made, some difference in path/environment/php.ini doesn't always make it available (apache vs cron vs CLI).

Oh, and one last thing, I'm parsing the raw email text, NOT POP3, and NOT IMAP. It's being piped into the PHP script via a .qmail email redirect.

I'm not expecting SOF to write it for me, I'm looking for some tips/starting points on doing it "right". This is one of those "wheel" problems that I know has already been solved.

Answer:
What are you hoping to end up with at the end?  The body, the subject, the sender, an attachment?  You should spend some time with
RFC2822
to understand the format of the mail, but here's the simplest rules for well formed email:
```
```
HEADERS\n
\n
BODY
```
```
That is, the first blank line (double newline) is the separator between the HEADERS and the BODY.  A HEADER looks like this:
```
```
HSTRING:HTEXT
```
```
HSTRING always starts at the beginning of a line and doesn't contain any white space or colons.  HTEXT can contain a wide variety of text, including newlines as long as the newline char is followed by whitespace.
The "BODY" is really just any data that follows the first double newline.  (There are different rules if you are transmitting mail via SMTP, but processing it over a pipe you don't have to worry about that).
So, in really simple, circa-1982
RFC822
terms, an email looks like this:
```
```
HEADER: HEADER TEXT
HEADER: MORE HEADER TEXT
  INCLUDING A LINE CONTINUATION
HEADER: LAST HEADER

THIS IS ANY
ARBITRARY DATA
(FOR THE MOST PART)
```
```
Most modern email is more complex than that though.  Headers can be encoded for charsets or
RFC2047
mime words, or a ton of other stuff I'm not thinking of right now.  The bodies are really hard to roll your own code for these days to if you want them to be meaningful.  Almost all email that's generated by an MUA will be
MIME
encoded.  That might be uuencoded text, it might be html, it might be a uuencoded excel spreadsheet.
I hope this helps provide a framework for understanding some of the very elemental buckets of email.  If you provide more background on what you are trying to do with the data I (or someone else) might be able to provide better direction.


Question: I'm experimenting with creating an add-in for Infopath 2007. The documentation is very skimpy. What I'm trying to determine is what kind of actions an add-in can take while designing a form. Most of the discussion and samples are for when the user is filling out the form. Can I, for example, add a new field to the form in the designer? Add a new item to the schema? Move a form field on the design surface? It doesn't appear so, but I can't find anything definitive.

Answer:
What are you hoping to end up with at the end?  The body, the subject, the sender, an attachment?  You should spend some time with
RFC2822
to understand the format of the mail, but here's the simplest rules for well formed email:
```
```
HEADERS\n
\n
BODY
```
```
That is, the first blank line (double newline) is the separator between the HEADERS and the BODY.  A HEADER looks like this:
```
```
HSTRING:HTEXT
```
```
HSTRING always starts at the beginning of a line and doesn't contain any white space or colons.  HTEXT can contain a wide variety of text, including newlines as long as the newline char is followed by whitespace.
The "BODY" is really just any data that follows the first double newline.  (There are different rules if you are transmitting mail via SMTP, but processing it over a pipe you don't have to worry about that).
So, in really simple, circa-1982
RFC822
terms, an email looks like this:
```
```
HEADER: HEADER TEXT
HEADER: MORE HEADER TEXT
  INCLUDING A LINE CONTINUATION
HEADER: LAST HEADER

THIS IS ANY
ARBITRARY DATA
(FOR THE MOST PART)
```
```
Most modern email is more complex than that though.  Headers can be encoded for charsets or
RFC2047
mime words, or a ton of other stuff I'm not thinking of right now.  The bodies are really hard to roll your own code for these days to if you want them to be meaningful.  Almost all email that's generated by an MUA will be
MIME
encoded.  That might be uuencoded text, it might be html, it might be a uuencoded excel spreadsheet.
I hope this helps provide a framework for understanding some of the very elemental buckets of email.  If you provide more background on what you are trying to do with the data I (or someone else) might be able to provide better direction.


Question: Is it in best interests of the software development industry for one framework, browser or language to win the war and become the de facto standard?  On one side it takes away the challenges of cross platform, but it opens it up for a single point of failure.  Would it also result in a stagnation of innovation, or would it allow the industry to focus on more important things (whatever those might be).

Answer:
I believe whenever there is only 1 option, it will definitely stagnate innovation.  If all we had was 1 language, then we wouldn't be able to solve anything but what that language was designed to solve.
Imperative languages like Java and C# solve a certain set of problems pretty well, but it also helps to think in a functional manner sometimes, such as with Haskell and Lisp.
Furthermore, cross platform issues are not an issue if you are talking about a web application, because you control the hardware and software (note, I am talking of the server side code of course, the browser cross platform issue is separate).
Paul Graham wrote a
great essay
on how the Web lets you as a developer use the tool you think will solve the problem best.


Question:
I want to define something like this in php:

$EL = "\n<br />\n";

and then use that variable as an "endline" marker all over my site, like this:

echo "Blah blah blah{$EL}";

How do I define $EL once (in only 1 file), include it on every page on my site, and not have to reference it using the (strangely backwards) global $EL; statement in every page function?

Answer:
Most PHP sites should have a file (I call it a header) that you include on every single page of the site. If you put that first line of code in the header file, then include it like this on every page:
```
```
include 'header.php';
```
```
you won't have to use the global keyword or anything, the second line of code you wrote should work.
Edit: Oh sorry, that won't work inside functions... now I see your problem.
Edit #2: Ok, take my original advice with the header, but use a
define()
rather than a variable. Those work inside functions after being included.


Question:
I've frequently encountered sites that put all of their JavaScript inside a namespace structure along the lines of:

namespaces = { com : { example: { example.com's data} }

However, setting this up safely with respect to other namespaced frameworks seems to require a relatively hefty amount of code (defined as > 2 lines).  I was wondering whether anyone knows of a concise way to do this? Furthermore, whether there's a relatively standard/consistent way to structure it? For example, is the com namespace directly attached to the global object, or is it attached through a namespace object?

[Edit: whoops, obviously {com = { ... } } wouldn't accomplish anything close to what I intended, thanks to Shog9 for pointing that out.]

Answer:
Javascript doesn't have stand-alone namespaces. It has functions, which can provide scope for resolving names, and objects, which can contribute to the named data accessible in a given scope.
Here's your example, corrected:
```
```
var namespaces = { com: { example: { /* example.com's data */ } } }
```
```
This is a variable
```
namespaces
```
being assigned an object literal. The object contains one property:
```
com
```
, an object with one property:
```
example
```
, an object which presumably would contain something interesting.
So, you can type something like
namespaces.com.example.
somePropertyOrFunctionOnExample
and it'll all work. Of course, it's also ridiculous. You don't have a hierarchical namespace, you have an object containing an object containing an object with the stuff you actually care about.
```
```
var com_example_data = { /* example.com's data */ };
```
```
That works just as well, without the pointless hierarchy.
Now
, if you actually
want
to build a hierarchy, you can try something like this:
```
```
com_example = com_example || {};
com_example.flags = com_example.flags || { active: false, restricted: true};

com_example.ops = com_example.ops || (function()
    {
       var launchCodes = "38925491753824"; // hidden / private
       return {
         activate: function() { /* ... */ },
         destroyTheWorld: function() { /* ... */ }
       };
    })();
```
```
...which is, IMHO, reasonably concise.


Question:
Real strange.

I cannot find a tool that enables one to display a SVN repository in graphical form.

I would like the ability to see changes in revision / time , branch / time graphs.

Does anyone know of one. Ideally it would be platform neutral or even better web based.

Solutions offered so far in brief:

svn-graph

Fisheye ( you want how
much !£?* )

Answer:
Fisheye
, from Atlassian, looks at an SVN repository and can show you a few graphs. Also provides a handy web interface for blame, diff, etc.
for example, some sample images at
one of the demo servers:
And if you like some pretty code metrics,
here are some samples
.


Question: What's the difference between struct and class in .NET?

Answer:
Well, for starters, a struct is passed by value rather than by reference.  Structs are good for relatively simple data structures, while classes have a lot more flexibility from an architectural point of view via polymorphism and inheritance.
Others can probably give you more detail than I, but I use structs when the structure that I am going for is simple.


Question:
I'm looking for a clear, concise and accurate answer.

Ideally as the actual answer, although links to good explanations welcome.

Answer:
Boxing & unboxing is the process of converting a primitive value into an object oriented wrapper class (boxing), or converting a value from an object oriented wrapper class back to the primitive value (unboxing).
For example, in java, you may need to convert an
```
int
```
value into an
```
Integer
```
(boxing) if you want to store it in a
```
Collection
```
because primitives can't be stored in a
```
Collection
```
, only objects.  But when you want to get it back out of the
```
Collection
```
you may want to get the value as an
```
int
```
and not an
```
Integer
```
so you would unbox it.
Boxing and unboxing is not inherently
bad
, but it is a tradeoff.  Depending on the language implementation, it can be slower and more memory intensive than just using primitives.  However, it may also allow you to use higher level data structures and achieve greater flexibility in your code.
These days, it is most commonly discussed in the context of Java's (and other language's) "autoboxing/autounboxing" feature.  Here is a
java centric explanation of autoboxing
.


Question:
I'm looking for a clear, concise and accurate answer.

Ideally as the actual answer, although links to good explanations welcome.

This also applies to VB.Net, but the keywords are different - ByRef and ByVal.

Answer:
```
out
```
means that the parameter will be initialised by the method:
```
```
int result; //not initialised

if( int.TryParse( "123", out result ) )
   //result is now 123
else
   //if TryParse failed result has still be
   // initialised to its default value (0)
```
```
```
ref
```
will force the underlying reference to be passed:
```
```
void ChangeMyClass1( MyClass input ) {
   input.MyProperty = "changed by 1";
   input = null;
   //can't see input anymore ...
   // I've only nulled my local scope's reference
}

void ChangeMyClass2( ref MyClass input ) {
   input.MyProperty = "changed by 2";
   input = null;
   //the passed reference is now null too.
}

MyClass tester = new MyClass { MyProperty = "initial value" };

ChangeMyClass1( tester );
// now tester.MyProperty is "changed by 1"

ChangeMyClass2( ref tester );
// now tester is null
```
```


Question: I've just started working on an ASP.NET project which I hope to open source once it gets to a suitable stage. It's basically going to be a library that can be used by existing websites. My preference is to support ASP.NET 2.0 through 3.5, but I wondered how many people I would be leaving out by not supporting ASP.NET 1.1? More specifically, how many people are there still using ASP.NET 1.1 for whom ASP.NET 2.0/3.5 is not an option? If upgrading your server is not an option for you, why not?

Answer:
Increasingly I think not.
The kind of large rigid organisation currently still clinging to 1.1 (probably because they're only just upgraded to it) is also the kind that's highly unlikely to look at open source solutions.
If I were starting a new ASP.Net project right now I'd stick with .Net 3.5 and probably the new MVC previews.


Question:
In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:

// the following results in an error:
echo array('a','b','c')[$key];

// this works, using an unnecessary variable:
$variable = array('a','b','c');
echo $variable[$key];

This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;)

Answer:
I wouldn't bother about that extra variable, really. If you want, though, you could also remove it from memory after you've used it:
```
```
$variable = array('a','b','c');
echo $variable[$key];
unset($variable);
```
```
Or, you could write a small function:
```
```
function indexonce(&$ar, $index) {
  return $ar[$index];
}
```
```
and call this with:
```
```
$something = indexonce(array('a', 'b', 'c'), 2);
```
```
The array should be destroyed automatically now.


Question:
From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows:

// Make sure the thread is done stopping
while (this.mThread.ThreadState == ThreadState.Running)
{
    Thread.Sleep(0);
}
// Respawn a thread if the current one is stopped or doesn't exist
if (this.mThread == null || this.mThread.ThreadState == ThreadState.Stopped)
{
    this.mThread = new Thread(new ParameterizedThreadStart(Monitor)); }
// Start the thread
if (check)
{
    this.mThread.Start(60000);
}
else
{
    this.mThread.Start(0);
}

So two questions - is this the correct way of doing things, and  it is, is there a way to prevent the error from occurring?

Answer:
A ThreadStateException is thrown because you're trying to start a thread that's not in a startable state. The most likely situations would be that it's already running, or that it has fully exited.
There are potentially a couple things that might be happening. First is, the thread might have transitioned from Running to StopRequested, which isn't fully stopped yet, so your logic doesn't create a new thread, and you're trying to start a thread which has just finished running or is about to finish running (neither of which is a valid state for restarting).
The other possibility is that the thread was aborted. Threads which are aborted go to the Aborted state, not the Stopped state, and of course are also not valid for restarting.
Really, the only kind of thread that is still alive that can be "restarted" is one that's suspended. You might want to use this conditional instead:
```
if (this.mThread == null || this.mThread.ThreadState != ThreadState.Suspended)
```


Question:
I've included a mobile web form in my asp.net project, I thought that it could/should be seen just for my mobile users but I realize that it can also be seen from any browser, I don't see problem there cause I could diff the access using HttpBrowserCapabilities.IsMobileDevice=true and transferring to the appropiate aspx page, but it results that when I access to the web form from my mobile device it is identified as IsMobileDevice = false and sends me to another page.

How could it be possible that?

The mobile device runs Pocket PC 2003.

Answer: Some are not recognized, because the UserAgent has been messed with or a new browser is being used. Such as Opera Mobile 9.5.  To fix this you need to create a Browser (*.browser) file specifically for defining this.  I had to do it for the new Mozilla based UserAgent that is being sent from Google.


Question:
I love list comprehensions in Python, because they concisely represent a transformation of a list.

However, in other languages, I frequently find myself writing something along the lines of:

foreach (int x in intArray)
  if (x > 3) //generic condition on x
    x++
    //do other processing

This example is in C#, where I'm under the impression LINQ can help with this, but is there some common programming construct which can replace this slightly less-than-elegant solution?  Perhaps a data structure I'm not considering?

Answer:
Depends on the language and what you need to do, a "map" as it's called in many languages could be what you're looking for. I don't know C#, but according to
this
page, .NET 2.0 calls map "ConvertAll".
The meaning of "map" is pretty simple - take a list, and apply a function to each element of it, returning a new list. You may also be looking for "filter", which would give you a list of items that satisfy a predicate in another list.


Question: I'm new to development (an admin by trade) and I'm setting up my development environment and I would like to set up a CruiseControl.Net server on Server 2008.  A quick Google did not turn up any instructions for getting it running on IIS 7.0, so I was wondering if anyone had experience getting this set up.

Answer:
I have never tried on Server 2008, but I have installed CruiseControl.NET on Vista which includes IIS 7.0.  I don't remember there being any problems.  You do have an admin background which should help if something does pop up.
Just use the
CruiseControl.NET wiki
to get you thru the install and getting it setup.  That is all I did.


Question: How can I get programmatic access to the call stack?

Answer:
Try
System.Diagnostics.StackTrace
.


Question:
I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:

cleaned = stringwithslashes
cleaned = cleaned.replace('\\n', '\n')
cleaned = cleaned.replace('\\r', '\n')
cleaned = cleaned.replace('\\', '')

How can I condense it?

Answer:
You can obviously concatenate everything together:
```
```
cleaned = stringwithslashes.replace("\\n","\n").replace("\\r","\n").replace("\\","")
```
```
Is that what you were after? Or were you hoping for something more terse?


Question: I've tried using source control for a couple projects but still don't really understand it.  For these projects, we've used TortoiseSVN and have only had one line of revisions.  (No trunk, branch, or any of that.)  If there is a recommended way to set up source control systems, what are they?  What are the reasons and benifits for setting it up that way?  What is the underlying differences between the workings of a centralized and distributed source control system?

Answer:
Think of source control as a giant "Undo" button for your source code. Every time you check in, you're adding a point to which you can roll back. Even if you don't use branching/merging, this feature alone can be very valuable.
Additionally, by having one 'authoritative' version of the source control, it becomes much easier to back up.
Centralized vs. distributed... the difference is really that in distributed, there isn't necessarily one 'authoritative' version of the source control, although in practice people usually still do have the master tree.
The big advantage to distributed source control is two-fold:
When you use distributed source control, you have the whole source tree on your local machine. You can commit, create branches, and work pretty much as though you were all alone, and then when you're ready to push up your changes, you can promote them from your machine to the master copy. If you're working "offline" a lot, this can be a huge benefit.
You don't have to ask anybody's permission to become a distributor of the source control. If person A is running the project, but person B and C want to make changes, and share those changes with each other, it becomes much easier with distributed source control.


Question:
I'm looking for a pre-written component (w/source) for a Delphi project that I'm working on, to generate mind-maps / concept-maps similar to these:

http://en.wikipedia.org/wiki/Image:MindMeister_screenshot_OS_X.jpg
http://en.wikipedia.org/wiki/Image:XMIND_2008_in_Windows_Vista.png

Any ideas?

Answer:
As a former Delphi developer, I sympathize.  It used to be that you could find a free component with source for just about anything.  You probably know about the
Delphi Super Page
(my old go-to source for everything Delphi).  I looked; no mind-mapping components, there.  (Of course, the site has not been updated in about 2 years).
I do have a suggestion, though, but it's not optimal:
StarUML
was written in Delphi, and it contains custom components for creating UML diagrams.  The source is available for download, and it seems to me that the UML primitives (boxes, lines, clouds and such) could be adapted to your purpose.  The web site is
http://staruml.sourceforge.net/en/
.
I know it's not ideal, but at least you would not have to start from scratch.
Good luck!


Question:
I've heard of the idea of bootstrapping a language, that is, writing a compiler/interpreter for the language in itself.  I was wondering how this could be accomplished and looked around a bit, and saw someone say that it could only be done by either

writing an initial compiler in a different language.

hand-coding an initial compiler in Assembly, which seems like a special case of the first

To me, neither of these seem to actually be bootstrapping a language in the sense that they both require outside support.  Is there a way to actually write a compiler in its own language?

Answer:
The way I've heard of is to write an extremely limited compiler in another language, then use that to compile a more complicated version, written in the new language. This second version can then be used to compile itself, and the next version. Each time it is compiled the last version is used.
This is the definition of
bootstrapping:
the process of a simple system activating a more complicated system that serves the same purpose.
EDIT: The
Wikipedia article on compiler bootstrapping
covers the concept better than me.


Question:
I've written a stored proc that will do an update if a record exists, otherwise it will do an insert. It looks something like this:

update myTable set Col1=@col1, Col2=@col2 where ID=@ID
if @@rowcount = 0
insert into myTable (Col1, Col2) values (@col1, @col2)

My logic behind writing it in this way is that the update will perform an implicit select using the where clause and if that returns 0 then the insert will take place.

The alternative to doing it this way would be to do a select and then based on the number of rows returned either do an update or insert. This I considered inefficient because if you are to do an update it will cause 2 selects (the first explicit select call and the second implicit in the where of the update). If the proc were to do an insert then there'd be no difference in efficiency.

Is my logic sound here?
Is this how you would combine an insert and update into a stored proc?

Answer:
Your assumption is right, this is the optimal way to do it and it's called
upsert/merge
.
Importance of UPSERT - from sqlservercentral.com
:
For every update in the case mentioned above we are removing one
  additional read from the table if we
  use the UPSERT instead of EXISTS.
  Unfortunately for an Insert, both the
  UPSERT and IF EXISTS methods use the
  same number of reads on the table.
  Therefore the check for existence
  should only be done when there is a
  very valid reason to justify the
  additional I/O. The optimized way to
  do things is to make sure that you
  have little reads as possible on the
  DB.
The best strategy is to attempt the
  update. If no rows are affected by the
  update then insert. In most
  circumstances, the row will already
  exist and only one I/O will be
  required.
Edit
:
Please check out
this answer
and the linked blog post to learn about the problems with this pattern and how to make it work safe.


Question:
In our place we're split between using mysqli and PDO for stuff like prepared statements and transaction support. Some projects use one, some the other. There is little realistic likelihood of us ever moving to another RDBMS.

I prefer PDO for the single reason that it allows named parameters for prepared statements, and as far as I am aware mysqli does not.

Are there any other pros and cons to choosing one over the other as a standard as we consolidate our projects to use just one approach?

Answer:
Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you're at home with PDO then there will at least be one thing less to learn at that point.
Apart from that I find the PDO API a little more intuitive, and it feels more truly object oriented. mysqli feels like it is just a procedural API that has been objectified, if you know what I mean. In short, I find PDO easier to work with, but that is of course subjective.


Question:
If there are any language designers out there (or people simply in the know), I'm curious about the methodology behind creating standard libraries for interpreted languages. Specifically, what seems to be the best approach? Defining standard functions/methods in the interpreted language, or performing the processing of those calls in the compiled language in which the interpreter is written?

What got me to thinking about this was the SO question about a stripslashes()-like function in Python. My first thought was "why not define your own and just call it when you need it", but it raised the question: is it preferable, for such a function, to let the interpreted language handle that overhead, or would it be better to write an extension and leverage the compiled language behind the interpreter?

Answer:
The line between "interpreted" and "compiled" languages is really fuzzy these days. For example, the first thing Python does when it sees source code is compile it into a bytecode representation, essentially the same as what Java does when compiling class files. This is what *.pyc files contain. Then, the python runtime executes the bytecode without referring to the original source. Traditionally, a purely interpreted language would refer to the source code continuously when executing the program.
When building a language, it is a good approach to build a solid foundation on which you can implement the higher level functions. If you've got a solid, fast string handling system, then the language designer can (and should) implement something like stripslashes() outside the base runtime. This is done for at least a few reasons:
The language designer can show that the language is flexible enough to handle that kind of task.
The language designer actually writes real code in the language, which has tests and therefore shows that the foundation is solid.
Other people can more easily read, borrow, and even change the higher level function without having to be able to build or even understand the language core.
Just because a language like Python compiles to bytecode and executes that doesn't mean it is slow. There's no reason why somebody couldn't write a Just-In-Time (JIT) compiler for Python, along the lines of what Java and .NET already do, to further increase the performance. In fact, IronPython compiles Python directly to .NET bytecode, which is then run using the .NET system including the JIT.
To answer your question directly, the only time a language designer would implement a function in the language behind the runtime (eg. C in the case of Python) would be to maximise the performance of that function. This is why modules such as the regular expression parser are written in C rather than native Python. On the other hand, a module like getopt.py is implemented in pure Python because it can all be done there and there's no benefit to using the corresponding C library.


Question:
Does anyone know how to transform a enum value to a human readable value?

For example:

ThisIsValueA should be "This is Value A".

Answer:
Most examples of this that I've seen involve marking your enum values up with [Description] attributes and using reflection to do the "conversion" between the value and the description. Here's an old blog post about it:
<
Link
>


Question:
I need to validate an integer to know if is a valid enum value.

What is the best way to do this in C#?

Answer:
Brad Abrams specifically warns against
```
Enum.IsDefined
```
in his post
The Danger of Oversimplification
.
The best way to get rid of this requirement (that is, the need to validate enums) is to remove ways where users can get it wrong, e.g., an input box of some sort. Use enums with drop downs, for example, to enforce only valid enums.


Question:
(assume php5) consider

<?php

    $foo = 'some words';

    //case 1
    print "these are $foo";

    //case 2
    print "these are {$foo}";

    //case 3
    print 'these are ' . $foo;
?>

Is there much of a difference between 1 and 2?

If not, what about between 1/2 and 3?

Answer:
Well, as with all "What might be faster in real life" questions, you can't beat a real life test.
```
```
function timeFunc($function, $runs)
{
  $times = array();

  for ($i = 0; $i < $runs; $i++)
  {
    $time = microtime();
    call_user_func($function);
    $times[$i] = microtime() - $time;
  }

  return array_sum($times) / $runs;
}

function Method1()
{
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are $foo";
}

function Method2()
{
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are {$foo}";
}

function Method3()
 {
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = "these are " . $foo;
}

print timeFunc('Method1', 10) . "\n";
print timeFunc('Method2', 10) . "\n";
print timeFunc('Method3', 10) . "\n";
```
```
Give it a few runs to page everything in, then...
0.0035568
0.0035388
0.0025394
So, as expected, the interpolation are virtually identical (noise level differences, probably due to the extra characters the interpolation engine needs to handle). Straight up concatenation is about 66% of the speed, which is no great shock. The interpolation parser will look, find nothing to do, then finish with a simple internal string concat. Even if the concat were expensive, the interpolator will still have to do it,
after
all the work to parse out the variable and trim/copy up the original string.
Updates By Somnath:
I added Method4() to above real time logic.
```
```
function Method4()
 {
  $foo = 'some words';
  for ($i = 0; $i < 10000; $i++)
    $t = 'these are ' . $foo;
}

print timeFunc('Method4', 10) . "\n";

Results were:

0.0014739
0.0015574
0.0011955
0.001169
```
```
When you are just declaring a string only and no need to parse that string too, then why to confuse PHP debugger to parse. I hope you got my point.


Question: Is it possible in .NET to list files on a remote location like an URL? Much in the same way the System.IO classes work. All I need is the URLs to images that are on a remote server.

Answer:
Short answer:
No, unless you have more control over that web-server
Long answer:
Here are possible solutions...
You will need server-side script that will do it locally and output this list in your preferred format.
Most of the web-servers implement default file-browsing pages, so you could theoretically parse those but this solution will be very fragile and not very portable even between different versions of the same web-server.
If you have FTP access...


Question:
I've seen it mentioned in many blogs around the net, but I believe it shoud be discussed here.
What can we do when we have an MVC framework (I am interested in ZEND) in PHP but our host does not provide mod_rewrite?
Are there any "short-cuts"? Can we transfer control in any way (so that a mapping may occur between pages)? Any ideas?
Thank you :-)

Answer:
mod_rewrite is almost essential in today's hosting environment..but unfortunately not everyone got the message.
Lots of the large php programs (I'm thinking magento, but most can cope) have a pretty-url fall back mode for when mod_rewrite isn't available.
URLs end up looking like www.site.com/index.php?load-this-page
They must be running some magic to grab the variable name from the $_GET variable and using it as the selector for what module/feature to execute.
In a related note, I've seen lots of messed up URLs in the new facebook site where it's using the #.  So links look like www.new.facebook.com/home.php#/inbox/  Clearly we're not meant to see that but it suggests that they're probably parsing the $_SERVER['REQUEST_URI'] variable.


Question:
ASP.NET MVC has been discussed on this forum a few times. I'm about to do a large migration of several websites from classic ASP/ASP.NET WebForms to ASP.NET MVC and was wondering what kind of advice those of you with experience in both technologies have.

What I have: a typical ASP.NET app with heavily coupled presentation/business logic, all sorts of messy ASP.NET-generated Javascript cruft, and so forth.

What I want: clean ASP.NET MVC-generated agnostic markup. 'Nuff said.

Any pointers, tips, tricks, or gotchas to be aware of?

Thanks!

Answer:
Wow, I'm not sure we're talking migration here anymore - the difference is more like re-writing!
As others have also said, MVC is a whole new way to build web apps - most of your presentation code won't carry across.
However, if you are re-writing in MVC what you already have is a good prototype. Your problem is likely to be that it would be hard to do bit by bit - for instance MVC uses URL renaming out-of-the-box, making linking back and forth rather messy.
Another question would be why? Many of us have big sprawling legacy applications that we'd like to be in the latest technologies, but if your application is already working why switch?
If I was looking at a new application right now MVC would be a very strong candidate, but there's no gain large enough to switching to it late in a project.


Question:
NSInteger/NSUInteger are Cocoa-defined replacements for the regular built-in types.

Is there any benefit to using the NS* types over the built-ins? Which do you prefer and why? Are NSInteger and int the same width on 32-bit / 64-bit platforms?

Answer:
64-bit is actually the raison d'être for NSInteger and NSUInteger; before 10.5, those did not exist. The two are simply defined as longs in 64-bit, and as ints in 32-bit:
```
```
#if __LP64__ || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
```
```
Thus, using them in place of the more basic C types when you want the 'bit-native' size.
CocoaDev has some more info.


Question: How can I permanently enable line numbers in IntelliJ IDEA?

Answer:
IntelliJ 14.X Onwards
From version 14.0 onwards, the path to the setting dialog is slightly different, a
General
submenu has been added between
Editor
and
Appearance
as shown below
IntelliJ 8.1.2 - 13.X
From IntelliJ 8.1.2 onwards, this option is in
File | Settings
1
. Within the
IDE Settings
section of that dialog, you'll find it under
Editor | Appearance.
On a Mac, these are named
IntelliJ IDEA | Preferences...


Question:
So I'm not quite convinced about OpenID yet, and here is why:

I already have an OpenID because I have a Blogger account. But I discovered that Blogger seems to be a poor provider when I tried to identify myself on the altdotnet page and recieved the following message:

You must use an OpenID persona that specifies a valid email address.

Lets forget the details of this little error and assume that I want to change to a different provider. So I sign up with a different provider and get a new, different OpenID - how would I switch my existing StackOverflow account to be associated with my new OpenID?

I understand this would be easy if I had my own domain set up to delegate to a provider, because I could just change the delegation. Assume I do not have my own domain.

Answer:
Ideally Stack Overflow would allow you to change your OpenID.
OTOH, ideally you would have set up
OpenID delegation
on your own site, and used that to identify yourself.
With delegation, you would need only change which service you delegate to. You'd still be identified by your own URL that you control. But that doesn't help now unless Stack Overflow lets you change it. Most sites tie OpenIDs to real accounts, and would let you switch or at least add additional OpenIDs. Doesn't seem like you could map OpenIDs to accounts 1:1 unless the result of access is totally trivial; otherwise you're in a situation like this where you lose your existing questions, answers, and reputation for switching IDs.


Question: Are we supposed to find workarounds in our web applications so that they will work in every situation? Is it time to do away with IE6 programming?

Answer:
I recommend people check their own user stats for their site before making this decision, but here's a common reference regarding popular browser versions :
http://www.w3schools.com/browsers/browsers_stats.asp


Question:
I am trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...

>>> import re
>>> mystring = r"This is \n a test \r"
>>> p = re.compile( "\\\\(\\S)" )
>>> p.sub( "\\1", mystring )
'This is n a test r'
>>> p.sub( "\\\\\\1", mystring )
'This is \\n a test \\r'
>>> p.sub( "\\\\1", mystring )
'This is \\1 a test \\1'

I'd like to replace \\[char] with \[char], but backreferences in Python don't appear to follow the same rules they do in every other implementation I've ever used. Could someone shed some light?

Answer:
Well, I think you might have missed the r or miscounted the backslashes...
```
```
"\\n" == r"\n"

>>> import re
>>> mystring = r"This is \\n a test \\r"
>>> p = re.compile( r"[\\][\\](.)" )
>>> print p.sub( r"\\\1", mystring )
This is \n a test \r
>>>
```
```
Which, if I understood is what was requested.
I suspect the more common request is this:
```
```
>>> d = {'n':'\n', 'r':'\r', 'f':'\f'}
>>> p = re.compile(r"[\\]([nrfv])")
>>> print p.sub(lambda mo: d[mo.group(1)], mystring)
This is \
 a test \
>>>
```
```
The interested student should also read Ken Thompson's
Reflections on Trusting Trust"
, wherein our hero uses a similar example to explain the perils of trusting compilers you haven't bootstrapped from machine code yourself.


Question:
I am trying to snoop on a log file that an application is writing to.

I have successfully hooked createfile with the detours library from MSR, but createfile never seems to be called with file I am interested in snooping on.  I have also tried hooking openfile with the same results.

I am not an experienced Windows/C++ programmer, so my initial two thoughts were either that the application calls createfile before I hook the apis, or that there is some other API for creating files/obtaining handles for them.

Answer:
Here's a link which might be of use:
Guerilla-Style File Monitoring with C# and C++
It is possible to create a file without touching CreateFile API but can I ask
what DLL injection method you're using
? If you're using something like Windows Hooks your DLL won't be installed until sometime after the target application initializes and you'll miss early calls to CreateFile. Whereas if you're using something like DetourCreateProcessWithDll your CreateFile hook can be installed prior to any of the application startup code running.
In my experience 99.9% of created/opened files result in a call to CreateFile, including files opened through C and C++ libs, third-party libs, etc. Maybe there are some undocumented DDK functions which don't route through CreateFile, but for a typical log file, I doubt it.


Question: I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible.  I'm looking for a simple explanation that might help me understand where and why I would want to use them.

Answer:
It's simple: A function that references variables from a containing scope, potentially after flow-of-control has left that scope. That last bit is very useful:
```
```
>>> def makeConstantAdder(x):
...     constant = x
...     def adder(y):
...         return y + constant
...     return adder
...
>>> f = makeConstantAdder(12)
>>> f(3)
15
>>> g = makeConstantAdder(4)
>>> g(3)
7
```
```
Note that 12 and 4 have "disappeared" inside f and g, respectively, this feature is what make f and g proper closures.