Question:
I'm using IIS 6 with EPiserver CMS which requires all requests to go through aspnet_isapi.dll.

I want to gzip all my static files (js, css mainly). Trying to setup compression in IIS didn't work.

Is there a setting in EPiServer that will allow me to achieve this?
Can .net framework compress files automatically?

Answer:
You'll need to configure the html extension in the IIS metabase
as a dynamically compressed extension
. You are probably  treating it as a static page. If the .js and .css extensions are mapped to aspnet_isapi they are considered as dynamic pages.
The setting in
metabase.xml
should look like this:
```
```
HcScriptFileExtensions="asp
dll
exe
js
css"
```
```
Don't forget to remove the extensions from
```
HcFileExtensions
```
(for static files) if you inserted them there before.
Hope this helps.


Question:
I am looking for any best practices or ideas on how you would create an interface with a DB from a .NET web application to upload data from Excel files
Should I use a mechanism that allows all the records to be loaded and flags the errors or should I use a mechanism that stops the load when an error occurs.

I've never had to deal with this type of requirement before so any help would be super!

Thanks

Answer:
do you want to put the excel files in the DB as a blob? or do you want to parse the files and put the records in the files into the db?
I'm assuming it is the latter.
As a user I'd like to have the option to know what the errors are so I can fix them and try again. I think how I try again depends on how much data I'm uploading.
I'd try to do a hybrid solution .. if there are only a few errors show a screen to correct those errors so the user can move on quickly. If there are a ton of errors you should just can it and have the user try all over again.
As far as the DB. Either have a separate table that uploads go into until they are checked and get with your "real" data, or have a UploadUniqueId column so you can roll-back any upload without much fuss.
delete tableName where UploadUniqueId = 'GUID'


Question:
I thought this code would work, but the regular expression doesn't ever match the \r\n. I have viewed the data I am reading in a hex editor and verified there really is a hex D and hex A pattern in the file.

I have also tried the regular expressions /\xD\xA/m and /\x0D\x0A/m but they also didn't match.

This is my code right now:

   lines2 = lines.gsub( /\r\n/m, "\n" )
   if ( lines == lines2 )
       print "still the same\n"
   else
       print "made the change\n"
   end

In addition to alternatives, it would be nice to know what I'm doing wrong (to facilitate some learning on my part).  :)

Answer:
```
```
lines2 = lines.split.join("\n")
```
```


Question:
I am using an ancient version of Oracle (8.something) and my ADO.NET application needs to do some fairly large transactions. Large enough to not fin in our small rollback segments. Now we have a large rollback segment as well but it is not used by default.

Oracle has a command to select the rollback segment to be used (SET TRANSACTION USE ROLLBACK SEGMENT MY_ROLLBACK_SEGMENT) but it needs to be the first command issued in the transaction. Unfortunately, it seems that ADO.NET issues some other commands at the beginning of a transaction since issuing this command right after .BeginTransaction() throws an error about SET TRANSACTION not being the first command.

I am sure I am not the only one who faced this issue. How do you solve it or how would you get around it?

Thanks

Answer:
If this is a 'one-off' requirement then one solution is to put the other rollback segments offline while you run your transactions then put them online when you've finished;
```
```
ALTER ROLLBACK SEGMENT <name> OFFLINE;

ALTER ROLLBACK SEGMENT <name> ONLINE;
```
```
Otherwise make all the rollback segments the same size.


Question:
Recently an application I wrote started not working on Internet Explorer. There has been no change to the underlying (ruby on rails) code.

In IE 6 or IE 7, I can make one request (HTTP Post) to the app, but when I try to make a 2nd  request, I get an "Operation Aborted" message. Everything works fine in firefox. The HTTP Request and Response headers are exactly the same. The response header for the correct and incorrect results both have the same content-length (about 104k). The correct response has the full content, but the incorrect response has the content cut off after bout 40k. (So about 65k of the response is just gone.)

The even trickier thing is that if I use the IP address instead of the domain name to make the request, everything works great.

This is an apache2 web server.

Any ideas?

Answer:
You could try to debug the issue using
Fiddler
. It's free HTTP Proxy tool for Internet Explorer.
It lists every detail of the request and response. Maybe you can see the actual cause of that behaviour inspecting the whole HTTP traffic.
Hope this helps!
alt text http://i.msdn.microsoft.com/Bb250446.ie_introfiddler_fig04(en-us,VS.85).gif


Question:
I'm working with an existing Java codebase which, while it can be invoked from an HTML page using an <APPLET> tag, does not actually subclass the Applet class. The same jars are also used in a non-browser context, so they did not subclass Applet.

Now I need to communicate some values from Java back to the Javascript of the invoking page. Normally one would do this using JSObject, but so far as I can one has to use JSObject.getWindow which only works for subclasses of Applet.

Is there either:

a way to use JSObject from something which isn't an Applet subclass?

some other mechanism to communicate back to the Javascript of the invoking page?

Answer:
Call
```
JSObject.getWindow(this)
```
in the applet. Then pass the
```
JSObject
```
into the code that needs it in the usual fashion.


Question:
I am creating a form in HTML that will be printed, with fields that need to be written in by the recipient. Basically what I want is a single line that stretches from the end of the field label to the side of the page. Here's how I'm doing it right now:

<table width="100%">
    <tr>
        <td width="1%">
            Label:
        </td>
        <td style="border-bottom-style:solid; border-bottom-width:1px;">
            &nbsp;
        </td>
    </tr>
</table>

This works, but there must be an easier way to do this without needing a whole table element. Any ideas?

Answer:
How about using the span tag?
```
```
Text
```
```


Question:
If you have to use String.Replace() to replace test 50 times, you essentially have to create a new string 50 times.  Does StringBuilder.Replace() do this more efficiently?  E.g., should I use a StringBuilder if I'm going to be replacing a lot of text, even while I won't be appending any data to it?

I'm using .NET, but I assume this would be the same as Java and possibly other languages.

Answer:
Yes, it is.
```
String.Replace
```
always creates a new string –
```
StringBuilder.Replace
```
doesn't.


Question: Is there an API to access Subversion from C#?

Answer:
Check
SubversionSharp
, its basically a C# wrapper library that fully covers the client API of Subversion.


Question:
I'm trying to come up with a reusable JS or jQuery function that would allow me to test if one object is a DOM descendant of another.

I've seen a model of testing for

$b.parents('nodename').length>0

Which is fantastic when you only need to check if an element is a child of any node by that name.

But what about a specific node? You can't test

$b.parents($a).length>0

Because jQuery parents takes a nodename expression as an argument to filter.

As a little background, I'm trying to test if a document click event's target is a child of a specific object. For instance, if the event.target is a child of $b, return true, otherwise, return false. But this function could have other implications later on.

Thanks!

Answer:
Try this:
```
```
$('#foo').filter(function(){

   return $(this).parent().is('#foo-parent');

});
```
```
So here we are selecting all the foo elements and then filtering only the elements that have the foo-parent as their immediate parent.
If you are looking to find if the any of the ancestors of the current object comply to the rule, then I guess it should be:
```
```
$('#foo').filter(function(){

   return $(this).parents().is('#foo-parent');

});
```
```


Question:
DataGridView, for example, lets you do this:

DataGridView dgv = ...;
DataGridViewCell cell = dgv[1,5];

but for the life of me I can't find the documentation on the index/square-bracket operator.  What do they call it?  Where is it implemented?  Can it throw?  How can I do the same thing in my own classes?

ETA: Thanks for all the quick answers.  Briefly: the relevant documentation is under the "Item" property; the way to overload is by declaring a property like public object this[int x, int y]{ get{...}; set{...} }; the indexer for DataGridView does not throw, at least according to the documentation.  It doesn't mention what happens if you supply invalid coordinates.

ETA Again: OK, even though the documentation makes no mention of it (naughty Microsoft!), it turns out that the indexer for DataGridView will in fact throw an ArgumentOutOfRangeException if you supply it with invalid coordinates.  Fair warning.

Answer:
```
```
Operators                           Overloadability

+, -, *, /, %, &, |, <<, >>         All C# binary operators can be overloaded.

+, -, !,  ~, ++, --, true, false    All C# unary operators can be overloaded.

==, !=, <, >, <= , >=               All relational operators can be overloaded,
                                    but only as pairs.

&&, ||                              They can't be overloaded

() (Conversion operator)            They can't be overloaded

+=, -=, *=, /=, %=                  These compound assignment operators can be
                                    overloaded. But in C#, these operators are
                                    automatically overloaded when the respective
                                    binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof  These operators can't be overloaded

    [ ]                             Can be overloaded but not always!
```
```
Source of the information
For bracket:
```
```
public Object this[int index]
{

}
```
```
##BUT
The array indexing operator
cannot be overloaded
; however, types can define indexers, properties that take one or more parameters. Indexer parameters are enclosed in square brackets, just like array indices, but indexer parameters can be declared to be of any type (unlike array indices, which must be integral).
From
MSDN


Question: I am having severe performance issues when compiling a moderately large ASP.Net website in Visual Studio 2008 (targeting .Net 3.5). I know there are some tips & registry hacks for improving compilation performance in VS 2005, are there any for VS 2008? Specifically, it seems that VS 2008 is compiling the whole website every time F5 is hit, even when no files have changed in that project since the last compile, or perhaps there is some way to skip the validation stage?

Answer:
I'm guessing this is an ASP.Net Website project and
not
an ASP.Net Web Application project. You'll get better compile performance from a Web Application project so you might consider converting it.
For a Website project, you can open the Website in Visual Studio, right click the web site project node in the Solution Explorer and click Properties. When the dialog box opens, click the Build item and set the item labeled "Before Running Startup Page" to "No Build" or "Build Page". This will prevent Visual Studio from compiling all the pages in your site and improve your local development experience at the cost of reduced compilation. Probably a worthy trade-off in your case.


Question: I know that jQuery and prototype have a $.each() function for iterating over each element in an array. Does YUI offer any help with this?

Answer:
What keeps you from simply
iterating
the array?
```
```
for(var i=0; i<ary.length; i++)
  // assuming that ary[] contains objects with a DoSometing() method
  ary[i].doSomething();
```
```


Question:
I'd like to make an (MS)SQL query that returns something like this:

Col1 Col2                  Col3
---- --------------------- ------
AAA  18.92                 18.92
BBB  20.00                 40.00
AAA  30.84                 30.84
BBB  06.00                 12.00
AAA  30.84                 30.84
AAA  46.79                 46.79
AAA  86.40                 86.40

where Col3 is equal to Col2 when Col1 = AAA and Col3 is twice Col2 when Col1 = BBB.
Can someone point me in the rigth direction please?

Answer:
You didn't mention what kind of database you're using.  Here's something that will work in SQL Server:
```
```
SELECT Col1, Col2,
    CASE WHEN Col1='AAA' THEN Col2 WHEN Col1='BBB' THEN Col2*2 ELSE NULL END AS Col3
FROM ...
```
```


Question:
Ruby on Rails controllers will automatically convert parameters to an array if they have a specific format, like so:

http://foo.com?x[]=1&x[]=5&x[]=bar

This would get converted into the following array:

['1','5','bar']

Is there any way I can do this with an ActionScript 3 HTTPService object, by using the request parameter?  For example, It would be nice to do something like the following:

var s:HTTPService = new HTTPService();
s.request['x[]'] = 1;
s.request['x[]'] = 5;
s.request['x[]'] = 'bar';

However, that will simply overwrite each value, resulting in only the last value being sent.  Anyone have a better idea?  I know I could just append stuff to the query string, but I'd like to do it in the POST body.

Answer:
I usually do something like this...
```
```
var s:HTTPService = new HTTPService();
s.url = "http://foo.com";
s.method = "post";
// add listeners...
s.addEventListenser(ResultEvent.RESULT,function(event:ResultEvent){

    mx.controls.Alert.show(event.result.toString());
});

// send the data...
s.send({
    a: 1,
    b: 5,
    c: "bar"
});
```
```
which would result in the HTTP Get / POST of:
http://foo.com?a=1&b=5&c=bar
You could also just create an associative array and pass it to the HTTPService send method, that would be something like:
```
```
var postdata:Object = {};

postdata["a"] = 1;
postdata["b"] = 5;
postdata["c"] = "bar";

// s is the HTTPService from above...
s.send(postdata);
```
```


Question:
How can I match (PCRE) everything inbetween two tags?

I tried something like this:

<!--\s*LoginStart\s*-->(.*)<!--\s*LoginEnd\s*-->

But it didn't work out too well for me..

I'm kind of new to regular expressions, so I was hoping if someone would be kind enough to explain to me how I would accomplish this, if its even possible with regular expressions.

Thanks

Answer:
PHP and regex?  Here's some suggestions:
```
```
'/<!--\s*LoginStart\s*-->(.*)<!--\s*LoginEnd\s*-->/Us'
```
```
Might be better - the
```
U
```
capitalized makes the regex non-greedy, which means it'll stop at the first
```
<!--
```
that may work.  But the important one is the
```
s
```
, which tells the regex to match a newline with the
```
.
```
character.
Depending on how certain you are on the capitalization, adding an
```
i
```
at the end will make the regex search case-insensitive.


Question:
So, I've been tasked with making a kiosk for the office for showing statistics about our SCRUM progress, build server status, rentability and so forth. It should ideally run a slideshow with bunch of different pages, some of them showing text, some showing graphs and so on.

What is the best approach for this? I first thought of powerpoint, but It should be able to take the images from a webserver so I can automate the graph generation procedure. I would also like to take text from an external source when showing "Who broke the build" or some page like that.

I have no doubt that ready-made systems exist, but I don't really know where to look for them.

Is this easy/hard in powerpoint? Or are there an ubiquous app that everybody but me knows about?

Answer:
I would recommend creating it as a series of web-pages, which uses Javascript or the meta refresh tag to cycle though the different pages. Simply full-screen the browser on a spare machine, and connect it to a projector/monitor/big TV.
This has lots of benefits:
it's
trivial
to display images from an external server (an
```
<img>
```
tag)
it will cost nothing to setup (it can run on basically any functioning machine), and runs in a browser
it is quick to do (you do not have to worry about cross-browser compatibility, or different screen resolutions as you know the exact machine you are developing for
it's expandable - while what you describe is probably possible within Powerpoint, but if you do it as a web-page, you can use Javascript (or a JS framework like jQuery), and it's very easy to serve the pages via a web-server, then you can use any server-side scripting language.
Basically, you would have a series of files, say
```
slide001.htm
```
,
```
slide002.htm
```
and
```
slide003.htm
```
. Slide 1 would redirect to slide002 after 30 seconds, slide002 to slide 003, and slide003 would redirect to slide001..
The specific things you mention: graph generation and "Who broke the build" text:
Not sure which CI tool you use, but many of them generate graphs anyway, so that would be required is having one "slide" with something like
```
<img src="http://hudson.abc/job/proj042/buildTimeGraph">
```
For the who-broke-the-build text, you would be easiest to run the slides as
```
.php
```
files served though a web-server, using
XAMMP
.
Then you would have a function that scrapes your CI server for whoever broke the last build, and in one of the slides, you would have
```
<?PHP echo(who_broke_build()); ?>
```
(Obviously if you know some other language/system better, use that!)
The final benefit I can think of is that, if you serve the files through a web-server, you can allow people display it locally, say as their browsers home-page.


Question: Joel often talks about using MS Excel for lightweight project management, but I'm curious about actual implementations of this idea. I've seen some templates that seem to clone MS Project via macros, which would be overkill for a lightweight project. Anyone have any useful templates?

Answer:
You have some pretty advance template with
Pipetalk Scheduler
alt text http://ep.yimg.com/ip/I/pipetalk_2055_216386
However, since it seems to be a
little too much
, I just transfered that to the
worst UI thread
;)


Question:
I found one source which successfully overrode Time.strftime like this:

class Time
  alias :old_strftime :strftime
  def strftime
    #do something
    old_strftime
  end
end

The trouble is, strftime is an instance method.  I need to override Time.now - a class method - in such away that any caller gets my new method, while the new method still calls the original .now method.  I've looked at alias_method and have met with no success.

Answer:
Class methods are just methods. I highly recommend against this, but you have two equivalent choices:
```
```
class Time
  class << self
    alias_method :old_time_now, :now

    def now
      my_now = old_time_now
      # new code
      my_now
    end
  end
end

class << Time
  alias_method :old_time_now, :now

  def now
    my_now = old_time_now
    # new code
    my_now
  end
end
```
```


Question:
I need some help regarding algorithm for randomness. So Problem is.

There are 50 events going to happen in 8 hours duration. Events can happen at random times.
Now it means in each second there is a chance of event happening is 50/(8*60*60)= .001736.
How can I do this with random generation algorithm?

I can get random number

int r = rand();
double chance = r/RAND_MAX;
if(chance < 0.001736)
    then event happens
else
    no event

But most of times rand() returns 0 and 0<0.001736 and I am getting more events than required.

Any suggestions?

sorry I forget to mention
I calculated chance as
double chance = (static_cast )(r) / (static_cast)(RAND_MAX);

It removed double from static_cast

double chance = (double)r/(double)(RAND_MAX);

Answer:
Both
```
r
```
and
```
RAND_MAX
```
are integers, so the expression
```
```
double chance = r / RAND_MAX;
```
```
is computed with integer arithmetic. Try:
```
```
double chance = 1.0 * r / RAND_MAX;
```
```
which will cause the division to be a floating point division.
However, a better solution would be to use a random function that returns a floating point value in the first place. If you use an integer random number generator, you will get some bias errors in your probability calculations.


Question:
I have often wondered why it is that non-English speaking programmers are forced to use a different language when programming when it would seem to be so easy to offer an IDE that could replace keywords with localized versions. Why can't the Germans use a "während..macht" loop?

Do programmers in Japan, Germany, France, Spain, Botswana just make extensive use of macros/define statements to make life more tolerable or do they just get used to the functional significance of print, if, then, while, do, begin, end, var, double, function, etc?

Perhaps the increased use of frameworks (J2EE/.NET) makes this more complicated, but it still seems worthwhile. On the other hand, if Klingon became the de-facto programming language in the US I'd probably regret suggesting this.

Answer:
In most programming languages, keywords are reserved, so they can't be used for variable names etc.
Now suppose the keywords changed every time you changed culture - code written in one culture couldn't be ported to another without changing identifiers. Ick. Furthermore, when anyone copied their code onto a question forum like this, we'd no longer be speaking the same language, as it were.
There are distinct advantages to only having one culture in the programming language itself...


Question:
I am using a WCF service and a net.tcp endpoint with serviceAuthentication's principal PermissionMode set to UseWindowsGroups.

Currently in the implementation of the service i am using the PrincipalPermission attribute to set the role requirements for each method.

        [PrincipalPermission(SecurityAction.Demand, Role = "Administrators")]
        [OperationBehavior(Impersonation = ImpersonationOption.Required)]
        public string method1()

I am trying to do pretty much the same exact thing, except have the configuration for the role set in the app.config. Is there any way to do this and still be using windows groups authentication?

Thanks

Answer:
If I understood well you want to select the role at runtime. This can be done with a
permission
demand within the WCF operation. E.g.
```
```
public string method1()
{
    PrincipalPermission p = new PrincipalPermission(null, "Administrators");
    p.Demand();
    ...
```
```


Question:
I have a netbook running Linux and a large collection of computer books and reference material as HTML. I'd like some compact way of storing these books which can be browed without unpacking them first. This would save space and reduce wear on my small SSD.

If there was some way to convince Firefox to browse files contained in ZIP file, this would be ideal. (I know iCab (Mac) had a web archive format that worked this way.)  Perhaps a Firefox plugin? A small web server that can serve directly from ZIP files? Some magic FUSE module? Does anyone have any ideas?

On my PDA (which the netbook is largely replacing) I used iSilo for this, but it's not available for Linux, its conversions are lossy and it costs money.

Answer:
You can use
OpenOffice.org
to open the html pages, and then save them as OO documents. OO documents are essentially a zip files.
Another option is to use OO to save as pdf.
You can even do this from a command line using this
OO macro
.
Same with
AbiWord
- you can use it on
commandline to convert
.
In the AbiWord example there is shown how to convert all files in a directory to a desired format (pdf). Then you can use
pdftools
to merge all pages in one document.
Also, I do not know what windows manager your laptop has, but if it is KDE, konqueror (the file and web browser for KDE) opens web pages from inside a zip file w/o any problem.
Most probably Gnome's Nautilus can do this as well (I have no Gnome here to test).
Have you ever tried to open a zip file with whatever file manager you have, and then click on a web page inside it?


Question: I have an HTTPHandler that is reading in a set of CSS files and combining them and then GZipping them.  However, some of the CSS files contain a Byte Order Mark (due to a bug in TFS 2005 auto merge) and in FireFox the BOM is being read as part of the actual content so it's screwing up my class names etc.  How can I strip out the BOM characters?  Is there an easy way to do this without manually going through the byte array looking for "ï»¿"?

Answer:
Expanding on
Jon's comment
with a sample.
```
```
var name = GetFileName();
var bytes = System.IO.File.ReadAllBytes(name);
System.IO.File.WriteAllBytes(name, bytes.Skip(3).ToArray());
```
```


Question: According to the C# compiler and the Silverlight 2 documentation, Silverlight doesn't provide a FindName method for the DataTemplate class.  I want to find a Border that's inside a ContentPresenter.  What's the best way in SilverLight 2?

Answer:
Not totally sure I understand the scenario, but since you mention the DataTemplate I'm assuming you're using a template.
If you're using a template then what you do is give your border a name (x:Name="border") and then override the OnApplyTemplate method. In that method you use GetTemplateChild and pass the name you used. This will return a reference to your border.
If you're not use a template and have a reference to the ContentPresenter then you could write a recursive function that looks at the Content property of the child and if it isn't a border then calls your same function on its content.


Question:
I would like to include some code coverage into our nightly build process. We're using CruiseControl, Ant, and Buckminster. Buckminster drives checkout from multiple repositories, and the PDE building and packaging of the product.

Has any one any experience integrating code coverage into an RCP headless build?

I have been looking at Cobertura, EMMA/EclEMMA, DbUnit though am very interested to hear of any experiences with these or any other tools.

Answer:
Cobertura seemed to be able to do the job for us.
Once the unit tests were running (a question all to itself), I was able to:
instrument the bundles as standalone Jars.
re-run the unit tests with a cobertura on the parent class loader class path.
The trick here is to use
```
osgi.parentClassloader=app
```
in the config.ini file used to run the unit test.
```
ext
```
== Java extensions
```
boot
```
== the boot class loader (default)
```
fwk
```
== framework?
```
app
```
== application, i.e. just like a normal application, with a classpath specified on the command line.
The instrumented code needed runtime access to the cobertura jar, so this last step was imperative.


Question:
I'm trying to watch the execution of a VB6 app and I'm running into an issue because once I enter the debugger and then hit Continue, it no longer lets me step through the code until I hit another break point.  I want to be able to execute a program without  stepping through something until I hit a point where I want to watch it execute.  Ideally this would be something to the effect of holding a key down while I pressed a button to 'step into' that function.

Thanks in advance!

[EDIT]: I'm aware that I can use break points to stop the execution.  To be more clear, the problem is that I don't know where the execution is going to, so I can't set the break point there (because I don't know where there is).  That's why I essentially want to be able to say, 'after this next thing that I do, break, no matter what'.  It sounds like this functionality does not exist, but I'm still keeping my fingers crossed.

Answer:
You can press the F8 key to step through the code line by line.  Alternatively, you can press SHIFT-F8 to step through line by line.
F8 will step you in to a function, where SHIFT-F8 will step you over the function.  If you click on the DEBUG menu in the VB IDE, you will see other options too.
EDIT:
You can also put a permanent break point in your code by using:
```
```
Debug.Assert False
```
```
By doing it this way, the 'breakpoint' is saved in your code.  When you compile the app, debug code is ignored.


Question:
Say we are traversing a graph and want to quickly determine if a node has been seen before or not. We have a few set preconditions.

Nodes have been marked with integers values 1..N

Graph is implemented with nodes having an adjacency list

Every integer value from 1..N occurs in the graph, which is of size N

Any ideas for doing this in a purely functional way?(No Hash tables or arrays allowed).

I want a data structure with two functions working on it; add(adds an encountered integer) and lookup(checks if integer has been added). Both should preferably take O(n) time amortized for N repetitions.

Is this possible?

Answer:
You can use a
Data.Set
. You add an element by creating a new set from the old one with
```
insert
```
and pass the new set around. You look up whether an element is a member of the set with
```
member
```
. Both operations are O(log n).
Perhaps, you could consider using a state monad to thread the passing of the set.


Question:
I have been trying to learn more about lambda expressions lately, and thought of a interesting exercise...

is there a way to simplify a c++ integration function like this:

// Integral Function
double integrate(double a, double b, double (*f)(double))
{
    double sum = 0.0;

    // Evaluate integral{a,b} f(x) dx
    for(int n = 0 ; n <= 100; ++n)
    {
        double x = a + n*(b-a)/100.0;
        sum += (*f)(x) * (b-a)/101.0;
    }
    return sum;
}

by using c# and lambda expressions?

Answer:
What about this:
```
```
public double Integrate(double a,double b, Func<double, double> f)
{
    double sum = 0.0;

    for (int n = 0; n <= 100; ++n)
    {
        double x = a + n * (b - a) / 100.0;
        sum += f(x) * (b - a) / 101.0;
    }
    return sum;
}
```
```
Test:
```
```
Func<double, double> fun = x => Math.Pow(x,2);
    double result = Integrate(0, 10, fun);
```
```


Question: Where should I be logging exceptions? At the data service tier(ExecuteDataSet, etc.) and/or at the data access layer and/or at the business layer?

Answer:
If you are throwing the exception you should log it when it occurs and then  bubble it up.  Otherwise only the end user should log an exception (you may have lots of tracing on of course in which case it may get logged quite a bit).
The end user may be a UI component or a Service or something...
If you handle an exception in you code somewhere - then that is the end user and you should log it there.  In most apps and in most cases it should be logged by the UI when it displays the error message to the user.


Question: I want to write a little app for myself which notifies me if there is a new version of php or mysql but I would need a feed or an xml file to read it from.

Answer:
PHP.net provides one
http://www.php.net/releases/index.php?serialize=1
An alternative that may allow you to add additional software later is looking into the feeds provided by freshmeat:
http://freshmeat.net/projects/mysql/


Question: Are there any Code Generators that would take a well-formed XML document, and write out an XSD schema based on how the XML document is structured?

Answer:
The XSD.exe utility (which is installed with Visual Studio) is capable of creating an XSD file from an XML file.
Here's the link on
MSDN
I believe it may also part of the .NET SDK, meaning you would not need a full-blown Visual Studio installation.


Question: In graph theory, what is the distinction between minimal distance (which Dijkstra's algorithm finds), and minimal path (which I'm not sure what it is)?

Answer: I'm not 100% sure, but it sounds like the minimal path would be the list of vertices visited when traversing the minimal distance path from vertex A to vertex B.


Question: what's the easiest way to bulk load my iTunes library xml into an existing SQL Server database?

Answer:
bcp with xml flag.
http://msdn.microsoft.com/en-us/library/ms162802.aspx
It really depends how you want it in there and what you're purposes are, which you haven't explained.


Question:
I have a JavaScript variable which holds an HTML page and due to the setup I need to extract everything between <div id="LiveArea"> and </div> from that variable using JavaScript.

Any help is greatly appreciated.

Answer:
I'm not sure I follow you when you say, "Javascript variable which holds an html page", but If you need to extract the HTML between such a div, you can use the element's innerHTML property.
```
```
var e = document.getElementById('LiveArea');
if(e) alert(e.innerHTML);
```
```


Question:
Here's some code I have:

MyClass* MyClass::getInstance()
{
   static MyClass instance;
   return &instance;
}

I want to look into this singleton's current values. But I'm currently paused three hours into execution, and the reason I'm paused is that I'm out of memory. So I can't put a breakpoint in this method there to see what the value is.

My question then is how to refer to this instance variable from a global scope. I've tried referring to it as MyClass::getInstance::instance but that doesn't work. I'm guessing getInstance has to be decorated somehow. Anyone know how?

This is in Visual Studio 2008.

Answer:
In gdb, you can put a watchpoint on the mangled name of the variable.
For example, with this function:
```
```
int f() {
    static int xyz = 0;
    ++xyz;

    return xyz;
}
```
```
I can watch _ZZ1fvE3xyz (as mangled by gcc 3.2.3 or gcc 4.0.1).


Question:
In Websphere when you do an LDAP query using LdapContext are the transmission of credentials encrypted?

LdapContext ctx = new InitialLdapContext (env, null);

Lets say I make an LdapContext for a web app to do some custom LDAP calls.

How do I know if my call is secure / encrypted?

Answer:
In order to secure/encrypt your LDAP calls you need to issue the "Start TLS" operation.
Otherwise I think transport is plain text.
For more:
http://java.sun.com/products/jndi/tutorial/ldap/ext/starttls.html
Obviously the Java API is based on LDAP itself.  So you could learn more about how the protocol itself handles it...i.e.:
http://en.wikipedia.org/wiki/Ldap#StartTLS


Question: I realized the solution to this problem while I was creating the documentation to ASK this question...so I am posting the answer if for no other reason than to keep me from wasting time on this in the future

Answer:
If the content to be TOGGLEd is displayed (visible) when the page is rendered the functions would be in the following order, if the content is hidden originally then reverse the functions
```
```

Upper div

Lover Div

```
```


Question: Does anyone have a suggestions as to the best way to allow users to select which columns appear in a datagrid?  I would like them to be able to set this up.  It would be stored with the user in a profile and loaded each time the user loads the grid.  I was thinking about something with ASP.NET personalization.

Answer:
There are several options for you here.
Add an 'X' image to the header for each column and with a javascript onclick event do a web method call to remove that column from the user's profile of what columns to load.
Have a customization flyout page where by there would be a checkbox list of all the columns and the user could either add or remove what columns from the grid.
There are a few more but they are less AJAX and more page reloading.


Question: Does anyone know of a good alternative to cron?  I would like something that can be run with  different time zones.

Answer:
You may consider
Quartz
(a java-based solution), that can take advantage of
```
Date
```
build in the appropriate TimeZone
.


Question: Can anybody tell me when Application_End is triggered in a lifecycle of an application? When all sessions are ended, will Application_End be triggered automatically? + Are there any other reasons why Application_End could be triggered?

Answer:
The
```
application_end
```
event primarily fires when the IIS pool is recycled or the application itself is unloaded. One other thing to note, that a change to a dependent file (say web.config) will cause the application to reload itself, which will in cause the application_end event to fire while it is closing itself off.
To note, the only instance I found of the application end event firing when the last user session times out is in some old documentation dated 2001. I'm not sure if that criteria still applies.


Question:
So if I have:

public class ChildClass : BaseClass
{
    public new virtual string TempProperty { get; set; }
}

public class BaseClass
{
    public virtual string TempProperty { get; set; }
}

How can I use reflection to see that ChildClass is hiding the Base implementation of TempProperty?

I'd like the answer to be agnostic between c# and vb.net

Answer:
Correction, if you are using VB the property you are looking for is "IsHideBySig".  This will be false in the case that the "new" keyword was used to define a method/property.
In the C# case, both instances are outputted as "hidebysig".  Thanks for pointing that out Greg.  I didn't realize I only tested this in VB.  Here's sample VB code that will repro this behavior.
```
```
Module Module1

    Class Foo
        Public Function SomeFunc() As Integer
            Return 42
        End Function
    End Class

    Class Bar
        Inherits Foo
        Public Shadows Function SomeFunc() As Integer
            Return 36
        End Function
    End Class

    Sub Main()
        Dim type = GetType(Bar)
        Dim func = type.GetMethod("SomeFunc")
        Stop
    End Sub

End Module
```
```


Question:
I have two system calls GetSystemTime() and GetThreadTimes() that I need to calculate the CPU utilization by a given Win32 thread.

For the sake of accuracy, I need to ensure that both GetSystemTime() and GetThreadTimes() are executed atomically; i.e. there should be no context switch in between a call to GetSystemTime() & GetThreadTimes().

The reason is that occasionally I end up with a percentage of over 100% (~ 1 in 500).

How can I ensure an atomic execution of the 2 function calls?

Thanks,
Sachin

Answer:
I'm not so sure you can. Unless you know what the underlying operations are in each function, and since they happen to be Windows API calls... good luck.
Would it not be possible to just adjust for percentages over 100?
```
```
perc = ( perc > 100.0f ) ? 100.0f : perc;
```
```


Question:
Do any of the existing JavaScript frameworks have a non-regex replace() function,
or has this already been posted on the web somewhere as a one-off function?

For example I want to replace "@!#$123=%" and I don't want to worry about which characters to escape. Most languages seem to have both methods of doing replacements. I would like to see this simple thing added.

Answer:
i may be misunderstanding your question, but javascript does have a
```
replace()
```
```
```
var string = '@!#$123=%';
var newstring = string.replace('@!#$123=%', 'hi');
```
```
edit
: (see comments) the 5th edition does seem to have this info in it, although it doesn't show up when i
link directly
to it. here's the relevant part:
The replace( ) method performs a search-and-replace operation. It takes a regular expression as its first argument and a replacement string as its second argument. It searches the string on which it is called for matches with the specified pattern. If the regular expression has the g flag set, the replace( ) method replaces all matches in the string with the replacement string; otherwise, it replaces only the first match it finds.
If the first argument to replace( ) is a string rather than a regular expression, the method searches for that string literally rather than converting it to a regular expression with the RegExp( ) constructor, as search( ) does.


Question:
Trying to establish a connection between my windows box (2003 server) and the oracle (11g) database.

I'm able to successfully ping the oracle host from the windows box. However tnsping command fails with the error tns-12532 error.

Any ideas to solve this issue?

Answer:
From
the Oracle Error Messages documentation
:
ORA-12532: TNS:invalid argument
Cause:
An internal function received an invalid parameter.
Action:
Not normally visible to the user. For further details, turn on tracing and reexecute the operation. If error persists, contact Oracle Customer Support.
Have you followed that path yet?


Question:
If I create a UserControl and add some objects to it, how can I grab the HTML it would render?

ex.

UserControl myControl = new UserControl();
myControl.Controls.Add(new TextBox());

// ...something happens

return strHTMLofControl;

I'd like to just convert a newly built UserControl to a string of HTML.

Answer:
Call its
```
.RenderControl()
```
method.


Question:
I am using this code to verify a behavior of a method I am testing:

    _repository.Expect(f => f.FindAll(t => t.STATUS_CD == "A"))
    .Returns(new List<JSOFile>())
    .AtMostOnce()
    .Verifiable();

_repository is defined as:

private Mock<IRepository<JSOFile>> _repository;

When my test is run, I get this exception:

Expression t => (t.STATUS_CD = "A") is not supported.

Can someone please tell me how I can test this behavior if I can't pass an expression into the Expect method?

Thanks!!

Answer:
In Rhino Mocks you would do something like this...
Instead of using an Expect, use a Stub and Ignore the arguments.  Then have --
```
```
Func<JSOFile, bool> _myDelegate;

_repository.Stub(f => FindAll(null)).IgnoreArguments()
   .Do( (Func<Func<JSOFile, bool>, IEnumerable<JSOFile>>) (del => { _myDelegate = del; return new List<JSOFile>();});
```
```
Call Real Code
*Setup a fake JSOFile object with STATUS_CD set to "A" *
```
```
Assert.IsTrue(_myDelegate.Invoke(fakeJSO));
```
```


Question:
How Can I put information in a outputstream from tapestry5 ?

I need a page when a user enters it open a dialog for save or open the file with the outputstream information.

I write the next code:

public class Index {

@Inject
private RequestGlobals requestGlobals;

@OnEvent("activate")
public void onActivate() {
    try {
        HttpServletResponse response = requestGlobals.getHTTPServletResponse();
        response.setContentType("text/txt");
        PrintWriter out = response.getWriter();
        out.println("hellooooooo");
        out.flush();
    } catch (IOException ex) {
        Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
    }
}

}

I hope that the result is only "helloooooooo" but is ("helloooooooo" + my html raw page)

Answer:
Your method should have a return type of StreamResponse. You return an implementation of the interface StreamResponse, which simply returns the data you want with the content type you want.
Look it up here:
http://tapestry.apache.org/tapestry5/apidocs/
more info here:
http://tapestry.formos.com/nightly/tapestry5/tapestry-core/guide/pagenav.html


Question:
I long thought that in C, all variables had to be declared at the beginning of the function. I know that in C99, the rules are the same as in C++, but what are the variable declaration placement rules for C89/ANSI C?

The following code compiles successfully with gcc -std=c89 and gcc -ansi:

#include <stdio.h>
int main() {
    int i;
    for (i = 0; i < 10; i++) {
        char c = (i % 95) + 32;
        printf("%i: %c\n", i, c);
        char *s;
        s = "some string";
        puts(s);
    }
    return 0;
}

Shouldn't the declarations of c and s cause an error in C89/ANSI mode?

Answer:
It compiles successfully because GCC allows the declaration of
```
s
```
as a GNU extension, even though it's not part of the C89 or ANSI standard. If you want to adhere strictly to those standards, you must pass the
```
-pedantic
```
flag.
The declaration of
```
c
```
at the start of a
```
{ }
```
block is part of the C89 standard; the block doesn't have to be a function.


Question: Is there any plugins for Eclipse for portlet design and deployment? I have never designed portlets so are there any good tutorials on the web as well?

Answer:
You do have a
tutorial
about portlet development (not portlet deployment though, that would be through an appropriate
eclipse-maven configuration
)
Portal eclipse
can also help to develop portlet in eclipse.


Question:
Can someone explain to me the difference between these 3 approaches to processing messages that fail delivery?

Poison Queue service

Dead-Letter Queue service

Using a response service to handle failures

I have "Programming WCF", but I don't really understand when you would use one of these over another, or when it would make sense to use more than one of them. Thanks!

Answer:
Poison message / dead letter message queues are used to place messages that have been determined to be undeliverable in a queue that will not try to deliver them anymore. You would do this if you might want to manually take a look at failed messages and process them at a later point. You use these type of queues when you want to keep bad messages from degrading the performance of your system by retrying over and over again.
On the other hand, a response service would be used to notify the sender that there was an error processing the message. Typically in this case you aren't planning on manually processing the bad message and need to let the system that sent the message in that the request has been rejected.
Note that these aren't exclusive. If you are using queues, there is always the chance that the message serialization might change enough to break messages that are in the queue in which case you might still want to have a dead letter queue even if you are using a response service.


Question:
I am trying to link the as3corelib library to use their JSON functionality following this tutorial. But am having trouble compiling it. My command looks like:

mxmlc --strict=true -library-path+=as3corelib.swc --file-specs  myapp.mxml

But I am getting this error:

_divided_mx_managers_SystemManager.as(13): col: 14 Error: Interface method getVisibleApplicationRect in namespace mx.managers:ISystemManager not implemented by
class _divided_mx_managers_SystemManager.

public class _divided_mx_managers_SystemManager

What is the problem?

Update: Is this because I am using Flex 3? The tutorial seems to be for Flex 2. If so, what do I need to do for Flex 3?

Answer:
Are you using the flex Gubmo sdk?
Looks like the method it's complaining about is in an interface that's part of Gumbo.
If so, then as3corelib probably won't work with it.


Question: Does Xcode support anything akin to Visual Studio style #region directives for arbitrary code folding?

Answer:
No, you can only fold code on various defined scoping levels in Xcode.
You can use little tricks to make navigating via the function menu easier, though.
```
```
#pragma mark
```
```
Allows you to create a grouping where the label following mark will show up in the function menu. If the label is a hyphen, a separator is inserted into the function menu.
Also, the following labels in comments will show up in the function menu:
```
```
// MARK:
// TODO:
// FIXME:
// !!!:
// ???:
```
```
Obviously since #pragma mark is not really portable, if you're building a portable application and need it to work with a compiler that doesn't just ignore #pragma directives that it doesn't understand, the comment-style mark is a decent alternative.


Question:
Anyone knows a good way to resize any window to for example 640x480?

Reason is, of course, screencasting.

Under windows I've used ZoneSize from donationcoder. (Btw: For Firefox it's easy, just use the web developer toolbar.)

Answer:
Use the
wmctrl
command:
To list the windows:
```
```
$ wmctrl -l
0x00c00003 -1 rgamble-desktop Bottom Expanded Edge Panel
0x00c00031 -1 rgamble-desktop Top Expanded Edge Panel
0x00e00022 -1 rgamble-desktop Desktop
0x0260007c  0 rgamble-desktop Google - Mozilla Firefox
```
```
To resize a window based on its title:
```
```
wmctrl -r Firefox -e 0,0,0,640,480
```
```
The arguments to the resize option are
```
gravity,X,Y,width,height
```
so this will place the window at the top-left corner of the screen and resize it to 640X480.


Question:
Here is what I am trying to do:
Given a date, a day of the week, and an integer n, determine whether the date is the nth day of the month.

For example:

input of 1/1/2009,Monday,2
would be false because 1/1/2009 is not the second Monday

input of
11/13/2008,Thursday,2
would return true because it is the second Thursday

How can I improve this implementation?

private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n)
{
    int d = date.Day;
    return date.DayOfWeek == dow && (d/ 7 == n || (d/ 7 == (n - 1) && d % 7 > 0));
}

Answer:
You could change the check of the week so the function would read:
```
```
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){
  int d = date.Day;
  return date.DayOfWeek == dow && (d-1)/7 == (n-1);
}
```
```
Other than that, it looks pretty good and efficient.


Question:
How can I create a Sidebar form in delphi.

I try the ScreenSnap and Align properties but I need that the form stay visible even if the user maximize other forms, without been on top. Just like the windows sidebar do.

Update: From the comments: if a window is maximized, it maximizes next to the window, not in front of or behind.

Answer:
You can call a Windows API function to force your application to stay on top:
```
```
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);
```
```


Question:
I am really stuck with this Parser Error Message telling me "Could not load the assembly 'App_Web_amlohswi'. Make sure that it is compiled before accessing the page."  I have been looking around for a few hours checking different posts here and googling information.  I have found out that I need to set up a new Application Pool that runs .NET 2.x.

(On a side note, my app is being developed in .NET 3.5, is there a way to set it up to use 3.5 instead of 2.x?)

Can someone provide me with a good explaination on how to set this up properly and (optionally) why is it necessary?

I am more used to developing in PHP so I am used to edit src >> upload >> success!

Thanks!

Answer:
ASP.NET 3.5 sites run in 2.0 app pools as long as that version of .NET is installed on the system.
You may have to set up web.config properly. Visual Studio should do this for you when you create a new project.
You should also make sure you don't combine 1.1 and 2.0 applications in the same app pool. Try putting it in a separate app pool and see that helps.


Question:
I have a web application project (wap) that is successfully being deployed to a development server by our tfsbuild server.

I'd like the build server to run our collection of webtests after deployment.

What is a best practice (or ANY practice) for doing this?

Answer:
You're almost there with your code. I agree with you, the MSDN is not quite explicit on what's inside that byte array, but here's what you can do :
```
```
IPAddress address = new IPAddress(_ClientIPAddress.Address.Skip(2).Take(4).ToArray());
```
```
The first two bytes do not seem to be used, but in the case of AF_INET (which is IPv4, or 2) the next four bytes are the IPv4 address of the client.
You might also want to make sure that your code will handle IPv6 (AF_INET6) properly, or handle the fact that AF_INET6 is a likely value. You'll probably need to read 16 bytes instead of 4 for this protocol.


Question: When using regular expressions in Ruby, what is the difference between $1 and \1?

Answer:
\1 is a backreference which will only work in the same
```
sub
```
or
```
gsub
```
method call, e.g.:
```
```
"foobar".sub(/foo(.*)/, '\1\1') # => "barbar"
```
```
$1 is a global variable which can be used in later code:
```
```
if "foobar" =~ /foo(.*)/ then
  puts "The matching word was #{$1}"
end
```
```
Output:
```
```
"The matching word was bar"
# => nil
```
```


Question: Here's the scenario - a client uploads a Sybase dump file to (gzipped) to our local FTP server. We have an automated process which picks these up and then moves them to different server within the network where the database server resides. Unfortunately, this transfer is over a WAN, which for large files takes a long time, and sometimes our clients forget to FTP in binary mode, which results in 10GB of transfer over our WAN all for nothing as the dump file can't be loaded at the other end. What I'd like to do, is verify the integrity of the dump file on the local server before sending it out over the WAN, but I can't just try and "load" the dump file, as we don't have Sybase installed (and can't install it). Are there any tools or bits of code that I can use to do this?

Answer:
There is no way to really verify the integrity of the dump file without loading it in some way by a backup server. The client should know whether the dump is successful or not via the backup log or output during the dump.
But to solve your problem you should use to SFTP or SCP, all transfers are done in binary, alleviating your problem.
Ensure that they are also using compression in the dump a value of 1-3 is more than enough, this should reduce your network traffic also.


Question:
I have a form that excepts a file upload in ASP.NET. I need to increase the max upload size to above the 4 MB default.

I have found in certain places referencing the below code at msdn.

[ConfigurationPropertyAttribute("maxRequestLength", DefaultValue = )]

None of the references actually describe how to use it, and I have tried several things with no success. I only want to modify this attribute for certain pages that are asking for file upload.

Is this the correct route to take? And how do I use this?

Answer:
If its windows 2003 / IIS 6.0 then check out AspMaxRequestEntityAllowed = "204800" in the file
metabase.xml
located in folder C:\windows\system32\inetsrv\
The default value of "204800" (~205Kb) is in my opinion too low for most users. Just change the value to what you think should be max.
If you cant save the file after editing it you have to either stop the ISS-server or enable the server to allow editing of the file:
(source:
itmaskinen.se
)
Edit: I did not read the question correct (how to set the maxrequest in webconfig). But this informatin may be of interrest for other people, many people who move their sites from win2000-server to win2003 and had a working upload-function and suddenly got the
Request.BinaryRead Failed
error will have use of it. So I leave the answer here.


Question: How would I go about creating a real world form creation class that I can use to display a new form with fields of different types, as how many fields I want, I can use drop downs and I can do all of this by using OOP?

Answer:
You definitely can. Consider a Form class which stores information about the form itself: the
```
method
```
,
```
action
```
,
```
enctype
```
attributes. Also throw in stuff like an optional heading and/or description text at the top. Of course you will also need an array of input elements. These could probably be put into their own class (though subclassing them for InputText, InputCheckbox, InputRadio maybe be a bit over the top). Here's a vague skeleton design:
```
```
class Form {
    var $attributes,    // array, with keys ['method' => 'post', 'action' => 'mypage.php'...]
        $heading,
        $description,
        $inputs        // array of FormInput elements
    ;

    function render() {
        $output = "<form " . /* insert attributes here */ ">"
              . "
" . $this->heading . "
"
              . "
" . $this->description . "
"
        ;
        // wrap your inputs in whatever output style you prefer:
        // ordered list, table, etc.
        foreach ($this->inputs as $input) {
            $output .= $input->render();
        }
        $output .= "</form>";
        return $output;
    }
}
```
```
The FormInput class would just need to store the basics, such as type, name, value, label. If you wanted to get tricky then you could apply validation rules which would then be converted to Javascript when rendering.


Question:
Say I have a sql query

SELECT fname, lname, dob, ssn, address1, address2, zip, phone,state from users

Now say the records are now either in dictionary base or a strongly typed collection.

I have a grid view control and i want to bind it to my collection but I only want to display fname, lname, dob and ssn and not the other columns.

Is there an easy way to extract the columns and then bind to the extracted item? Not sure if LINQ would be helpful here.

This is a test project as I am getting familiar with the web world wqith VS-2008

Answer:
Perhaps LINQ and an anonymous class could do the trick for you.
```
```
from user in UserCollection
select new { FirstName=user.fname, LastName=user.lname, Dob=user.dob, SSN=user.ssn }
```
```


Question: What does the quote "Level of Indirection solves every Problem" mean in Computer Science?

Answer:
Generally it means that by increasing the level of abstraction one can make the problem easier to understand/resolve.
Be careful with your abstractions though, the full quote at least as I heard it is, "You can solve every problem with another level of indirection, except for the problem of too many levels of indirection".


Question:
I am using SQL Server Reporting Services 2008 (though this seems to be an issue for me in 2005 also).  I have a report that has one page per customer (i.e. paged on customerId).  The odd thing I'm seeing is that the first report (i.e. first page of the report) has a bit of extra white space at the top than the other pages.  In general this seems to occur when you have a title for the report and paging (so that the first page has the title, but each successive page does not).  The report I'm dealing with does not have a title like that, but still has this extra white space.

What I'm wondering is how do I prevent that extra white space on this first page of the report.  How do I make each page of the report identical?

I do not have a header or footer applied to the report either.

Answer:
There are a couple of different causes for extra space at the top of the HTML render of a page in any version of Reporting Services.  There are a couple of tricks to working around this depending upon the cause of the problem:
Move the title from the Header to the Body of the report.  If the title is a label, this doesn't always help.
If you are using a table, then add a separate row to the header of the table.  This seems to work very well, particularly when you render to Excel.  However, not all report requirements can support this as a solution.
In SSRS 2000/2005, if you are using a container such as a rectangle or group, then the odds that you will having a spacing issue increase.  If you can move the title out of the container, then this can help reduce the likelihood of a problem.  I haven't tried using the Tablix grouping controls in SSRS 2008, so I can't tell if this will work in SSRS 2008.
If you keep the header and footer objects on even you aren't adding any labels to the regions, then these can lead to extra spaces on the first page.
It is difficult to give you better advice without reproducing your exact problem.  If you want to post the code for a sample RDL file temporarily, then I can try to reproduce the problem in SSRS 2008 on my machine and see if I can provide you with a custom solution to your problem.


Question:
I need to construct some rather simple SQL, I suppose, but as it's a rare event that I work with DBs these days I can't figure out the details.

I have a table 'posts' with the following columns:

id, caption, text

and a table 'comments' with the following columns:

id, name, text, post_id

What would the (single) SQL statement look like which retrieves the captions of all posts which have one or more comments associated with it through the 'post_id' key? The DBMS is MySQL if it has any relevance for the SQL query.

Answer:
You're basically looking at performing a subquery --
```
SELECT p.caption FROM posts p WHERE (SELECT COUNT(*) FROM comments c WHERE c.post_id=p.id) > 1;
```
This has the effect of running the
```
SELECT COUNT(*)
```
subquery for each row in the posts table. Depending on the size of your tables, you might consider adding an additional column,
```
comment_count
```
, into your
```
posts
```
table to store the number of corresponding
```
comments
```
, such that you can simply do
```
SELECT p.caption FROM posts p WHERE comment_count > 1
```


Question:
I've written a cheap & cheerful sound board in for my Mac, and I play the various sounds with NSSound like this:

-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {
    BOOL wasPlaying = FALSE;

    if([nowPlaying isPlaying])  {
        [nowPlaying stop];
        wasPlaying = TRUE;
    }

    if(soundEffect != nowPlaying)
    {
        [soundEffect play];
        nowPlaying = soundEffect;
    } else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {
        [nowPlaying play];
    }
}

Rather than just stop it dead, I'd like it to fade out over a couple of seconds or so.

Answer:
Something like this perhaps? You probably want a more linear dropoff, but the basic idea is make a loop and sleep the period of time till the next update.
```
```
if([nowPlaying isPlaying])  {
    for(int i = 1; i < 100; ++i)
    {
        [nowPlaying setVolume: (1.0 / i)];
        Sleep(20);
    }
    [nowPlaying stop];
    wasPlaying = TRUE;
}
```
```


Question:
I've heard that enabling Link-Time Code Generation (the /LTCG switch) can be a major optimization for large projects with lots of libraries to link together. My team is using it in the Release configuration of our solution, but the long compile-time is a real drag. One change to one file that no other file depends on triggers another 45 seconds of "Generating code...". Release is certainly much faster than Debug, but we might achieve the same speed-up by disabling LTCG and just leaving /O2 on.

Is it worth it to leave /LTCG enabled?

Answer:
It is hard to say, because that depends mostly on your project - and of course the quality of the LTCG provided by VS2005 (which I don't have enough experience with to judge). In the end, you'll have to measure.
However, I wonder why you have that much problems with the extra duration of the release build. You should only hand out reproducible, stable, versioned binaries that have reproducible or archived sources. I've rarely seen a reason for frequent, incremental release builds.
The recommended setup for a team is this:
Developers typically create only incremental debug builds on their machines. Building a release should be a complete build from source control to redistributable (binaries or even setup), with a new version number and labeling/archiving the sources. Only these should be given to in-house testers / clients.
Ideally, you would move the complete build to a separate machine, or maybe a virtual machine on a good PC. This gives you a stable environment for your builds (includes, 3rd party libraries, environment variables, etc.).
Ideally, these builds should be automated ("one click from source control to setup"), and should run daily.


Question:
Can someone show me how to get the top & left position of a div or span element when one is not specified?

ie:

<span id='11a' style='top:55px;' onmouseover="GetPos(this);">stuff</span>
<span id='12a' onmouseover="GetPos(this);">stuff</span>

In the above, if I do:

document.getElementById('11a').style.top

The value of 55px is returned. However, if I try that for span '12a', then nothing gets returned.

I have a bunch of div/spans on a page that I cannot specify the top/left properties for, but I need to display a div directly under that element.

Answer:
This function will tell you the x,y position of the element relative to the page. Basically you have to loop up through all the element's parents and add their offsets together.
```
```
function getPos(el) {
    // yay readability
    for (var lx=0, ly=0;
         el != null;
         lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
    return {x: lx,y: ly};
}
```
```
However, if you just wanted the x,y position of the element relative to its container, then all you need is:
```
```
var x = el.offsetLeft, y = el.offsetTop;
```
```
To put an element directly below this one, you'll also need to know its height. This is stored in the offsetHeight/offsetWidth property.
```
```
var yPositionOfNewElement = el.offsetTop + el.offsetHeight + someMargin;
```
```


Question: How can I check whether a variable is defined in Ruby?  Is there an isset-type method available?

Answer:
```
defined?(your_var)
```
will work. Depending on what you're doing you can also do something like
```
your_var.nil?
```


Question:
I need to generate random numbers within a specified interval, [max;min].

Also, the random numbers should be uniformly distributed over the interval, not located to a particular point.

Currenly I am generating as:

for(int i=0; i<6; i++)
{
    DWORD random = rand()%(max-min+1) + min;
}

From my tests, random numbers are generated around one point only.

Example
min = 3604607;
max = 7654607;

Random numbers generated:

3631594
3609293
3630000
3628441
3636376
3621404

From answers below: OK, RAND_MAX is 32767. I am on C++ Windows platform. Is there any other method to generate random numbers with a uniform distribution?

Answer:
If you want numbers to be uniformly distributed over the range, you should break your range up into a number of equal sections that represent the number of points you need. Then get a random number with a min/max for each section.
As another note, you should probably not use
```
rand()
```
as it's not very good at actually generating random numbers. I don't know what platform you're running on, but there is probably a better function you can call like
```
random()
```
.


Question:
We have an internal .NET case management application that automatically creates a new case from an email. I want to be able to identify other emails that are related to the original email so we can prevent duplicate cases from being created.

I have observed that many, but not all, emails have a thread-index header that looks useful.

Does anybody know of a straightforward algorithm or package that we could use?

Answer:
As far as I know, there's not going to be a 100% foolproof solution, as not all email clients or gateways preserve or respect all headers.
However, you'll get a pretty high hit rate with the following:
Every email message should have a unique "Message-ID" field. Find this, and keep a record of it as a part of the case. (See
RFC-822
)
If you receive two messages with the same Message-ID, discard the second one as it's a duplicate.
Check for the "In-Reply-To" field, if the ID shown matches a known Message-ID then you know the email is related.
The "References" and "Original-Message-ID" headers have similar meanings.
If your system ever generates emails, include a CaseID# in the subject line in a way that you can search for it if you get an email back (eg: [Case#20081114-01]); most people don't edit subject lines when replying.
The internet standards
RFC-822
,
RFC-2076
and
RFC-4021
may be useful further reading.
Given that there will always be messages that are missed (for whatever reason), you'll also probably want related features in your case management system - say, "Close as Duplicate Case" or "Merge with Duplicate Case", along with tools to make it easier to find duplicates.


Question:
I'm writing a website in JSP using Struts and Hibernate. I'm looking for a way to implement a rich UI where you can have more than just buttons. For examples, drag and drops, drop down lists that updates itself in real time as you type more letters out etc. Is there a way to use something like Swing with Struts and Hibernate? Or are there any other options available for making a rich UI?? (I'm open to abandon Struts and/or Hibernate if there are better alternatives)

Fundamental problem: The organization I work for have strict rules about what development tools and open source libraries we can or cannot use, and is pretty slow on updating their approval list. None of the AJAX things (e.g. GWT, dojo) are on the list yet.

Thank you for taking the time to read this post!

Answer:
As far as I know, there's not going to be a 100% foolproof solution, as not all email clients or gateways preserve or respect all headers.
However, you'll get a pretty high hit rate with the following:
Every email message should have a unique "Message-ID" field. Find this, and keep a record of it as a part of the case. (See
RFC-822
)
If you receive two messages with the same Message-ID, discard the second one as it's a duplicate.
Check for the "In-Reply-To" field, if the ID shown matches a known Message-ID then you know the email is related.
The "References" and "Original-Message-ID" headers have similar meanings.
If your system ever generates emails, include a CaseID# in the subject line in a way that you can search for it if you get an email back (eg: [Case#20081114-01]); most people don't edit subject lines when replying.
The internet standards
RFC-822
,
RFC-2076
and
RFC-4021
may be useful further reading.
Given that there will always be messages that are missed (for whatever reason), you'll also probably want related features in your case management system - say, "Close as Duplicate Case" or "Merge with Duplicate Case", along with tools to make it easier to find duplicates.


Question:
Say I have a method that needs to pull 8 values from a map with 100 elements in it. Which do you think would be preferable:

Walk in a for loop from begin to end once, pulling the elements out by switching on the key?

Or using find 8 times to get those values?

Answer:
I would use find 8 times.  It will be less (and more obvious) code.
You should try not make performance judgements based on small numbers since (a) it isn't likely to be a performance bottleneck either way at this size and (b) the numbers may change in the future -- choose the algorithm with the best asymptotic performance.
Note: you mention 'switching' on the key ... that may apply in your case, but in general you can't switch on the key value in a map.  Allowing for this would make the code to searching for M items in a map by iteration even more complex.


Question:
For instance, does the compiler know to translate

string s = "test " + "this " + "function";

to

string s = "test this function";

and thus avoid the performance hit with the string concatenation?

Answer:
Yes. This is guaranteed by the C# specification. It's in section 7.18 (of the C# 3.0 spec):
Whenever an expression fulfills the
  requirements listed above, the
  expression is evaluated at
  compile-time. This is true even if the
  expression is a sub-expression of a
  larger expression that contains
  non-constant constructs.
(The "requirements listed above" include the + operator applied to two constant expressions.)
See also
this question
.


Question:
Getting the subdomain from a URL sounds easy at first.

http://www.domain.example

Scan for the first period then return whatever came after the "http://" ...

Then you remember

http://super.duper.domain.example

Oh. So then you think, okay, find the last period, go back a word and get everything before!

Then you remember

http://super.duper.domain.co.uk

And you're back to square one. Anyone have any great ideas besides storing a list of all TLDs?

Answer:
Anyone have any great ideas besides
  storing a list of all TLDs?
No, because each TLD differs on what counts as a subdomain, second level domain, etc.
Keep in mind that there are top level domains, second level domains, and subdomains.  Technically speaking, everything except the TLD is a subdomain.
In the domain.com.uk example, "domain" is a subdomain, "com" is a second level domain, and "uk" is the TLD.
So the question remains more complex than at first blush, and it depends on how each TLD is managed.  You'll need a database of all the TLDs that include their particular partitioning, and what counts as a second level domain and a subdomain.  There aren't too many TLDs, though, so the list is reasonably manageable, but collecting all that information isn't trivial.  There may already be such a list available.
Looks like
http://publicsuffix.org/
is one such list—all the common suffixes (.com, .co.uk, etc) in a list suitable for searching.  It still won't be easy to parse it, but at least you don't have to maintain the list.
A "public suffix" is one under which
  Internet users can directly register
  names. Some examples of public
  suffixes are ".com", ".co.uk" and
  "pvt.k12.wy.us". The Public Suffix
  List is a list of all known public
  suffixes.
The Public Suffix List is an
  initiative of the Mozilla Foundation.
  It is available for use in any
  software, but was originally created
  to meet the needs of browser
  manufacturers. It allows browsers to,
  for example:
Avoid privacy-damaging "supercookies" being set for
  high-level domain name suffixes
Highlight the most important part of a domain name in the user
  interface
Accurately sort history entries by site
Looking through the list
, you can see it's not a trivial problem.  I think a list is the only correct way to accomplish this...


Question:
I have this code in my aspx page;

<a href="javascript:void(0);" onclick=<% Print(); %> title="Print listings">Print</a>

which presents a link to print a listings to a pdf when the user clicks on it; as you can note the script calls a function from the behind code.

The problem is that when I coded this it happens that when I go this page it prints to pdf when is loading, I thought it would wait for a click but instead it performs the printing.

What is the problem? thanks in advance.

PD. I'm working with VS2005 and for the pdf creation I use iTextSharp.

Answer:
Its a bit hard to tell exactly what is happening from your code snippet, but I would assume that you are outputting the pdf file to the response stream as part of the print() function.
This is will display the pdf on load because the code behind is evaluated at render time (just before it sends the code to the browser) instead of being evaluated on the client.
To get the behavior you would like the best method is to create a http handler file (ashx) that will accept any required arguments as request variables on the url and will then output the pdf to the stream.
You can then just create a href to the ashx file with the correct arguments to dispaly the document.


Question:
Is there anyway to get Eclipse to automatically look for static imports? For example, now that I've finally upgraded to Junit 4, I'd like to be able to write:

assertEquals(expectedValue, actualValue);

hit Ctrl + Shift + O and have Eclipse add:

import static org.junit.Assert.assertEquals;

Maybe I'm asking too much.

Answer:
Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede),  go to
Window->Preferences->Java->Editor->Content Assist
and check the checkbox for
Use static imports (only 1.5 or higher)
.
This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (
CTRL
+
1
) on the line it will give you the option to add the static import which is good enough.


Question:
I need to replace our Ajax Modal Popup controls with a JavaScript equivalent. We use this as a simple context sensitive help type popup. I did a quick browse but didn't see quite what I was looking for. I just need some text and a simple Close button/link, but I would like the page darkened below the popup, as it does with the Ajax modal control.

Can anyone suggest a nice JavaScript popup/help type solution that you've used?

Answer:
Maybe you are looking for something like
this
? [ui.jquery.com]
It's the simplest one, and can come bundled with a lot of other eye candy. Of course you could also look around the rest of the
jQuery plug-ins page
, specially the
Windows and Overlays section
.


Question:
C#: How would you cycle through items in a listview using next and previous buttons?

Background:

Let's say you have 10 items in a listview.

Next to the listview there are two buttons titled previos and next.

Problem:

How would you cycle through those listview items after clicking the Next and or Previous button?

Answer:
Without testing it, I'm guessing this would work:
```
```
for(int i=0;i<listView.Items.Count;i++)
      listView.Items[i]
```
```


Question:
Is there a way I can set up callbacks on (or automataically log) method parameters, entries, and exits without making explicit calls within each method? I basically want to log this information to my logger class (which is static) without having to do it manually for each method.

Right now I have to call Logger::logEntry() and Logger::logExit() in every method to accomplish this. I would love to not have to do this:

class TestClass {
    public function tester($arg) {
        Logger::logEntry();
        Logger::info('Parameter $arg => ' . $arg);

        // Do some stuff...

        Logger::logExit();
    }
}

Answer:
you could use the magic function
```
__call
```
. It gets called when no functions match that name. Rename your methods to be prefixed with something, (eg: underscore), and optionally set them to private/protected.
```
```
class TestClass {
    public function __call($function, $args) {
        Logger::logEntry();
        Logger::info('Parameters: ' . implode(", ", $args);

        $localFunc = "_" . $function;
        $return = $this->$localFunc($args);

        Logger::logExit();

        return $return;
    }

    private function _tester() {
        // do stuff...
        return "tester called";
    }
}

 $t = new TestClass();
 echo $t->tester();
 // "tester called"
```
```


Question: I have a string which holds a decimal value in it and I need to convert that string into a floating point variable. So an example of the string I have is "5.45" and I want a floating point equivalent so I can add .1 to it. I have searched around the internet, but I only see how to convert a string to an integer.

Answer:
You don't need to convert it at all:
```
```
% perl -e 'print "5.45" + 0.1;'
5.55
```
```


Question:
To send a serial string character to the serial port.  I would need to call WriteFile(handle, "A", strlen("A"), ...)

However, what if I want to specify and send a hex or binary number?  For example, I want to send WriteFile(handle, 0x41, sizeOf(0x41), ...) ?

Is there a function that allow me to do this?

Answer:
If you just want to write one byte, it still needs to be in an array.
So you would need:
```
```
int buffer[1024];
buffer[0] = 42;

WriteFile(handle, buffer, 1);
```
```
See this:
http://msdn.microsoft.com/en-us/library/aa365747(VS.85).aspx


Question:
Is it possible to perform a named-group match in Perl's regex syntax as with Python's? I always bind the $n values to proper names after matching, so I'd find it more convenient to do it in the regex itself if it's possible.

Python does it like so:

>>> import re
>>> regex = re.compile(r'(?P<count>\d+)')
>>> match = regex.match('42')
>>> print match.groupdict()
{'count': '42'}

I know the ?P indicates that it's a Python-specific regex feature, but I'm hoping it's in Perl in a different way or was added later on. Is there any way to get a result hash in a similar manner in Perl?

Answer:
AFIK
PCRE
has named group capturing as:
```
```
(?'NAME'pattern)
(?<NAME>pattern)
```
```
You can find info
here
.


Question:
I'm looking to calculate the number of months between 2 date time fields.

Is there a better way than getting the Unix timestamp and then dividing by 2 592 000 (seconds) and rounding up within MySQL?

Answer:
The
DATEDIFF
function can give you the number of days between two dates.  Which is more accurate, since... how do you define a month?  (28, 29, 30, or 31 days?)


Question:
I was trying to follow some instructions today, and it starts with the comment

REM  In SQLPlus I manually copy in each line and execute it.

That's nice, I don't have SQLPlus, I have SQLDeveloper.  The lines that were pasted in were of the type:

@\\server\dir\dir\dir\commandfile1.txt;
COMMIT;

...etc.

It didn't like it when I tried that in a SQL window.  I opened up and pasted in the commands by hand, and it wasn't happy with that either.  (Did I mention that I'm not so good with this application nor Oracle, but that everyone else was out today?)  The files there started with code like:

rem
set echo on
rem
execute procedure_name ('parameter1', 'parameter2');

A co-worker did have SQLPlus, and together we got it resolved.  But, is there a way for me to do this with SQLDeveloper, so I'm not stuck if he's out too?

Answer:
This would do it:
```
```
begin
    procedure_name ('parameter1', 'parameter2');
end;
/
```
```


Question:
I was wondering if anyone can help me get started with creating a room in Sandy 3D. I know I can generate the planes, but I am unsure as to how to implement simple physics (i.e. the player cannot walk through a wall). Is there a simple way to do this, or should I look into something like WOW (3D physics engine for Flash)?

Thanks,
Cameron

Answer:
This would do it:
```
```
begin
    procedure_name ('parameter1', 'parameter2');
end;
/
```
```


Question: I have a MySQL table where an indexed INT column is going to be 0 for 90% of the rows. If I change those rows to use NULL instead of 0, will they be left out of the index, making the index about 90% smaller?

Answer:
It looks like it does index the
```
NULL
```
s too.
Be careful when you run this because MySQL will LOCK the table for WRITES during the index creation. Building the index can take a while on large tables even if the column is empty (all nulls).
Reference
.


Question:
I have an Asp.Net 1.1 application that uses the following code to write out an image file to a pop up web page.

    Response.ContentType="image/tiff"   'Only for Tif files
    Dim objStream As Object
    objStream = Server.CreateObject("ADODB.Stream")
    objStream.open()
    objStream.type = 1
    objStream.loadfromfile(localfile)
    Response.BinaryWrite(objStream.read)

I'm testing this out with TIF files. The files are being displayed correctly in IE6 and Safari but in IE7 they are not displaying and nothing seems to be returning to the web page. Files with jpg, gif extensions are being displayed properly. What might be the problem here?

Answer:
Have you tried setting the
Content-Disposition
to Inline?
```
```
Response.AppendHeader("Content-Disposition", "inline");
```
```


Question:
I am trying to write a console app that simply lists the number of lists at the sharepoint root.

I tried doing it by using the following code, but the object SPContext.Current is null.  Any ideas of how to get the web object?

 SPWeb web = SPContext.Current.Site.OpenWeb("http://localhost") ;

Answer:
```
```
SPSite spSite = new SPSite("http://myurl");
SPWeb spMySite = spSite.Allwebs["mysite"];
SPWeb spRootsite = spsite.RootWeb;
```
```
The console app will only run on the server as usual.
Also, the url used
http://myurl
can be a url to a page and an SPSite object will be created. E.g.
http://myurl/mysite/pages/default.aspx
will get a valid SPSite object.


Question:
It seems like the classical way to handle transactions with JDBC is to set auto-commit to false. This creates a new transaction, and each call to commit marks the beginning the next transactions.
On multithreading app, I understand that it is common practice to open a new connection for each thread.

I am writing a RMI based multi-client server application, so that basically my server is seamlessly spawning one thread for each new connection.
To handle transactions correctly should I go and create a new connection for each of those thread ?
Isn't the cost of such an architecture prohibitive?

Answer:
Yes, in general you need to create a new connection for each thread.  You don't have control over how the operating system timeslices execution of threads (notwithstanding defining your own critical sections), so you could inadvertently have multiple threads trying to send data down that one pipe.
Note the same applies to any network communications.  If you had two threads trying to share one socket with an HTTP connection, for instance.
Thread 1 makes a request
Thread 2 makes a request
Thread 1 reads bytes from the socket, unwittingly reading the response from thread 2's request
If you wrapped all your transactions in critical sections, and therefore lock out any other threads for an entire begin/commit cycle, then you might be able to share a database connection between threads.  But I wouldn't do that even then, unless you really have innate knowledge of the JDBC protocol.
If most of your threads have infrequent need for database connections (or no need at all), you might be able to designate one thread to do your database work, and have other threads queue their requests to that one thread.  That would reduce the overhead of so many connections.  But you'll have to figure out how to manage connections per thread in your environment (or ask another specific question about that on StackOverflow).
update:
To answer your question in the comment, most database brands don't support multiple concurrent transactions on a single connection (InterBase/Firebird is the only exception I know of).
It'd be nice to have a separate transaction object, and to be able to start and commit multiple transactions per connection.  But vendors simply don't support it.
Likewise, standard vendor-independent APIs like JDBC and ODBC make the same assumption, that transaction state is merely a property of the connection object.


Question:
I am having a Html hyperlink. I need to link this hyperlink to another page.When I place the mouse over the link. It should show the image.
how to do this

Answer:
you can do this using javascript..
This will create a square that follows your mouse on div or element hover.
Create a .js file with those contents here:
```
```
var WindowVisible = null;
function WindowShow() {
    this.bind = function(obj,url,height,width) {
        obj.url = url;
        obj.mheight = height;
        obj.mwidth = width;
        obj.onmouseover = function(e) {
            if (WindowVisible == null) {
                if (!e) e = window.event;
                var tmp = document.createElement("div");
                tmp.style.position = 'absolute';
                tmp.style.top = parseInt(e.clientY + 15) + 'px';
                tmp.style.left = parseInt(e.clientX + 15) + 'px';
                    var iframe = document.createElement('iframe');
                    iframe.src = this.url;
                    iframe.style.border = '0px';
                    iframe.style.height = parseInt(this.mheight)+'px';
                    iframe.style.width = parseInt(this.mwidth)+'px';
                    iframe.style.position = 'absolute';
                    iframe.style.top = '0px';
                    iframe.style.left = '0px';
                tmp.appendChild(iframe);
                tmp.style.display = 'none';
                WindowVisible = tmp;
                document.body.appendChild(tmp);
                tmp.style.height = parseInt(this.mheight) + 'px';
                tmp.style.width = parseInt(this.mwidth) + 'px';
                tmp.style.display = 'block';
            }
        }
        obj.onmouseout = function() {
            if (WindowVisible != null) {
                document.body.removeChild(WindowVisible);
                WindowVisible = null;
            }
        }
        obj.onmousemove = function(e) {
            if (!e) e = window.event;
            WindowVisible.style.top = parseInt(e.clientY + 15) + 'px';
            WindowVisible.style.left = parseInt(e.clientX + 15) + 'px';
        }
    }
}
```
```
Then in your html do the following:
Include the .js file
```
<script type="text/javascript" src="myfile.js"></script>
```
Put in your web page:
```
```

```
```
Here is a full implementation in a HTML:
```
```

    <title>test page</title>

```
```
bye bye!


Question:
Is there a better free TreeView control that exists for Visual Studio 2008 / .NET 3.5?

I believe I need something a little more powerful than the out-of-the box version. I'm not exactly sure for what yet but I thought I'd ask quickly before I get too far in to my project.

Answer:
TreeViewAdv
seems to be pretty nice. It is described with the following features on SourceForge.net:
Extensible advanced TreeView.
100% management C# code.
Features: Model/View architecture.
Multicolumns.
Multiselection.
Different controls for each node: CheckBox, Icon, Label ...
Drag&Drop highlighting.
Load on demand.
Incremental search.
We will most likely use this in one or two occasions in an upcoming project, IIRC.
HTH


Question:
Example C API signature:

void Func(unsigned char* bytes);

In C, when I want to pass a pointer to an array, I can do:

unsigned char* bytes = new unsigned char[1000];
Func(bytes); // call

How do I translate the above API to P/Invoke such that I can pass a pointer to C# byte array?

Answer:
You can use unsafe code:
```
```
unsafe
{
     fixed(byte* pByte = byteArray)
     IntPtr intPtr = new IntPtr((void *) pByte);
     Func(intPtr);
}
```
```
If you need to use safe code, you can use a few tricks:
```
```
IntPtr intPtr = Marshal.AllocHGlobal(Marshal.SizeOf(byteArray));
Marshal.Copy(byteArray, 0, intPtr, Marshal.SizeOf(byteArray));

Func(intPtr);

Marshal.FreeHGlobal(intPtr);
```
```
However, the safe code is going to be slow IMHO.


Question:
When do you call Microsoft.Security.Application.AntiXss.HtmlEncode?  Do you do it when the user submits the information or do you do when you're displaying the information?

How about for basic stuff like First Name, Last Name, City, State, Zip?

Answer:
You should only encode or escape your data at the last possible moment, whether that's directly before you put it in the database, or display it on the screen. If you encode too soon, you run the risk of accidentally double encoding (you'll often see
```
&amp;
```
on newbies' websites - myself included).
If you do want to encode sooner than that, then take measures to avoid the double encoding. Joel wrote an article about good uses for hungarian notation, where he advocated use of prefixes to determine what is stored in the variable. eg: "us" for unsafe string, "ss" for safe string.
```
```
usFirstName = getUserInput('firstName')

ssFirstName = cleanString(usFirstName);
```
```
Also note that it doesn't matter what the type of information is (city, zip code, etc) - leaving any of these unchecked is asking for trouble.


Question:
Given the following class, what is your opinion on the best way to handle create/edit where Attributes.Count  can be any number.

public class Product {
  public int Id {get;set;}
  public string Name {get;set;}
  public IList<Attribute> Attributes {get;set;}
}

public class Attribute {
  public string Name {get;set;}
  public string Value {get;set;}
}

The user should be able to edit both the Product details (Name) and Attribute details (Name/Value) in the same view, including adding and deleting new attributes.

Handling changes in the model is easy, what's the best way to handle the UI and ActionMethod side of things?

Answer:
Depends on the experience you are looking to create for the user. I have implemented something similar for tagging content. In the model, Tags are represented as IList, but the UI shows a comma delimited list in a single text field. I then handle merging the items in the list into a string to populate the text field, and I split the input to put items back into the IList in the model.
In my DAL, I then deal with converting the List into LINQ entities, handle inserts and deletes, etc.
It isn't the most straight forward code, but it isn't too difficult to manage and it gives the user an expected interface.
I'm sure there are other ways to handle it but I would focus on what would work best for the user and then work out the mapping details based on that.


Question:
Given the following domain classes:

class Post {
   SortedSet tags
   static hasMany = [tags: Tag]
}

class Tag {
   static belongsTo = Post
   static hasMany = [posts: Post]
}

From my understanding so far, using a hasMany will result in hibernate Set mapping.
However, in order to maintain uniqueness/order, Hibernate needs to load the entire set from the database and compare their hashes.

This could lead to a significant performance problem with adding and deleting posts/tags
if their sets get large. What is the best way to work around this issue?

Answer:
The ordering of the set is guaranteed by the
```
Set
```
implementation, ie, the
```
SortedSet
```
. Unless you use a
```
List
```
, which keeps track of indexes on the db, the ordering is server-side only.
If your domain class is in a
```
SortedSet
```
, you have to implement
```
Comparable
```
in order to enable the proper sorting of the set.
The question of performance is not really a question per se. If you want to access a single
```
Tag
```
, you should get it by its
Id
. If you want the sorted tags, well, the sort only makes sense if you are looking at all
```
Tags
```
, not a particular one, so you end up retrieving all
```
Tags
```
at once. Since the sorting is performed server-side and not db-side, there is really not much difference between a
```
SortedSet
```
and a regular
```
HashSet
```
in regards to Db.


Question:
I prefer to use jQuery with my ASP.NET MVC apps than the Microsoft Ajax library. I have been adding a parameter called "mode" to my actions, which I set in my ajax calls. If it is provided, I return a JsonViewResult. If it isn't supplied, I assume it was a standard Http post and I return a ViewResult.

I'd like to be able to use something similar to the IsMvcAjaxRequest in my controllers when using jQuery so I could eliminate the extra parameter in my Actions.

Is there anything out there that would provide this capability within my controllers or some simple way to accomplish it? I don't want to go crazy writing code since adding a single parameter works, it just isn't ideal.

Answer:
See Simons answer below.  The method I describe here is no longer needed in the latest version of ASP.NET MVC.
The way the
```
IsMvcAjaxRequest
```
extension method currently works is that it checks
```
Request["__MVCASYNCPOST"] == "true"
```
, and it only works when the method is a HTTP POST request.
If you are making HTTP POST requests throug jQuery you could dynamically insert the
```
__MVCASYNCPOST
```
value into your request and then you could take advantage of the
```
IsMvcAjaxRequest
```
extension method.
Here is a
link to the source of the IsMvcAjaxRequest extension method
for your convenience.
Alternatively, you could create a clone of the
```
IsMvcAjaxRequest
```
extension method called
```
IsjQueryAjaxRequest
```
that checks
```
Request["__JQUERYASYNCPOST"] == "true"
```
and you could dynamically insert that value into the HTTP POST.
Update
I decided to go ahead and give this a shot here is what I came up with.
Extension Method
```
```
public static class HttpRequestBaseExtensions
{
    public static bool IsjQueryAjaxRequest(this HttpRequestBase request)
    {
        if (request == null)
            throw new ArgumentNullException("request");

        return request["__JQUERYASYNCPOST"] == "true";
    }
}
```
```
Checking from an action if a method is a jQuery $.ajax() request:
```
```
if (Request.IsjQueryAjaxRequest())
    //some code here
```
```
JavaScript
```
```
$('form input[type=submit]').click(function(evt) {
    //intercept submit button and use AJAX instead
    evt.preventDefault();

    $.ajax(
        {
            type: "POST",
            url: "<%= Url.Action("Create") %>",
            dataType: "json",
            data: { "__JQUERYASYNCPOST": "true" },
            success: function(data) {alert(':)');},
            error: function(res, textStatus, errorThrown) {alert(':(');}
        }
    );
});
```
```


Question:
Ok, so I have VS 2008 and SVN. When I "rebuild all" a handful of my .dll's disappear from my bin folder.

I have these .dll's in a library folder and that's where I am referencing them from.

When I go to publish the app the publish fails, I think they are related. When I reboot my web.config (change something and save) this error goes away. However, the publish still fails.

When I go to the folder and update svn puts all of them back of course, but then it just happens all over again.

Thank you.

Answer:
Sounds like the build procedure removes the contents of your bin directory on build.
I don't understnad where you say you are referencing them from the library folder- and they also exist in the bin directory.
Your publish could be failing for other reasons- it is most helpful to post the errors.
Updating SVN reverts the files to the latest version- so if you have no file, the latest version is the one that exists in your repository.
Things to check:
You are probably receiving errors on your build- it sounds like the DLL's are actually output from other projects in your solution, so you should check if they are building properly or if they are being output to a different directory instead of your bin folder.
Your subversion repository probably shouldn't have any binary or intermediate files such as dll, lib, exe, suo, ncb, and some others but those are the main ones.
Post more details here- from the sound of it, it seems you may be overlooking errors that you didn't post here.


Question:
I was really looking at the differences between pass by value and how Java allocates objects and what java does to put objects on the stack.

Is there anyway to access objects allocated on the heap?  What mechanisms does java enforce to guarantee that the right method can access the right data off the heap?

It seems like if you were crafty and maybe even manipulate the java bytecode during runtime, that you might be able to manipulate data off the heap when you aren't supposed to?

Answer:
All objects in Java are located on the heap.  I'm not quite sure what you mean by "access objects from the heap".  The only things stored on the stack are the list of functions which called into the current context and their local variables and parameters.  All local variables and parameters are either primitive types or references.
If you allocate an object using
```
new
```
(which is the only way to allocate non-primitive types; yes this includes array types), then the object is allocated on the heap, and a reference to that object is stored on either the stack or the heap, depending on if the reference is stored in a local variable/parameter or as a member of another object.
When passed as parameters to functions, all objects are passed by reference - if the function modifies the parameter, the original object is also modified.  Identically, one could also say that the object references are passed by value - if you change a parameter to refer to a new object, it will continue to refer to that object for the duration of the function, but the original object which was passed in will still refer to whatever it referred to before.  Primitive types are also passed by value.