q:
Are there any useful techniques for reducing the repetition of constants in a CSS file?

(For example, a bunch of different selectors which should all apply the same colour, or the same font size)?

[A]
You can use multiple inheritance in your html elements (e.g.
```
<div class="one two">
```
) but I'm not aware of a way of having constants in the CSS files themselves.
This link (the first found when googling your question) seems to have a fairly indepth look at the issue:
http://icant.co.uk/articles/cssconstants/


q: Help!  I have an Axis web service that is being consumed by a C# application.  Everything works great, except that arrays of long values always come across as [0,0,0,0] - the right length, but the values aren't deserialized.  I have tried with other primitives (ints, doubles) and the same thing happens.  What do I do?  I don't want to change the semantics of my service.

[A]
Here's what I ended up with.  I have never found another solution out there for this, so if you have something better, by all means, contribute.
First, the long array definition in the wsdl:types area:
```
```
<xsd:complexType name="ArrayOf_xsd_long">
    <xsd:complexContent mixed="false">
      <xsd:restriction base="soapenc:Array">
        <xsd:attribute wsdl:arrayType="soapenc:long[]" ref="soapenc:arrayType" />
      </xsd:restriction>
    </xsd:complexContent>
  </xsd:complexType>
```
```
Next, we create a SoapExtensionAttribute that will perform the fix.  It seems that the problem was that .NET wasn't following the multiref id to the element containing the double value.  So, we process the array item, go find the value, and then insert it the value into the element:
```
```
[AttributeUsage(AttributeTargets.Method)]
public class LongArrayHelperAttribute : SoapExtensionAttribute
{
    private int priority = 0;

    public override Type ExtensionType
    {
        get { return typeof (LongArrayHelper); }
    }

    public override int Priority
    {
        get { return priority; }
        set { priority = value; }
    }
}

public class LongArrayHelper : SoapExtension
{
    private static ILog log = LogManager.GetLogger(typeof (LongArrayHelper));

    public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute)
    {
        return null;
    }

    public override object GetInitializer(Type serviceType)
    {
        return null;
    }

    public override void Initialize(object initializer)
    {
    }

    private Stream originalStream;

    private Stream newStream;

    public override void ProcessMessage(SoapMessage m)
    {
        switch (m.Stage)
        {
            case SoapMessageStage.AfterSerialize:
                newStream.Position = 0; //need to reset stream
                CopyStream(newStream, originalStream);
                break;

            case SoapMessageStage.BeforeDeserialize:
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = false;
                settings.NewLineOnAttributes = false;
                settings.NewLineHandling = NewLineHandling.None;
                settings.NewLineChars = "";
                XmlWriter writer = XmlWriter.Create(newStream, settings);

                XmlDocument xmlDocument = new XmlDocument();
                xmlDocument.Load(originalStream);

                List<XmlElement> longArrayItems = new List<XmlElement>();
                Dictionary<string, XmlElement> multiRefs = new Dictionary<string, XmlElement>();
                FindImportantNodes(xmlDocument.DocumentElement, longArrayItems, multiRefs);
                FixLongArrays(longArrayItems, multiRefs);

                xmlDocument.Save(writer);
                newStream.Position = 0;
                break;
        }
    }

    private static void FindImportantNodes(XmlElement element, List<XmlElement> longArrayItems,
                                           Dictionary<string, XmlElement> multiRefs)
    {
        string val = element.GetAttribute("soapenc:arrayType");
        if (val != null && val.Contains(":long["))
        {
            longArrayItems.Add(element);
        }
        if (element.Name == "multiRef")
        {
            multiRefs[element.GetAttribute("id")] = element;
        }
        foreach (XmlNode node in element.ChildNodes)
        {
            XmlElement child = node as XmlElement;
            if (child != null)
            {
                FindImportantNodes(child, longArrayItems, multiRefs);
            }
        }
    }

    private static void FixLongArrays(List<XmlElement> longArrayItems, Dictionary<string, XmlElement> multiRefs)
    {
        foreach (XmlElement element in longArrayItems)
        {
            foreach (XmlNode node in element.ChildNodes)
            {
                XmlElement child = node as XmlElement;
                if (child != null)
                {
                    string href = child.GetAttribute("href");
                    if (href == null || href.Length == 0)
                    {
                        continue;
                    }
                    if (href.StartsWith("#"))
                    {
                        href = href.Remove(0, 1);
                    }
                    XmlElement multiRef = multiRefs[href];
                    if (multiRef == null)
                    {
                        continue;
                    }
                    child.RemoveAttribute("href");
                    child.InnerXml = multiRef.InnerXml;
                    if (log.IsDebugEnabled)
                    {
                        log.Debug("Replaced multiRef id '" + href + "' with value: " + multiRef.InnerXml);
                    }
                }
            }
        }
    }

    public override Stream ChainStream(Stream s)
    {
        originalStream = s;
        newStream = new MemoryStream();
        return newStream;
    }

    private static void CopyStream(Stream from, Stream to)
    {
        TextReader reader = new StreamReader(from);
        TextWriter writer = new StreamWriter(to);
        writer.WriteLine(reader.ReadToEnd());
        writer.Flush();
    }
}
```
```
Finally, we tag all methods in the Reference.cs file that will be deserializing a long array with our attribute:
```
```
[SoapRpcMethod("", RequestNamespace="http://some.service.provider",
        ResponseNamespace="http://some.service.provider")]
    [return : SoapElement("getFooReturn")]
    [LongArrayHelper]
    public Foo getFoo()
    {
        object[] results = Invoke("getFoo", new object[0]);
        return ((Foo) (results[0]));
    }
```
```
This fix is long-specific, but it could probably be generalized to handle any primitive type having this problem.

s: huggingface

c: devops

d: intermediate


q:
I am creating a small modal form that is used in Winforms application. It is basically a progress bar of sorts. But I would like the user to be able to click anywhere in the form and drag it to move it around on the desktop while it is still being displayed.

How can I implement this behavior?

[A]
Microsoft KB Article 320687
has a detailed answer to this question.
Basically, you override the WndProc method to return HTCAPTION to the WM_NCHITTEST message when the point being tested is in the client area of the form -- which is, in effect, telling Windows to treat the click exactly the same as if it had occured on the caption of the form.
```
```
private const int WM_NCHITTEST = 0x84;
private const int HTCLIENT     = 0x1;
private const int HTCAPTION    = 0x2;

protected override void WndProc(ref Message m)
{
    switch(m.Msg)
    {
        case WM_NCHITTEST:
        base.WndProc(ref m);

        if ((int)m.Result == HTCLIENT)
            m.Result = (IntPtr)HTCAPTION;
        return;
    }

    base.WndProc(ref m);
}
```
```


q:
I am trying to set a javascript date so that it can be submitted via JSON to a .NET type, but when attempting to do this, jQuery sets the date to a full string, what format does it have to be in to be converted to a .NET type?

var regDate = student.RegistrationDate.getMonth() + "/" + student.RegistrationDate.getDate() + "/" + student.RegistrationDate.getFullYear();
j("#student_registrationdate").val(regDate); // value to serialize

I am using MonoRail on the server to perform the binding to a .NET type, that aside I need to know what to set the form hidden field value to, to get properly sent to .NET code.


q:
I am writing a query in which I have to get the data for only the last year. What is the best way to do this?

SELECT ... FROM ... WHERE date > '8/27/2007 12:00:00 AM'

[A]
The following adds -1 years to the current date:
```
```
SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
```
```


q: I have an images folder with a png in it.  I would like to set a MenuItem's icon to that png.  How do I write this in procedural code?

[A]
```
```
menutItem.Icon = new System.Windows.Controls.Image
       {
           Source = new BitmapImage(new Uri("images/sample.png", UriKind.Relative))
       };
```
```


q: Using CFML (ColdFusion Markup Langauge, aka ColdFusion), how can you compare if two single dimension arrays are the same?

[A]
There's a very simple way of comparing two arrays using CFML's underlying java. According to a recent blog by Rupesh Kumar of Adobe (
http://coldfused.blogspot.com/
), ColdFusion arrays are an implementation of java lists (java.util.List). So all the Java list methods are available for CFML arrays.
So to compare 2 arrays all you need to do is use the equals method. It returns a YES if the arrays are equal and NO if they are not.
```
```
<cfset array1 = listToArray("tom,dick,harry,phred")/>
<cfset array2 = listToArray("dick,harry,phred") />
<cfset array3 = listToArray("tom,dick,harry,phred")/>

<cfoutput>
Array2 equals Array1 #array2.equals(array1)# (returns a NO)

Array3 equals Array1 #array3.equals(array1)# (returns a YES)

</cfoutput>
```
```


q:
Currently I am setting up an application that can deploy other web apps to Tomcat 6 clusters.  It is set up right now to have a one to one relationship between deployed web application and a cluster.  My current reasoning for this is so that I can change the JVM args of the Tomcat server without disrupting other applications and so that the memory usage of the single application will not conflict with other applications.

The question is, what is considered best practice in terms of tomcat instance clusters?  Should you only have one application running per cluster or multiple applications like in a single tomcat instance environment? Or does this depend on the size of your application?

Thank you

[A]
Divide your services by resource requirements at the very least. For example, if you are running a photo album site, separate your image download server from your image upload server. The download server will have many more requests, and because most people have a lower upload speed the upload server will have longer lasting connections. Similarly, and image manipulation server would probably have few connections, but it should fork off threads to perform the CPU intensive image manipulation tasks asynchronously from the web user interface.
If you have the hardware to do it, it's a lot easier to manage many separate tomcat instances with one application each than a few instances with many applications.


q:
I'd like to ignore multiple wildcard routes.  With asp.net mvc preview 4, they ship with:

RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

I'd also like to add something like:

RouteTable.Routes.IgnoreRoute("Content/{*pathInfo}");

but that seems to break some of the helpers that generate urls in my program.  Thoughts?

[A]
This can be quite tricky.
When attempting to figure out how to map route data into a route, the system currently searches top-down until it finds something where all the required information is provided, and then stuffs everything else into query parameters.
Since the required information for the route "Content/{*pathInfo}" is entirely satisfied always (no required data at all in this route), and it's near the top of the route list, then all your attempts to map to unnamed routes will match this pattern, and all your URLs will be based on this ("Content?action=foo&controller=bar")
Unfortunately, there's no way around this with action routes. If you use named routes (f.e., choosing Html.RouteLink instead of Html.ActionLink), then you can specify the name of the route to match. It's less convenient, but more precise.
IMO, complex routes make the action-routing system basically fall over. In applications where I have something other than the default routes, I almost always end up reverting to named-route based URL generation to ensure I'm always getting the right route.


q:
I'm doing some PHP stuff on an Ubuntu server.

The path I'm working in is /mnt/dev-windows-data/Staging/mbiek/test_list but the PHP call getcwd() is returning /mnt/dev-windows/Staging/mbiek/test_list (notice how it's dev-windows instead of dev-windows-data).

There aren't any symbolic links anywhere.

Are there any other causes for getcwd() returning a different path from a local pwd call?

Edit

I figured it out.  The DOCUMENT_ROOT in PHP is set to /mnt/dev-windows which throws everything off.

[A]
Which file are you calling the getcwd() in and is that file is included into the one you are running (e.g. running index.php, including startup.php which contains gwtcwd()).
Is the file you are running in /dev-windows/ or /dev-windows-data/? It works on the file you are actually running.
Here's an example of my current project:
index.php
```
```
<?php
    require_once('./includes/construct.php');
    //snip
?>
```
```
includes/construct.php
```
```
<?php
    //snip
    (!defined('DIR')) ? define('DIR', getcwd()) : NULL;

    require_once(DIR . '/includes/functions.php');
    //snip
?>
```
```


q:
How do you OCR an tiff file using Tesseract's interface in c#?

Currently I only know how to do it using the executable.

[A]
The source code seemed to be geared for an executable, you might need to rewire stuffs a bit so it would build as a DLL instead. I don't have much experience with Visual C++ but I think it shouldn't be too hard with some research. My guess is that someone might have had made a library version already, you should try Google.
Once you have tesseract-ocr code in a DLL file, you can then import the file into your C# project via Visual Studio and have it create wrapper classes and do all the marshaling stuffs for you. If you can't import then
DllImport
will let you call the functions in the DLL from C# code.
Then you can take a look at the original executable to find clues on what functions to call to properly OCR a tiff image.


q:
Is there an online resource somewhere that maintains statistics on the install-base of Java including JRE version information? If not, is there any recent report that has some numbers?

I'm particularly interested in Windows users, but all other OS's are welcome too.


q:
I'm currently using VS2005 Profesional and .NET 2.0, and since our project is rather large (25 projects in the solution), I'd like to try VS 2008, since its theoretically faster with larger projects.

Before doing such thing, i'd like to know if what I've read is true: can I use VS2008 in ".net 2.0" mode? I don't want my customers to install .net 3.0 or .3.5, I just want to install VS2008, open my solution and start working from there.

Is this possible?

P.D.: the solution is a c# Window Forms project.

[A]
yes, vs2008 can "
target
" a framework, but i think by default, if converting from vs2005 - vs2008 it just keeps it at framework 2.0


q:
I frequently work with multiple instances of Visual Studio, often working on different branches of the same solution.

Visual C++ 6.0 used to display the full path of the current source file in its title bar, but Visual Studio 2005 doesn't appear to do this. This makes it slightly more awkward than it should be to work out which branch of the solution I'm currently looking at (the quickest way I know of is to hover over a tab so you get the source file's path as a tooltip).

Is there a way to get the full solution or file path into the title bar, or at least somewhere that's always visible, so I can quickly tell which branch is loaded into each instance?

[A]
There is not a native way to do it, but you can achieve it with a macro. The details are described here in full:
How To Show Full File Path (or Anything Else) in VS 2005 Title Bar
You just have to add a little Visual Basic macro to the EvironmentEvents macro section and restart Visual Studio.
Note: The path will not show up when you first load Visual Studio, but it will whenever you change which file you are viewing. There is probably a way to fix this, but it doesn't seem like a big deal.


q:
Is there a way to specify a child's initial window position in Qt?

I have an application that runs on Linux and Windows and it looks like the default behavior of Qt lets the Window Manager determine the placement of the child windows.

On Windows, this is in the center of the screen the parent is on which seems reasonable.

On Linux, in GNOME (metacity) it is always in the upper left-hand corner which is annoying.  I can't find any window manager preferences for metacity that allow me to control window placement so I would like to override that behavior.

[A]
Qt Widget Geometry
Call the move(x, y) method on the child window before show(). The default values for x and y are 0 so that's why it appears in the upper left-hand corner.
You can also use the position of the parent window to compute a relative position for the child.


q:
How could i implement Type-Safe Enumerations in Delphi in a COM scenario ? Basically, i'd like to replace a set of primitive constants of a enumeration with a set of static final object references encapsulated in a class ? .
In Java, we can do something like:

public final class Enum
{
    public static final Enum ENUMITEM1 = new Enum ();
    public static final Enum ENUMITEM2 = new Enum ();
    //...
    private Enum () {}
}

and make comparisons using the customized enumeration type:

if (anObject != Enum.ENUMITEM1) ...

I am currently using the old Delphi 5 and i would like to declare some enums parameters on the interfaces, not allowing that client objects to pass integers (or long) types in the place of the required enumeration type.
Do you have a better way of implementing enums other than using the native delphi enums  ?

[A]
What is wrong with native Delphi enums? They are type safe.
```
```
type
  TMyEnum = (Item1, Item2, Item3);

if MyEnum <> Item1 then...
```
```
Since Delphi 2005 you can have consts in a class, but Delphi 5 can not.
```
```
type
  TMyEnum = sealed class
  public
    const Item1 = 0;
    const Item2 = 1;
    const Item3 = 2;
  end;
```
```


q:
This error just started popping up all over our site.

Permission denied to call method to Location.toString

I'm seeing google posts that suggest that this is related to flash and our crossdomain.xml.  What caused this to occur and how do you fix?

[A]
Are you using javascript to communicate between frames/iframes which point to different domains? This is not permitted by the JS "same origin/domain" security policy. Ie, if you have
```
```
<iframe name="foo" src="foo.com/script.js">
<iframe name="bar" src="bar.com/script.js">
```
```
And the script on bar.com tries to access
```
window["foo"].Location.toString
```
, you will get this (or similar) exceptions. Please also note that the same origin policy can also kick in if you have content from different subdomains.
Here
you can find a short and to the point explanation of it with examples.


q:
I have one field that I need to sum lets say named items
However that field can be part of group a or b
In the end I need to have all of the items summed for group a and group b

when I say grouped I mean there is a LEFT OUTER JOIN to another table the previous table has a type for the items and the one being joined has a group assigned for this item type

Sorry guys Im a little new to sql I am going to try out what you have given me an get back to you

Ok I feel like we are getting close just not yet allain's I can get them to separate but the issue I need to have both groups to sum on the same row which is difficult because I also have several LEFT OUTER JOIN's involved

Tyler's looks like it might work too so I am trying to hash that out real fast

Alain's seems to be the way to go but I have to tweek it a little more

[A]
Maybe I'm not understanding the complexity of what you're asking but... shouldn't this do?
```
```
SELECT groupname, SUM(value)
FROM items
WHERE groupname IN ('a', 'b')
GROUP BY groupname
```
```
And if you don't care which of a or b the item belongs to then this will do:
```
```
SELECT SUM(value)
FROM items
WHERE groupname IN ('a', 'b')
```
```


q:
In Maven, dependencies are usually set up like this:

<dependency>
  <groupId>wonderful-inc</groupId>
  <artifactId>dream-library</artifactId>
  <version>1.2.3</version>
</dependency>

Now, if you are working with libraries that have frequent releases, constantly updating the <version> tag can be somewhat annoying. Is there any way to tell Maven to always use the latest available version (from the repository)?

[A]
Are you possibly depending on development versions that obviously change a lot during development?
Instead of incrementing the version of development releases, you could just use a snapshot version that you overwrite when necessary, which means you wouldn't have to change the version tag on every minor change. Something like 1.0-SNAPSHOT...
But maybe you are trying to achieve something else ;)


q: I am trying to be a "good" programmer and have unit tests for my ColdFusion application but haven't been able to find a code coverage tool that can tie into the test that I'm using. For those of you who do unit tests on your ColdFusion code, how have you approached this problem?

[A]
Many
have
asked
, but to date there remains no ColdFusion code coverage tool.
The latest ColdFusion features .NET integration in addition to J2EE integration, so if you require code coverage metrics (ie, customer requirements) then (aside from choosing something other than ColdFusion) you might define what parts need such coverage and break them out into .NET or J2EE objects which you can profile with readily available tools.
Alternately, you can do some analysis yourself - use a parser to insert
cftrace
tags after every control statement and then parse the results.
Lastly, ColdFusion does have some
basic stack trace
ability - I don't know if it goes deeper than that, but it's worth exploring to see what you can parse from that.
I hope this helps!
-Adam Davis


q:
I would like to know if I can open 2 different diagrams using MS Visio and each diagram have its own window. I've tried in several ways, but I always end up with 1 Visio window ...

I'm using a triple monitor setup and I'd like to put one diagram to each side of my main monitor.

[]'s

André Casteliano

PS: I'm using Visio 2007 here.

[A]
Visio 2005 allows you to open visio multiple times - does this not work in 2007?  Try opening a visio document, and then starting another instance of visio from the Start-->Programs menu.
If not, read on...
Visio is an MDI interface - you'll need to stretch the whole visio window across the two monitors in question, then choose the "Window" menu and select "Tile" after you've opened your two documents.
Alternately, in the upper right hand corner just below the application minimize, restore and close buttons you'll find the document minimize, restore and close.  Choose restore, and you can manipulate the windows inside the main visio app.
Hope this helps!
-Adam Davis


q:
I want to create a draggable and resizable window in JavaScript for cross browser use, but I want to try and avoid using a framework if I can.

Has anyone got a link or some code that I can use?

[A]
Avoiding a framework altogether will leave you with lots of code and a bunch of tedious browser-testing.
If you would consider a framework I'd suggest jQuery with the
jqDnR
plugin. I think it will solve your problem or perhaps you could combine the functionality of the
jQuery draggables
with the
jQuery resizables


q:
I've heard that unit testing is "totally awesome", "really cool" and "all manner of good things" but 70% or more of my files involve database access (some read and some write) and I'm not sure how to write a unit test for these files.

I'm using PHP and Python but I think it's a question that applies to most/all languages that use database access.

[A]
Ideally, your objects should be persistent ignorant. For instance, you should have a "data access layer", that you would make requests to, that would return objects. This way, you can leave that part out of your unit tests, or test them in isolation.
If your objects are tightly coupled to your data layer, it is difficult to do proper unit testing. The first part of unit test, is "unit". All units should be able to be tested in isolation.
In my C# projects, I use
```
NHibernate
```
with a completely separate Data layer. My objects live in the core domain model and are accessed from my application layer. The application layer talks to both the data layer and the domain model layer.
The application layer is also sometimes called the "Business Layer".
If you are using PHP, create a specific set of classes
ONLY
for data access. Make sure your objects have no idea how they are persisted and wire up the two in your application classes.
Another option would be to use mocking/stubs.


q: I want to create a simple http proxy server that does some very basic processing on the http headers (i.e. if header x == y, do z).  The server may need to support hundreds of users.  I can write the server in C# (pretty easy) or c++ (much harder).  However, would a C# version have as good of performance as a C++ version?  If not, would the difference in performance be big enough that it would not make sense to write it in C#?

[A]
The proxy server you describe would deal mostly with string data and I think its reasonable to implement in C#.  In your example,
```
```
if header x == y, do z
```
```
the slowest part might actually be doing whatever 'z' is and you'll have to do that work regardless of the language.


q:
I want to build an ASP.NET MVC application with Boo instead of C#. If you know the steps to configure this type of project setup, I'd be interested to know what I need to do.

The MVC project setup is no problem. What I'm trying to figure out how to configure the pages and project to switch to use the Boo language and compiler.

[A]
So there are two levels of "work with Boo". One would be all the code (namely, the Controllers), and the other would be the views.
For the code, I assume Boo compiles to standard .NET assemblies, so simply properly following the naming conventions using by ASP.NET MVC should allow you to write Controllers. You will probably need to start with a C# or VB version of the MVC web application project template and port some of the boilerplate code over into Boo to get the solution entirely in Boo (I presume Boo supports Web Application projects?).
The other half is views. Someone will need to port the Brail view engine over to the ASP.NET MVC view engine system. This may already be done, but I don't know for sure. If it's not, then this is probably a significant amount of work to be done.
Probably the best place to get answers to these kinds of questions is the
MvcContrib community on CodePlex
.


q: I have class method that returns a list of employees that I can iterate through.  What's the best way to return the list? Typically I just return an ArrayList. However, as I understand, interfaces are better suited for this type of action.  Which would be the best interface to use? Also, why is it better to return an interface, rather than the implementation (say ArrayList object)?  It just seems like a lot more work to me.

[A]
Personally, I would use a
List
<Employee> for creating the list on the backend, and then use
IList
when you return.  When you use interfaces, it gives you the flexability to change the implementation without having to alter who's using your code.  If you wanted to stick with an ArrayList, that'd be a non-generic
IList
.


q: What are the ways to retrieve data submitted to the web server from a form in the client HTML in ASP.NET?

[A]
In VB.NET
For POST requests:
```
```
value = Request.Form("formElementID")
```
```
For GET requests:
```
```
value = Request.QueryString("formElementID")
```
```


q: How do I write the results from a mysql query to file?  I just need something quick.  Output can be CSV, XML, HTML, etc.

[A]
```
```
SELECT a,b,a+b
  FROM test_table
  INTO OUTFILE '/tmp/result.txt'
  FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
```
```
(the docs show INTO OUTFILE up in the SELECT .. portion which may work as well, but I've never tried it that way)
http://dev.mysql.com/doc/refman/5.0/en/select.html
INTO OUTFILE creates a file on the server; if you are on a client and want it there, do:
```
```
mysql -u you -p -e "SELECT ..." >  file_name
```
```


q: Given a username and a password for a domain user, what would be the best way to authenticate that user programatically?

[A]
You can use some hacks to
authenticate
only.
```
```
Try
    Dim directoryEntry as New DirectoryEntry("LDAP://DomainController:389/dc=domain,dc=suffix", "username", "password")
    Dim temp as Object = directoryEntry.NativeObject
    return true
Catch
    return false
End Try
```
```
If the user is not valid, the directory entry NativeObject cannot be accessed and throws an exception.  While this isn't the most efficient way (exceptions are evil, blah blah blah), it's quick and painless.  This also has the super-cool advantage of working with all LDAP servers, not just AD.


q:
Is there a pattern using Linq to dynamically create a filter?

I have the need to create custom filtering on a list, in the past I would just dynamically create the SQL...it doesn't seem like this is possible with Linq.

[A]
Check out the
Dynamic Linq Library
from ScottGu's blog:
For example, below is a standard type-safe LINQ to SQL VB query that retrieves data from a Northwind database and displays it in a ASP.NET GridView control:
```
```
Dim Northwind As New NorthwindDataContext
Dim query = From q In Northwind.Products Where p.CategoryID = 2 And p.UnitPrice > 3 Order By p.SupplierID Select p

Gridview1.DataSource = query
GridView1.DataBind()
```
```
Using the LINQ DynamicQuery library I could re-write the above query expression instead like so
```
```
Dim Northwind As New NorthwindDataContext
Dim query = Northwind.Products .where("CategoryID=2 And UnitPrice>3") . OrderBy("SupplierId")
Gridview1.DataSource = query
GridView1.DataBind()
```
```
Notice how the conditional-where clause and sort-orderby clause now take string expressions instead of code expressions.  Because they are late-bound strings I can dynamically construct them.  For example: I could provide UI to an end-user business analyst using my application that enables them to construct queries on their own (including arbitrary conditional clauses).


q:
If possible one that supports at least spell checking:

C# string literals

HTML content

Comments

[A]
FxCop ships with a spell check now
- have you tried that?
Here's a nice add-on
for Visual Studio 2005/2008 by Mikhail Arkhipov of MSFT.


q: Is there anything similar on Windows what would achieve the same as the InputManager on OS X?

[A]
Require SSL on the application
In a custom error page for the 403 redirect the browser to the incoming URL, changing http to https along the way.
Note: Keep port 80 open for this - or there won't be a server to listen for requests to redirect.


q:
I like to use static functions in C++ as a way to categorize them, like C# does.

Console::WriteLine("hello")

Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory?

What about static const?

[A]
I'm all for using static
functions
. These just make sense especially when organized into modules (
```
static class
```
in C#).
However,
the moment
those functions need some kind of external (non compile-time const) data, then that function should be made an instance method and encapsulated along with its data into a class.
In a nutshell: static functions ok, static data bad.


q: What's the best way to allow a user to browse for a file in C#?

[A]
```
```
using (OpenFileDialog dlg = new OpenFileDialog())
{
    dlg.Title = "Select a file";
    if (dlg.ShowDialog()== DialogResult.OK)
    {
        //do something with dlg.FileName
    }
}
```
```


q:
How can I check the existence of an element in jQuery?

The current code that I have is this:

if ($(selector).length > 0) {
    // Do something
}

Is there a more elegant way to approach this? Perhaps a plugin or a function?

[A]
Yes!
```
```
jQuery.fn.exists = function(){ return this.length > 0; }

if ($(selector).exists()) {
    // Do something
}
```
```
This is in response to:
Herding Code podcast with Jeff Atwood


q:
How can I replace lone instances of \n with \r\n (LF alone with CRLF) using a regular expression in C#?

I know to do it using plan String.Replace, like:

myStr.Replace("\n", "\r\n");
myStr.Replace("\r\r\n", "\r\n");

However, this is inelegant, and would destroy any "\r+\r\n" already in the text (although they are not likely to exist).

[A]
Will this do?
```
```
[^\r]\n
```
```
Basically it matches a '\n' that is preceded with a character that is not '\r'.
If you want it to detect lines that start with just a single '\n' as well, then try
```
```
([^\r]|$)\n
```
```
Which says that it should match a '\n' but only those that is the first character of a line or those that are
not
preceded with '\r'
There might be special cases to check since you're messing with the definition of lines itself the '$' might not work too well. But I think you should get the idea.
EDIT:
credit @Kibbee Using look-ahead s is clearly better since it won't capture the matched preceding character and should help with any edge cases as well. So here's a better regex + the code becomes:
```
```
myStr = Regex.Replace(myStr, "(?<!\r)\n", "\r\n");
```
```


q: I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.

[A]
I found the answer here:
http://blog.sqlauthority.com/2007/08/22/sql-server-t-sql-script-to-insert-carriage-return-and-new-line-feed-in-code/
You just concatenate the string and insert a
```
CHAR(13)
```
where you want your line break.
Example:
```
```
DECLARE @text NVARCHAR(100)
SET @text = 'This is line 1.' + CHAR(13) + 'This is line 2.'
SELECT @text
```
```
This prints out the following:
This is line 1.
This is line 2.


q:
Looking for a way to display a PDF in Flex. I'm sure there are several ways. Looking for the easiest to maintain / integrate / most user friendly. I'm guessing it's possible to display a browser window in the app and render it, but if it goes off of IE / FireFox it's not acceptable for this project.

Thanks...

[A]
Check out Share on
Acrobat.com
, there you can upload PDFs and make them embedable Flash files (sort of like YouTube for documents). Should be possible to load those into Flex. Not an ideal solution, but unfortunately you need to convert the PDF to an SWF somehow to be able to load it into a Flex application. I don't know of any good tools that do this. If someone else knows please share.
If you target AIR you can load a PDF into a HTML view, but that doesn't work when running in the browser (the HTML component is only available in AIR).


q:
When running a Java app from eclipse my ImageIcon shows up just fine.

But after creating a jar the path to the image obviously gets screwed up.

Is there a way to extract an image from the jar at runtime so I can then open it up?  Or, is there a better way to do this?

I'd like to distribute a single jar file if possible.

[A]
You can try something like:
```
```
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("/images/image.jpg");
```
```
In your JAR file, you might have a directory structure of:
MyJAR.jar
- com (class files in here)
- images
----image.jpg


q:
I want to return StudentId to use elsewhere outside of the scope of the $.getJSON()

j.getJSON(url, data, function(result)
{
    var studentId = result.Something;
});

//use studentId here

I would imagine this has to do with scoping, but it doesn't seem to work the same way c# does

[A]
Yeah, my previous answer does not work because I didn't pay any attention to your code. :)
The problem is that the anonymous function is a callback function - i.e. getJSON is an async operation that will return at some indeterminate point in time, so even if the scope of the variable were outside of that anonymous function (i.e. a closure), it would not have the value you would think it should:
```
```
var studentId = null;
j.getJSON(url, data, function(result)
{
    studentId = result.Something;
});

// studentId is still null right here, because this line
// executes before the line that sets its value to result.Something
```
```
Any code that you want to execute with the value of studentId set by the getJSON call needs to happen either
within
that callback function or
after
the callback executes.


q:
Alright.

So I figure it's about time I get into unit testing, since everyone's been banging on about it for long enough.  I've installed NUnit and gone through a few "intro to unit testing" type tutorials.

I'm currently putting together a small framework to help with the rebuild of one of our web apps, so I've created a VS2008 project for my framework and I want to unit test it as I go.

How on earth do I go about unit testing the WebControls?  The methods are all protected or private, and since it's a framework, there isn't much else but WebControls.

Any pointers?

Burns

[A]
Ues the
```
assembly:InternalsVisibleTo
```
attribute and you'll be able to access those private members.
Put it in your webcontrol project's
AssemblyInfo.cs
(under
Properties
node)
```
```
[assembly:InternalsVisibleTo("YourTestProjectName")]
```
```


q: I'm currently creating an explicit reference to this in the outer class so that I have a name to refer to in the anonymous inner class.  Is there a better way to do this?

[A]
Use
```
EnclosingClass.this
```


q:
I have a Person object with two constructors - one takes an int (personId), the other a string (logonName).  I would like another constructor that takes a string (badgeNumber).  I know this can't be done, but seems it might be a common situation.  Is there a graceful way of handling this?  I suppose this would apply to any overloaded method.  Code:

public class Person
{
    public Person() {}

    public Person(int personId)
    {
        this.Load(personId);
    }

    public Person(string logonName)
    {
        this.Load(logonName);
    }

    public Person(string badgeNumber)
    {
        //load logic here...
    }

...etc.

[A]
You might consider using custom types.
For example, create LogonName and BadgeNumber classes.
Then your function declarations look like...
```
```
public Person(LogonName ln)
{
    this.Load(ln.ToString());
}

public Person(BadgeNumber bn)
{
    //load logic here...
}
```
```
Such a solution might give you a good place to keep the business logic that governs the format and usage of these strings.


q:
I have a method that where I want to redirect the user back to a login page located at the root of my web application.

I'm using the following code:

Response.Redirect("~/Login.aspx?ReturnPath=" + Request.Url.ToString());

This doesn't work though.  My assumption was that ASP.NET would automatically resolve the URL into the correct path.  Normally, I would just use

Response.Redirect("../Login.aspx?ReturnPath=" + Request.Url.ToString());

but this code is on a master page, and can be executed from any folder level.  How do I get around this issue?

[A]
What about using
```
```
Response.Redirect(String.Format("http://{0}/Login.aspx?ReturnPath={1}", Request.ServerVariables["SERVER_NAME"], Request.Url.ToString()));
```
```


q:
Using WPF, I have a TreeView control that I want to set its ItemTemplate dynamically through procedural code.  How do I do this?  I assume I need to find the resource somewhere.

myTreeViewControl.ItemTemplate =   ??

[A]
If the template is defined in your <Window.Resources> section directly:
```
```
myTreeViewControl.ItemTemplate = this.Resources["SomeTemplate"] as DataTemplate;
```
```
If it's somewhere deep within your window, like in a <Grid.Resources> section or something, I think this'll work:
```
```
myTreeViewControl.ItemTemplate = this.FindResource("SomeTemplate") as DataTemplate;
```
```
And if it's elsewhere in your application, I
think
App.FindResource("SomeTemplate") will work.


q: What is the content type for MHT files?

[A]
message/rfc822
RFC 822 - STANDARD FOR THE FORMAT OF ARPA INTERNET TEXT MESSAGES
Here is a hyperlink:
message/rfc822


q:
I am using VMWare tools for Ubuntu Hardy, but for some reason vmware-install.pl finds fault with my LINUX headers. The error message says that the "address space size" doesn't match.

To try and remediate, I have resorted to vmware-any-any-update117, and am now getting the following error instead:

In file included from include/asm/page.h:3,
       from /tmp/vmware-config0/vmmon-only/common/hostKernel.h:56,
       from /tmp/vmware-config0/vmmon-only/common/task.c:30:
include/asm/page_32.h: In function ‘pte_t native_make_pte(long unsigned int)’:
include/asm/page_32.h:112: error: expected primary-expression before ‘)’ token
include/asm/page_32.h:112: error: expected ‘;’ before ‘{’ token
include/asm/page_32.h:112: error: expected primary-expression before ‘.’ token
include/asm/page_32.h:112: error: expected `;' before ‘}’ token

Can anyone help me make some sense of this, please?

[A]
This error ofter occurs because incompatibility of VMWare Tools Version and recent Kernels (You can test it using older Kernels). Sometimes you can fix some thing with patches all over the internet, but I prefer to downgrade my kernel or don't using latest distribution's version in VMWare. It can be really annoying. Another problem you may have is with your mouse pointer in X Windows, like if it was a inch to left or below than it really shows.
About vmware-any-any-update117, it's a patch to VMWare running under linux, usually Workstation version. It won't have effect in Tools.


q: What is the best way to profile a controller action in Ruby on Rails. Currently I am using the brute-force method of throwing in puts Time.now calls between what I think will be a bottleneck. But that feels really, really dirty. There has got to be a better way.

[A]
Use the Benchmark standard library and the various tests available in Rails (unit, functional, integration). Here's an example:
```
```
def test_do_something
  elapsed_time = Benchmark.realtime do
    100.downto(1) do |index|
      # do something here
    end
  end
  assert elapsed_time < SOME_LIMIT
end
```
```
So here we just do something 100 times, time it via the Benchmark library, and ensure that it took less than SOME_LIMIT amount of time.
You also may find these links useful: The
Benchmark.realtime reference
and the
Test::Unit reference
. Also, if you're into the 'book reading' thing, I picked up the idea for the example from
Agile Web Development with Rails
, which talks all about the different testing types and a little on performance testing.


q:
I've been trying to wrap my head around how threads work in Python, and it's hard to find good information on how they operate. I may just be missing a link or something, but it seems like the official documentation isn't very thorough on the subject, and I haven't been able to find a good write-up.

From what I can tell, only one thread can be running at once, and the active thread switches every 10 instructions or so?

Where is there a good explanation, or can you provide one? It would also be very nice to be aware of common problems that you run into while using threads with Python.

[A]
Below is a basic threading sample. It will spawn 20 threads; each thread will output its thread number. Run it and observe the order in which they print.
```
```
import threading
class Foo (threading.Thread):
    def __init__(self,x):
        self.__x = x
        threading.Thread.__init__(self)
    def run (self):
          print str(self.__x)

for x in xrange(20):
    Foo(x).start()
```
```
As you have hinted at Python threads are implemented through time-slicing. This is how they get the "parallel" effect.
In my example my Foo class extends thread, I then implement the
```
run
```
method, which is where the code that you would like to run in a thread goes. To start the thread you call
```
start()
```
on the thread object, which will automatically invoke the
```
run
```
method...
Of course, this is just the very basics. You will eventually want to learn about semaphores, mutexes, and locks for thread synchronization and message passing.


q:
I have a bunch of .NET frameworks installed on my machine.

I know that with the Java JDK, I can use the 6.0 version to target 5.0 and earlier.

Can I do something similar with the .NET framework - target 1.0 and 2.0 with the 3.0 framework?

[A]
(
Updated
)
You need to compile with the 1.0 compilers. These are only available with the 1.0 release of the runtime/SDK.
The 2.0/3.5 compilers won't emit 1.0-compatible assemblies.
Visual Studio 2008 can generate 2.0 assemblies, but 1.0 was left off.


q: The MediaElement doesn't support rounded corners (radiusx, radiusy). Should I use a VideoBrush on a Rectangle with rounded corners?

[A]
Yeah - In a way you're both asking and answering the question yourself... But that is one of the two options I can think of. The reasons that might be a problem is that you lose some of the features/control you get from the MediaElement control. Another option is to do this:
Add your MediaElement to your page.
Draw a Rectangle on top of it and set wanted corner radius
Right click the rectangle in Blend and choose "Create Clipping Path"
Apply the clipping path to your MediaElement
That way you're still using a MediaElement control, but you can "clip" away what ever you want to get the desired rounded effect.
This example shows a clipped MediaElement. I know it's not easy to picture the vector path, but if you open it open in Blend you will see a rounded MediaElement.
```
```
<MediaElement
        Height="132" Width="176" Source="Egypt2007.wmv"
        Clip="M0.5,24.5 C0.5,11.245166 11.245166,0.5 24.5,0.5 L151.5,0.5
              C164.75484,0.5 175.5,11.245166 175.5,24.5 L175.5,107.5 C175.5,
              120.75484 164.75484,131.5 151.5,131.5 L24.5,131.5 C11.245166,
              131.5 0.5,120.75484 0.5,107.5 z"/>
```
```


q:
I see many similar questions, however I want to find the Username of the currently logged in user using Java.

Its probably something like:

System.getProperty(current.user);

But, I'm not quite sure.

[A]
You're actually really close. This is what you're looking for:
```
```
System.getProperty("user.name")
```
```


q:
Using regular expressions, what is the simplest way to fetch a websites HTML and find the value inside this tag (or any attribute's value for that matter):

<html>
  <head>
  [snip]
  <meta name="generator" value="thevalue i'm looking for" />
  [snip]

[A]
Depends on how sophisticated of an Http request you need to build (authentication, etc). Here's one simple way I've seen used in the past.
```
```
StringBuilder html = new StringBuilder();
java.net.URL url = new URL("http://www.google.com/");
BufferedReader input = null;
try {
    input new BufferedReader(
        new InputStreamReader(url.openStream()));

    String htmlLine;
    while ((htmlLine=input.readLine())!=null) {
        html.appendLine(htmlLine);
    }
}
finally {
    input.close();
}

Pattern exp = Pattern.compile(
    "<meta name=\"generator\" value=\"([^\"]*)\" />");
Matcher matcher = exp.matcher(html.toString());
if(matcher.find())
{
    System.out.println("Generator: "+matcher.group(1));
}
```
```
Probably plenty of typos here to be found when compiled.
(hope this wasn't homework)


q: Without the use of any external library, what is the simplest way to fetch a website's HTML content into a String?

[A]
I'm currently using this:
```
```
String content = null;
URLConnection connection = null;
try {
  connection =  new URL("http://www.google.com").openConnection();
  Scanner scanner = new Scanner(connection.getInputStream());
  scanner.useDelimiter("\\Z");
  content = scanner.next();
  scanner.close();
}catch ( Exception ex ) {
    ex.printStackTrace();
}
System.out.println(content);
```
```
But not sure if there's a better way.


q:
When you get a badge or aren't logged in to stack overflow there's a groovy little notification bar at the top of the page that lets you know there's something going on.

I know the SOflow team use JQuery, but I was wondering if anyone knew of an implementation of the same style of notification system in asp.net AJAX.

On a side note, what's the "official" name for this style of notification bar?


q:
I'm trying to fetch some HTML from various blogs and have noticed that different providers use the same tag in different ways.

For example, here are two major providers that use the meta name generator tag differently:

Blogger: <meta content='blogger' name='generator'/> (content first, name later and, yes, single quotes!)

WordPress: <meta name="generator" content="WordPress.com" /> (name first, content later)

Is there a way to extract the value of content for all cases (single/double quotes, first/last in the row)?

P.S. Although I'm using Java, the answer would probably help more people if it where for regular expressions generally.

[A]
Those differences are not really important according to the XHTML standard.
In other words, they are exactly the same thing.
Also, if you replace double quotes with single quotes would be the same.
The typical way of 'normalizing' an xml document is to pare it using some API that treats the document as its Infoset representation. Both DOM and SAX style APIs work that way.
If you want to parse them by hand (or with a RegEx) you have to replicate all those things in your code and, in my opinion, that's not practical.


q:
Using SqlServer, and trying to update rows from within the same table. I want to use a table alias for readability.
This is the way I am doing it at the moment:

UPDATE ra
SET ra.ItemValue = rb.ItemValue
FROM dbo.Rates ra, dbo.Rates rb
WHERE ra.ResourceID = rb.ResourceID
AND ra.PriceSched = 't8'
AND rb.PriceSched = 't9'

Are there easier / better ways?

[A]
```
```
UPDATE ra
   SET ra.ItemValue = rb.ItemValue
  FROM dbo.Rates ra
 INNER JOIN dbo.Rates rb
         ON ra.ResourceID = rb.ResourceID
WHERE ra.PriceSched = 't8'
  AND rb.PriceSched = 't9';
```
```
This might help in improving performance.


q:
Depending on my mood I seem to waffle back and forth between wanting a Lisp-1 and a Lisp-2.  Unfortunately beyond the obvious name space differences, this leaves all kinds of amusing function name/etc problems you run into.  Case in point, trying to write some code tonight I tried to do (map #'function listvar) which, of course, doesn't work in CL, at all.  Took me a bit to remember I wanted mapcar, not map.  Of course it doesn't help when slime/emacs shows map IS defined as something, though obviously not the same function at all.

So, pointers on how to minimize this short of picking one or the other and sticking with it?

[A]
Map
is more general than mapcar, for example you could do the following rather than using mapcar:
```
```
(map 'list #'function listvar)
```
```
How do I keep scheme and CL separate in my head? I guess when you know both languages well enough you just know what works in one and not the other. Despite the syntactic similarities they are quite different languages in terms of style.


q:
I'm writing an app that will need to make use of Timers, but potentially very many of them.  How scalable is the System.Threading.Timer class?  The documentation merely say it's "lightweight", but doesn't explain further.  Do these timers get sucked into a single thread (or very small threadpool) that processes all the callbacks on behalf of a Timer, or does each Timer have its own thread?

I guess another way to rephrase the question is: How is System.Threading.Timer implemented?

[A]
I think you might want to rethink your design (that is, if you have control over the design yourself). If you're using so many timers that this is actually a concern for you, there's clearly some potential for consolidation there.
Here's a good article from MSDN Magazine from a few years ago that compares the three available timer classes, and gives some insight into their implementations:
http://msdn.microsoft.com/en-us/magazine/cc164015.aspx


q:
I am coding a client-server application using Eclipse's RCP.
We are having trouble testing the interaction between the two sides
as they both contain a lot of GUI and provide no command-line or other
remote API.

Got any ideas?

[A]
I have about 1.5 years worth of experience with the RCP framework, I really liked it. We simply JUnit for testing...
It's sort of cliche to say, but if it's not easy to test, maybe the design needs some refactoring?
Java and the RCP framework provide great facilities for keeping GUI code and logic code separate. We used the MVC pattern with the observer, observable constructs that are available in Java...
If you don't know about observer / observable construct that are in Java, I would HIGHLY recommend you take a look at this:
http://www.javaworld.com/javaworld/jw-10-1996/jw-10-howto.html
, you will use it all the time and your apps will be easier to test.


q: I've recently come to maintain a large amount of scientific calculation-intensive FORTRAN code.  I'm having difficulties getting a handle on all of the, say, nuances, of a forty year old language, despite google & two introductory level books.  The code is rife with "performance enhancing improvements".  Does anyone have any guides or practical advice for de-optimizing FORTRAN into CS 101 levels?  Does anyone have knowledge of how FORTRAN code optimization operated? Are there any typical FORTRAN 'gotchas' that might not occur to a Java/C++/.NET raised developer taking over a FORTRAN 77/90 codebase?

[A]
Well, in one sense, you're lucky, 'cause Fortran doesn't have much in the way of subtle flow-of-control constructs or inheritance or the like.  On the other, it's got some truly amazing gotchas, like the arithmetically-calculated branch-to-numeric-label stuff, the implicitly-typed variables which don't require declaration, the lack of true keywords.
I don't know about the "performance enhancing improvements".  I'd guess most of them are probably ineffective, as a couple of decades of compiler technology have made most hinting unnecessary.  Unfortunately, you'll probably have to leave things the way they are, unless you're planning to do a massive rewrite.
Anyway, the core scientific calculation code should be fairly readable.  Any programming language using infix arithmetic would be good preparation for reading Fortran's arithmetic and assignment code.


q:
I mostly use Java and generics are relatively new. I keep reading that Java made the wrong decision or that .NET has better implementations etc. etc.

So, what are the main differences between C++, C#, Java in generics? Pros/cons of each?

[A]
Wikipedia has great write-ups comparing both
Java/C# generics
and
Java generics/C++
templates. The
main article on Generics
seems a bit cluttered but it does have some good info in it.


q:
I have a mapping application that needs to draw a path, and then display icons on top of the path. I can't find a way to control the order of virtual earth layers, other than the order in which they are added.

Does anyone know how to change the z index of Virtual Earth shape layers, or force a layer to the front?


q: How can I find out which Service Pack is installed on my copy of SQL Server?

[A]
From TechNet:
Determining which version and edition of SQL Server Database Engine is running
```
```
-- SQL Server 2000/2005
SELECT  SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

-- SQL Server 6.5/7.0
SELECT @@VERSION
```
```


q:
I tried finding a python script in google that will generate a random terrain when the game starts (or each time a the player advances to a new scene) but all the tools I found are for creating a terrain to render it, not for the game mode.

Any idea how/where to find one?

(I'm assuming that since Blender3D has game programming capabilities, it is OK for someone to ask in SO)

[A]
Is this link related?
http://blenderartists.org/forum/showthread.php?t=77794
To generate terrain (height map) the algorithm is pretty simple (fractal plasma), something like this algorithm (Java):
http://www.sinc.stonybrook.edu/stu/jseyster/plasma/
If you Google search for "fractal plasma python" you might find some example code.


q:
Is it still worth to add the log4j library to a Java 5 project just to log
let's say some exceptions to a file with some nice rollover settings.
Or will the standard util.logging facility do the job as well?

What do you think?

[A]
I'd say you're probably fine with util.logging for the needs you describe.
For a good decision tree, have a look at
Log4j vs java.util.logging
Question One :
Do you anticipate a need for any of the clever handlers that Log4j has that JUL does not have, such as the SMTPHandler, NTEventLogHandler, or any of the very convenient FileHandlers?
Question Two :
Do you see yourself wanting to frequently switch the format of your logging output? Will you need an easy, flexible way to do so? In other words, do you need Log4j's PatternLayout?
Question Three :
Do you anticipate a definite need for the ability to change complex logging configurations in your applications, after they are compiled and deployed in a production environment? Does your configuration sound something like, "Severe messages from this class get sent via e-mail to the support guy; severe messages from a subset of classes get logged to a syslog deamon on our server; warning messages from another subset of classes get logged to a file on network drive A; and then all messages from everywhere get logged to a file on network drive B"? And do you see yourself tweaking it every couple of days?
If you can answer yes to any of the above questions, go with Log4j. If you answer a definite no to all of them, JUL will be more than adequate and it's conveniently already included in the SDK.
That said, pretty much every project these days seems to wind up including log4j, if only because some other library uses it.


q:
What is the best way to upload a file to a Document Library on a SharePoint server through the built-in web services that version WSS 3.0 exposes?

Following the two initial answers...

We definitely need to use the Web Service layer as we will be making these calls from remote client applications.

The WebDAV method would work for us, but we would prefer to be consistent with the web service integration method.

There is additionally a web service to upload files, painful but works all the time.

Are you referring to the “Copy” service?
We have been successful with this service’s CopyIntoItems method. Would this be the recommended way to upload a file to Document Libraries using only the WSS web service API?

I have posted our code as a suggested answer.

[A]
From a colleage at work:
Lazy way: your Windows WebDAV filesystem interface. It is bad as a programmatic solution because it relies on the WindowsClient service running on your OS, and also only works on websites running on port 80. Map a drive to the document library and get with the file copying.
There is additionally a web service to upload files, painful but works all the time.
I believe you are able to upload files via the FrontPage API but I don’t know of anyone who actually uses it.


q:
What is the best way to include an html entity in XSLT?

<xsl:template match="/a/node">
    <xsl:value-of select="."/>
    <xsl:text>&nbsp;</xsl:text>
</xsl:template>

this one returns a XsltParseError

[A]
You can use CDATA section
```
```
<xsl:text disable-output-escaping="yes"><![CDATA[ ]]></xsl:text>
```
```
or you can describe &nbsp in local DTD:
```
```
<!DOCTYPE xsl:stylesheet [ <!ENTITY nbsp " "> ]>
```
```
or just use
```

```
instead of
```

```


q: There seem to be many ways to define singletons in Python. Is there a consensus opinion on Stack Overflow?

[A]
Being relatively new to Python I'm not sure what the most common idiom is, but the simplest thing I can think of is just using a module instead of a class. What would have been instance methods on your class become just functions in the module and any data just becomes variables in the module instead of members of the class. I suspect this is the pythonic approach to solving the type of problem that people use singletons for.
If you really want a singleton class, there's a reasonable implementation described on the
first hit on Google
for "Python singleton", specifically:
```
```
class Singleton:
    __single = None
    def __init__( self ):
        if Singleton.__single:
            raise Singleton.__single
        Singleton.__single = self
```
```
That seems to do the trick.


q: I have done Java and JSP programming in the past, but I am new to Java Server Faces and want to know if there's a set of best practices for JSF development.

[A]
Some tips:
Understand the JSF request
lifecycle
and where your various pieces of code fit in it. Especially find out why your model values will not be updated if there are validation errors.
Choose a tag library and then stick with it. Take your time to determine your needs and prototype different libraries. Mixing different taglibs may cause severe harm to your mental health.


q:
I need to decrement a Javascript date by 1 day, so that it rolls back across months/years correctly.  That is, if I have a date of 'Today', I want to get the date for 'Yesterday'.

It always seems to take more code than necessary when I do this, so I'm wondering if there's any simpler way.

What's the simplest way of doing this?

[Edit: Just to avoid confusion in an answer below, this is a JavaScript question, not a Java one.]

[A]
```
```
var today = new Date();
var yesterday = new Date().setDate(today.getDate() -1);
```
```


q:
I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace.

I'm using SqlConnection for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google.

[A]
```
```
using (var conn = new SqlConnection(yourConnectionString))
{
    var cmd = new SqlCommand("insert into Foo values (@bar)", conn);
    cmd.Parameters.AddWithValue("@bar", 17);
    conn.Open();
    cmd.ExecuteNonQuery();
}
```
```


q:
Im searching a tool which allows me to specify some folders as "bookmarks" and than access them on the commandline (on Windows XP) via a keyword. Something like:

C:\> go home
D:\profiles\user\home\> go svn-project1
D:\projects\project1\svn\branch\src\>

I'm currently using a bunch of batch files, but editing them by hand is a daunting task. On Linux there is cdargs or shell bookmarks but I haven't found something on windows.

Thanks for the Powershell suggestion, but I'm not allowed to install it on my box at work, so it should be a  "classic" cmd.exe solution.

[A]
With PowerShell you could add the folders as variables in your profile.ps1 file, like:
```
```
$vids="C:\Users\mabster\Videos"
```
```
Then, like Unix, you can just refer to the variables in your commands:
```
```
cd $vids
```
```
Having a list of variable assignments in the one ps1 file is probably easier than maintaining separate batch files.


q:
Source

RegexOptions.IgnoreCase is more expensive than I would have thought (eg, should be barely measurable)

Assuming that this applies to PHP, Python, Perl, Ruby etc as well as C# (which is what I assume Jeff was using), how much of a slowdown is it and will I incur a similar penalty with /[a-zA-z]/ as I will with /[a-z]/i ?

[A]
Yes, [A-Za-z] will be much faster than setting the
```
RegexOptions.IgnoreCase
```
, largely because of Unicode strings. But it's also much more limiting -- [A-Za-z] does
not
match accented international characters, it's literally the A-Za-z ASCII set and nothing more.
I don't know if you saw Tim Bray's answer to my message, but it's a good one:
One of the trickiest issues in internationalized search is upper and lower case. This notion of case is limited to languages written in the Latin, Greek, and Cyrillic character sets. English-speakers naturally expect search to be case-insensitive if only because they’re lazy: if Nadia Jones wants to look herself up on Google she’ll probably just type in nadia jones and expect the system to take care of it.
So it’s fairly common for search systems to “normalize” words by converting them all to lower- or upper-case, both for indexing and queries.
The trouble is that the mapping between cases is not always as straightforward as it is in English. For example, the German lower-case character “ß” becomes “SS” when upper-cased, and good old capital “I” when down-cased in Turkish becomes the dotless “ı” (yes, they have “i”, its upper-case version is “İ”). I have read (but not verified first-hand) that the rules for upcasing accented characters such “é” are different in France and Québec. One of the results of all this is that software such as java.String.toLowerCase() tends to run astonishingly slow as it tries to work around all these corner-cases.
http://www.tbray.org/ongoing/When/200x/2003/10/11/SearchI18n


q:
I'm new to NAnt but have some experience with Ant and CruiseControl.

What I want to do is have my SVN project include all tools needed (like NUnit and Mocks etc) so I can check out onto a fresh machine and build. This strategy is outlined by J.P Boodhoo here.

So far so good if I only want to run on Windows, but I want to be able to check out onto Linux and build/test/run against Mono too. I want no dependencies external to the SVN project. I don't mind having two sets of tools in the project but want only one NAnt build file

This must be possible - but how? what are the tricks / 'traps for young players'

[A]
This shouldn't be a particularly difficult excercise. We do some fairly similar stuff on one of my projects since half of it runs on Java using Ant to run relevant targets, and the other half is .Net (C#) for the UI. The projects get run on windows machines for development, but the servers (Java) run linux, but in the UAT environment (linux) we need to run the nunits (integration tests). The real trick (not really a difficult trick) behind this is having a NAnt build file that can run in both environments which seems to be the same thing you're trying to do here.
Of course you realise you'll need to install NAnt on Mono first:
```
```
$ export MONO_NO_UNLOAD=1
$ make clean
$ make
$ mono bin/NAnt.exe clean build
```
```
And then your build file needs to be written in such a way that it seperates concerns. Some parts of the build file written for windows will not work in linux for example. So you really just need to divide it up ito specific targets in the build file. After that, there are a number of ways you can run a specific targets from the command line. An example might look like this:
```
```
<project name="DualBuild">
  <property name="windowsDotNetPath" value="C:\WINDOWS\Microsoft.NET\Framework\v3.5" />
  <property name="windowsSolutionPath" value="D:\WorkingDirectory\branches\1234\source" />
  <property name="windowsNUnitPath" value="C:\Program Files\NUnit-Net-2.0 2.2.8\bin" />
  <property name="monoPath" value="You get the idea..." />

  <target name="BuildAndTestOnWindows" depends="WinUpdateRevision, WinBuild, WinTest" />
  <target name="BuildAndTestOnLinux" depends="MonoUpdateRevision, MonoBuild, MonoTest" />

  <target name="WinUpdateRevision">
    <delete file="${windowsSolutionPath}\Properties\AssemblyInfo.cs" />
    <exec program="subwcrev.exe" basedir="C:\Program Files\TortoiseSVN\bin\"
          workingdir="${windowsSolutionPath}\Properties"
          commandline="${windowsSolutionPath} .\AssemblyInfoTemplate.cs
                       .\AssemblyInfo.cs" />
    <delete file="${windowsSolutionPath}\Properties\AssemblyInfo.cs" />
    <exec program="subwcrev.exe" basedir="C:\Program Files\TortoiseSVN\bin\"
          workingdir="${windowsSolutionPath}\Properties"
          commandline="${windowsSolutionPath} .\AssemblyInfoTemplate.cs
                       .\AssemblyInfo.cs" />
  </target>

  <target name="WinBuild">
    <exec program="msbuild.exe"
          basedir="${windowsDotNetPath}"
          workingdir="${windowsSolutionPath}"
          commandline="MySolution.sln /logger:ThoughtWorks.CruiseControl.MsBuild.XmlLogger,
                       ThoughtWorks.CruiseControl.MsBuild.dll;msbuild-output.xml
                       /nologo /verbosity:normal /noconsolelogger
                       /p:Configuration=Debug /target:Rebuild" />
  </target>

  <target name="WinTest">
    <exec program="NCover.Console.exe"
          basedir="C:\Program Files\NCover"
          workingdir="${windowsSolutionPath}">
      <arg value="//x "ClientCoverage.xml"" />
      <arg value=""C:\Program Files\NUnit-Net-2.0 2.2.8\bin
                       \nunit-console.exe"
                       MySolution.nunit /xml=nunit-output.xml /nologo" />
    </exec>
  </target>

  <target name="MonoUpdateRevision">
    You get the idea...
  </target>

  <target name="MonoBuild">
    You get the idea...
  </target>

  <target name="MonoTest">
    You get the idea...
  </target>

</project>
```
```
For brevity, I've left both sides out. The neat thing is you can use NUnit as well as NAnt on both environments and that makes things really easy from a dependency point of view. And for each executable you can swap out for others that work in that environment, for example (xBuild for MSBuild, and svn for tortoise etc)
For more help on Nunit etc on Mono, check out
this fantastic post
.
Hope that helps,
Cheers,
Rob G


q:
I have a tree structure in memory that I would like to render in HTML using a Django template.

class Node():
  name = "node name"
  children = []

There will be some object root that is a Node, and children is a list of Nodes. root will be passed in the content of the template.

I have found this one discussion of how this might be achieved, but the poster suggests this might not be good in a production environment.

Does anybody know of a better way?

[A]
I think the canonical answer is: "Don't".
What you should probably do instead is unravel the thing in your
view
code, so it's just a matter of iterating over (in|de)dents in the template. I think I'd do it by appending indents and dedents to a list while recursing through the tree and then sending that "travelogue" list to the template. (the template would then insert
```
<li>
```
and
```
</li>
```
from that list, creating the recursive structure with "understanding" it.)
I'm also pretty sure recursively including template files is really a
wrong
way to do it...


q: In XLST how would you find out the length of a node-set?

[A]
```
```
<xsl:variable name="length" select="count(nodeset)"/>
```
```


q:
What is the simplest SQL query to find the second largest integer value in a specific column?

There are maybe duplicate values in the column.

[A]
The easiest would be to get the second value from this result set in the application:
```
```
SELECT DISTINCT value
FROM Table
ORDER BY value DESC
LIMIT 2
```
```
But if you must select the second value using SQL, how about:
```
```
SELECT MIN(value)
FROM ( SELECT DISTINCT value
       FROM Table
       ORDER BY value DESC
       LIMIT 2
     ) AS t
```
```


q:
Does anyone have a trusted Proper Case or PCase algorithm (similar to a UCase or Upper)?  I'm looking for something that takes a value such as "GEORGE BURDELL" or "george burdell" and turns it into "George Burdell".

I have a simple one that handles the simple cases.  The ideal would be to have something that can handle things such as "O'REILLY" and turn it into "O'Reilly", but I know that is tougher.

I am mainly focused on the English language if that simplifies things.

UPDATE: I'm using C# as the language, but I can convert from almost anything (assuming like functionality exists).

I agree that the McDonald's scneario is a tough one.  I meant to mention that along with my O'Reilly example, but did not in the original post.

[A]
What programming language do you use? Many languages allow callback functions for regular expression matches. These can be used to propercase the match easily. The regular expression that would be used is quite simple, you just have to match all word characters, like so:
```
```
/\w+/
```
```
Alternatively, you can already extract the first character to be an extra match:
```
```
/(\w)(\w*)/
```
```
Now you can access the first character and successive characters in the match separately. The callback function can then simply return a concatenation of the hits. In pseudo Python (I don't actually know Python):
```
```
def make_proper(match):
    return match[1].to_upper + match[2]
```
```
Incidentally, this would also handle the case of “O'Reilly” because “O” and “Reilly” would be matched separately and both propercased. There are however other special cases that are not handled well by the algorithm, e.g. “McDonald's” or generally any apostrophed word. The algorithm would produce “Mcdonald'S” for the latter. A special handling for apostrophe could be implemented but that would interfere with the first case. Finding a thereotical perfect solution isn't possible. In practice, it might help considering the length of the part after the apostrophe.


q:
I am looking for any strategies people use when implementing server applications that service client TCP (or UDP) requests: design patterns, implementation techniques, best practices, etc.

Let's assume for the purposes of this question that the requests are relatively long-lived (several minutes) and that the traffic is time sensitive, so no delays are acceptable in responding to messages.  Also, we are both servicing requests from clients and making our own connections to other servers.

My platform is .NET, but since the underlying technology is the same regardless of platform, I'm interested to see answers for any language.

[A]
The modern approach is to make use of the operating system to multiplex many network sockets for you, freeing your application to only processing active connections with traffic.
Whenever you open a socket it's associated it with a selector. You use a single thread to poll that selector. Whenever data arrives, the selector will indicate the socket which is active, you hand off that operation to a child thread and continue polling.
This way you only need a thread for each concurrent operation. Sockets which are open but idle will not tie up a thread.
Using the select() and poll() methods
Building Highly Scalable Servers with Java NIO


q:
The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case.

Even though imagesavealpha is set, something isn't quite right.

What's the best way to preserve the transparency in the resampled image?

$uploadTempFile = $myField[ 'tmp_name' ]
list( $uploadWidth, $uploadHeight, $uploadType )
  = getimagesize( $uploadTempFile );

$srcImage = imagecreatefrompng( $uploadTempFile );
imagesavealpha( $targetImage, true );

$targetImage = imagecreatetruecolor( 128, 128 );
imagecopyresampled( $targetImage, $srcImage,
                    0, 0,
                    0, 0,
                    128, 128,
                    $uploadWidth, $uploadHeight );

imagepng(  $targetImage, 'out.png', 9 );

[A]
I believe this should do the trick:
```
```
$srcImage = imagecreatefrompng($uploadTempFile);
imagealphablending($srcImage, false);
imagesavealpha($srcImage, true);
```
```
edit:
Someone in the PHP docs claims
```
imagealphablending
```
should be true, not false. YMMV.


q:
Instead of relying on my host to send an email, I was thinking of sending the email messages using my Gmail account. The emails are personalized emails to the bands I play on my show.

Is it possible to do it?

[A]
Be sure to use
```
System.Net.Mail
```
, not the deprecated
```
System.Web.Mail
```
. Doing SSL with
```
System.Web.Mail
```
is a gross mess of hacky extensions.
```
```
using System.Net;
using System.Net.Mail;

var fromAddress = new MailAddress("from@gmail.com", "From Name");
var toAddress = new MailAddress("to@example.com", "To Name");
const string fromPassword = "fromPassword";
const string subject = "Subject";
const string body = "Body";

var smtp = new SmtpClient
{
    Host = "smtp.gmail.com",
    Port = 587,
    EnableSsl = true,
    DeliveryMethod = SmtpDeliveryMethod.Network,
    UseDefaultCredentials = false,
    Credentials = new NetworkCredential(fromAddress.Address, fromPassword)
};
using (var message = new MailMessage(fromAddress, toAddress)
{
    Subject = subject,
    Body = body
})
{
    smtp.Send(message);
}
```
```
Additionally go to the
Google Account > Security
page and look at the
Signing in to Google > 2-Step Verification
setting.
If it is enabled, then you have to generate a password allowing .NET to bypass the 2-Step Verification. To do this, click on
Signing in to Google > App passwords
, select app = Mail, and device = Windows Computer, and finally generate the password. Use the generated password in the
```
fromPassword
```
constant instead of your standard Gmail password.
If it is disabled, then you have to turn on
Less secure app access
, which is not recommended! So better enable the 2-Step verification.


q:
Let's say I had a program in C# that did something computationally expensive, like encoding a list of WAV files into MP3s. Ordinarily I would encode the files one at a time, but let's say I wanted the program to figure out how many CPU cores I had and spin up an encoding thread on each core. So, when I run the program on a quad core CPU, the program figures out it's a quad core CPU, figures out there are four cores to work with, then spawns four threads for the encoding, each of which is running on its own separate CPU. How would I do this?

And would this be any different if the cores were spread out across multiple physical CPUs? As in, if I had a machine with two quad core CPUs on it, are there any special considerations or are the eight cores across the two dies considered equal in Windows?

[A] Where each thread goes is generally handled by the OS itself...so generate 4 threads on a 4 core system and the OS will decide which cores to run each on, which will usually be 1 thread on each core.


q:
I am looking for a lean and well constructed open source implementation of a B-tree library written in C. It needs to be under a non-GPL license so that it can be used in a commercial application. Ideally, this library supports the B-tree index to be stored/manipulated as a disk file so that large trees can be built using a configurable (ie: minimal) RAM footprint.

Note: Since there seemed to be some confusion, a Binary Tree and a B-Tree are not the same thing.

[A]
The author of the
SQLite implementation
has disclaimed copyright.  If LGPL is okay, then maybe you could use
GNUpdate's implementation
?


q: On SO 18 Joel mentioned an algorithm that would rank items based on their age and popularity and it's based on gravity.  Could someone post this? C# would be lovely, but really any language (well, I can't do LISP) would be fine.

[A]
My understanding is that it is approximately the following from another
Jeff Atwood
post
```
```
t = (time of entry post) - (Dec 8, 2005)
x = upvotes - downvotes

y = {1 if x > 0, 0 if x = 0, -1 if x < 0)
z = {1 if x < 1, otherwise x}

log(z) + (y * t)/45000
```
```


q:
This query works great:

var pageObject = (from op in db.ObjectPermissions
                  join pg in db.Pages on op.ObjectPermissionName equals page.PageName
                  where pg.PageID == page.PageID
                  select op)
                 .SingleOrDefault();

I get a new type with my 'op' fields.  Now I want to retrieve my 'pg' fields as well, but

select op, pg).SingleOrDefault();

doesn't work.

How can I select everything from both tables so that they appear in my new pageObject type?

[A]
You must create a new anonymous type:
```
```
select new { op, pg }
```
```
Refer to the official
guide
.


q:
The product-group I work for is currently using gcc 3.4.6 (we know it is ancient) for a large low-level c-code base, and want to upgrade to a later version. We have seen performance benefits testing different versions of gcc 4.x on all hardware platforms we tested it on. We are however very scared of c-compiler bugs (for a good reason historically), and wonder if anyone has insight to which version we should upgrade to.

Are people using 4.3.2 for large code-bases and feel that it works fine?

[A]
I don't have a specific version for you, but why not have a 4.X
and
3.4.6 installed? Then you could try and keep the code compiling on both versions, and if you run across a show-stopping bug in 4, you have an exit policy.


q:
Here's the situation:  I need to bind a WPF FixedPage against a DataRow.  Bindings don't work against DataRows; they work against DataRowViews.  I need to do this in the most generic way possible, as I know nothing about and have no control over what is in the DataRow.

What I need is to be able to get a DataRowView for a given DataRow.  I can't use the Find() method on the DefaultView because that takes a key, and there is no guarantee the table will have a primary key set.

Does anybody have a suggestion as to the best way to go around this?

[A]
```
```
row.Table.DefaultView[row.Table.Rows.IndexOf(row)]
```
```
This is an okay answer.  But if you find yourself in this situation, you should consider learning more about DataViews and how they are used, then refactor your code to be view-centric rather than table-centric.


q:
So I've got a hobby site I'm working on.  I've got items that are tagged and I want to associate those items with photos from Flickr.  Even with restrictive searches, I might get results numbering in the thousands.

Requirements:

I want to display between 10-20 pictures but I want to randomize the photos each time.

I don't want to hit Flickr every time a page request is made.

Not every Flickr photo with the same tags as my item will be relevant.

How should I store that number of results and how would I determine which ones are relevant?


q:
Is there any way to Write files to App_Data under medium trust hack?

Im sure I've heard about some hack, is that true?

[A] I don't think you are able to create new files, but you should be able to write to existing files in the App_Data folder.  But I have honestly never experienced any problems with Medium Trust and writing to the App_Data folder.  Are you sure it has the necessary permissions needed for writing files to the hard drive?


q:
Anybody have a good example how to deep clone a WPF object, preserving databindings?

The marked answer is the first part.

The second part is that you have to create an ExpressionConverter and inject it into the serialization process.  Details for this are here:

http://www.codeproject.com/KB/WPF/xamlwriterandbinding.aspx?fid=1428301&df=90&mpp=25&noise=3&sort=Position&view=Quick&select=2801571

[A]
How about:
```
```
public static T DeepClone<T>(T from)
    {
        using (MemoryStream s = new MemoryStream())
        {
            BinaryFormatter f = new BinaryFormatter();
            f.Serialize(s, from);
            s.Position = 0;
            object clone = f.Deserialize(s);

            return (T)clone;
        }
    }
```
```
Of course this deep clones any object, and it might not be the fastest solution in town, but it has the least maintenance... :)


q:
Is there some way I can use URLs like:

http://www.blog.com/team-spirit/

instead of

http://www.blog.com/?p=122

in a Windows hosted PHP server?

[A]
This is how I did it with WordPress on IIS 6.0
http://www.coderjournal.com/2008/02/url-rewriter-reverse-proxy-iis-wordpress/
However it all depends on what version of IIS you are using.  If you are lucky enough to use IIS 7.0 you don't really have to worry about pretty urls because everything is supported out of the box.  However if you are using IIS 6.0 you are going to have to use a rewriter and some rules to force the IISness out of IIS.


q:
Is there an easy way to discover a File's creation time with Java?  The File class only has a method to get the "last modified" time.  According to some resources I found on Google, the File class doesn't provide a getCreationTime() method because not all file systems support the idea of a creation time.

The only working solution I found involes shelling out the the command line and executing the "dir" command, which looks like it outputs the file's creation time.  I guess this works, I only need to support Windows, but it seems very error prone to me.

Are there any third party libraries that provide the info I need?

Update: In the end, I don't think it's worth it for me to buy the third party library, but their API does seem pretty good so it's probably a  good choice for anyone else that has this problem.

[A]
I like the answer on
jGuru
that lists the option of using
JNI
to get the answer. This might prove to be faster than shelling out and you may encounter other situations such as this that need to be implemented specifically for windows.
Also, if you ever need to port to a different platform, then you can port your library as well and just have it return -1 for the answer to this question on *ix.


q:
What are the best practices in setting up a new instance of TFS 2008 Workgroup edition?

Specifically, the constraints are as follows:

Must install on an existing Windows Server 2008 64 bit

TFS application layer is 32 bit only

Should I install SQL Server 2008, Sharepoint and the app layer in a virtual instance of Windows Server 2008 or 2003(I am already running Hyper-V) or split the layers with a database on the host OS and the app layer in a virtual machine?

Edit: Apparently, splitting the layers is not recommended

[A] I just upgraded our team to TFS 2008, from TFS 2005. The hardest part was upgrading SharePoint 2.0 to 3.0, so I would make sure to do that first, if you have not already installed TFS 2008. We had a couple of other difficulties, but they were all either related to the SharePoint upgrade, or to the fact that we were using an aftermarket Policy package - Scrum for TeamSystem. We are on SQL Server 2005, so I cannot address SQL Server 2008. As for  splitting the layers, we did not do this either, as we are running on                          Windows Server 2003 and everything ran under the host OS.


q:
I'm new to NHibernate (my 1st big project with it).

I had been using a simple method of data access by creating the ISession object within a using block to do my grab my Object or list of Objects, and in that way the session was destroyed after exiting the code block.

This doesn't work in a situation where lazy-loading is required, however.

For example, if I have a Customer object that has a property which is a collection of Orders, then when the lazy-load is attempted, I get a Hibernate exception.

Anyone using a different method?

[A]
Keep your session open for your entire unit of work.  If your session is life is too small, you cannot benefit from the session level cache (which is significant).  Any time you can prevent a roundtrip to the database is going to save a lot of time.   You also cannot take advantage of lazy loading, which is crucial to understand.
If your session lifetime is too big, you can run into other issues.
If this is a web app, you'll probably do fine with the session-per-httpRequest pattern.  Basically this is an HttpModule that opens the session at the beginning of the request and flushes/closes at the end.  Be sure to store the session in HttpContext.Items  NOT A STATIC VARIABLE.  <--- leads to all kinds of problems that you don't want to deal with.
You might also look at
RhinoCommons
for a unit of work implementation.


q:
I'm trying to find the latitude and longitude of the corners of my map while in birdseye view.  I want to be able to plot pins on the map, but I have hundreds of thousands of addresses that I want to be able to limit to the ones that need to show on the map.

In normal view, VEMap.GetMapView().TopLeftLatLong and .BottomRightLatLong return the coordinates I need; but in Birdseye view they return blank (or encrypted values).  The SDK recommends using VEBirdseyeScene.GetBoundingRectangle(), but this returns bounds of up to two miles from the center of my scene which in major cities still returns way too many addresses.

In previous versions of the VE Control, there was an undocumented VEDecoder object I could use to decrypt the LatLong values for the birdseye scenes, but this object seems to have disappeared (probably been renamed).  How can I decode these values in version 6.1?

[A]
According to
http://dev.live.com/virtualearth/sdk/
this should do the trick:
```
```
function GetInfo()
{
  alert('The latitude,longitude at the center of the map is: '+map.GetCenter());
}
```
```


q:
I am consuming the Twitter API and want to convert all URLs to hyperlinks.

What is the most effective way you've come up with to do this?

from

string myString = "This is my tweet check it out http://tinyurl.com/blah";

to

This is my tweet check it out <a href="http://tinyurl.com/blah">http://tinyurl.com/>blah</a>

[A]
Regular expressions are probably your friend for this kind of task:
```
```
Regex r = new Regex(@"(https?://[^\s]+)");
myString = r.Replace(myString, "$1");
```
```
The regular expression for matching URLs might need a bit of work.


q:
So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".

I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.

I'm using latest version of rhino mocks

[A]
Using MoQ it looks something like this:
```
```
var request = new Mock<HttpRequestBase>();
request.Expect(r => r.HttpMethod).Returns("GET");
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Expect(c => c.Request).Returns(request.Object);
var controllerContext = new ControllerContext(mockHttpContext.Object
, new RouteData(), new Mock<ControllerBase>().Object);
```
```
I think the Rhino Mocks syntax is similar.


q: Where can I find a good tutorial on learning ASP.NET MVC using VB.net 2008 as the language? Most in-depth tutorials that I found in searching the web were written in C#.

[A]
Have you tried adding the word "VB" to your searches??
http://www.myvbprof.com/2007_Version/MVC_Intro_Tutorial.aspx
http://www.asp.net/learn/mvc/tutorial-07-vb.aspx
<
Link
>


q:
When making changes using SubmitChanges(), LINQ sometimes dies with a ChangeConflictException exception with the error message Row not found or changed, without any indication of either the row that has the conflict or the fields with changes that are in conflict, when another user has changed some data in that row.

Is there any way to determine which row has a conflict and which fields they occur in, and also is there a way of getting LINQ to ignore the issue and simply commit the data regardless?

Additionally, does anybody know whether this exception occurs when any data in the row has changed, or only when data has been changed in a field that LINQ is attempting to alter?

[A]
I've gotten this error in a circumstance completely unrelated to what the error message describes.
What I did was load a LINQ object via one DataContext, and then tried to SubmitChanges() for the object via a different DataContext - gave this exact same error.
What I had to do was call DataContext.Table.Attach(myOldObject), and then call SubmitChanges(), worked like a charm.
Worth a look, especially if you're of the opinion that there really shouldn't be any conflicts at all.


q:
Can anyone tell me if there is a way with generics to limit a generic type argument T to only:

Int16

Int32

Int64

UInt16

UInt32

UInt64

I'm aware of the where keyword, but can't find an interface for only these types,

Something like:

static bool IntegerFunction<T>(T value) where T : INumeric

[A]
There's no constraint for this. It's a real issue for anyone wanting to use generics for numeric calculations.
I'd go further and say we need
```
```
static bool GenericFunction<T>(T value)
    where T : operators( +, -, /, * )
```
```
Or even
```
```
static bool GenericFunction<T>(T value)
    where T : Add, Subtract
```
```
Unfortunately you only have interfaces, base classes and the keywords
```
struct
```
(must be value-type),
```
class
```
(must be reference type) and
```
new()
```
(must have default constructor)
You could wrap the number in something else (similar to
```
INullable<T>
```
) like
here on codeproject
.
You could apply the restriction at runtime (by reflecting for the operators or checking for types) but that does lose the advantage of having the generic in the first place.


q:
How do I get today's date in C# in mm/dd/yyyy format?

I need to set a string variable to today's date (preferably without the year), but there's got to be a better way than building it month-/-day one piece at a time.

BTW: I'm in the US so M/dd would be correct, e.g. September 11th is 9/11.

Note: an answer from kronoz came in that discussed internationalization, and I thought it was awesome enough to mention since I can't make it an 'accepted' answer as well.

kronoz's answer

[A]
```
```
DateTime.Now.ToString("M/d/yyyy");
```
```
http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx


q: I'm using an older version of ASP.NET AJAX due to runtime limitations, Placing a ASP.NET Validator inside of an update panel does not work. Is there a trick to make these work, or do I need to use the ValidatorCallOut control that comes with the AJAX toolkit?

[A]
@jmein
Actually the problem is that the Validator client script's don't work when placed inside of an updatePanel (UpdatePanels refresh using .innerHTML, which adds the script nodes as text nodes, not script nodes, so the browser does not run them).
The fix was a patch released by microsoft that fixes this issue. I found it with the help of Google.
http://blogs.msdn.com/mattgi/archive/2007/01/23/asp-net-ajax-validators.aspx


q: So I'm interested in hearing different thoughts about what is the best way to go about unit testing XNA Game/Applications.  Astute googlers can probably figure out why I'm asking, but I didn't want to bias the topic :-)

[A]
I would that this question is geared more toward the approach of
unit testing in game development
.  I mean, XNA is a framework.  Plug in
NUnit
, and begin writing test cases while you develop.
Here
is a post on SO about unit testing a game.  It'll give you a little insight into how you need to think while progressing.


q:
I've got a problem where incoming SOAP messages from one particular client are being marked as invalid and rejected by our XML firewall device. It appears extra payload data is being inserted by Visual Studio; we're thinking the extra data may be causing a problem b/c we're seeing "VsDebuggerCausalityData" in these messages but not in others sent from a different client who is not having a problem. It's a starting point, anyway.

The question I have is how can the client remove this extra data and still run from VS? Why is VS putting it in there at all?

Thanks.

[A]
A quick google reveals that this should get rid of it, get them to add it to the web.config or app.config for their application.
```
```
<configuration>
  <system.diagnostics>
    <switches>
       <add name="Remote.Disable" value="1" />
    </switches>
  </system.diagnostics>
</configuration>
```
```
The information is debug information that the receiving service can use to help trace things back to the client.  (maybe, I am guessing a little)
I have proposed a follow up
question
to determine were the magic switch actually comes from.


q:
This question would probably apply equally as well to other languages with C-like multi-line comments. Here's the problem I'm encountering. I'm working with Java code in Eclipse, and I wanted to comment out a block of code. However, there is a string that contains the character sequence "*/", and Eclipse thinks that the comment should end there, even though it is inside a string. It gives me tons of errors and fails to build.

/*
   ... some Java code ...
   ... "... */ ..." ...
   ... more Java code ...
*/

Does the Java specification match with Eclipse's interpretation of my multi-line comment? I would like to think that Java and/or Eclipse would account for this sort of thing.

[A]
Eclipse is correct. There is no interpretation context inside a comment (no escaping, etc). See
JLS §3.7
.