Question:
We are using trac and are really satisfied with it. However, out of the box, trac is best suited for single-project environments only. I'd be interested to hear about the various approaches people take to make it work with multiple projects nevertheless and their experiences with them. Are there any plugins to recommend? Any patches, tweaks or whatnots? Are you maybe even using an entirely different bug-tracking system that offers all of trac's functionality plus multi-project support?

We recently started managing a second project ourselves which generally works okay but also has some drawbacks, especially where the two projects overlap because of common library code we wrote that is used in both projects. How do you handle this?

(I'll attach our own current approach as an answer to this post.)

Answer:
The approach we took is to create another trac environment for each new project and set up
InterTrac
links for simpler cross-referencing between the two. We also use a common base
Trac.ini
file via the [inherit] directive.
Besides the ambiguity issues with shared code mentioned in the question, this has a couple of drawbacks that may or may not affect you, depending on the nature of your projects and your workflow:
creating new projects is not an easy process; it can not be done via the browser interface
ticket numbers are not unified: each new project environment starts fresh from #1 - at least with InterTrac aliases you can easily disambiguate them
you have to take extra care when installing and configuring plugins so they will be installed and configured for all environments


Question: In Delphi 2009 whereabouts do you turn on the option to treat warnings as errors?

Answer:
Just found the answer soon after I posted this!  Might be useful for other people.
Navigate to '
```
Project -> Options - > Delphi Compiler -> Hints and Warnings
```
' and change the value of '
```
Output Warnings
```
' to '
```
as errors
```
'
I was looking for an option similar to what Visual Studio has


Question:
Looking at System.Collections.Generic.Dictionary<TKey, TValue>, it clearly implements ICollection<KeyValuePair<TKey, TValue>>, but doesn't have the required "void Add(KeyValuePair<TKey, TValue> item)" function.

This can also be seen when trying to initialize a Dictionary like this:

private const Dictionary<string, int> PropertyIDs = new Dictionary<string, int>()
{
    new KeyValuePair<string,int>("muh", 2)
};

which fails with

No overload for method 'Add' takes '1' arguments

Why is that so?

Answer:
The expected API is to add via the two argument
```
Add(key,value)
```
method (or the
```
this[key]
```
indexer); as such, it uses explicit interface implementation to provide the
```
Add(KeyValuePair<,>)
```
method.
If you use the
```
IDictionary<string, int>
```
interface instead, you will have access to the missing method (since you can't hide anything on an interface).
Also, with the collection initializer, note that you can use the alternative syntax:
```
```
Dictionary<string, int> PropertyIDs = new Dictionary<string, int> {
  {"abc",1}, {"def",2}, {"ghi",3}
}
```
```
which uses the
```
Add(key,value)
```
method.


Question:
I have been trying to include a file in a included file e.g

main.cpp file

#include <includedfile.cpp>
int main(){
     cout<<name<<endl;
}

includedfile.cpp

#include <iostream>
using namespace std;
string name;
name = "jim";

this code does not work, the debuger says that name is not defined.

Answer:
You cannot have statements exist outside of a method!
```
```
name = "jim"; // This is outside of any method, so it is an error.
```
```
You could refactor your code so the variable declaration is also an initial assignment, which should be valid (my C++ is a bit rusty, so I might be wrong on this point).
```
```
string name = "jim";
```
```


Question:
I have 3 lists, I will make them simple here.

list of letters

A

B

C

list of numbers

1

2

3

Mixed

A,1

A,2

B,2

B,3

C,1

C,3

I need to know what is missing:

A,3

B,1

C,2

The list of letters has about 85 entries

and the list of numbers has about 500 entries.

The mixed list has about 75,000 entries.

I can use either a database query (mysql 5.0) or Turbo Delphi 2006 to process text files. What would be the best way to find what is missing?

Thanks,

  Dave

Answer:
A cross join would produce every combination there is, given that you have both of your lists in SQL tables:
```
```
SELECT
  Letter + ',' + Number AS Combination
FROM
  NumberList,
  LetterList
```
```
Using the combined result (maybe save it into a temporary table), you can use a NOT EXISTS query to find what is missing:
```
```
SELECT
  Combination
FROM
  AllCombinations AS a
WHERE
  NOT EXISTS
  (SELECT 1 FROM MyCombitations AS m WHERE m.Combination = a.Combination)
```
```
This would require a table
```
MyCombitations
```
, which lists all of the combinations you actually have and want to check against the full list.
If you want to speed things up, you should use a permanent table of combinations and an index on the
```
MyCombitations.Combination
```
field. For repeated querying this is definitely advisable.


Question:
In a table I have the following schema

table1:
playerID int primary key,
nationalities nvarchar

table2:
playerID int,
pubVisited nvarchar

Now, I want to set all the players' playedVisited to null, for player whose nationality is "England", any idea on how to do this?

Answer:
Judging by the
nvarchar
type, you're using MSSQL. Now, in MySQL you could use a subselect in the update .. where clause but MSSQL has its own update .. from clause:
```
```
UPDATE table2
SET
    table2.pubVisited = null
FROM table1
WHERE
    table2.playerID = table1.playerID and table1.nationalities = 'England'
```
```
Haven't tested it though, so it might not work.


Question:
SELECT `name` , COUNT(*) AS `count`
FROM `t1`, `t2`
WHERE `t2`.`id` = `t1`.`id`
GROUP BY `t2`.`id`

I want to obtain the name from t1 and the number of rows in t2 where the id is the same as on t1.

I've got the above so far, however it won't return any data if there are no rows in t2 that match. I'd prefer count to be 0 (or NULL) if there are no rows, and the name still returns.

Edit: I'd like to be able to sort by the count descending. (or name ASC) is that possible?

Answer:
Do a union to get the other set
```
```
SELECT `name` , COUNT(*) AS `count`
FROM `t1`, `t2`
WHERE `t2`.`id` = `t1`.`id`
GROUP BY `t2`.`id`
UNION
Select name, 0 as count
from t1
where NOT EXISTS (select 1 from t2 where `t2`.`id` = `t1`.`id`)
```
```


Question:
I have the following code block in my xslt;

      <xsl:when test="StatusData/Status/Temperature > 27">
        <td bgcolor="#ffaaaa">
          <xsl:value-of select="StatusData/Status/Temperature" />
        </td>
      </xsl:when>

But as you might guess when the value is 34,5 instead of 34.5 it is recognised as a string which makes integer comparison not possible. I thought replacing , with . would be solution that needs a char replace. My question is how I can do this
or
It would be great to know more about string operations in XSLT...

Answer:
There is a
```
translate()
```
function in XPath:
```
```
test="translate(StatusData/Status/Temperature, ",", ".") > 27"
```
```
Additionally you should make use of the number function, which converts it's argument to a number (or NaN, if that fails):
```
```
test="number(translate(StatusData/Status/Temperature, ",", ".")) > 27.0"
```
```
See the
documentation for
```
translate()
```
and the
documentation for
```
number()
```
at w3.org.


Question:
I am having an string like this

string str = "dfdsfdsf8fdfdfd9dfdfd4"

I need to check whether the string contains number by looping through the array.

Answer:
What about a regular expression:
```
```
bool val = System.Text.RegularExpressions.Regex.IsMatch(str, @"\d");
```
```


Question:
Ok guys and gals, here is my problem:

I've built a custom control that uses a textbox to present data to the user.

When the user interacts with the control the value of that textbox is altered with client side javascript.

I also have a button on my page. When the user clicks the button I want to take the value from the custom control (aka. the textbox) and use it elsewhere.

So, in the onClick event for the button I do something like this:

this.myLabel.Text = this.customControl.Value;

The problem is that the custom control does not have the new textbox value available. In the custom control the textbox is empty. However, I can see the correct value in the Request.Form collection.

Am I doing something wrong here? Or should I be reading from Request.Form?!

Answer:
Ah ha! I've solved my own problem!
Because I had set Readonly="True" on the textbox control ASP.NET was not picking up it's value from the postback.
Instead I should have manually added the readonly attribute to the textbox during my user control construction.
eg.
```
```
this.textBox.Attributes.Add("readonly", "readonly");
```
```


Question:
In IIS I can configure my custom error pages.

For each HTTP Error code I can say where to go. Several codes have a number of "sub" codes available. For example 404 has a regular 404, 404;1, 404;2 and so on..

What are they for? When are they returned? Should I make custom pages for these errors? Can I somehow easely configure all code "families" to come to the same page?

Answer:
401 - Access denied. IIS defines several different 401 errors that indicate
a more specific cause of the error
. These specific error codes are displayed in the browser but are not displayed in the IIS log:
401.1 - Logon failed.
401.2 - Logon failed due to server configuration.
401.3 - Unauthorized due to ACL on resource.
401.4 - Authorization failed by filter.
401.5 - Authorization failed by ISAPI/CGI application.
401.7 – Access denied by URL authorization policy on the Web server (This error code is specific to IIS 6.0.)
Here is the
complete list
in the MSDN documentation for
IIS 5.0 and 6.0
and for
IIS 7.0, 7.5 and 8.0
.
If you want to show your visitors or users a nice custom message depending on these subcode, you could do it. But you needn't.


Question:
I'd like to hear what is the motivation behind the bulk of sealed classes in the .Net framework. What is the benefit of sealing a class? I cannot fathom how not allowing inheritance can be useful and most likely not the only one fighting these classes.

So, why is the framework designed this way and wouldn't it be unbreaking change to unseal everything? There must be another reason than just being evil?

Answer:
Sometimes classes are too precious and not designed to be inherited.
Runtime/Reflection can make inheritance assumptions about sealed classes when looking for types. A great example of this is - Attributes are recommended to be sealed for lookup runtime speed. type.GetCustomAttributes(typeof(MyAttribute)) will perform significantly faster if MyAttribute is sealed.
The MSDN article for this topic is
Limiting Extensibility by Sealing Classes
.


Question:
Any code can be reused in a way or an other, at least if you modify the code. Random code is not very reusable as such. When I read some books, they usually say that you should explicitly make the code reusable by taking into account other situations of code usage too. But certain code should not be an omnipotent all doing class either.

I would like to have reusable code that I don't have to change later. How do you make code reusable? What are the requirements for code being reusable? What are the things that reusable code should definitely have and what things are optional?

Answer:
See
10 tips on writing reusable code
for some help.
Keep the code DRY. Dry means "Don't Repeat Yourself".
Make a class/method do just one thing.
Write unit tests for your classes AND make it easy to test classes.
Remove the business logic or main code away from any framework code
Try to think more abstractly and use Interfaces and Abstract classes.
Code for extension. Write code that can easily be extended in the future.
Don't write code that isn't needed.
Try to reduce coupling.
Be more Modular
Write code like your code is an External API


Question:
I have a written a Visual C++ console application (i.e. subsystem:console) that prints useful diagnositic messages to the console.

However, I would like to keep the application minimized most of the time, and instead of minimizing to the taskbar, appear as a nice icon on the system tray. I would also like to restore the console when the system tray icon is clicked.

How should I change my program to do this?

Answer:
This is going to be an ugly hack.
First, you have to retrieve the
```
hWnd
```
/
```
hInstance
```
of you console application. Right now, I can only come up with one way:
Create a Guid with
```
CoCreateGuid()
```
Convert it to a string
Set the title of the console window to this guid with
```
SetConsoleTitle()
```
Find the
```
hWnd
```
of the your window with the Guid as the tile with
```
FindWindow()
```
And you can do it from the usual way from this point.
See http://www.gidforums.com/t-9218.html for more info.
Don't forget the rename your console window to the original title once you're done.
As you can see, even though this is possible to do, it's a horrible and painful solution. Please don't do it. Please do not minimize console applications to the system tray.
It is not something you are supposed to be able to do in the Windows API.


Question:
I have a dictionary where keys are strings, and values are integers.

stats = {'a': 1, 'b': 3000, 'c': 0}

How do I get the key with the maximum value? In this case, it is 'b'.

Is there a nicer approach than using an intermediate list with reversed key-value tuples?

inverse = [(value, key) for key, value in stats.items()]
print(max(inverse)[1])

Answer:
You can use
```
operator.itemgetter
```
for that:
```
```
import operator
stats = {'a': 1000, 'b': 3000, 'c': 100}
max(stats.iteritems(), key=operator.itemgetter(1))[0]
```
```
And instead of building a new list in memory use
```
stats.iteritems()
```
. The
```
key
```
parameter to the
```
max()
```
function is a function that computes a key that is used to determine how to rank items.
Please note that if you were to have another key-value pair 'd': 3000 that this method will only return
one
of the
two
even though they both have the maximum value.
```
```
>>> import operator
>>> stats = {'a': 1000, 'b': 3000, 'c': 100, 'd': 3000}
>>> max(stats.iteritems(), key=operator.itemgetter(1))[0]
'b'
```
```
If using Python3:
```
```
>>> max(stats.items(), key=operator.itemgetter(1))[0]
'b'
```
```


Question:
I have a Nant build script which CruiseControl uses to build a solution on-demand.

However, we only recently got CruiseControl so our official build number is different from what is listed in CruiseControl.

I know CruiseControl injects some properties into build scripts so that I can access the CC build number in the script (CCNetLabel) but how do I pass a value back to CC to use as the build number on the UI screen?

Example, CC says build number 2

nAnt script increments a buildnumber.xml value every build, and the official build number is on 123.

I want the CC UI to show last successful build number: 123, not 2, so how do I pass that value back up?

Answer:
Did you try to use some environment variables? I believe CCNet can handle these.
I'll dig a bit on this.
Well I see a solution, quite dirty, but anyhow:
1- Add a
defaultlabeller
section in your CCNET project definition. It will contains the pattern of the build number you want to display.
2- Within NAnt, have a script to update your configuration file, inserting the build number you want to see.
3- Touch (in the Unix sense) the ccnet.exe.config file so as to make it re-load the projects configuration files.
et voilà.


Question:
I've become very comfortable in the world of pointer-free, garbage-collected programming languages. Now I have to write a small Mac component. I've been learning Objective-C, but as I confront the possibility of dangling pointers and the need to manage retain counts, I feel disheartened.

I know that Objective-C now has garbage collection but this only works with Leopard. My component must work with Tiger, too.

I need to access some Cocoa libraries not available to Java, so that rules out my usual weapon of choice.

What are my alternatives? Especially with no explicit pointers and automatic garbage collection.

Answer:
Look at
Python
and
wxPython
(the wxWidgets in Python).
The wxWidgets have a very elegant App-Doc-View application design pattern that's very, very nice.  It's not used enough, IMO.  I haven't found any wxPython examples of this App-Doc-View example, so you have to use the C examples to reason out how it would work in Python.
I'd post examples, but I haven't got it all working yet, either.


Question:
Why doesn't this work?

DECLARE @temp table
(ShipNo int,
 Supplier varchar(10)
)

INSERT INTO @temp VALUES (1,'CFA')
INSERT INTO @temp VALUES (1, 'TFA')
INSERT INTO @temp VALUES (2, 'LRA')
INSERT INTO @temp VALUES (2, 'LRB')
INSERT INTO @temp VALUES (3, 'ABC')
INSERT INTO @temp VALUES (4, 'TFA')

Declare @OrderBy varchar(255)
sET @OrderBy = 'Supplier'

SELECT ROW_NUMBER() OVER (ORDER BY
CASE @OrderBy
 WHEN 'Supplier' THEN Supplier
 WHEN 'ShipNo' THEN ShipNo
END
) AS RowNo,
ShipNo,
Supplier
FROM @temp

But if you cast the ShipNo to a varchar in the Case statement it DOES work?

Answer:
From Books Online:
```
```
CASE
WHEN Boolean_expression THEN result_expression
    [ ...n ]
[
    ELSE else_result_expression
]
END
```
```
"The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion."
So Supplier and ShipNo must be the same datatype.


Question:
Im trying to craft a regex that only returns <link> tag hrefs

Why does this regex return all hrefs including <a hrefs?

(?&lt;=&lt;link\s+.*?)href\s*=\s*[\'\"][^\'\"]+

<link rel="stylesheet" rev="stylesheet" href="idlecore-tidied.css?T_2_5_0_228" media="screen">
<a href="anotherurl">Slash Boxes&lt;/a>

Answer:
```
```
/(?<=<link\s+.*?)href\s*=\s*[\'\"][^\'\"]+[^>]*>/
```
```
i'm a little shaky on the back-references myself, so I left that in there. This regex though:
```
```
/(<link\s+.*?)href\s*=\s*[\'\"][^\'\"]+[^>]*>/
```
```
...works in my Javascript test.


Question:
I have a couple of dropdown boxes on a normal ASP.Net page.

I would like the user to be able to change these and to have the page Pseudo-post back to the server and store these changes without the user having to hit a save button.

I don't really need to display anything additional as the dropdown itself will reflect the new value, but I would like to post this change back without having the entire page flash due to postback

I have heard that this is possible using AJAX.Net...

Can someone point me in the right direction?

Answer:
Add a reference to System.Web.Extensions and System.Web.Extensions.Design to your website.  Then put a scriptmanager on your page and wrap your ddl in an updatepanel.  Do whatever you want on the back-end.
For example...
```
```
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
  <ContentTemplate>

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" OnSelectedIndexChanged="yourDDL_SelectedIndexChanged">
</asp:DropDownList>

  </ContentTemplate>
</asp:UpdatePanel>

protected void yourDDL_SelectedIndexChanged(object sender, EventArgs e)
{
// do whatever you want
}
```
```


Question:
I'm writing a JPA connector to a legacy sistem. The problem is, DB design in the system is.. well.. horrible.

I need to implement an entity that maps to three tables. I can do it using named sql queries, but the probem is, I have to use this entity in a OneToMany relation (this entity is on the many side). So how do I tell JPA it needs to use a specific named query with specific parameter?

And a subquestion: does any1 have any good on-line JPA documentation? I can't find anything decent :-/

Answer:
I haven't actually found a way to do this with JPA. To solve problems like this I ended up using a named query.
As far as documentation, I have been using
TopLink's
and
Hibernate's
.
If you find a better way, please post it here!


Question: Why does the PRINT statement in T-SQL seem to only sometimes work?  What are the constraints on using it?  It seems sometimes if a result set is generated, it becomes a null function, I assumed to prevent corrupting the resultset, but could it's output not go out in another result set, such as the row count?

Answer:
So, if you have a statement something like the following, you're saying that you get no 'print' result?
```
select * from sysobjects
PRINT 'Just selected * from sysobjects'
```
If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the
timing
of seeing the print statements, you may want to try using something like
```
raiserror ('My Print Statement', 10,1) with nowait
```
This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.


Question:
I want to use Visual Studio snippets to generate SQL code, for example we have standard naming conventions for foreign keys etc and it would be great if I could just expand a snippet in my SQL script file.

However as far as I can tell the only languages that are supported by the Snippet manager are C#, VB J# and XML

http://msdn.microsoft.com/en-gb/library/ms171421(VS.80).aspx

Does anyone know of a way to have a snippet expand to SQL?

Derek

Answer:
So, if you have a statement something like the following, you're saying that you get no 'print' result?
```
select * from sysobjects
PRINT 'Just selected * from sysobjects'
```
If you're using SQL Query Analyzer, you'll see that there are two tabs down at the bottom, one of which is "Messages" and that's where the 'print' statements will show up.
If you're concerned about the
timing
of seeing the print statements, you may want to try using something like
```
raiserror ('My Print Statement', 10,1) with nowait
```
This will give you the message immediately as the statement is reached, rather than buffering the output, as the Query Analyzer will do under most conditions.


Question: Can I really and truly trust .NET to initialize fields (like ints, structs and the like)?   And what if I still want to initialize those fields - what could be the repercussions?

Answer:
Yes, you can really trust .NET to initialize fields to their default values.
There are basically no repercussions for doing it explicitly. (One small caveat here: if you initialize static fields explicitly, then anyone running the type initializer a second time via reflection will end up re-initializing those fields. This is a real corner case though!)
Do whatever promotes the most readability in your particular codebase.


Question:
How to 'group by' a query using an alias, for example:

select count(*), (select * from....) as alias_column
from table
group by alias_column

I get 'alias_column' : INVALID_IDENTIFIER error message. Why? How to group this query?

Answer:
```
```
select
  count(count_col),
  alias_column
from
  (
  select
    count_col,
    (select value from....) as alias_column
  from
    table
  ) as inline
group by
  alias_column
```
```
Grouping normally works if you repeat the respective expression in the GROUP BY clause. Just mentioning an alias is not possible, because the SELECT step is the last step to happen the execution of a query, grouping happens earlier, when alias names are not yet defined.
To GROUP BY the result of a sub-query, you will have to take a little detour and use an nested query, as indicated above.


Question:
ASP.NET 3.5 SP1 adds a great new ScriptCombining feature to the ScriptManager object as demonstrated on this video. However he only demonstrates how to use the feature with the ScriptManager on the same page. I'd like to use this feature on a site where the scriptmanager is on the master page but can't figure out how to add the scripts I need for each page programmatically to the manager. I've found this post to use as a starting point, but I'm not really getting very far. can anyone give me a helping hand?

Thanks, Dan

Answer:
Give this a shot:
```
```
ScriptReference SRef = new ScriptReference();
    SRef.Path = "~/Scripts/Script.js";

    ScriptManager.GetCurrent(Page).CompositeScript.Scripts.Add(SRef);
```
```
That will get the current scriptmanager (even if it is on a master page) and add a script reference to the CompositeScript properties.


Question:
I noticed that the ASP.NET cache items are inspected (and possibly removed) every 20 seconds (and oddly enough each time at HH:MM:00, HH:MM:20 and HH:MM:40). I spent about 15 minutes looking how to change this parameter without any success. I also tried to set the following in web.config, but it did not help:

<cache privateBytesPollTime="00:00:05" />

I’m not trying to do anything crazy, but it would be nice if it was, say, 5 seconds instead of 20, or at least 10 for my application.

Answer:
According to the
documentation
, privateBytesPollTime is for "worker process memory usage" and the default is 1 second.  I don't think this relates to cache item removal.
I did confirm your results using an item removal callback- it looks like items are removed at the bottom of the minute, :20, and :40 seconds.  This suggests that an item may remain in the cache for up to 20 seconds past the AbsoluteExpiration set on them.  I couldn't find any documentation stating whether the 20 second polling interval could be changed.


Question:
Take a very simple case as an example, say I have this URL:

http://www.example.com/65167.html

and I wish to serve that content under:

http://www.example.com/about

UPDATE: Note that the 'bad' URL is the canonical one (it's produced by a CMS which uses it internally for linking), so "/about" is just a way of polishing it.

I have two broad options: a server-side redirect or a client-side one. I always thought that server-side would be preferable since it's more efficient, i.e. HTTP traffic is approximately halved. However, SEO techniques tend to favour a single URL for a resource, thus client-side is to be preferred.

How do you resolve this conflict, and are there other factors I've omitted?

Answer:
Apache HTTPD's mod_rewrite can leave a browser showing a SEO-friendly URL in its location bar while redirecting to a numeric URL on the server:
```
```
RewriteEngine on
RewriteRule ^/about$ /65167.html [L]
```
```


Question:
I'm currently in the process of writing a wizard and want to make each page validate before moving onto the next page.

I want to prevent the user from progressing by calling the Validate() method on every child control on the page and and stopping navigation if any of them fail.

The problem is that the Validate() method on every child control is a private method so I can't access it directly. Can anyone give me some advice on how to get a result from the Validate() method on a TextBox (For example) using Reflection?

Many thanks!

Edit: Sorry - should have specified, this is Windows Forms, .Net 2.0

Answer:
If you are talking asp.net you can set the ValidationGroup attribute on the control then call
```
this.Validate("GroupName")
```
on the page for the group you need to validate.
Forget the group and just call
```
Validate()
```
if you need to validate the whole page.


Question:
I'm refactoring some old JavaScript code and there's a lot of DOM manipulation going on.

var d = document;
var odv = d.createElement("div");
odv.style.display = "none";
this.OuterDiv = odv;

var t = d.createElement("table");
t.cellSpacing = 0;
t.className = "text";
odv.appendChild(t);

I would like to know if there is a better way to do this using jQuery. I've been experimenting with:

var odv = $.create("div");
$.append(odv);
// And many more

But I'm not sure if this is any better.

Answer:
Simply supplying the HTML of elements you want to add to a jQuery constructor
```
$()
```
will return a jQuery object from newly built HTML, suitable for being appended into the DOM using jQuery's
```
append()
```
method.
For example:
```
```
var t = $("

");
$.append(t);
```
```
You could then populate this table programmatically, if you wished.
This gives you the ability to specify any arbitrary HTML you like, including class names or other attributes, which you might find more concise than using
```
createElement
```
and then setting attributes like
```
cellSpacing
```
and
```
className
```
via JS.


Question:
The default output from Drupal's Form API is:

<input id="edit-submit" class="form-submit" type="submit" value="Save" name="op"/>

How do I theme that so I get:

<button id="edit-submit" class="form-submit" type="submit">
  <span>Save</span>
</button>

I need the inner span-tag so I can use the sliding doors CSS technique.

I guess I need to override theme_button($element) from form.inc but my attempts so far have been unsuccessful.

Answer:
The basic idea to themeing a form_foo if you're using a plain PHP theme (like Chameleon), is to write a function called theme_form_foo().
You can also theme one element (like this button) specifically, by declaring a theme function just for it. See
https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7
Note that, with D6, in both cases you'll need to declare the function in the theme registry, otherwise Drupal won't notice this override. This is not necessary in D5. If you're using phptemplate, you'll need it too, although PHPtemplate takes care of the registry outside the forms case:
http://drupal.org/node/132442#theme-registry
The documentation for this is available on a.d.o. :
http://api.drupal.org/api/file/developer/topics/forms_api.html


Question:
I can use an bitmap in a menu

CMenu men;
CBitmap b;
b.LoadBitmap(IDB_0);
men.AppendMenu( MF_ENABLED,1,&b);

I can draw an icon into a DC

  CImageList IL;
  IL.Create(70, 14, ILC_COLOR16 | ILC_MASK, 1, 0);
  IL.Add(AfxGetApp()->LoadIcon(IDI_0));
  IL.Draw ( pDC,  0,  rcIcon.TopLeft(),  ILD_BLEND50 );

But I cannot find a simple way to show an icon in a menu.  I would like to do this

CMenu men;
CBitmap b;
// here the miracle happens, load the icon into the bitmap
men.AppendMenu( MF_ENABLED,1,&b);

Seems like this should be possible.

This is the same question as this.  However that question referred to the MFC feature pack, did not get answered, and has shown no activity for a month, so I thought it would be worthwhile to ask it again in reference to basic MFC.

Answer:
I asked the question you reference.
The way to add (normal, 16-bit color) icons to menus is to make a toolbar with the same resource id as the menu you want to have icons in. You then assign id's to each of the toolbar buttons, the same id's as the menu entries. Make a wizard-generated new MFC application and you'll see how it works there.
The answers to the question I posted suggested that it should work the same for 32-bit images with transparency for the Feature Pack toolbars; I haven't gotten around to test it out though.
If your specific problem is how to make dynamically-generated menus, I think you should pass the id of an existing entry in a toolbar and then that image will be used.
Not a real answer to your question but maybe it'll point you in the right direction.


Question:
On a Windows 2003 server I have a pure .NET 3.5 C# app (no unmanaged code). It connects to various other remote systems via sockets and acts like a data hub. It runs for 10-15 hours fine with no problem but from time to time it just disappears. If I watch the app using task manager the memory usage remains constant.

In the Main() function I wrap the invocation of the rest of the app in a try .. catch block which it just blows completely past - the catch block which logs the exception to a file is ignored. If I manually raise an exception for testing, the catch block is invoked.

Prior to entering the try .. catch I do :

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

The system has Dr. Watson on it, but nothing gets written in the directory DRWTSN32.EXE is pointing to.

How can I catch whatever exception is causing this?

Answer:
If it's a Windows Forms application, you could try
```
Application.ThreadException
```
.


Question:
Is there an efficient way to take a subset of a C# array and pass it to another peice of code (without modifying the original array)? I use CUDA.net which has a function which copies an array to the GPU. I would like to e.g. pass the function a 10th of the array and thus copy each 10th of the array to the GPU seperately (for pipelining purposes).

Copying the array in this way should be as efficient as copying it in one go. It can be done with unsafe code and just referencing the proper memory location but other than that I'm not sure. The CopyTo function copies the entire array to another array so this does not appear useful.

Answer:
I'm not sure how efficient this is but...
```
```
int[] myInts = new int[100];

//Code to populate original arrray

for (int i = 0; i < myInts.Length; i += 10)
{
    int[] newarray = myInts.Skip(i).Take(10).ToArray();
    //Do stuff with new array
}
```
```


Question:
I've just come across a property setter that catches exceptions (all Exceptions; I know that's bad, but it's not relevant here), and only logs them.  First of all, I think it should through them again as well; why wait for a crash and a log study when you can know something is wrong right away?

However, my main question is, do I validate against invalid date values, add a RuleViolation object to a ValidationRules object on my document, or throw an InvalidDate exception, or just let the CLR throw the exception for me (invalid dates are nothing but invalid dates, not checked for range etc.)

Answer:
Catching and rethrowing is the worst thing to do. Its expensive to TRY, if youre just going to rethrow what the point? You can
catch unhandled exceptions with the global.asax
for example if you need to log them.
In terms of validation, from a web perspective i always use regex validators for dates, these fire client and server side so i know when im inside an
```
```
if(Page.IsValid)
```
```
block that my txtDate.Text is a valid date, so i dont bother checking because its just wasteful.


Question:
class C {
  T a;
public:
  C(T a): a(a) {;}
};

Is it legal?

Answer:
Yes it is legal and works on all platforms.
It will correctly initialize your member variable a, to the passed in value a.
It is considered by some more clean to name them differently though, but not all.  I personally actually use it a lot :)
Initialization lists with the same variable name works because the syntax of an initialization item in an initialization list is as follows:
<member>(<value>)
You can verify what I wrote above by creating a simple program that does this:  (It will not compile)
```
```
class  A
{

   A(int a)
   : a(5)//<--- try to initialize a non member variable to 5
   {
   }
};
```
```
You will get a compiling error something like: A does not have a field named 'a'.
On a side note:
One reason why you
may not want
to use the same member name as parameter name is that you would be more prone to the following:
```
```
class  A
{

   A(int myVarriable)
   : myVariable(myVariable)//<--- Bug, there was a typo in the parameter name, myVariable will never be initialized properly
   {
   }
   int myVariable;
};
```
```
On a side note(2):
One reason why you
may want
to use the same member name as parameter name is that you would be less prone to the following:
```
```
class  A
{

   A(int myVariable_)
   {
     //<-- do something with _myVariable, oops _myVariable wasn't initialized yet
     ...
     _myVariable = myVariable_;
   }
   int _myVariable;
};
```
```
This could also happen with large initialization lists and you use _myVariable before initializing it in the initialization list.


Question:
I'm trying to get a specific asp:button onclick event to fire when I press the enter key in a specific asp:textbox control.

The other factor to be taken into account is that the button is within a asp:Login control template.

I've no idea how to do this, suggestions on a postcard please.

Answer:
You need to do it with javascript. It's really easy with
jQuery.
You can do something like (off the top of my head, not tested):
```
```
$('#myTextBox').keypress(function(e){
    if(e.which == 13)
        $('#myBtn').click();
});
```
```
Edit: Be aware that although jQuery works exceptionally cross browser, there are some quirks with keypress described
here
.
Whoops i didnt see you said the "enter key" i thought you said "any key", yeah in that case use DefaultButton on asp:panel


Question:
For my website I configured some custom error pages.
If I generate a 404, the redirect works fine.
When hitting a 400, the "bad request" text shows up instead of the configured URl.

As a test I copied the URL from 404 to 400. No change.
Then I changed the redirect to a file. No change.

Any ideas?

Answer:
Check what's in your web.config file in the
```
customErrors
```
section. That has a
```
defaultRedirect
```
attribute, and an
```
error
```
subtag with a
```
redirect
```
attribute. These can conflict with your other configuration settings in IIS.


Question: A quick question: When declaring the DLLImport Attribute in .Net, where does the runtime look to resolve that DLL dependency? Would I have to dump the DLL and all of its dependencies in the bin folder?

Answer:
Generally, you'd expect it to look at whatever's defined in the user's Path.
To find out what this contains, from a command prompt, type
```
echo %PATH%
```
[Enter]


Question:
I am running my HTTPServer in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.

The Python documentation states that BaseHTTPServer.HTTPServer is a subclass of SocketServer.TCPServer, which supports a shutdown method, but it is missing in HTTPServer.

The whole BaseHTTPServer module has very little documentation :(

Answer:
I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve_forever (from SocketServer.py) method looks like this:
```
```
def serve_forever(self):
    """Handle one request at a time until doomsday."""
    while 1:
        self.handle_request()
```
```
You could replace (in subclass)
```
while 1
```
with
```
while self.should_be_running
```
, and modify that value from a different thread. Something like:
```
```
def stop_serving_forever(self):
    """Stop handling requests"""
    self.should_be_running = 0
    # Make a fake request to the server, to really force it to stop.
    # Otherwise it will just stop on the next request.
    # (Exercise for the reader.)
    self.make_a_fake_request_to_myself()
```
```
Edit: I dug up the actual code I used at the time:
```
```
class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):

    stopped = False
    allow_reuse_address = True

    def __init__(self, *args, **kw):
        SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw)
        self.register_function(lambda: 'OK', 'ping')

    def serve_forever(self):
        while not self.stopped:
            self.handle_request()

    def force_stop(self):
        self.server_close()
        self.stopped = True
        self.create_dummy_request()

    def create_dummy_request(self):
        server = xmlrpclib.Server('http://%s:%s' % self.server_address)
        server.ping()
```
```


Question:
I'm scanning through a file looking for lines that match a certain regex pattern, and then I want to print out the lines that match but in alphabetical order. I'm sure this is trivial but vbscript isn't my background

my array is defined as

Dim lines(10000)

if that makes any difference, and I'm trying to execute my script from a normal cmd prompt

Answer:
From
microsoft
Sorting arrays in VBScript has never been easy; that’s because VBScript doesn’t have a sort command of any kind. In turn, that always meant that VBScript scripters were forced to write their own sort routines, be that a bubble sort routine, a heap sort, a quicksort, or some other type of sorting algorithm.
So (using .Net as it is installed on my pc):
```
```
Set outputLines = CreateObject("System.Collections.ArrayList")

'add lines
outputLines.Add output
outputLines.Add output

outputLines.Sort()
For Each outputLine in outputLines
    stdout.WriteLine outputLine
Next
```
```


Question:
How do you do your Hibernate session management in a Java Desktop Swing application? Do you use a single session? Multiple sessions?

Here are a few references on the subject:

http://www.hibernate.org/333.html

http://blog.schauderhaft.de/2008/09/28/hibernate-sessions-in-two-tier-rich-client-applications/

http://in.relation.to/Bloggers/HibernateAndSwingDemoApp

Answer:
Single session. Start transaction when you need to do a set of operations (like update data after dialog box OK button), commit the tx at the end. The connection though is constantly open (since it's the same session), and thus all opportunities for caching can be used by both Hib and RDBMS.
It may also be a good idea to implement a transparent session re-open in case the connection went dead -- users tend to leave applications open for extended periods of time, and it should continue to work Monday even if DB server was rebooted on weekend.
Update
Jens Schauder provided a reason to use multiple sessions: partial (unwanted) updates to the session. Well, that comes down to the way you use Hibernate.
Suppose we have two dialogs open (as in Jens' blog example). If user clicks a radiobox, and we immediately update a Hibernate entity associated with this radiobox, then, when user clicks Cancel, we're in trouble -- session is already updated.
The right way, as I see it, is to update dialog variables (non-Hibernate objects) only. Then, when user clicks OK, we begin a transaction, merge updated objects, commit the transaction. No garbage gets ever saved into session.
```
```
MyHibernateUtils.begin();
Settings settings = DaoSettings.load();
// update setttings here
DaoSettings.save(settings);
MyHibernateUtils.commit();
```
```
If we implement such a clean separation of concerns, we can later switch to multiple sessions with a simple change of MyHibernateUtils.begin() implementation.
As for possible memory leak, well... Transaction.commit() calls Session.flush(), which AFAIK, cleans the cache too. Also, one may manually control the caching policy by calling Session.setCacheMode().


Question:
I'm using java and referring to the "double" datatype.
To keep it short, I'm reading some values from standard input that I read in my code as doubles (I would much rather use something like BigInteger but right now it's not possible).

I expect to get double values from the user but sometimes they might input things like:
999999999999999999999999999.9999999999
which I think is beyond an accurate representation for double and get's rounded to 1.0E27 (probably).

I would like to get some pointers on how to detect whether a specific value would be unable to be accurately represented in a double and would require rounding (so that I could refuse that value or other such actions).

Thank you very much

Answer:
Most values entered by humans won't be exactly representable with a double.
For instance, do you want to prevent the user from entering 0.1? That's not exactly representable as a double.
To find the scale of the error, you could do something like:
```
```
BigDecimal userAsDecimal = new BigDecimal(userInput);
double userAsDouble = double.parseDouble(userInput);
BigDecimal doubleToDecimal = new BigDecimal(userAsDouble);
BigDecimal error = userAsDecimal.subtract(userAsDouble).abs();
```
```
Then check whether "error" is tolerably small.


Question:
I have a HQL query that can generate either an IList of results, or an IEnumerable of results.

However, I want it to return an array of the Entity that I'm selecting, what would be the best way of accomplishing that? I can either enumerate through it and build the array, or use CopyTo() a defined array.

Is there any better way? I went with the CopyTo-approach.

Answer:
Which version of .NET are you using?  If it's .NET 3.5, I'd just call
```
ToArray()
```
and be done with it.
If you only have a non-generic IEnumerable, do something like this:
```
```
IEnumerable query = ...;
MyEntityType[] array = query.Cast<MyEntityType>().ToArray();
```
```
If you don't know the type within that method but the method's callers do know it, make the method generic and try this:
```
```
public static void T[] PerformQuery<T>()
{
    IEnumerable query = ...;
    T[] array = query.Cast<T>().ToArray();
    return array;
}
```
```


Question:
I know about SortedSet, but in my case I need something that implements List, and not Set. So is there an implementation out there, in the API or elsewhere?

It shouldn't be hard to implement myself, but I figured why not ask people here first?

Answer:
Why not encapsulate a set with a list, sort like:
```
```
new ArrayList( new LinkedHashSet() )
```
```
This leaves the other implementation for someone who is a real master of Collections ;-)


Question:
I have a JFrame with a menu bar and a canvas covering all the remaining surface. When I click on the menu bar, the menu opens behind the Canvas and I can't see it. Has anyone experienced this? Other than resizing the Canvas (which I am reluctant to do) is there any solution?

Thanks,

Vlad

Answer:
You're experiencing heavyweight vs. lightweight issues.
The quick fix:
```
```
// Call this sometime before you use your menus
JPopupMenu.setDefaultLightWeightPopupEnabled(false)
```
```
Heavyweight vs. Lightweight


Question: How do I implement the WS addressing using WCF?

Answer:
WCF automatically inserts appropriate WS-Addressing headers into messages created with the wsHttpBinding, and probably with some other bindings too.
Did you mean that you want to exert some control over those headers?


Question:
I have a need to determine what security group(s) a user is a member of from within a SQL Server Reporting Services report. Access to the report will be driven by membership to one of two groups: 'report_name_summary' and 'report_name_detail'. Once the user is executing the report, we want to be able to use their membership (or lack of membership) in the 'report_name_detail' group to determine whether or not a "drill down" should be allowed.

I don't know of any way out of the box to access the current user's AD security group membership, but am open to any suggestions for being able to access this info from within the report.

Answer:
You can add custom code to a report.
This link
has some examples.
Theoretically, you should be able to write some code like this, and then use the return value to show/hide what you want.  You may have permissions problems with this method, though.
```
```
Public Function ShouldReportBeHidden() As Boolean
Dim Principal As New System.Security.Principal.WindowsPrincipal(System.Security.Principal.WindowsIdentity.GetCurrent())
If (Principal.IsInRole("MyADGroup")) Then
    Return False
Else
    Return True
End If
End Function
```
```
Alternatively
, you could add your detail report as a subreport of your summary report.  Then you could use the security functionality built in to SSRS to restrict access to your sub report.


Question:
What are some strategies to achieve code separation in AJAX applications?

I am building a PHP application that I would like to have a nice AJAX front end on.  I have long since learned to use some kind of templating in my PHP code to make sure I maintain good separation between my logic and display code, but I'm having trouble finding good ways to do this with the JavaScript code on the front end.  I'm using jQuery to make the fetching of XML data and DOM manipulation easy, but I'm finding that the logic and layout code is starting to intermix.

The real problem is that I get XML data from the back end that then has to be reformatted and helpful text has to be wrapped around it (directions and the like).  I've thought about sending over already formatted HTML, but that would require extensive reworking of the backend, and there must be a better way than what I have come up with on my own.

Answer:
I am not 100% sure I get what your issue but what you can do, especially if we are talking about a single page style AJAX application is to use Singletons classes geared toward specific tasks.
```
```
var XMLFormatter = function(){
    /* PRIVATE AREA */

    /* PUBLIC API */
    return {
        formatXML : function(xml){
            /* DO SOMETHING RETURN SOMETHING */
        }
    }
}();
```
```
What you are left with is a static XMLFormatter class that can be called anywhere on the page like so...
```
```
function useClass(){
    $('#test').update(XMLFormatter.formatXML(someXML))
}
```
```
This function can be used as a callback on the AJAX requests.  I use this method for page logic by creating a Page class taht returns an object with an init method that is called when the page is loaded.  The init method then attaches the various events and stuff to my page and it's elements.  This is approach is talked about in
Pro JavaScript Design Patterns
well worth the read if you have the time and money.
It's also worth bearing in mind that Javascript is quite different in comparison to other languages and usually peoples best-practise approaches are usually just ones adapted from Java.  While this is OK it's not using Javascript to it's full potential.  Remember Javascript is quite event driven due to it's closeness to UI interaction and you will find a some event code mingling with other code. Crockfords website (
http://javascript.crockford.com/
) has some best-practice articles plus a number of other useful tips.


Question:
Can someone explain why there is the need to add an out or in parameter to indicate that a generic type is Co or Contra variant in C# 4.0?

I've been trying to understand why this is important and why the compiler can't just figure it out..

Thanks,

Josh

Answer:
The
```
in
```
and
```
out
```
keywords have been keywords since C# 1.0, and have been used in the context of
```
in
```
- and
```
out
```
- parameters to methods.
Covariance and contravariance are constraints on how one can implement an interface. There is no good way to infer them - the only way, I think, is from usage, and that would be messy and in the end it wouldn't work.


Question:
Someone left the organisation but before leaving, he locked all the files for an unknown reason.

How do you unlock them all so that the other developers can work?

Answer:
For the following operation, you will need to be either a project administrator for the project you want to undo the check-in on or a Team Foundation Administrator if you want to do this across all projects.
If you still have the username of the person, you can simply do something like this:
Open up Visual Studio command prompt (Start -> Programs -> Microsoft Visual Studio 200X -> Visual Studio Tools -> Visual Studio 200X Command Prompt)
Run the following command:
tf lock /lock:none
  /workspace:WorkspaceName;USERNAME
  /recursive $/
To get the list of workspaces for a user, just run the following command from the same prompt:
tf workspaces /owner:username
For more commands, check
tf /?


Question: What's the best way to write a LINQ query that inserts a record and then returns the primary key of that newly inserted record using C# ?

Answer:
The primary key value will be in that property after the SubmitChanges().
```
```
MyTable record = new MyTable();
record.Name = "James Curran";
db.MyTable.InsertOnSubmit(record);
db.SubmitChanges();
Console.WriteLine("record inserted as ID : {0}", record.Id);
```
```


Question:
When I am using a form containing <input id="myFile" type="file" runat="server" /> to upload a file, my server-side code only sees the filename without the full path when using Firefox, while it works just fine in IE.

Is it possible to retrieve the full file path server-side in this case?

Answer:
You can never be sure of getting a full filepath or even a reliable filename or content-type submitted in a file upload file. Even if you get a full filepath you don't know what the path separator character is on the client's operating system, or whether a file extension (if present) denotes anything at all.
If your application requires the filepath/filename/content-type of a submitted file for anything more than giving the user a default title for the item uploaded, it's doing something wrong and will need fixing.


Question:
I've got this python dictionary "mydict", containing arrays, here's what it looks like :

mydict = dict(
    one=['foo', 'bar', 'foobar', 'barfoo', 'example'],
    two=['bar', 'example', 'foobar'],
    three=['foo', 'example'])

i'd like to replace all the occurrences of "example" by "someotherword".

While I can already think of a few ways to do it, is there a most "pythonic" method to achieve this ?

Answer:
```
```
for arr in mydict.values():
    for i, s in enumerate(arr):
        if s == 'example':
            arr[i] = 'someotherword'
```
```


Question:
Duplicate:

What happens if you call erase on a map element while iterating from begin to end

How to filter items from a stdmap

I have a map map1<string,vector<string>> i have a iterator for this map "itr".
i want to delete the entry from this map which is pointed by "itr".
i can use the function map1.erase(itr); after this line the iterator "itr" becomes invalid.
as per my requirement in my project,the iterator must point to the next element. can any body help me regerding this
thans in advance:)
santhosh

Answer:
```
```
map<...>::iterator tmp(iter++);
map1.erase(tmp);
```
```


Question:
Multistrings (double null-terminated string of null-separated strings) are common in the Windows API. What's a good method for converting a multistring returned from an API to a C# string collection and vice versa?

I'm especially interested in proper handling of character encoding (Windows XP an later).

The following method seems to be okay for creating a multistring, but I don't have an example of decoding a multistring.

static string StringArrayToMultiString(
    ICollection<string> stringArray
    )
{
    StringBuilder multiString = new StringBuilder();

    if (stringArray != null)
    {
        foreach (string s in stringArray)
        {
            multiString.Append(s);
            multiString.Append('\0');
        }
    }

    return multiString.ToString();
}

Answer:
This might be naïve, but how about:
```
```
static string[] MultiStringToArray(string multiString)
{
    return multiString.TrimEnd('\0').Split('\0');
}
```
```
Also - aren't you missing the final
```
\0
```
(you state double-null-terminated) in
```
StringArrayToMultiString
```
?
And it might be easier to call if the array was a
```
params string[]
```
array - something like:
```
```
static string StringArrayToMultiString(params string[] values)
{
    if (values == null) throw new ArgumentNullException("values");
    StringBuilder multiString = new StringBuilder();

    foreach (string s in values)
    {
        multiString.Append(s);
        multiString.Append('\0');
    }
    return multiString.ToString();
}
```
```
[edited after clarification about final \0]


Question:
I have a few links that should all open in the same window or tab.
To accomplish this I've given the window a name like in this example code:

<a href="#" onClick='window.open("http://somesite.com", "mywindow", "");'>link 1</a>
<a href="#" onClick='window.open("http://someothersite.com", "mywindow", "");'>link 2</a>

This works OK in internet explorer, but firefox always opens a new tab/window.
Any ideas?

Answer:
The window.open() function in Javascript is specifically designed to open a new window, please see:
w3schools documentation
. It actually sounds like IE is handling things in a non-standard way (which is hardly surprising).
If you want to relocate the existing location to a new page using Javascript, you should look at the
location.replace()
function.
Generally speaking I would recommend that you develop for Firefox and then fix for IE. Not only does Firefox offer better development tools but its implementation of W3C standards tends to be more correct.


Question:
I've been able to find Xaml Object Mapping Specification, WPF Xaml Vocabulary Specification, and Silverlight Xaml Vocabulary Specification documents online but no WF Xaml Vocabulary Specification document for Windows Workflows.  I want to be able to specify workflows without using a Visual Studio IDE.

Does anybody know if this specification exists and if so, where to find it?

Answer:
xps spec
may or may not be up to date with the ecma work
XAML object spec
WPF XAML spec 2006
Silverlight xaml spec
So far there is no WF spec.
Douglas


Question:
Less than 10 client computers, each with their own installation have to upload data to a central server.

The client database looks like:

tblSales
- rowGuid
- randomNumber

Central Server database:

rowGuid

randomNumber

dateInserted

I plan to use WCF to send the files to the central server.

How can I verify the rows were inserted to the server?  What kind of verification options do I have?

I could return the # of rows inserted and compare that with the # that was sent, but is there any other more robust method?

Answer:
Using WCF you're going to be basically calling a function thru a proxy.  Just have that function return a bool true for success or false for failure.
```
```
bool Success;
Success = MyWCFService.InsertRecord(MyNewRecord);
```
```


Question: If we develop a winform app using an MVC architecture, it should not be too hard to change over to WPF at a later date, correct?

Answer:
Well designed WPF application heavily leverage data-binding. As such, you might consider using classes such as ObservableCollection and others and implement IPropertyNotify when designing your model.
Look up some references to the M-V-VM pattern advocated by Microsoft product groups (e.g., Blend) for more information.


Question:
In your “enterprise” work environment, how are engineers held accountable for performing code inspections and unit testing?  What processes do you follow (formal methodology or custom process) to ensure the quality of your software?  Do you or have you tried implementing a developer "signoff" sheet for deliverables?

Thanks in advance!

Update:  I forgot to mention we are using Code Collaborator to perform our inspections.  The problem is getting people to "get it" and buy into doing them outside of a core group of people.  As stalbot pointed out below it is a cultural change but the question becomes, how do you change your culture to promote quality initiatives such as reviews/unit tests?

Answer:
We lean heavily on ITIL concepts. While we don't need the full scale ITSM that ITIL provides, we have implemented processes that draw from some of the best practices in ITIL, specifically in the areas of Change Management and Release Management.
Code reviews are part of our RM strategy. As a change or new piece of code makes its way through our RM process, a lot of eyes look at it. Ultimately the Release Manager makes the call on approval or rework, and all of this is documented (we use TFS and SharePoint). Formal code reviews are held by the Release Manager and the technical team he selects. The primary developer for a release candidate is held accountable for adherence to standards, functionality, and a verification of a completed test plan. If the quality standards aren't met, the deliverable is rejected and the project schedule is updated to reflect the rework.
Yes, this is all very heavy. I work in government and we have complex laws to follow, specifically in the areas of taxes, ADA compliance, and so on.


Question:
I'm trying to do a subselect in pgsql aka postgresql and the example I found doesn't work:

SELECT id FROM (SELECT * FROM table);

Answer:
I think you need something like:
```
```
SELECT * FROM table WHERE id IN (SELECT id FROM table2);
```
```
I don't understand what your non-working subquery is attempting to do, it seems like you could just say
```
SELECT id FROM table
```
because presently its not valid SQL92 syntax.


Question:
So here is the simple code:

    [System.ComponentModel.DefaultValue(true)]
    public bool AnyValue { get; set; }

I am sure I don't set AnyValue to false again (I just created it). This property is a property of a Page class of ASP.NET. And I am cheking the value in a button event handling function. But somehow it is still false.
I wonder when actually it is set true? On compile time? When class is instantiated?

What do you think about what I am doing wrong?

Answer:
DefaultValue does
NOT
set the value.
What it does is tell VisualStudio what the default value is.  When a visual element (Button, listbox etc) is selected on a form, and the Property panel is displayed, VS will
bold
the values of properties which are set to something besides the value given in DefaultValue.
Hence in your case, since AnyValue is false, but it's DefaultValue is true, then is will display
false
in bold in the Property panel.  If you were to manually change it to "true", then it will be displayed non-bolded.


Question:
How can I document a member inline in .Net? Let me explain. Most tools that extract documentation from comments support some kind of inline documentation where you can add a brief after the member declaration. Something like:

public static string MyField; /// <summary>Information about MyField.</summary>

Is there a way to do this in C# or the .NET languages?

Answer:
Yep, just put it BEFORE the thing you want to comment
```
```
/// <summary>Information about MyField.</summary>
public static string MyField;
```
```


Question:
I´ve been looking for it yet in stackoverflow without success...

Is it posible a connection pooling in asp.net? Is it worthwhile? How?

Answer:
It is actually really simple, simply add the following parameters to your connection string and (either in code or in the web.config) and ASP.NET will pick up the rest:
```
```
Min Pool Size=5; Max Pool Size=60; Connect Timeout=300;
```
```
Note: The Connection Timeout is in seconds and is not required.


Question:
I have a program that runs osql.exe from microsoft sql server tools directory and runs a script.

The problem is that on computers that don't have an installation of sql server, this tool is missing. So my question is whether or not is possible to run it as a standalone( along with any dll that may be required ) meaning that run them from Process.Start from a local directory of the application.

Answer:
Why are you spawning osql?
I've written simple programs to execute scripts using SMO - mostly insired by
this post
.
EDIT
The jist of the post is to use
SQL Server Management Objects (SMO)
.
```
Server.ConnectionContext.ExecuteNonQuery
```
parses SQL with
```
GO
```
statements in it.


Question:
Lets say I have an array like this:

string [] Filelist = ...

I want to create an Linq result where each entry has it's position in the array like this:

var list = from f in Filelist
    select new { Index = (something), Filename = f};

Index to be 0 for the 1st item, 1 for the 2nd, etc.

What should I use for the expression Index= ?

Answer:
Don't use a query expression. Use
the overload of
```
Select
```
which passes you an index
:
```
```
var list = FileList.Select((file, index) => new { Index=index, Filename=file });
```
```


Question:
I'm writing some mail-processing software in Python that is encountering strange bytes in header fields.  I suspect this is just malformed mail; the message itself claims to be us-ascii, so I don't think there is a true encoding, but I'd like to get out a unicode string approximating the original one without throwing a UnicodeDecodeError.

So, I'm looking for a function that takes a str and optionally some hints and does its darndest to give me back a unicode.  I could write one of course, but if such a function exists its author has probably thought a bit deeper about the best way to go about this.

I also know that Python's design prefers explicit to implicit and that the standard library is designed to avoid implicit magic in decoding text. I just want to explicitly say "go ahead and guess".

Answer:
+1 for the
chardet
module (suggested by
```
@insin
```
).
It is not in the standard library, but you can easily install it with the following command:
```
```
$ pip install chardet
```
```
Example
:
```
```
>>> import chardet
>>> import urllib
>>> detect = lambda url: chardet.detect(urllib.urlopen(url).read())
>>> detect('http://stackoverflow.com')
{'confidence': 0.85663169917190185, 'encoding': 'ISO-8859-2'}
>>> detect('https://stackoverflow.com/questions/269060/is-there-a-python-lib')
{'confidence': 0.98999999999999999, 'encoding': 'utf-8'}
```
```
See
Installing Pip
if you don't have one.


Question: I want to use LabVIEW's Call Library Function Node to access a DLL function, and have this function return a string to displayed on my VI. How would I go about doing this? I am quite happy returning numbers from my DLL, but am really struggling to find any examples of how to return a string.

Answer:
I assume from your question that you already have a DLL that can return numbers to Labview.  To return a string from the DLL, I have created a DLL with the following C++ function
```
```
void returnString(char myString[])
{
  const char *aString = "test string";
  memcpy(myString, aString, 12);
}
```
```
In Labview I then use the Call Library Function Node and configure it as follows
```
Library Name or Path: c:\path\to\my\custom.dll
           Function Name: returnString
           Calling Convention: C

    Parameters:
           Parameter: return type
                type: void

           Parameter: arg1
                type: String
                string format: C String Pointer

    Function prototype:
        void returnString(CStr arg1);
```
After connect the arg1 output in the block diagram to a string indicator and run.  The string "test string" should appear in the front panel.
I tried to have the returnString function be of type CStr as in
```
```
CStr returnString()
{ ...
 }
```
```
but I got build errors when compiling the DLL project.
Update
Thanks to @bk1e comment don't forget to pre-allocate space in Labview for the string.


Question:
I know about this question: Which (third-party) debug visualizers for Visual Studio 2005/2008 do you use?

But I don't want to know what debug visualizers you use, I want to know which debug visualizers are out there.

I have only found Mole (http://www.codeproject.com/KB/macros/MoleForVisualStudioEdit.aspx), which is great. But there has to be plenty more out there?

Enlighten me.

Answer:
From a quick web search...
There is the one referenced in the blog post from the related question:
http://blogs.msdn.com/dparys/archive/2007/10/23/das-debugger-visualizer-item-template.aspx
LINQ to SQL Debug Visualizer
Graphics Debug Visualizer
Windows Identity Debug Visualizer
Conchango XML Debug Visualizer
SubSonic Collections Debug Visualizer
PowerShell Debug Visualizer
Xml Visualizer v.2
WCF Visualizers Tool
WPF Dependency Object Visualizer
DB Connection Visualizer
Debugger Visualizer for BizTalk 2006: MessageContext
DataSet Debug Visualizer
GUID Debug Visualizer
Debug Inspector
WPF Brush Visualizer
Expression Tree Visualizer
ANTLR4 Parse Tree Visualizer
DateTime Visualizer


Question:
I am fairly new to WPF and I am having a problem with inheriting from a user control.

I created a User Control and now I need to inherit from that control and add some more functionality.

Has anyone does this sort of thing before?  Any help would be greatly appreciated.

Thank you

Answer:
Well .. you create your base control
```
```
public abstract class BaseUserControl : UserControl{...}
```
```
then in the XAML file :
```
```
<Controls:BaseUserControl x:Class="Termo.Win.Controls.ChildControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Controls="clr-namespace:Namespace.Of.Your.BaseControl">
```
```
And that should work.
EDIT:
Hmm.. this example is useful when you have a base control without XAML and then inherit from it. The other way around(from a base control with Xaml) - I'm not sure how you can go about it.
EDIT2:
Apparently from
this post + comments
i take that what you want might not be possible.


Question:
My new project is targeting an embedded ARM processor.  I have a build system that uses a cross-compiler running on an Ubuntu linux box.  I like to use unit testing as much as possible, but I'm a little bit confused about how to proceed with this setup.

I can't see how to run unit tests on the ARM device itself (somebody correct me if I'm wrong).  I think that my best option is to compile the code on the build machine using its own native compiler for the unit tests.  Is this approach fundamentally flawed?  Is unit testing on a different platform a waste of time?

I'm planning to use CppUnit on the build machine using the native compiler for the unit tests.  Then I'll cross compile the code for the ARM processor and do integration and system testing on the target device itself.  How would you structure the source code and the test code to keep this from turning into a tangled mess?

Answer:
With embedded device it depends on what interfaces (hardware) you have.
For example the motion control cards I deal with uses a command line interface. The IDE they ship uses it as it primary method of interacting with the cards. It works the same way regardless if I am using PCI, IDE, Serial, or Ethernet.
The DLL they ship for programming give access to the command line interface. So I can send a string, and read back the response. So what I do for my unit tests is have a physical card hooked (or in) my development machine. I send it commands after uploading the software, read the response and if they are correct it passes the test.
I also have extra hardware, a black box if you will, that simulates a machine that motion control card is normally hooked up too. It helps with the automated sets but there is a manual phase as I have to set switches to simulate different setups on the machine.
I have achieved a greater degree of automation by taking a digital I/O card and using it outputs to feed into the inputs of the motion control card and the same in reverse.
I found that for most hardware you have to have some type of simulator hardware.
The exception being the rare package that comes with a software simulator.
I know this isn't probably ideal as not every developer can have one of these on their desk. My hardware simulator so I can give it to whoever it working on the motion control software at the time. If it can't be portable then having a dedicated testing or hardware development computer would be in order.
Finally it boils down on the specifics of your hardware and what support the manufacturer gives in terms of software and simulators. To help you more you will need to post more specifics.


Question:
Is there any technology out there that will allow you to do side-by-side updates of production schemas?

The goal is to have zero down time when applying updates to a schema in production.
Weblogic 10 has a similar feature for their Java EE apps where by you deploy the new version of the app and new connections go to the new app, while the existing connections continue to the old app.  When all the old connections complete/timeout, the old app is retired and the new app continues on...zero down time.

Is there something similar in Oracle?

Answer:
Yes. There is online redefinition package.
DBMS_Redefinition
But I doubt this will give you zero downtime, this doesn't account for every possible change to a schema. This lets you do some table changes. I think you need to define zero and how extensive the changes you want to make. Usually if you change the database, you have to change your client as well. If you changed your database, how would the client switch automatically from the old proc signature to the new proc signature - Instantaneously?
Databases don't work like apps. There either is a FK from tableA to tableB or there isn't... it can't not be there for current connection and exist only for new connection in the same manner as your application can. Databases just aren't the same.
That being said, there is rumor that Oracle is working on package versioning... so you could connect to a specific version of a package to make such a migration simpler. But again... that would work for packages, DBMS_redef would work for tables... but that's not the sum total of your database.


Question:
[1] In JDBC, why should we first load drivers using Class.forName("some driver name").
Why SUN didnt take care of loading driver within the getConnection() method itself.If I pass driver name as a parameter to the getConnection() method.

[2] I want to understand JBDC internals.Any pointers towards it are appreciated.

Answer:
With JDBC 4, you no longer need to use Class.forName(...) see
here
for one article explaining this:
Connection to a database requires that a suitable JDBC database driver be loaded in the client's VM. In the early days of JDBC, it was common to load a suitable driver via Class.forName(), passing in the name of the class implementing the JDBC Driver interface. The DriverManager class later offered a more flexible means of managing JDBC drivers in a client application. For a driver to become available, DriverManager's registerDriver() had to be invoked with the driver's class name. Alternatively, you could specify the drivers to load via the jdbc.drivers system property. When DriverManager initializes, it attempts to load the drivers associated with that property.
JDBC 4 adds the
J2SE Service Provider
mechanism as another means to specify database drivers. For this to work, driver JAR files must include the file META-INF/services/java.sql.driver. That file must contain a single line with the name of the JDBC driver's implementation of the Driver interface. Invoking getConnection() on DriverManager will load a driver so packaged, if needed. Upon loading the driver, an instance of the driver is created, and then registerDriver() is invoked to make that driver available to clients.
Have a look at
Sun's JDBC link
for more information on JDBC. The JDBC 4.0 Specification is relatively a nice read compared to some other specs...


Question:
We use Tomcat to host our WAR based applications.  We are servlet container compliant J2EE applications with the exception of org.apache.catalina.authenticator.SingleSignOn.

We are being asked to move to a commercial Java EE application server.

The first downside to changing that
I see is the cost.  No matter what
the charges for the application
server, Tomcat is free.

Second is the complexity.  We don't
use either EJB nor EAR features (of
course not, we can't), and have not missed them.

What then are the benefits I'm not seeing?

What are the drawbacks that I haven't mentioned?

Mentioned were...

JTA - Java Transaction API - We
control transaction via database
stored procedures.

JPA - Java Persistence API - We use
JDBC and again stored procedures to
persist.

JMS - Java Message Service - We use
XML over HTTP for messaging.

This is good, please more!

Answer:
Cost isn't necessarily a downside as there a few free J2EE servers, e.g. JBoss and Glassfish.
Your question assumes that (J2EE = Servlet + EJB + EAR) and therefore, there's no point in using anything more than a Servlet container if you're not using EJB or EAR. This is simply not the case, J2EE includes a lot more than this. Examples include:
JTA - Java transaction API
JPA - Java persistence API
JMS - Java messaging specification
JSF - technology for constructing user interfaces out of components
Cheers,
Donal


Question: I have implemented a SAX parser in Java by extending the default handler. The XML has a ñ in its content. When it hits this character it breaks. I print out the char array in the character method and it simply ends with the character before the ñ. The parser seems to stop after this as no other methods are called even though there is still much more content. ie the endElement method is never called again. Has anyone run into this problem before or have any suggestion on how to deal with it?

Answer:
What's the encoding on the file? Make sure the file's encoding decloration matches it. Your parser may be defaulting to ascii or ISO-8859-1. You can set the encoding like so
```
```
<?xml version="1.0" encoding="UTF-8"?>
```
```
UTF-8 will cover that character, just make sure that's what the file actually is in.


Question:
We have an Java application running on Weblogic server that picks up XML messages from a JMS or MQ queue and writes it into another JMS queue. The application doesn't modify the XML content in any way. We use BEA's XMLObject to read and write the messages into queues.

The XML messages contain the encoding type declarations as UTF-8.

We have an issue when the XML contains characters that are out side the normal ASCII range (like £ symbol for example). When the message is read from the queue we can see that the £ symbol is intact, however once we write it to the destination queue, the £ symbol is lost and is replaced with Â£ instead.

I have checked the OS level settings (locale settings) and everything seems to be fine. What else should I be checking to make sure that this doesn't happen?

Answer:
Without a few more specifics, I'd guess that there is a method that optionally takes an encoding somewhere that isn't specified and is defaulting to ISO-8859-1. Commonly, check anything that passes between an InputStream/OutputStream and a Reader/Writer.
For instance, an
OutputStreamWriter
takes an optional encoding that you could be leaving out.


Question:
I have a not-so-small class under development (that it changes often) and I need not to provide a public copy constructor and copy assignment.
The class has objects with value semantics, so default copy and assignment work.

the class is in a hierarchy, with virtual methods, so I provide a virtual Clone() to avoid slicing and to perform "polymorphic copy".

I don't want to declare copy assignment and construction protected AND to define them (and to maintain in-sync with changes) unless I have some special thing to perform.

Do someone knows if there's another way?

thanks!

UgaSofT

Answer:
I don't think there is anything in the C++ language that allows you to do this.  Although I'd love to be wrong on this point.
I've run into this in the past and come up with the following solution.  Asumme the class is C1.
Define a private inner class called Data
Put all of my members I would delare in C1 on Data instead
Define a protected copy constructor that just copies Data instances between C1.
This approach has a couple of downsides.  Namely it feels a bit un-natural and eliminates direct field access (can be mitigated with small accessor functions).
It's a roundabout way of doing what you're looking for but it avoids you having to write the copy constructor by hand.


Question: I have a multi-threaded Windows application that occasionally deadlocks. Inevitably this happens on a customer system and not when the software is in test. What is the easiest way of getting a Windows Minidump of the current state of the application? If it could also terminate the application so the user can restart it and continue using the system that would be great.

Answer:
See the Microsoft support article
How to use ADPlus to troubleshoot "hangs" and "crashes"
, as well as the helpful blog post
Debugging Production Applications using ADPlus
.
Both of these articles are about "ADPlus", a VBScript tool supplied with Debugging Tools for Windows that can be used to generate minidumps from a production environment (which can later be loaded up with WinDbg on your development machine). ADPlus has a lot of functionality and a lot of options, so it may take some reading, experimentation, and practice to find the best way to use it in your environment.


Question:
Is there an event for when a document is edited?
If not, does anyone know where I could find a list of the available VBA events?

Answer:
Here are the events for the document object:
http://msdn.microsoft.com/en-us/library/aa140279(office.10).aspx
Events
```
```
DocumentBeforeClose : Immediately before any open document closes.
DocumentBeforePrint : Before any open document is printed.
DocumentBeforeSave : Before any open document is saved.
DocumentChange : A new document is created, when an existing document is opened, or when another document is made the active document.
DocumentOpen : A document is opened.
EPostageInsert : A user inserts electronic postage into a document.
EPostagePropertyDialog : A user clicks the E-postage Properties (Labels and Envelopes dialog box) button or Print Electronic Postage toolbar button. This event allows a third-party software application to intercept and show their properties dialog box.
MailMergeAfterMerge : After all records in a mail merge have merged successfully.
MailMergeAfterRecordMerge : After each record in the data source successfully merges in a mail merge.
MailMergeBeforeMerge : A merge is executed before any records merge.
MailMergeBeforeRecordMerge : As a merge is executed for the individual records in a merge.
MailMergeDataSourceLoad : The data source is loaded for a mail merge.
MailMergeDataSourceValidate : A user performs address verification by clicking Validate in the Mail Merge Recipients dialog box.
MailMergeWizardSendToCustom : The custom button is clicked on step six of the Mail Merge Wizard.
MailMergeWizardStateChange : A user changes from a specified step to a specified step in the Mail Merge Wizard.
NewDocument : A new document is created.
Quit : The user quits Word.
WindowActivate : Any document window is activated.
WindowBeforeDoubleClick : The editing area of a document window is double-clicked, before the default double-click action.
WindowBeforeRightClick : The editing area of a document window is right-clicked, before the default right-click action.
WindowDeactivate : Any document window is deactivated.
WindowSelectionChange : The selection changes in the active document window.
WindowSize : The application window is resized or moved.
```
```
There are also Auto Macros:
AutoNew, AutoOpen, AutoExec, AutoExit


Question:
I have just been getting into low level programming (reading/writing to memory that sort of thing) and have run into an issue i cannot find an answer to.

The piece of information i want to read from has an address that is relative to a DLL loaded in memory e,g, it is at mydll.dll + 0x01234567. the problem im having is that the dll moves around in memory but the offset stays the same. Is there anyway to find out the location of this dll in memory.

I am currently trying to do this preferably in c# but i would be grateful for help in most highish level languages.

Answer:
From a Win32 perspective you need to use the
GetModuleHandle
and
GetModuleInformation
functions.  These let you look the module handle up by name, and then retrieve information, including the base address about that handle.
It should be straight forward to wrap these APIs using the standard P/Invoke wrappers.


Question:
Excel has a Conditional Formatting... option under the Format menu that allows you to change the style/color/font/whatever of a cell depending upon its value.  But it only allows three conditions.

How do I get Excel to display say, six different background cell colors depending upon the value of the cell?  (IE Make the cell red if the value is "Red", and blue if "Blue" etc.)

Answer:
You will need to write something in VBA.
See example here:
Get Around Excels 3 Criteria Limit in Conditional Formatting
:
```
```
Private Sub Worksheet_Change(ByVal Target As Range)

Dim icolor As Integer

    If Not Intersect(Target, Range("A1:A10")) is Nothing Then

        Select Case Target

            Case 1 To 5
                icolor = 6
            Case 6 To 10
                icolor = 12
            Case 11 To 15
                icolor = 7
            Case 16 To 20
                icolor = 53
            Case 21 To 25
                icolor = 15
            Case 26 To 30
                icolor = 42
            Case Else
                'Whatever
        End Select

        Target.Interior.ColorIndex = icolor
    End If
End Sub
```
```


Question:
I have a list of items that I am displaying in a floated list, with each item in the list at a fixed width so that there's two per row. What is the best practice to prevent this horrible thing from happening:

alt text http://x01.co.uk/floated_items.gif

Possibilites:

Trim to a specified number of characters before displaying the data.  Requires guesswork on how many characters will be "safe".

Overflow: hidden.  Hacky.

Remove the background and just have a top border on each item.

Possible but silly:

Have a scrollbar in each item by doing overflow: auto, this will look horrendous.

Add a background image to the container.  It's not guaranteed that there's always an equal number of items so this option is out.

Any help on this irritating issue appreciated!

Answer:
Are you using a fixed font size, i.e. specified in px? If not you also need to consider the various text size options of each browser which is probably going to make the concept of trimming the string redundant. If it is fixed then perhaps seeing how many Ws you can fit in and restricting your text to that -3 and appending an ellipsis, not sure what this list is for so that's one approach.
Personally I'd probably use overflow:hidden as that covers all eventualities and ensures that it'll always keep your layout consistent.
I guess the last option would be to keep a tight control over what can be added to the list and prevent the problem occuring in the first place. Prevention better than cure as they say, although probably unhelpfully.


Question:
I'm running Apache on Windows XP via Xampplite, and could use help configuring my virtual directory. Here's what I'm hoping to do on my dev box:

I want my source files to live outside of the xampp htdocs dir

on my local machine I can access the project at http://myproject

others on my local network can access the project at my.ip.address/myproject

keep localhost pointing to the xampp's htdocs folder so I can easily add other projects.

I've got 1 & 2 working by editing the windows hosts file, and adding a virtual directory in xampp's apache\conf\extra\httpd-vhosts.conf file. I don't immediately see how to do 3 without messing up 4.

Answer:
Figured it out: use
Alias
for #3, instead of VirtualHost, thus:
```
```
Alias /myproject "C:/path/to/my/project"
<Directory "C:/path/to/my/project">
  Options Indexes FollowSymLinks MultiViews ExecCGI
  AllowOverride All
  Order allow,deny
  Allow from all
</Directory>
```
```


Question: The number of products out there right now still seems to be slim.

Answer:
I've had good success using
TableDifference
for data warehousing scenarios.


Question:
When you are somewhere between version 1 and version 2, what do you do to maintain your software?

The terms Patch, Hotfix, Maintenance Release, Service Pack, and others are all blurry from my point of view, with different definitions depending on who you talk to.

What do you call your incremental maintenance efforts between releases?

Answer:
When I hear those terms this is what comes to mind:
Patch - Publicly released update to
fix a known bug/issue
Hotfix - update to fix a very
specific issue, not always publicly
released
Maintenance Release - Incremental
update between service packs or
software versions to fix multiple
outstanding issues
Service Pack - Large Update that
fixes many outstanding issues,
normally includes all Patches,
Hotfixes, Maintenance releases that
predate the service pack
That being said that isn't how we do updates at all.  We just increment the version and/or build number (which is based on the date) and just call it an "Update".  For most software I find that easier, you can easily see that one computer is running 1.1.50 vs 1.2.25 and know which is newer.


Question:
I have a DataGrid with 5 template columns,

However when I try and add some dynamically created controls into the grid, it fails, as there are no rows.

-Can i add a blank row in and use that? and how?
-Or any other way?

Answer:
When I hear those terms this is what comes to mind:
Patch - Publicly released update to
fix a known bug/issue
Hotfix - update to fix a very
specific issue, not always publicly
released
Maintenance Release - Incremental
update between service packs or
software versions to fix multiple
outstanding issues
Service Pack - Large Update that
fixes many outstanding issues,
normally includes all Patches,
Hotfixes, Maintenance releases that
predate the service pack
That being said that isn't how we do updates at all.  We just increment the version and/or build number (which is based on the date) and just call it an "Update".  For most software I find that easier, you can easily see that one computer is running 1.1.50 vs 1.2.25 and know which is newer.


Question:
I have a form which is used to insert/display and update. In the edit mode (update), when I pass my BO back to the Controller, what is the best possible way to check if any of the property values were changed, in order to execute the update to the datastore?

textbox1.text = CustomerController.GetCustomerInformation(id).Name

A customer object is returned from the controller. I need to check if the the object is dirty in order to execute an update. I would assume the object sent from the client has to be compared with the one sent from the controller when I do:

CustomerController.Save(customer)

How is this normally done?

Answer:
A good way is to have an IsDirty flag on the object and have all the setable properties update that flag if they are changed.  Have the flag initialized to false when the object is loaded.
An example property would look like this:
```
```
public string Name {
    get { return _name; }
    set {
        _name = value;
        _isDirty = true;
    }
}
```
```
Then when you get the object back you can simply check,
```
Customer.IsDirty
```
to see if you need to commit the changes to the database.  And as an added bonus you get some humour from the resulting text :) (
oh those dirty customers
)
You can also opt to always save the object regardless of whether it has been changed, my preference is to use a flag.


Question:
At the moment I have setup a custom ok cancel dialog with a drop down in c#. The ok and cancel buttons use the DialogResult property so no code behind it. What I now need to do is validate the drop down to check it isn't left empty before posting back a dialogresult.

Is this possible?

Answer:
From
here
Double-click the  Closing field, and implement it as follows:
```
```
private void Second_Closing(object sender,
        System.ComponentModel.CancelEventArgs e)
{
    // When the user attempts to close the form, don't close it...
    e.Cancel = (dropdown.selecteditemindex >= 0);
}
```
```


Question:
Is there a tool to generate WiX XML given a .reg file?

In 2.0, you were supposed to be able to run tallow to generate registry XML:

tallow -r my.reg

For what it's worth, the version of tallow I have is producing empty XML.

In 3.0, tallow has been replaced with heat, but I can't figure out how to get it to produce output from a .reg file.

Is there a way to do this in 3.0?

Answer:
I couldn't find a tool, so I made one.
The source code may not be elegant, but it seems to work:
```
```
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;

namespace Reg2Wix
{
    class Program
    {
        static void PrintUsage()
        {
            Console.WriteLine("reg2wix <input file> <output file>");
        }

        /// <summary>
        /// Parse the hive out of a registry key
        /// </summary>
        /// <param name="keyWithHive"></param>
        /// <param name="hive"></param>
        /// <param name="key"></param>
        static void ParseKey(string keyWithHive, out string hive, out string key)
        {
            if (keyWithHive == null)
            {
                throw new ArgumentNullException("keyWithHive");
            }
            if (keyWithHive.StartsWith("HKEY_LOCAL_MACHINE\\"))
            {
                hive = "HKLM";
                key = keyWithHive.Substring(19);
            }
            else if (keyWithHive.StartsWith("HKEY_CLASSES_ROOT\\"))
            {
                hive = "HKCR";
                key = keyWithHive.Substring(18);
            }
            else if (keyWithHive.StartsWith("HKEY_USERS\\"))
            {
                hive = "HKU";
                key = keyWithHive.Substring(11);
            }
            else if (keyWithHive.StartsWith("HKEY_CURRENT_USER\\"))
            {
                hive = "HKCU";
                key = keyWithHive.Substring(18);
            }
            else
            {
                throw new ArgumentException();
            }
        }

        /// <summary>
        /// Write a WiX RegistryValue element for the specified key, name, and value
        /// </summary>
        /// <param name="writer"></param>
        /// <param name="key"></param>
        /// <param name="name"></param>
        /// <param name="value"></param>
        static void WriteRegistryValue(XmlWriter writer, string key, string name, string value)
        {
            if (writer == null)
            {
                throw new ArgumentNullException("writer");
            }
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (value == null)
            {
                throw new ArgumentNullException("value");
            }

            string hive;
            string keyPart;
            ParseKey(key, out hive, out keyPart);

            writer.WriteStartElement("RegistryValue");

            writer.WriteAttributeString("Root", hive);
            writer.WriteAttributeString("Key", keyPart);
            if (!String.IsNullOrEmpty(name))
            {
                writer.WriteAttributeString("Name", name);
            }
            writer.WriteAttributeString("Value", value);
            writer.WriteAttributeString("Type", "string");
            writer.WriteAttributeString("Action", "write");

            writer.WriteEndElement();
        }

        /// <summary>
        /// Convert a .reg file into an XML document
        /// </summary>
        /// <param name="inputReader"></param>
        /// <param name="xml"></param>
        static void RegistryFileToWix(TextReader inputReader, XmlWriter xml)
        {
            Regex regexKey = new Regex("^\\[([^\\]]+)\\]$");
            Regex regexValue = new Regex("^\"([^\"]+)\"=\"([^\"]*)\"$");
            Regex regexDefaultValue = new Regex("@=\"([^\"]+)\"$");

            string currentKey = null;

            string line;
            while ((line = inputReader.ReadLine()) != null)
            {
                line = line.Trim();
                Match match = regexKey.Match(line);
                if (match.Success)
                {
                    //key track of the current key
                    currentKey = match.Groups[1].Value;
                }
                else
                {
                    //if we have a current key
                    if (currentKey != null)
                    {
                        //see if this is an acceptable name=value pair
                        match = regexValue.Match(line);
                        if (match.Success)
                        {
                            WriteRegistryValue(xml, currentKey, match.Groups[1].Value, match.Groups[2].Value);
                        }
                        else
                        {
                            //see if this is an acceptable default value (starts with @)
                            match = regexDefaultValue.Match(line);
                            if (match.Success)
                            {
                                WriteRegistryValue(xml, currentKey, (string)null, match.Groups[1].Value);
                            }
                        }
                    }
                }
            }
        }

        /// <summary>
        /// Convert a .reg file into a .wsx file
        /// </summary>
        /// <param name="inputPath"></param>
        /// <param name="outputPath"></param>
        static void RegistryFileToWix(string inputPath, string outputPath)
        {
            using (StreamReader reader = new StreamReader(inputPath))
            {
                using (XmlTextWriter writer = new XmlTextWriter(outputPath, Encoding.UTF8))
                {
                    writer.Formatting = Formatting.Indented;
                    writer.Indentation = 3;
                    writer.IndentChar = ' ';
                    writer.WriteStartDocument();
                    writer.WriteStartElement("Component");
                    RegistryFileToWix(reader, writer);
                    writer.WriteEndElement();
                    writer.WriteEndDocument();
                }
            }
        }

        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                PrintUsage();
                return;
            }
            RegistryFileToWix(args[0], args[1]);
        }
    }
}
```
```


Question:
I have set a canvas' background to an image of a company logo.  I would like for this image to be aligned to the bottom right corner of the canvas.

Is it possible to do this, or would it require for the image to be added into the canvas as a child?  That would not work with this program as all children of the canvas are handled differently.

Thank You

Answer:
AFAIK The WPF Canvas needs child UI elements to be positioned using absolute co-ordinates.
To achieve the right-bottom-anchored effect, I think you'd need to
handle the window resize event, recalculate and apply the Top,Left co-ordinates
for the child Image element to always stick to the right buttom corner.
```
```
<Window x:Class="HelloWPF.Window1" xmlns...
    Title="Window1" Height="300" Width="339">
    <Canvas>
        <Image Canvas.Left="195" Canvas.Top="175" Height="87" Name="image1" Stretch="Fill" Width="122" Source="dilbert2666700071126ni1.gif"/>
    </Canvas>
</Window>
```
```


Question: Ages ago when I was a java developer I could make separate ant scripts that I would call from my main ant script. I would put properties unique to each environment where my main script would run. I want to do the same thing in MSBuild but I can't find out how to chain MSBuild scripts together.

Answer:
You need to
Import
them.
```
```
<Import Project="MyTargets" Condition="Exists('MyTargets')"/>
```
```