q:
I have a simple question. Is there a way ( using reflections I suppose ) to iterate all the static values of a class?

For instance

class Any {
    static int one = 1;
    static int two = 2;
    static int three = 3;

    public static void main( String [] args ) {
          for( int i : magicMethod( Any.class ) ){
              System.out.println( i );
          }
    }
 }

Output

 1
 2
 3

Thanks.

[A]
Hey.. it was very easy.  :P
```
```
Field [] constants = Main.class.getFields();
      Object some = new Main();
      for( Field field : constants ){
          if(Modifier.isStatic(field.getModifiers() ) &&
             field.getType() == int.class  ) {
                    System.out.println( field.getInt( some  ) );
          }
      }
```
```


q:
Given a UTC time string like this:

2005-11-01T00:00:00-04:00

What is the best way to convert it to a DateTime using a Crystal Reports formula?

My best solution is posted below.

I hope someone out there can blow me away with a one-liner...

[A]
Here is my best solution, with comments:
```
```
//assume a date stored as a string in this format:
//2005-11-01T00:00:00-04:00
//return a DateTime value
StringVar fieldValue;
StringVar datePortion;
StringVar timePortion;
NumberVar yearPortion;
NumberVar monthPortion;
NumberVar dayPortion;
NumberVar hourPortion;
NumberVar minutePortion;
NumberVar secondPortion;

//store the field locally so i can easily copy-paste into another formula
//(where the field name will be different)
//Crystal formulas do not use a powerful language.
fieldValue := {PACT.ReferralDate};

//break up the date & time parts.
//ignore the -04:00 offset part of the time.
datePortion := Split (fieldValue,"T")[1];
timePortion := Split(Split (fieldValue,"T")[2],"-")[1];

yearPortion := ToNumber(Split(datePortion,"-")[1]);
monthPortion := ToNumber(Split(datePortion,"-")[2]);
dayPortion := ToNumber(Split(datePortion,"-")[3]);

hourPortion := ToNumber(Split(timePortion,":")[1]);
minutePortion := ToNumber(Split(timePortion,":")[2]);
secondPortion := ToNumber(Split(timePortion,":")[3]);

//finally, return the result as a date-time
DateTime(yearPortion,monthPortion,dayPortion,hourPortion,minutePortion,secondPortion);
```
```

s: huggingface

c: devops

d: intermediate


q:
how do i check if an item is selected or not in my listbox?
so i have a button remove, but i only want that button to execute if an item is selected in the list box. im using asp.net code behind C#. I'd prefer if this validation occurred on the server side.

cheers..

[A]
On the callback for the button click, just check if the selected index of the list box is greater than or equal to zero.
```
```
protected void removeButton_Click( object sender, EventArgs e )
{
    if (listBox.SelectedIndex >= 0)
    {
        listBox.Items.RemoveAt( listBox.SelectedIndex );
    }
}
```
```


q: In adobe Flex datagrid height is equally to fix height . I want to make datagrid height is depend data .

[A] You can set each row of the datagrid to fit based on the contents of a particular column of that row by setting the "variableRowHeight" attribute to true on the datagrid and setting the "wordWrap" attribute to true on the dataGridColumn that will contain the variable height content.


q: Is there a built-in way to know if a given session variable is a serialized object? Say I retrieve a value like $_SESSION['foo'], but I don't know if it was originally a string or if it is a serialized object. Is there some way to check, or once serialized does PHP just see a string as a string as a string?

[A]
A string is a string is a string. I think the best you'll be able to do is just try to unserialize it, and if it works, it works. If it doesn't, it doesn't.
The only other option would be to use a regex to see if it "looks" like a serialized object. Just running
```
unserialize()
```
on it might be easier though.


q:
This is a little confusing to explain, so bear with me here...

I want to set up a system where a user can send templated emails via my website, except it's not actually sent using my server - it instead just opens up their own local mail client with an email ready to go. The application would fill out the body of the email with predefined variables, to save the user having to type it themselves. They can then edit the message as desired, should it not exactly suit their purposes.

There's a number of reasons I want it to go via the user's local mail client, so getting the server to send the email is not an option: it has to be 100% client-side.

I already have a mostly-working solution running, and I'll post the details of that as an answer, I'm wondering if there's any better way?

[A]
The way I'm doing it now is basically like this:
The HTML:
```
```
<textarea id="myText">
    Lorem ipsum...
</textarea>
<button onclick="sendMail(); return false">Send</button>
```
```
The Javascript:
```
```
function sendMail() {
    var link = "mailto:me@example.com"
             + "?cc=myCCaddress@example.com"
             + "&subject=" + encodeURIComponent("This is my subject")
             + "&body=" + encodeURIComponent(document.getElementById('myText').value)
    ;

    window.location.href = link;
}
```
```
This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.


q:
I have a build server running CruiseControl.NET. It works well for the 7 projects that are configured to run on that server (let's call it server A).

Now I have a new project that I wish to build on a different server (server B), but I want it to appear in the same ccnet dashboard as the existing projects.

How do I configure CCNet for this scenario?

[A]
In
```
dashboard.config
```
(default location is
```
c:\Program Files\CruiseControl.NET\webdashboard\dashboard.config
```
) take a look at the
Servers Configuration Block
:
```
```
<servers>
       <server name="local" url="tcp://localhost:21234/CruiseManager.rem"
               allowForceBuild="true" allowStartStopBuild="true" />
   </servers>
```
```
It allows you to configure the remote servers you want to report on - just add another
```
<server />
```
node.
To force the changes to appear on your CruiseControl.NET dashboard, edit the web.config file in the same folder and save it. Refresh the dashboard web page.


q: Can anyone reccomend a .net control (winforms) that can be used to as a designer to edit xml files / DSL files ??

[A]
Why might an XSLT fail?
An XSLT will fail because of obvious things like typos. However, the most likely situation relates to namespace usage. If you declared a default namespace for your XML but don't include that in your XSLT, the XSLT won't match the templates as you might expect.
The following example adds the
```
xmlns:business
```
attribute which declares that items qualified by the
```
business
```
prefix belong to the namespace
```
mynamespace.uri
```
. I then used this prefix to qualify the Address and Addresses template matches. Of course, you will need to change the namespace URI to whatever matches the default namespace of your XML file.
```
```
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt"
                xmlns:business="mynamespace.uri"
                exclude-result-prefixes="msxsl">
  <xsl:template match="/">
    <xsl:apply-templates select="@*|node()"/>
  </xsl:template>

  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
  </xsl:template>

  <xsl:template match="business:Addresses">
    <xsl:element name="BusinessAddresses">
      <xsl:apply-templates select="@*|node()" />
    </xsl:element>
  </xsl:template>

  <xsl:template match="business:Address">
    <xsl:element name="BusinessAddress">
      <xsl:apply-templates select="@*|node()"/>
    </xsl:element>
  </xsl:template>
</xsl:stylesheet>
```
```
How do you match templates based on element location as well as name?
There are several ways to achieve this last part to your problem, BusinessAddress or ContactAddress, but the easiest is to modify the template
```
match
```
attributes to consider parent nodes. If you think of the
```
match
```
attribute as a path into the XML for a node, this option becomes clearer (contents of templates left out for brevity):
```
```
<xsl:template match="business:Business/business:Addresses>
</xsl:template>

<xsl:template match="business:Business/business:Addresses/business:Address">
</xsl:template>

<xsl:template match="business:Contact/business:Addresses">
</xsl:template>

<xsl:template match="business:Contact/business:Addresses/business:Address">
</xsl:template>
```
```
Other methods exist for achieving this if the
```
match
```
remains based on just the element name, but they're harder to implement, follow, and maintain as they involve the use of conditional checks on the parent node hierarchy of the element being processing, all within the template.


q:
I'm just concerned about Windows, so there's no need to go into esoterica about Mono compatibility or anything like that.

I should also add that the app that I'm writing is WPF, and I'd prefer to avoid taking a dependency on System.Windows.Forms if at all possible.

[A]
The simplest way would be to create an Autoplay Handler:
http://www.codeproject.com/KB/system/AutoplayDemo.aspx
Autoplay Version 2 is a feature in
  Windows XP that will scan the first
  four levels of a removable media, when
  it arrives, looking for media content
  types (music, graphics, or video).
  Registration of applications is done
  on a content type basis. When a
  removable media arrives, Windows XP
  determines what actions to perform by
  evaluating the content and comparing
  it to registered handlers for that
  content.
A
detailed MSDN article
is also available.


q:
Given a Django.db models class:

class P(models.Model):
   type = models.ForeignKey(Type) # Type is another models.Model class
   name = models.CharField()

where one wishes to create a new P with a specified type, i.e. how does one make "type" to be a default, hidden field (from the user), where type is given likeso:

http://x.y/P/new?type=3

So that in the form no "type" field will appear, but when the P is saved, its type will have id 3 (i.e. Type.objects.get(pk=3)).

Secondarily, how does one (& is it possible) specify a "default" type in the url, via urls.py, when using generic Django views, viz.

urlpatterns = ('django.generic.views.create_update',
  url(r'^/new$', 'create_object', { 'model': P }, name='new_P'),
)

I found that terribly difficult to describe, which may be part of the problem. :) Input is much appreciated!

[A]
To have a default Foreign Key in a model:
```
```
mydefault = Type.objects.get(pk=3)

class P(models.Model):
   type = models.ForeignKey(Type, default=mydefault) # Type is another models.Model class
   name = models.CharField()
```
```
Note that using
```
pk=x
```
is pretty ugly, as ideally you shouldn't care what the primary key is equal to.  Try to get to the object you want by some other attribute.
Here
's how you put defaults in your urls:
```
```
# URLconf
urlpatterns = patterns('',
    (r'^blog/$', 'blog.views.page'),
    (r'^blog/page(?P<num>\d+)/$', 'blog.views.page'),
)

# View (in blog/views.py)
def page(request, num="1"):
    # Output the appropriate page of blog entries, according to num.
```
```
In the above example, both URL patterns point to the same view -- blog.views.page -- but the first pattern doesn't capture anything from the URL. If the first pattern matches, the page() function will use its default argument for num, "1". If the second pattern matches, page() will use whatever num value was captured by the regex.


q: Pretty self explanatory. I just need to export lists easily to xml format. Are there any tools that accomplish this?

[A]
You can write a c# application pretty easily to connect to the sp list and export it out yourself.
A quick search on codeplex search comes up with one such program already made for this purpose! Hope this can help you:
http://www.codeplex.com/SPListReader
http://www.codeplex.com/SPListReader/Release/ProjectReleases.aspx?ReleaseId=15420


q:
Im developing a "desktop" for WM6+ and i was wondering if i can override the draw that WM does when it starts the OS (like the start menu, softkey bar, and background) basically have my program draw the today screen instead of windows. My program will of course integrate everything that the original "screen" integrated.

C++

[A]
Do you want to implement a today screen "theme" or have the device operate in kiosk mode? The first one is easy - you would need great experience to do the second one.
There are commercial solutions available that will enable you to operate your device in "Kiosk" mode. These aren't cheap though. If you plan to do it yourself, then good knowledge of Windows CE OS is needed - I suggest that you download Platform Builder (I am not sure how they call it now) and have a look at the source code. This is the best way to learn about the internals of the system.
One, not so perfect but easy to implement solution, is to create a full screen application and have it launched at start up. You need also to intercept the hardware keys.


q:
I'm using JMX to save some diagnostic information from a remote process. Looking at the interface in jconsole shows that the return type is CompositeData (the data actually comes back as CompositeDataSupport). I want to output all the key/value pairs that are associated with this object.

The problem is that the interface just seems to have a "values()" method with no way of getting the keys. Am I missing something here? Is there some other way to approach this task?

Thanks!

[A]
If I'm not mistaken you could do
```
```
Set< String > keys = cData.getCompositeType().keySet();
```
```
(given that cData is a CompositeData object)
http://java.sun.com/j2se/1.5.0/docs/api/javax/management/openmbean/CompositeType.html#keySet()


q:
I am adding objects into a java Vector using its add(Object) method.
In my example, the first 5 objects are identical, followed by 2 instances different from the first five.
For some reasons, as soon as I insert the first one that is different, it changes the entire vector to that value!

'values' is an iterator containing something like
'1','1','1','1','1','2','2'

Vector temp = new Vector();
while (values.hasNext()) {
     temp.add(values.next());
     System.out.println(temp.toString());
}

It will output something like

[1]

  [1,1]

  [1,1,1]

  [1,1,1,1]

  [1,1,1,1,1]

  [2,2,2,2,2,2]

  [2,2,2,2,2,2,2]

I tried using a LinkedList, as well as using add(object, index). Same thing happened.

[A]
I suspect that, somehow, the "objects" you are getting from the iterator are really multiple references to a single instance of a mutable object, which is changing its state from "1" to "2". The thing I can't guess at is how it's changing state in this apparently single-threaded operation.
Can you post more complete code? Show where
```
values
```
comes from and how it is initialized.


q:
This is truly a beginner question, so I apologize in advance.

I have Visual Studio 2008 Standard installed and would like to create a small Windows application that does NOT require any .NET framework when run on computers. Does VS 2008 Standard support such a feature? Any pointers on how to accomplish this would be fantastic.

Thanks in advance.

[A]
Sure, you can definitely do this. You'll have to write your application in C++, though.
To get started, go to File | New, and under Project Types pick one of the options under Visual C++. For the minimal dependencies, I would suggest one of the Win32 options. Both the "Win32 Console Application" and the "Win32 Project" options appear to take you to the same wizard, which if you click Application Settings on the left lets you pick whether to create a console app or a windows app. A console app will run in a console window like cmd.exe, whereas a windows app will initially have no UI (you'll have to do the UI yourself).
Be aware that even if you don't depend on the .NET runtime, you'll still need to have the CRT dlls available on machines that will be running your program. The redistributables for these live under the Visual Studio install dir, which if you installed in the default location would be C:\Program Files\Microsoft Visual Studio 9.0\VC\redist.


q:
Has anyone found a plugin for Visual Studio to allow for PowerShell syntax highlighting or IntelliSense? If not, does anyone have any idea why not?  I keep hoping someone else with copious free time would have tackled this by now. I have hope since other folks have managed to take the limited documentation and build custom IntelliSense providers for other languages such as NHaml.

Edit: To clarify,I'm not looking for a list of IDEs that can be used to develop PowerShell . I spend 90% of my day in Visual Studio.  It already does a really good job of slicing and dicing code. That is the IDE I prefer to use to edit all text and code.  The lack of PowerShell syntax highlighting now that I work with PowerShell scripts is down right painful.

[A]
I have not seen anything about Visual Studio  Intellisense for PowerShell scripts.
I recommend you to try some other tools like:
PowerTab
PowerGUI
Look this screen cast:
(source:
aaronlerch.com
)


q: Is there some nice documentation for Windows batch scripting I can download and refer to while offline?

[A]
Google hits, for "windows batch scripting documentation" - first page:
http://labmice.techtarget.com/scripting/batchfiles.htm
http://www.allenware.com/icsw/icswidx.htm


q:
If you have a Property that gets and sets to an instance variable then normally you always use the Property from outside that class to access it.

My question is should you also always do so within the class? I've always used the Property if there is one, even within the class, but would like to hear some arguments for and against as to which is the most correct and why.

Or is it just a matter of coding standards being used on the project?

[A]
It depends on whether you want to apply any logic implemented within the property setter, and so you really have to decide on a case by case basis.
When you go directly to the private field, you know that the field is being set to exactly what you say.
When you go through the Property, the value gets set according to the setter logic, so you get any business rules or validation you want over values assigned to that field.
Pretty hard to come up with a rule about when doing either is 'correct', about the only one I'd say I follow is that in constructor initialisation I'd pretty much never use the Property.


q:
We currently just utilize soap webservices for all our communication but have been thinking about moving to WCF instead. What are the benefits of using it over an asmx service?

If we do go with a WCF service, can other languages still communicate with it? SOAP is standardized and all languages can interact with it.

Are there any really good examples of how to get started with WCF that show the benefits of it over soap?

EDIT

I just found this question which is quite helpful.

The Getting Started Tutorial is great.

[A]
There's a bit of a learning curve with WCF, but once you learn it it's no harder to implement than an asmx web services. One advantage is you can easily switch protocols and serialization from binary remoting all the way to
web protocols
. It's also easy to host either in IIS or out.
Other languages can communicate with the web protocols. Binary, not so much...
I just dug into the
Getting Started Tutorial
. It does a good job of showing the relative ease-of-use. From there, take a look at
Hosting
and more detailed
Features
.


q:
I have problems with how to design some classes. I have three classes. One superclass, and two subclasses.

One subclass (AnimatedCharacter) is made by flash, and is used to display the object on screen. The other (CharacterPhysics) is made by myself to extend the superclass.

The problem is that the object I use, is of the type AnimatedCharacter, so I can't just put it in a variable of type CharacterPhysics.

What I tried is some sort of Decorator pattern, by giving the object of type CharacterPhysics a reference to the other object. But now I have to override all the methods of the superclass and pass the methodcalls to the reference. Not an ideal situation.

Does someone know how to solve this kind of problem?

alt text http://www.freeimagehosting.net/uploads/7a95f8352c.png

[A]
I don't quite understand the purpose of this class structure you describe (the class names confuse me), but in general a few things come to mind that might help you:
Almost always the best solution is to try and rethink your class model by evaluating whether you should for example break up the
responsibilities
of classes in an alternate way so that you could utilize inheritance and polymorphism in a better way.
"The problem is that the object I use,
  is of the type AnimatedCharacter, so I
  can't just put it in a variable of
  type CharacterPhysics."
If you want to put an
```
AnimatedCharacter
```
into a variable of type
```
CharacterPhysics
```
, the former should extend the latter, or you should have a common interface (or superclass) for both and then type the variable as such. If this is not possible, my opinion is that you should probably try to rethink and refactor your whole class structure, assuming that you have a solid "object-oriented" reason for wanting to do this in the first place ;).
If the above is not possible, there are some other tricks you can evaluate in your context:
The use of
mixins
can work as a "poor man's multiple inheritance". Derek Wischusen has some examples on how to implement them in AS3 at
flexonrails.net
.
"Kind of" implementing the decorator pattern with
flash.utils.Proxy
. The problem with this approach is that you defer a lot of error checking from compile time to runtime, but the good thing is that you don't have to manually write the "proxying" implementations of all of the methods of the "decorated" object, but write just one (
```
callProperty()
```
) instead.


q:
How do I pick/ delete all the documents from Solr using the boolean NOT notion?

i.e. How do I delete all the documents from Solr who's id does NOT start with A59?

[A]
Use
```
-
```
to indicate
```
NOT
```
.
For example, to query  documents with id not starting with A59, the query would be:
```
-id:A59*
```
, that is:
```
/solr/select/?q=-id:A59*
```
To delete by query, post the query in a delete message to the update handler, as specified
here
.
EDIT:
```
NOT
```
(all uppercase) can also be used as boolean operator


q:
I'm trying to use a dojo combobox with an Ajax data source.  What I have is

<div dojoType="dojo.data.ItemFileReadStore"
     jsId="tags"
     url="<%=ResolveClientUrl("~/Tag/TagMatches")%>" >
</div>
<select dojoType="dijit.form.ComboBox"
        store="tags"
        value=""
        name="tagName">
</select>

Which does work except that I can't restrict the search set on the server side because I don't know how to change the url from which the data is pulled in order to specify a parameter.  Any hints?

[A]
If I understand you correctly, you want the client to load different set of data from the server based on some general condition defined elsewhere.
Basically there is no need to have a
```
<div>
```
pre-defined. You can also create the
```
ItemFileReadStore
```
directly in JavaScript:
earlier...:
```
```
var tagMatchUrlBase = '<%=ResolveClientUrl("~/Tag/TagMatches")%>';
```
```
later...:
```
```
var tagMatchUrl = tagMatchUrlBase + "?f=" + escape(somefilterString);
var store = new dojo.data.ItemFileReadStore({url: tagMatchUrl});
tagName.store = store;
// maybe use store.fetch() to pre-select item #1
```
```


q:
I have a class that stores a serialized value and a type. I want to have a property/method returning the value already casted:

public String Value { get; set; }

public Type TheType { get; set; }

public typeof(TheType) CastedValue { get { return Convert.ChangeType(Value, typeof(_Type)); }

Is this possible in C#?

[A]
It's possible if the class containing the property is generic, and you declare the property using the generic parameter:
```
```
class Foo<TValue> {
    public string Value { get; set; }
    public TValue TypedValue {
        get {
            return (TValue)Convert.ChangeType(Value, typeof(TValue));
        }
    }
}
```
```
An alternative would be to use a generic method instead:
```
```
class Foo {
    public string Value { get; set; }
    public Type TheType { get; set; }

    public T CastValue<T>() {
         return (T)Convert.ChangeType(Value, typeof(T));
    }
}
```
```
You can also use the
```
System.ComponentModel.TypeConverter
```
classes to convert, since they allow a class to define it's own converter.
Edit
: note that when calling the generic method, you must specify the generic type parameter, since the compiler has no way to infer it:
```
```
Foo foo = new Foo();
foo.Value = "100";
foo.Type = typeof(int);

int c = foo.CastValue<int>();
```
```
You have to know the type at compile time.  If you don't know the type at compile time then you must be storing it in an
```
object
```
, in which case you can add the following property to the
```
Foo
```
class:
```
```
public object ConvertedValue {
    get {
        return Convert.ChangeType(Value, Type);
    }
}
```
```


q:
:vimgrep looks like a really useful thing.

Here's how to use it:

:vim[grep][!] /{pattern}/[g][j] {file} ...

:help says that you can essentially glob {file} to name, say, *.c for the current directory. I may have started Vim with a list of files that is complicated enough that I don't want to manually type it in for {file}, and besides Vim already knows what those files are.

What I would like to do is vimgrep over any of:

:args

:files

:buffers

What variable(s) would I use in place of {file} to name, respectively, any of those lists in a vimgrep command?

[A]
You can do this:
```
```
:bufdo vimgrep /pattern/ %
```
```
% substitutes the buffer name.


q: One of the files in my current head revision got corrupted. I want to make an older revision of that file the head revision as usually people sync to head revsion in my project. How to do that?

[A]
You should revert all changes since that old reversion. In principle,
```
```
svn merge -rHEAD:oldrev filename
svn commit -m "rolled back to oldrev"
```
```
should do. The later revisions are still there, but reverted.


q:
What are the pros and cons of LINQ (Language-Integrated Query)?

What are the best and worst cases in which to use LINQ?

How have you benefitted or not benefitted from using LINQ?

Which data sources benefit the least and the most from LINQ?

[A]
I'm a massive fan of LINQ - although it needs to be kept in perspective, and not treated as a silver bullet.
Pros:
Declarative approach makes queries easier to understand and more compact
Extensibility and expression trees allow mostly consistent querying of multiple sources
Even in-process queries can be implemented in ways other than LINQ to Objects - e.g. Parallel LINQ and my own Push LINQ framework. Very flexible.
Fabulously
useful for in-process queries, where it's easiest to understand
Great to be able to avoid SQL in strings etc
Wide range of operators provided by default, and others can easily be added for LINQ to Objects
Language features introduced primarily for LINQ are widely applicable elsewhere (yay for lambdas)
Cons:
Query expressions aren't understood well enough, and are overused. Often simple method invocation is shorter and simpler.
Inevitable inconsistencies between provider - impedance mismatch is still present, which is reasonable but needs to be understood
There will always be some things you can do in SQL but not in LINQ
Without understanding what's going on, it's easy to write very inefficient code
It's hard to write a LINQ provider. This may well be inevitable, but more guidance from Microsoft would be appreciated.
It's a new way of thinking about data access for most developers, and will need time for understanding to percolate
Not specifically LINQ but related to it - the way extension methods are discovered in C# isn't granular enough
Some operators are "missing", particularly the equivalents of
```
OrderBy
```
for things other than ordering - e.g. finding the item with the maximum value of a property
Deferred execution and streaming are poorly understood (but improving)
Debugging can be very tricky due to deferred execution and streaming
In some specific cases, LINQ can be significantly slower than manual code. The better you understand the internal workings, the better you'll be able to predict this. (And of course, if performance is important to you, you should have appropriate tests around it.)
I find it's best when dealing with in-process queries. They're easy to predict, understand  and extend. Complementary technologies like LINQ to XML and Parallel LINQ are great. LINQ to Objects can be used almost anywhere.
LINQ to SQL etc are really nice where they're appropriate, but they're harder to understand and need more expertise. They're also only applicable in certain areas of your code.


q:
I am having a .cs file, i need to execute that file..
I don't have experience in C#.. Please help.. Do we have to install any software to run it..

Currently i am using windows XP..

Please help me...

[A]
Grab the
.NET SDK
(perhaps not needed, see comments) and see if you can compile your .cs file with
CSC.exe
Alternatively try Visual
Studio Express Edition
But if you don't have ANY experience with software engineering, this might not be the best way to start...


q:
I met an interesting issue about C#. I have code like below.

List<Func<int>> actions = new List<Func<int>>();

int variable = 0;
while (variable < 5)
{
    actions.Add(() => variable * 2);
    ++ variable;
}

foreach (var act in actions)
{
    Console.WriteLine(act.Invoke());
}

I expect it to output 0, 2, 4, 6, 8. However, it actually outputs five 10s.

It seems that it is due to all actions referring to one captured variable. As a result, when they get invoked, they all have same output.

Is there a way to work round this limit to have each action instance have its own captured variable?

[A]
Yes - take a copy of the variable inside the loop:
```
```
while (variable < 5)
{
    int copy = variable;
    actions.Add(() => copy * 2);
    ++ variable;
}
```
```
You can think of it as if the C# compiler creates a "new" local variable every time it hits the variable declaration. In fact it'll create appropriate new closure objects, and it gets complicated (in terms of implementation) if you refer to variables in multiple scopes, but it works :)
Note that a more common occurrence of this problem is using
```
for
```
or
```
foreach
```
:
```
```
for (int i=0; i < 10; i++) // Just one variable
foreach (string x in foo) // And again, despite how it reads out loud
```
```
See section 7.14.4.2 of the C# 3.0 spec for more details of this, and my
article on closures
has more examples too.
Note that as of the C# 5 compiler and beyond (even when specifying an earlier version of C#), the behavior of
```
foreach
```
changed so you no longer need to make local copy. See
this answer
for more details.


q:
whats the best way to export a Datagrid to excel? I have no experience whatsoever in exporting datagrid to excel, so i want to know how you guys export datagrid to excel.
i read that there are a lot of ways, but i am thinking to just make a simple export excel to datagrid function.i am using asp.net C#

cheers..

[A]
The simplest way is to simply write either csv, or html (in particular, a
```
<table><tr><td>...</td></tr>...</table>
```
) to the output, and simply pretend that it is in excel format via the content-type header. Excel will happily load either; csv is simpler...
Here's a similar example (it actually takes an IEnumerable, but it would be similar from any source (such as a
```
DataTable
```
, looping over the rows).
```
```
public static void WriteCsv(string[] headers, IEnumerable<string[]> data, string filename)
        {
            if (data == null) throw new ArgumentNullException("data");
            if (string.IsNullOrEmpty(filename)) filename = "export.csv";

            HttpResponse resp = System.Web.HttpContext.Current.Response;
            resp.Clear();
            // remove this line if you don't want to prompt the user to save the file
            resp.AddHeader("Content-Disposition", "attachment;filename=" + filename);
            // if not saving, try: "application/ms-excel"
            resp.ContentType = "text/csv";
            string csv = GetCsv(headers, data);
            byte[] buffer = resp.ContentEncoding.GetBytes(csv);
            resp.AddHeader("Content-Length", buffer.Length.ToString());
            resp.BinaryWrite(buffer);
            resp.End();
        }
        static void WriteRow(string[] row, StringBuilder destination)
        {
            if (row == null) return;
            int fields = row.Length;
            for (int i = 0; i < fields; i++)
            {
                string field = row[i];
                if (i > 0)
                {
                    destination.Append(',');
                }
                if (string.IsNullOrEmpty(field)) continue; // empty field

                bool quote = false;
                if (field.Contains("\""))
                {
                    // if contains quotes, then needs quoting and escaping
                    quote = true;
                    field = field.Replace("\"", "\"\"");
                }
                else
                {
                    // commas, line-breaks, and leading-trailing space also require quoting
                    if (field.Contains(",") || field.Contains("\n") || field.Contains("\r")
                        || field.StartsWith(" ") || field.EndsWith(" "))
                    {
                        quote = true;
                    }
                }
                if (quote)
                {
                    destination.Append('\"');
                    destination.Append(field);
                    destination.Append('\"');
                }
                else
                {
                    destination.Append(field);
                }

            }
            destination.AppendLine();
        }
        static string GetCsv(string[] headers, IEnumerable<string[]> data)
        {
            StringBuilder sb = new StringBuilder();
            if (data == null) throw new ArgumentNullException("data");
            WriteRow(headers, sb);
            foreach (string[] row in data)
            {
                WriteRow(row, sb);

            }
            return sb.ToString();
        }
```
```


q:
I've been tasked to write our department's C# Programming Standard (including guidelines).  What sort of standards/guidelines should I include?  I've already taken bits from various standards around the net (and pieces from Code Complete), but I'd like hear from developers in the field.

I've already got:
Naming Conventions - General/Variables/Classes/Methods/Interfaces/Controls

General Programming Practices - Documentation (comments etc), [WIP]

OO Programming Practices - Encapsulation, [WIP]

What else would be useful?  What shouldn't I include?

[A]
Have you already suggested that everyone reads the "
Design Guidelines for Class Library Developers
"? That covers the bulk of it. Other than that, I'd want to hammer home:
You should very rarely be creating your own structs. Don't think of them as lightweight classes.
Structs should never be mutable.
Fields should always be private, apart from readonly fields where the type of the field is immutable
Only attempt lock-free programming if you're sure that a simpler solution will be too slow - and have evidence!
Readability is king
Be aware of cultural issues - in particular, read Microsoft's
String Handling Recommendations
I'll add more as I think of them...


q:
I am refering to the question on changing the classpath programmatically.

I read and found out that there is some function under System class as getproperties where we can retrieve the properties and then also can set it using setProperties().

The answers however I got was that It Wont work. I have not tried this myself, however, i am taking the call.

Just to clarify, then why these  setProperty() and getProperty() methods are there if they cannot alter it at run time. Or is this specific to the classpath property only ?

I will appreciate if someone can present a scenario where they are really helpful?

[A]
System.setProperty can be used to set some security or protocol handler at the beginning of a program. Like:
```
```
/*
Add the URL handler to the handler property. This informs
IBMJSSE what URL handler to use to handle the safkeyring
support. In this case IBMJCE.
*/
System.setProperty("java.protocol.handler.pkgs", "com.ibm.crypto.provider");
```
```
or for
using SSL
:
```
```
System.setProperty("javax.net.ssl.keyStore", context.getRealPath(KEYSTORE));
System.setProperty("javax.net.ssl.keyStorePassword", "password");
System.setProperty("javax.net.ssl.trustStore", context.getRealPath(TRUSTSTORE));
System.setProperty("javax.net.debug", "ssl");
HttpClient httpClient = new HttpClient();
GetMethod httpGet = new GetMethod("https://something.com");
httpClient.executeMethod(httpGet);
return new String(httpGet.getResponseBody());
```
```
But beware, because it
changes the environment at runtime for
ALL
applications running in the same jvm
.
If for example one application needs to run with saxon and the other with xalan and both make use of System.setProperty to set the transformerFactory, then you will run into trouble
As said in
Monitored System.setProperty
article,
System.setProperty() can be an evil call.
It is 100% thread-hostile
It contains super-global variables
It is extremely difficult to debug when these variables mysteriously change at runtime
Regarding the classpath property, as
I said in a previous question
, it can not be easily changed as runtime.
In particular, java System property java.class.path is used to build a linked link when the JRE is instantiated, then
is not re-read
. Therefore, changes you make to the property don't really do anything to the existing virtual machine.


q: Does anyone know any good and free .NET Windows Controls Library

[A]
Mono
WinForms
lags behind Microsoft, but includes many of the familiar controls. If you are ready to try something different, Mono has other
Gui ToolKits
.


q: The default GWT StackPanel is not enough good, i want to have functionality similar to outlook stack panel. May be there is already something exists?

[A]
If you don't mind using EXT-GWT, a much prettier fully compliant GWT UI toolkit then this might be more what your looking for.
The Example
.
GXT as it is also called can do lots of good things for a GUI.


q:
I could do this in C#..

int number = 2;
string str = "Hello " + number + " world";

..and str ends up as "Hello 2 world".

In VB.NET i could do this..

Dim number As Integer = 2
Dim str As String = "Hello " + number + " world"

..but I get an InvalidCastException "Conversion from string "Hello " to type 'Double' is not valid."

I am aware that I should use .ToString() in both cases, but whats going on here with the code as it is?

[A]
In VB I believe the string concatenation operator is & rather than + so try this:
```
```
Dim number As Integer = 2
Dim str As String = "Hello " & number & " world"
```
```
Basically when VB sees + I suspect it tries do numeric addition or use the addition operator defined in a type (or no doubt other more complicated things, based on options...) Note that
```
System.String
```
doesn't define an addition operator - it's all hidden in the compiler by calls to
```
String.Concat
```
. (This allows much more efficient concatenation of multiple strings.)


q:
Sometimes when I am debugging code in Eclipse it happens that although I can see and inspect class member variables without any difficulty I am unable to inspect the values of variables declared locally within functions. As an aside, any parameters to the current function lose their 'real' names and instead one sees their values listed in the Variables window as arg0, arg1, arg2, etc but at least the values are visible.

This is occurring at present in relation to classes defined within the core JDK. I have verified that the installed and current JRE is a JDK.

Is anybody able to shed some light on this behaviour?

[A]
Apparently, the
answer
is:
the rt.jar that ships with the JDK (where the core Java classes live) is not compiled with full debug information included in the .class files, so the debugger does not have local variable info.
Unfortunately, this is not something that Eclipse can do anything about - all debuggers will have the same problem with JDK core classes.
The
release notes of Eclipse 3.4
states:
Missing debug attributes
The debugger requires that class files be compiled with debug attributes if it is to be able to display line numbers and local variables. Quite often, class libraries (for example, "rt.jar") are compiled without complete debug attributes, and thus local variables and method arguments for those classes are not visible in the debugger.


q:
In c#, is there any difference in the excecution speed for the order in which you state the condition?

if (null != variable) ...
if (variable != null) ...

Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.

If there is no difference, what is the advantage of the first one?

[A]
I guess this is a C programmer that has switched languages.
In C, you can write the following:
```
```
int i = 0;
if (i = 1)
{
    ...
}
```
```
Notice the use of a single equal sign there, which means the code will assign 1 to the variable i, then return 1 (an assignment is an expression), and use 1 in the if-statement, which will be handled as true. In other words, the above is a bug.
In C# however, this is not possible. There is indeed no difference between the two.


q:
Using DBIx::Class and I have a resultset which needs to be filtered by data which cannot be generated by SQL.  What I need to do is something effectively equivalent to this hypothetical example:

my $resultset     = $schema->resultset('Service')->search(\%search);
my $new_resultset = $resultset->filter( sub {
    my $web_service = shift;
    return $web_service->is_available;
} );

Reading through the docs gives me no clue how to accomplish a strategy like this.

[A]
You can’t really, due to the goals for which DBIC result sets are designed:
They compile down to SQL and run a single query, which they do no earlier than when you ask for results.
They are composable.
Allowing filtering by code that runs on the Perl side would make it extremely hairy to achieve those properties, and would hide the fact that such result sets actually run N queries when composed.
Why do you want this, anyway? Why is simply retrieving the results and filtering them yourself insufficient?
Encapsulation
? (Eg. hiding the filtering logic in your business logic layer but kicking off the query in the display logic layer.) Then write a custom ResultSet subclass that has an accessor that runs the query and does the desired filtering.
Overhead
? (Eg. you will reject most results so you don’t want the overhead of creating objects for them.) Then use HashRefInflator.


q:
Is there a way to pass null arguments to C# methods (something like null arguments in c++)?

For example:

Is it possible to translate the following c++ function to C# method:

private void Example(int* arg1, int* arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}

[A]
From C# 2.0:
```
```
private void Example(int? arg1, int? arg2)
{
    if(arg1 == null)
    {
        //do something
    }
    if(arg2 == null)
    {
        //do something else
    }
}
```
```


q: I need to get all the dates present in the date range using SQL Server 2005

[A]
If you have the dates in a table and simply want to select those between two dates you can use
```
```
select * from yourTable where yourDate between date1 and date2
```
```
If you want to produce the dates from nothing you could do it with a loop or you could populate a temporary table with dates and then select from that.


q:
How do I save a Tlistviews layout in Delphi 2007?

I have been asked to write some code to allow users to re-order columns in a TListview (well all TListviews in our application), I have the code working (by manipulating the columns index and setting width to zero to hide columns not needed) but now I need a way to save the state of the view when to form exits.

What is the best way to do this? I thought about serialization, but I dont need the data or sort order so that seamed a bit overkill to me.

Some things to ponder
     It needs to be on a per user basis
     It needs to be flexible, in-case we add a new column in the middle of the listview
     There is no garantee that the Column headding will be unique
     The listview name may not be unique across the application

Any ideas?

[A]
If you only want to save and load a certain part of the data you can store it n an ini or xml file.
General data can be written to the file. Columns is another problem. You need to find an unique identification for each column. The ini could be something like:
```
```
[Settings]

[Col_1]
position=1
width=500
title=hello world
align=left
sort=ascending

.. etc for more fields and more columns.
```
```
If you uses a listview helper class, you only need to write the code once:
```
```
TListviewHelper = class helper for TListView;
public
  procedure SaveToFile(const AFilename: string);
  procedure LoadFromFile(const AFileName: string);
end;

procedure TListviewHelper.SaveToFile(const AFilename: string);
var
  ini : TIniFile;
begin
  ini := TIniFile.Create(AFileName);
  try
    // Save to ini file
  finally
    ini.Free;
  end;
end;

procedure TListviewHelper.LoadFromFile(const AFileName: string);
var
  ini : TIniFile;
begin
  ini := TIniFile.Create(AFileName);
  try
    // Load from ini file
  finally
    ini.Free;
  end;
end;
```
```
If TListviewHelper is within scope, you have access to the extra methods.


q:
We have a couple of applications running on Java 5 and would like now to bring in an application based on Java 6. Can both java versions live together under Windows?

Is there any control panel to set the appropriate Java version for different applications, or any other way to set up, what version of Java will be used to run that particular application?

[A]
Of course you can use multiple versions of Java under Windows. And different applications can use different Java versions. How is your application started? Usually you will have a batch file where there is something like
```
```
java ...
```
```
This will search the Java executable using the PATH variable. So if Java 5 is first on the PATH, you will have problems running a Java 6 application. You should then modify the batch file to use a certain Java version e.g. by defining a environment variable
```
JAVA6HOME
```
with the value
```
C:\java\java6
```
(if Java 6 is installed in this directory) and change the batch file calling
```
```
%JAVA6HOME%\bin\java ...
```
```


q:
My requirement is I have server J2EE web application and client J2EE web application. Sometimes client can go offline. When client comes online he should be able to synchronize changes to and fro. Also I should be able to control which rows/tables need to be synchronized based on some filters/rules. Is there any existing Java frameworks for doing it? If I need to implement on my own, what are the different strategies that you can suggest?

One solution in my mind is maintaining sql logs and executing same statements at other side during synchronization. Do you see any problems with this strategy?

[A]
The biggist issue with synchronization is when the user edits something offline, and it is edited online at the same time. You need to merge the two changed pieces of data, or deal with the UI to allow the user to say which version is correct.  If you eliminate the possibility of both being edited at the same time, then you don't have to solve this sticky problem.
The method is usually to add a field 'modified' to all tables, and compare the client's modified field for a given record in a given row, against the server's modified date.  If they don't match, then you replace the server's data.
Be careful with autogenerated keys - you need to make sure your data integrity is maintained when you copy from the client to the server.  Strictly running the SQL statements again on the server could put you in a situation where the autogenerated key has changed, and suddenly your foreign keys are pointing to different records than you intended.
Often when importing data from another source, you keep track of the primary key from the foreign source as well as your own personal primary key. This makes determining the changes and differences between the data sets easier for difficult synchronization situations.


q:
I have the following file/line:

pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200
pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200

and so on.
I wish to parse this and take the key value pairs and put them in a structure:

struct pky
{
    pky() :
      a_id(0),
      sz_id(0),
      cr_id(0),
      cp_id(0),
      cv_id(0),
      ct_id(0),
      fr(0),
      g('U'),
      a(0),
      pc(0),
      p_id(0)
    { }
};

wherein either all the structure fields are used or some might be omitted.

How do I create a C++ class, which will do the same? I am new to C++ and not aware of any functions or library which would do this work.

Each line is to be processed, and the structure will be populated with one line each time and used, before it is flushed. The structure is later used as a parameter to a function.

[A]
Unfortunately, your source data file is human-oriented, which means that you're going to have to do a bunch of string parsing in order to get it into the structure.  Otherwise, if the data had been written directly as a binary file, you could just use fread() to pop it directly into the struct.
If you want to use an "elegant" (ie, ugly minimalistic approach), you could make a loop of sorts to parse each line, basically using strchr() to first find the '=' character, then the next space, then using atoi() to convert each number into a real int, and then using some pointer hackery to push them all into the structure.  The obvious disadvantage there is that if the structure changes, or is even reorganized somehow, then the whole algorithm here would silently break.
So, for something that would be more maintainable and readable (but result in more code), you could just push each value into a vector, and then go through the vector and copy each value into the appropriate strucutre field.


q:
I have a problem with Lucene.NET. During an index, I receive the error 'Access to the path segments is denied'. Or sometimes 'Access to the path deletable is denied'. I eventually gave 'Everyone' full security rights to the index directory, but the problem still existed.

I then found out that during the index run, lucene renames the segments file to 'segments.new', and then this error happens. I guess some process still tries to read from the old segments file after it has been renamed? I have no clue as to why this happens, or how to fix this. Strangely enough, my co-developers can run the index on their computer without a problem.

The error happens at happens in Lucene.Net.Index.IndexModifier.AddDocument(Document).

Any ideas would be much appreciated.

[A]
I suspect that your IndexModifier is in contention with a Searcher.
Here's how I use Lucene.Net in my
bug tracking
app,
BugTracker.NET
, which seems to be working ok.
I create the index at app startup.
I create a searcher and keep it around so that the index isn't reloaded with each search. All threads share the same searcher. When the searcher searches, it grabs a lock, searches, then releases the lock, so that another thread can search.  Forces the searches into single file is doable in my app because Lucene.NET is quick and a bug tracking system isn't THAT busy.
Meanwhile, I have an IndexWriter that updates the index when there is a data change. It is just changing a little bit so it does its task quick too.   When it needs to run, it grabs the same lock, destroys the searcher, updates the index, and the re-recreates the searcher.  The new searcher stays around until the next update of the index. The searcher always is working with an up-to-date index.
You can get the BugTracker.NET source and look at the files my_lucene.cs and search_text.aspx. It's all in those two files, and there isn't that much code.


q:
Is there a way of converting special folder paths to a full file name (and back) or do I need to code my own (not hard I know, but no point if it exists)

e.g. I want to store the file name of a template for an application, which the user can then change, it exists in the LocalApplicationData folder.

what I would like to store is the location of the file in the format:

%LOCALAPPDATA%\MyApp\Templates\Report Template.xls

so that this application file can be used by many users, each user when they open it will get the Report Template from their own local app directory.

I can write

replace("%LOCALAPPDATA%", _
    System.Environment.GetFolderPath(
         System.Environment.SpecialFolder.LocalApplicationData))

and vice versa

when I come to save the file location, however is there a System.IO (or similar) call to do this for me, rather than having to go through every possible special folder?

[A]
Look at:
Environment.ExpandEnvironmentVariables
After some looking around I don't think there is a built-in way available to convert it back, though.
You can do this though:
```
```
static void Main(string[] args)
{
    var values = Enum.GetValues(typeof(Environment.SpecialFolder));

    foreach (Environment.SpecialFolder value in values)
        Console.WriteLine(value + " : " + Environment.GetFolderPath(value));

    Console.ReadKey();
}
```
```


q:
I tried this on J2ME

try {
    Image immutableThumb = Image.createImage( temp, 0, temp.length);
} catch (Exception ex) {
    System.out.println(ex);
}

I hit this error:
java.lang.IllegalArgumentException:

How do I solve this?

[A]
Image.createImage() throws an IllegalArgumentException if the first argument is incorrectly formatted or otherwise cannot be decoded. (I'm assuming that temp is a byte[]).
http://java.sun.com/javame/reference/apis/jsr118/javax/microedition/lcdui/Image.html#createImage(byte[],%20int,%20int)
(This URL refuses to become a hyperlink for some reason (?))


q:
I have a binded DataGridView where depending on some BoundItem property value that line will be read only. What is the best way to implement this?
Thanks

[A]
in the rowenter event, set the readonly property of the row accordingly
```
```
private sub MyView_RowEnter(...) handles MyView.RowEnter
    MyView.Rows(e.Rowindex).ReadOnly = (condition)
end sub
```
```


q:
I'm considering migrating my c# application from using custom GDI+ drawn controls to a WPF application with custom controls etc. I would like to know what's involved and what to expect.

Are there any resources people can recommend that might help? Or indeed any personal experiences that might be beneficial?

[A]
This is actually a project i am working on at the moment although I have been lucky enough to be able to start again. If you can do this I would strongly recommend it, obviously keeping the core functionality of the old system/controls but start afresh. It is always nice to start from a base and to know where things went wrong/right previously.
Personally i have found the
msdn website
extremely useful, if not stackoverflow is a very good place for knowledge. I would be happy to give pointers if you need any.
Also if you ever have any questions about databinding this is the place to go:
bea costa
she has covered most stuff there.
On an extra note we have experienced a huge improvement in performance with using wpf over GDI.


q:
My screenshot http://dl.getdropbox.com/u/240752/stars.gif

I want to have it so that only the text is underlined. The only way I can see of doing this is this:

.no-underline {
   text-decoration:none;
}
.underline {
  text-decoration:underline;
}

<a href="#" class="no-underline"><span class="underline">Average customer review rating</span><img src="img/five-stars.gif" alt="five stars" width="78" height="16" title="5 star review rating" /></a>

Is this the best way? or does someone know a leaner way? Thanks.

[A]
No other solution really. Though you can shorten it a little:
```
```
Link Text

a.imgLink { text-decoration: none; }
a.imgLink span { text-decoration: underline; }
```
```
That way you only need to specify one class.


q:
I am currently working in C/C++ in a Unix environment and am new to Linux environments. I would like to learn about the Linux OS and learn C# as the next level of programming language for my career.

I decided to put Ubuntu Linux on my laptop. But I am not sure whether we can write, compile and run C# programs in Linux environments or not.

The only IDE I know for C# is MS Visual Studio. Is there are any possible way to work in C# in a Linux environment?

If I have no other option, I'll have both operating systems on my laptop - Vista to learn C# and Linux for the other OS.

[A]
Learn
Mono
.
The Mono Project is an open
  development initiative sponsored by
  Novell to develop an open source, UNIX
  version of the Microsoft .NET
  development platform. Its objective is
  to enable UNIX developers to build and
  deploy cross-platform .NET
  Applications. The project implements
  various technologies developed by
  Microsoft that have now been submitted
  to the ECMA for standardization.
You can use the
MonoDevelop
IDE.
MonoDevelop is a free GNOME IDE
  primarily designed for C# and other
  .NET languages.


q:
Is there any way to (unit) test my own HtmlHelpers? In case when I'd like to have custom control (rendered by HtmlHelper) and I know requierements for that control how could I write tests first - and then write code? Is there a specific (nice) way to do that?

Is it worth?

[A]
The main problem is that you have to mock the HtmlHelper because you may be using methods of the helper to get routes or values or returning the result of another extension method. The HtmlHelper class has quite a lot of properties and some of them quite complex like the ViewContext or the current Controller.
This post from Ben Hart
that explains how to create such a mock with Moq. Can be easily translated to another mock framework.
This is my Rhino Mocks version adapted to the changes in the MVC Framework. It's not fully tested but it's working for me but don't expect perfect results:
```
```
public static HtmlHelper CreateHtmlHelper(ViewDataDictionary viewData)
    {
        var mocks = new MockRepository();

        var cc = mocks.DynamicMock<ControllerContext>(
            mocks.DynamicMock<HttpContextBase>(),
            new RouteData(),
            mocks.DynamicMock<ControllerBase>());

        var mockViewContext = mocks.DynamicMock<ViewContext>(
            cc,
            mocks.DynamicMock<IView>(),
            viewData,
            new TempDataDictionary());

        var mockViewDataContainer = mocks.DynamicMock<IViewDataContainer>();

        mockViewDataContainer.Expect(v => v.ViewData).Return(viewData);

        return new HtmlHelper(mockViewContext, mockViewDataContainer);
    }
```
```


q:
I basically have a page which shows a "processing" screen which has been flushed to the browser.  Later on I need to redirect this page, currently we use meta refresh and this normally works fine.

With a new payment system, which includes 3D secure, we potentially end up within an iframe being directed back to our site from a third party.

I need to be able to redirect from this page, either using javascript or meta-refresh, and bust out of the iframe if it exists.

Cheers!

(I have done busting out of iframes before but can't find my old code and a google search was useless, thought it was the perfect time to try Stackoverflow out!)

[A]
So I added the following to my redirected pages.  Luckily they have nothing posted at them so can be simply redirected.  Also the use of javascript is ok as it is required to get to that point in the site.
```
```
<script type="text/javascript" language="javascript">
    if (top.frames.length>0)
    setTimeout("top.location = window.location;",100);
</script>
```
```


q:
The code looks like below:

namespace Test
{
    public interface IMyClass
    {
        List<IMyClass> GetList();
    }

    public class MyClass : IMyClass
    {
        public List<IMyClass> GetList()
        {
            return new List<IMyClass>();
        }
    }
}

When I Run Code Analysis i get the following recommendation.

Warning    3   CA1002 : Microsoft.Design : Change 'List' in 'IMyClass.GetList()' to use Collection, ReadOnlyCollection or KeyedCollection

How should I fix this and what is good practice here?

[A]
I would personally declare it to return an interface rather than a concrete collection. If you really want list access, use
```
IList<T>
```
. Otherwise, consider
```
ICollection<T>
```
and
```
IEnumerable<T>
```
.


q:
I'm working on a search module that searches in text columns that contains html code. The queries are constructed like: WHERE htmlcolumn LIKE '% searchterm %';

Default the modules searches with spaces at both end of the searchterms, with wildcards at the beginning and/or the end of the searchterms these spaces are removed (*searchterm -> LIKE '%searchterm %'; Also i've added the possibility to exclude results with certain words (-searchterm -> NOT LIKE '% searchterm %'). So far so good.

The problem is that words that that are preceded by an html-tag are not found (<br/>searchterm is not found when searching on LIKE '% searchterm.., also words that come after a comma or end with a period etc.).
What i would like to do is search for words that are not preceded or followed by the characters A-Z and a-z. Every other characters are ok.

Any ideas how i should achieve this? Thanks!

[A]
You could use a regular expression:
http://dev.mysql.com/doc/refman/5.0/en/regexp.html


q:
I run a website where users can post items (e.g. pictures). The items are stored in a MySQL database.

I want to query for the last ten posted items BUT with the constraint of a maximum of 3 items can come from any single user.

What is the best way of doing it? My preferred solution is a constraint that is put on the SQL query requesting the last ten items. But ideas on how to set up the database design is very welcome.

Thanks in advance!

BR

[A]
This is difficult because MySQL does not support the LIMIT clause on sub-queries. If it did, this would be rather trivial... But alas, here is my naïve approach:
```
```
SELECT
  i.UserId,
  i.ImageId
FROM
  UserSuppliedImages i
WHERE
  /* second valid ImageId */
  ImageId = (
    SELECT MAX(ImageId)
    FROM UserSuppliedImages
    WHERE UserId = i.UserId
  )
  OR
  /* second valid ImageId */
  ImageId = (
    SELECT MAX(ImageId)
    FROM   UserSuppliedImages
    WHERE UserId = i.UserId
      AND ImageId < (
        SELECT MAX(ImageId)
        FROM UserSuppliedImages
        WHERE UserId = i.UserId
      )
    )
  /* you get the picture...
     the more "per user" images you want, the more complex this will get */
LIMIT 10;
```
```
You did not comment on having a preferred result order, so this selects the latest images (assuming
```
ImageId
```
is an ascending auto-incrementing value).
For comparison, on SQL Server the same would look like this:
```
```
SELECT TOP 10
  img.ImageId,
  img.ImagePath,
  img.UserId
FROM
  UserSuppliedImages img
WHERE
  ImageId IN (
    SELECT TOP 3 ImageId
    FROM UserSuppliedImages
    WHERE UserId = img.UserId
  )
```
```


q: Given a html document, what is the most correct and concise regular expression pattern to remove the query strings from each url in the document?

[A]
You can't usefully parse HTML with a regexp. If you know the format of the page in advance — eg.
links are always in the form < a href="url with no unnecessary character escapes">, or
all links are absolute, and no other non-link strings beginning with http: exist
then you can just about get away with it, but for general [X]HTML a regexp parser is unsuitable.
Depending on what language you're using, you'd need to find either an HTML parser library (eg. Python's BeautifulSoup), or an HTML tidier combined with a standard XML parser, then scan the document for < a> elements (and maybe others, eg. < img> if you're interested in those?), then split the attribute value on ‘?’.


q:
I'm trying to parse a html page and extract 2 values from a table row.
The html for the table row is as follows: -

<tr>
<td title="Associated temperature in (ºC)" class="TABLEDATACELL" nowrap="nowrap" align="Left" colspan="1" rowspan="1">Max Temperature (ºC)</td>
<td class="TABLEDATACELLNOTT" nowrap="nowrap" align="Center" colspan="1" rowspan="1">6</td>
<td class="TABLEDATACELLNOTT" nowrap="nowrap" align="Center" colspan="1" rowspan="1"> 13:41:30</td>
</tr>

and the expression I have at the moment is:

<tr>[\s]<td[^<]+?>Max Temperature[\w\s]*</td>[\s]
<td[^<]+?>(?<value>([\d]+))</td>[\s]
<td[^<]+?>(?<time>([\d\:]+))</td>[\s]</tr>

However I don't seem to be able to extract any matches.
Could anyone point me in the right direction, thanks.

[A]
When you write
```
<td[^<]+?>
```
I guess you really mean
```
<td[^>]*>
```
That is "opening brace, td, maybe stuff other than
closing
brace..."


q: What's the difference between <b> and <strong>, <i> and <em> in HTML/XHTML? When should you use each?

[A]
```
<b>
```
and
```
<i>
```
are explicit - they specify bold and italic respectively.
```
<strong>
```
and
```
<em>
```
are semantic - they specify that the enclosed text should be "strong" or "emphasised" in some way, usually bold and italic, but allow for the actual styling to be controlled via CSS.  Hence these are preferred in modern web pages.


q:
I'd like to send mail without bothering with the SMTP-Server which is used for delivery.

So JavaMail API doesn't work for me because I have to specify a SMTP server to connect to.

I'd like the library to find out on its own which SMTP server is responsible for which email address by querying the MX record of the mail address domain.

I'm looking for something like Aspirin. Unfortunately I can't use Aspirin itself because the development stopped 2004 and the library fails to communicate with modern spam hardened servers correctly.

An embeddable version of James would do the task. But I haven't found documentation concerning whether this is possible.

Or does anyone know about other libraries I could use?

[A]
One possible solution: get the MX record on your own and use
JavaMail API
.
You can get the MX record using the
dnsjava
project:
Maven2 dependency:
```
```
<dependency>
    <groupId>dnsjava</groupId>
    <artifactId>dnsjava</artifactId>
    <version>2.0.1</version>
</dependency>
```
```
Method for MX record retrieval:
```
```
public static String getMXRecordsForEmailAddress(String eMailAddress) {
    String returnValue = null;

    try {
        String hostName = getHostNameFromEmailAddress(eMailAddress);
        Record[] records = new Lookup(hostName, Type.MX).run();
        if (records == null) { throw new RuntimeException("No MX records found for domain " + hostName + "."); }

        if (log.isTraceEnabled()) {
            // log found entries for debugging purposes
            for (int i = 0; i < records.length; i++) {
                MXRecord mx = (MXRecord) records[i];
                String targetString = mx.getTarget().toString();
                log.trace("MX-Record for '" + hostName + "':" + targetString);
            }
        }

        // return first entry (not the best solution)
        if (records.length > 0) {
            MXRecord mx = (MXRecord) records[0];
            returnValue = mx.getTarget().toString();
        }
    } catch (TextParseException e) {
        throw new RuntimeException(e);
    }

    if (log.isTraceEnabled()) {
        log.trace("Using: " + returnValue);
    }
    return returnValue;
}

private static String getHostNameFromEmailAddress(String mailAddress) throws TextParseException {
    String parts[] = mailAddress.split("@");
    if (parts.length != 2) throw new TextParseException("Cannot parse E-Mail-Address: '" + mailAddress + "'");
    return parts[1];
}
```
```
Sending mail via JavaMail code:
```
```
public static void sendMail(String toAddress, String fromAddress, String subject, String body) throws AddressException, MessagingException {
    String smtpServer = getMXRecordsForEmailAddress(toAddress);

    // create session
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpServer);
    Session session = Session.getDefaultInstance(props);

    // create message
    Message msg = new MimeMessage(session);
    msg.setFrom(new InternetAddress(fromAddress));
    msg.setRecipient(Message.RecipientType.TO, new InternetAddress(toAddress));
    msg.setSubject(subject);
    msg.setText(body);

    // send message
    Transport.send(msg);
}
```
```


q: Can someone supply me with a regex to match a search term that is not preceded or followed by [a-z] and [A-Z]? (Other characters are OK.) I.e., when searching for key, I don't want keyboard in my search results, but key. is okay.

[A]
If you're using Perl, what you need is
```
\b
```
, aka "word boundary":
```
```
m/\bkey\b/
```
```


q: When writing unit tests, do you place your tests inside the assembly you wish to test or in a separate test assembly? I have written an application with the tests in classes in a separate assembly for ease of deloyment as I can just exclude the assembly. Does anyone write there tests within the assembly you wish to test and if so what is the justification for it?

[A]
I have a single solution with an interface project, a tests project, a domain project and a data project. When i release i just publish the interface, which doesnt reference Tests so it doesnt get compiled in.
Edit: The bottom line is really that you dont want it to be part of your final release. You can achieve this automatically in VS by using a separate project/assembly. However you can have it in the same assembly, but then just not compile that code if you're using nant or msbuild. Bit messy though, keep things tidy, use a separate assembly :)


q:
I have a <select>. Using JavaScript, I need to get a specific <option> from the list of options, and all I know is the value of the option.  The option may or may not be selected.

Here's the catch: there are thousands of options and I need to do this a few hundred times in a loop. Right now I loop through the "options" array and look for the option I want. This is too slow (in the sense that on my very fast machine the browser locked up until I killed it after a few minutes).

Is there any faster way to do this? I'll take browser-specific ways, but of course a DOM-standard way would be nice.

[A]
With jQuery something like this could be faster:
```
```
$("#idselect option[value='yourval']")
```
```
http://docs.jquery.com/Selectors/attributeEquals#attributevalue


q:
Got into a situation where in a schema i have a table, say table ACTION , while i got a synonym called ACTION as well which refers to another table to another schema.

Now, when i run the query

select * from ACTION

it will select the records from the table, but not the synonym.

Anyway for me to select from the synonym AND the table both together?

Thanx

[A]
Well, your underlying ACTION table should be renamed, let's say do LOCAL_ACTION.
Let's pretend your ACTION synonym is on otheruser.LOCAL_ACTION table...
Then you can redefine the ACTION synonym to be:
```
```
SELECT * from LOCAL_ACTION
UNION
SELECT * from otheruser.LOCAL_ACTION
```
```
Then in the end, select * from ACTION will give you a combined list of both tables.


q:
Is there a function in glut which moves the mouse to a specific position?
There is a similar function in SDL (SDL_WarpMouse) but I want to stick to glut.

[A]
I've just found it, you just have to ask the right question and google helps :D
Its
```
glutWarpPointer(middleX, middleY)
```
;


q:
I need to pull some BLOB data from a SQL Server 2005 database and generate a SQL script to insert this same data in another database, in another server.

I am only allowed to do this using SQL scripts, I can't use any other utility or write a program in Java or .NET to do it.

The other big restriction I have is that I don't have access to the original database (where the original BLOB data is) when I run the script, to copy the BLOB data to the target database, so the data should already be encoded within the SQL script file.

Summing up: is there a way to encode the BLOB data into text so that I can dump it into a SQL INSERT command within a script text file and run it?

I am able to run special T-SQL statements and stored procedures if needed to.

[A]
This article "
Copy Text or Image into or out of SQL Server
" could help:
You could integrate the TEXTCOPY command line tool in a stored procedure:
```
```
CREATE PROCEDURE sp_textcopy (
  @srvname     varchar (30),
  @login       varchar (30),
  @password    varchar (30),
  @dbname      varchar (30),
  @tbname      varchar (30),
  @colname     varchar (30),
  @filename    varchar (30),
  @whereclause varchar (40),
  @direction   char(1))

AS

DECLARE @exec_str varchar (255)
SELECT @exec_str =
         'textcopy /S ' + @srvname +
         ' /U ' + @login +
         ' /P ' + @password +
         ' /D ' + @dbname +
         ' /T ' + @tbname +
         ' /C ' + @colname +
         ' /W "' + @whereclause +
         '" /F ' + @filename +
         ' /' + @direction
EXEC master..xp_cmdshell @exec_str
```
```
You'll have to change/extend it a little in order to read the created file into the other database.
As
Vinko
writes in the comment to this answer, hold in mind that this requires enabling xp_cmdshell in the surface area configuration.
Description of TEXTCOPY:
Copies a single text or image value into or out of SQL Server. The value
is a specified text or image 'column' of a single row (specified by the
"where clause") of the specified 'table'.
If the direction is IN (/I) then the data from the specified 'file' is
copied into SQL Server, replacing the existing text or image value. If the
direction is OUT (/O) then the text or image value is copied from
SQL Server into the specified 'file', replacing any existing file.


q: Why is it called a single in VB.net?  I'm sure there is a good reason but it doesn't seem intuitive to a non formally trained programmer like me.

[A]
I think it is a
```
shorthand
```
for
```
"Single-precision"
```
```
Double
```
is "
```
Double-precision"
```
While
```
C-style int
```
and
```
float
```
was probably referring to
```
"integer"
```
and
```
"floating point"
```


q:
I have a form that displays file information in a TabControl, and I'd like the pages to have the file's icon in their tab.  How do I get the icon associated with a file type?

I'd prefer solutions that don't involve looking things up in the registry, but if that's the only way then so be it.

[A]
CodeProject
has some classes you can download.
First get the
```
FileAssociationInfo
```
, and from that get the
```
ProgramAssociationInfo
```
.  The
```
pai
```
object can give you the icon.
```
```
FileAssociationInfo fai = new FileAssociationInfo(".bob");
ProgramAssociationInfo pai = new ProgramAssociationInfo(fai.ProgID);
ProgramIcon icon = pai.DefaultIcon;
```
```


q:
I've accidentally removed Win2K compatibility from an application by using GetProcessID.

I use it like this, to get the main HWND for the launched application.

ShellExecuteEx(&info); // Launch application
HANDLE han = info.hProcess; // Get process

cbinfo.han = han;

//Call EnumWindows to enumerate windows....
//with this as the callback

static BOOL CALLBACK enumproc(HWND hwnd, LPARAM lParam)
{
  DWORD id;
  GetWIndowThreadProcessID(hwnd, &id);
  if (id == GetProcessID(cbinfo.han))
    setResult(hwnd)
 ...
}

Any ideas how the same function could be acheived on Win2K?

[A]
There is an 'sort-of-unsupported' function: ZwQueryInformationProcess(): see
http://msdn.microsoft.com/en-us/library/ms687420.aspx
This will give you the process id (amongst other things), given the handle. This isn't guaranteed to work with future Windows versions, so I'd suggest having a helper function that tests the OS version and then uses GetProcAddress() to call either GetProcessId() for XP and above, and ZwQueryInformationProcess() for Win2K only.


q:
In my Seam application, I have a Seam component that returns a (@Datamodel) list of items I want to transform into a set of <li> HTML elements. I have this working without a problem.

But now, I want to split up the list according to an EL expression. So the EL expression determines if a new <ul> element should be started. I tried the following:

<s:fragment rendered="#{action.isNewList(index)}">
  <ul>
</s:fragment>
<!-- stuff that does the <li>'s goes here -->
<s:fragment rendered="#{action.isNewList(index)}">
  </ul>
</s:fragment>

But that's invalid, because the nesting for <ul> is wrong.

How should I do this?

[A]
I'm not familiar with the Seam Framework, but if I understand the problem correctly something like this might work.
```
```
<!-- before your loop, open your first <ul> if the (@Datamodel) is not empty -->

<s:fragment rendered="#{action.isNewList(index)}">
  </ul>
  <ul>
</s:fragment>
<!-- stuff that does the <li>'s goes here -->

<!-- after your loop, close your last </ul> if the (@Datamodel) is not empty -->
```
```


q:
is there any way of making sure that, one user is logged in only once?

I would like to avoid two different persons logging into the system with the same login/password.

I guess I could do it myself by checking in the django_session table before logging in the user, but I rather prefer using the framework, if there is already such functionality.

Cheers,

Thanks for the responses!

[A]
Logged in twice is ambiguous over HTTP.  There's no "disconnecting" signal that's sent.  You can frustrate people if you're not careful.
If I shut down my browser and drop the cookies -- accidentally -- I might be prevented from logging in again.
How would the server know it was me trying to re-login vs. me trying to login twice?
You can try things like checking the IP address.  And what if the accidental disconnect was my router crashing, releasing my DHCP lease?  Now I'm trying to re-login, but I have a new address and no established cookie.  I'm not trying to create a second session, I'm  just trying to get back on after my current session got disconnected.
the point is that there's no well-established rule for "single session" that can be installed in a framework. You have to make up a rule appropriate to your application and figure out how to enforce it.


q:
I know, it depends on the webapp. But in the normal case, what do you do: one servlet, that serves different pages (like an standalone-application with changing content) or for every page a single servlet.

Take for instance a blog. There is the start-page with the most recent blog-entries, an article-view for displaying one blog-entry and an archive. Do you implement this with three different servlets, or one that is dispatching to the functions. At least a good part of the stuff is shared, like http-headers.

So, what are your experiences, what works best?

[A]
Usually you will create a servlet per use case. Servlets acts like controllers for your application. When you identify an interaction from a user then implement a servlet to control that interaction.
That is, if you are using plain servlet/JSP to build the site. If you are using a framework like struts you will find that they implement the front controller pattern and use a single servlet that recieves all the requests and forwards these requests to action classes that implement the actual logic of the user request. this is much harder to do yourself but its a good practice...its the reason why so many people use these frameworks.
So the short answer is, you will create many servlets per webapp since each webapp will expose several use cases.
[EDIT] Re-reading your question it seems as if you are using the term
site
to mean page or view. Again, it depends on what is happening on that view. For instance, To display the newest blog entry, you can have a servlet that constructs the list of entries from the database for display. If the user clicks on an entry then another servlet can retrieve that single entry for viewing and so on. Mainly, each action is a use case therefore a different servlet.


q: What do I have to do to convert a DIB to a BMP?

[A]
Check the API GdipCreateBitmapFromGdiDib
Example:
http://www.codeproject.com/KB/GDI-plus/DIBtoBitmap.aspx


q:
I have a solution which contains many class libraries and an ASP .NET website which references those assemblies.

When I build the solution from within the IDE, all assemblies referenced by the website end up in the bin directory. Great!

When I use MsBuild from the command line, all the referenced assemblies are not copied to the bin directory. Why?

My command line is simply:

msbuild.exe d:\myproject\mysolution.sln

[A]
Which msbuild are you referencing? Is it the right one?
I generally call like this (from a batch file):
%WINDIR%\Microsoft.NET\Framework\v3.5\msbuild.exe deploy.proj /v:n
In this example, deploy.proj is just a regular msbuild file that does some other stuff before and after calling msbuild on the .sln file.


q:
What is the accepted practice for indenting SQL statements?  For example, consider the following SQL statement:

SELECT column1, column2
FROM table1
WHERE column3 IN
(
SELECT TOP(1) column4
FROM table2
INNER JOIN table3
ON table2.column1 = table3.column1
)

How should this be indented?  Many thanks.

[A]
This is my personal method.  Depending on the length of the join condition I sometimes indent it on the line below.
```
```
SELECT
  column1,
  column2
FROM
  table1
WHERE
  column3 IN (
    SELECT TOP(1)
      column4
    FROM
      table2
      INNER JOIN table3 ON table2.column1 = table3.column1
  )

SELECT
  column1,
  column2
FROM
  table1
WHERE
  column3 IN (
    SELECT TOP(1)
      column4
    FROM
      table2
      INNER JOIN table3
        ON table2.column1 = table3.column1 -- for long ones
  )
```
```


q: I am looking for things like reordering of code that could even break the code in the case of a multiple processor.

[A]
Yes, but what exactly is your question?
However, since this is an interesting topic: tricks that compilers and processors use to optimize code should not break code, even with multiple processors, in the absence of race conditions in that code. This is called the guarantee of sequential consistency: if your program does not have any race conditions, and all data is correctly locked before accessing, the code will behave as if it were executed sequentially.
There is a really good video of Herb Sutter talking about this here:
http://video.google.com/videoplay?docid=-4714369049736584770
Everyone should watch this :)


q:
We are currently setting up the evaluation criteria for a trade study we will be conducting.

One of the criterion we selected is reliability (and/or robustness - are these the same?).

How do you assess that software is reliable without being able to afford much time evaluating it?

Edit: Along the lines of the response given by KenG, to narrow the focus of the question:
You can choose among 50 existing software solutions. You need to assess how reliable they are, without being able to test them (at least initially). What tangible metrics or other can you use to evaluate said reliability?

[A]
Well, the keyword 'reliable' can lead to different answers... When thinking of reliability, I think of two aspects:
always giving the right answer (or the best answer)
always giving the same answer
Either way, I think it boils down to some repeatable tests. If the application in question is not built with a strong suite of unit and acceptance tests, you can still come up with a set of manual or automated tests to perform repeatedly.
The fact that the tests always return the same results will show that aspect #2 is taken care of. For aspect #1 it really is up to the test writers: come up with good tests that would expose bugs or imperfections.
I can't be more specific without knowing what the application is about, sorry. For instance, a messaging system would be reliable if messages were always delivered, never lost, never contain errors, etc etc... a calculator's definition of reliability would be much different.


q:
I wrote a PHP code like this

$site="http://www.google.com";
$content = file_get_content($site);
echo $content;

But when I remove "http://" from $site I get the following warning:

Warning:
  file_get_contents(www.google.com)
  [function.file-get-contents]: failed
  to open stream:

I tried try and catch but it didn't work.

[A]
You can prepend an @:
```
$content = @file_get_contents($site);
```
This will supress any warning -
use sparingly!
. See
Error Control Operators
Edit: When you remove the 'http://' you're no longer looking for a web page, but a file on your disk called "www.google....."


q: Is there a way on the CVS command line to list all files associated with a tag?

[A]
I think it's
```
```
cvs ls -lR -r tag
```
```
but I'm on SVN now, so you'll have to test it.


q:
I'd like to be able to place all my ASP Classic include files outside of the web root. This assures no include files can be called directly via the URL.

What is the best way to accomplish this?

I know I can use a virtual directory to reference an includes folder outside of web root, but doesn't that still allow direct access to that directory via the URL? Perhaps I'm misunderstanding the nature of virtual directories.

[A]
From
this article
:
(I've never need to do this myself)
Understood.  Make a virtual directory
  'inside' your Default Web Site that
  points to the files 'outside' your
  working folder.  In your code
  reference the virtual directory that
  points to the folder / files outside
  your normal structure.  For example
Your default website is a local folder
  called c:\websites\example.com.  Under
  example.com, all your folders and
  files.  However, the files you want on
  a file server called FileServerA in a
  folder called D:\MyWebsiteIncludes.
  The UNC path is
  \FileServerA\D$\MyWebSiteIncludes or
  if you create a share on the folder,
  \FileServerA\MyWebsiteIncludes  On
  the web server, create a virtual
  directory that maps to either share
  path.  You'll need to make sure the
  proper credentials are configured to
  access the files on the remote server.


q:
i want something like this

the user enter a website link

i need check the link if the link
doesn't start with 'http://' I want
to append 'http://' to the link .

how can I do that in PHP ?


q:
Is Lucene.Net suitable as the search engine for frequently changing content?

Or more specificically, can anybody give a subjective opinion on how quickly lucene.net indexes can be updated. Any other approaches to searching frequently changing content would be great.

We’re developing a forum. Forum posts will be frequently added to the forum repository. We think we need these posts to be added to lucene index very quickly (<0.5s) to become available to search. There’ll be about 5E6 posts in the repository initially. Assume search engine running on non-exotic server (I know this is very vague!).

Other suggestions with regard to addressing the issue of searching frequently changing content appreciated. The forum posts need to be searchable on a variable number of named tags (tag name and value must match). A SQL based approach (based on Toxi schema) isn’t giving us the performance we’d like.

[A]
Out forums (
http://episteme.arstechnica.com
) use Lucene as the search backend, so it's doable.  Posts aren't indexed quite as quickly as you'd like, but we could solve that by beefing up the indexing hardware and using a smarter caching strategy.
The general answer to this question is: it depends what your write/update pattern is.  Forums are relatively easy, since most content is new and existing content is updated less frequently.
For a forum, I'd recommend having an "archive" index and a "live" index.  The live index might include posts from the last day, week, year, while the archive index will include a large body of posts that probably won't ever be touched again.  So when someone creates a new post, it will initially be indexed in the live index.  At a later time, some batch job would clear out the live index, and reindex everything into the archive.
Lucene's very good at querying across multiple indexes.  You should abuse that ability. :)


q:
What is the meaning of the concepts 'covariance' and 'contravariance'?

Given 2 classes, Animal and Elephant (which inherits from Animal), my understanding is that you would get a run-time errors if you try and put an Elephant into an array of Animals, and this happens because Elephant is "bigger" (more specific) than Animal.  But could you place an Animal into an array of Elephant, seeing how Elephant is guaranteed to contain the Animal properties?

[A]
Have a look at this overview of covariance and contravariance in C# 4.0 and see if that helps:
http://blogs.msdn.com/charlie/archive/2008/10/27/linq-farm-covariance-and-contravariance-in-visual-studio-2010.aspx


q: Some programs read the company name that you entered when Windows was installed and display it in the program. How is this done? Are they simply reading the name from the registry?

[A]
Check the API SystemParametersInfo and a constant named SPI_GETOEMINFO
```
```
int details = SystemParametersInfo(SPI_GETOEMINFO, OEMInfo.Capacity, OEMInfo, 0);
        if (details != 0)
        {
            MessageBox.Show(OEMInfo.ToString());
        }
```
```
That will return the companyname for the OEM. I dont think you have to enter company name when installing windows, only computer name ( I can be wrong here)
You can see all the constants and examples here:
http://pinvoke.net/default.aspx/Enums.SystemMetric


q:
http://localhost:50034/Admin/Delete/723

Always needs this parameter to perform the action, however, if you go to the URL without the parameter, an exception occurs. How do you handle this and redirect back to the main page without doing anything?

Thanks.

[A]
```
```
public ActionResult Details(int? Id)
{
     if (Id == null)
           return RedirectToAction("Index");
     return View();
}
```
```


q:
This function exists on OS X and allows you to pass custom local to the function. setlocale is not thread-safe, and passing locale as parameter is.

If there is no equivalent, any way of locale-independent printf, or printf just for doubles (%g) will be ok.

[A]
You might try
```
uselocale
```
, which sets the thread locale (rather than the process locale) before calling
```
printf
```
.


q:
Does anyone know if it is possible to embed a file open dialog inside your own form?

We have a tabbed dialog and on one of the tabs we want the user to be able to browse for a file with the same functionality as the the standard open dialog e.g.  'Look in' combobox, places bar, shell file list, file name comboedit with name completion etc etc.

I've looked at recreating the dialog with some 3rd party components, namely Jam Shell Browser Components

I can get most of the functionality this way, but I'm missing a couple of things e.g. the places bar and the filename auto completion\suggestion

[A]
I don't want to say it's impossible but considering the amount of ugly winapi hacks you'd probably involve I suggest "recreating the dialog with some 3rd party components" but with
VirtualShellTools
.
VirtualShellTools can be downloaded from
this SVN archive
.
And
here's the google code project page
.
(At least it has the filename autocompletion combobox though i am not sure if it has the places bar). Hope it helps.


q:
I'm finding a couple for Java in general but no plugins for netbeans that I can see.

Thanks

[A]
I've used the
PMD NetBeans plugin
, and
here
are the installation instructions (may be a little outdated, due to the speed of NetBeans development, but I got them to work).
Here's a list of
tools for static analyisis
.  Maybe you can cross-check for others that offer NetBeans support.
EDIT:
Those instruction are a little bit old, so I put a more up-to-date set
here
(links to my blog).


q:
So I'm writing a page which does some reporting and it's pretty dynamic, the user has the ability to group data and sort columns. I've been able to get my dynamic grouping down and then the sorting except now my generated linq-to-sql sql order by statement is backwards from what I want it to be. I think I need to figure out how to get at the Result returned from the LinqDataSource when the Sorting event is fired in the ListView so that I can then append my grouping order by clauses.

Currently I'm overriding the LinqDataSource selecting event to provide it's result and do the dynamic grouping there, but then the Result is modified by the Sort on the listview and I was thinking there must be some way to get at that result during the Sorting or Sorted event.

Any insight would be appreciated, in the meantime I will be attempting to figure this out myself.


q:
I want to explicitly call a view from my controller.

Right now I have:

def some_action
  .. do something ...
  respond_to do |format|
    format.xml
  end
end

... then it calls my some_action.xml.builder view.  How can I call some other view?  Is there a parameter in respond_to I'm missing?

Thanks,

JP

[A]
See the
Rendering section of the ActionController::Base documentation
for the different ways you can control what to render.
You can tell Rails to render a specific view (template) like this:
```
```
# Renders the template located in [TEMPLATE_ROOT]/weblog/show.r(html|xml) (in Rails, app/views/weblog/show.erb)
  render :template => "weblog/show"

# Renders the template with a local variable
  render :template => "weblog/show", :locals => {:customer => Customer.new}
```
```


q:
Anyone using MozyPro to backup SQL Server databases?

I'm concerned about the way it does the backup. It just copies data files the way they are. Not using the backup database command.

Is it safe?

[A]
MozyPro uses the Volume Shadow Service (VSS) to create backups for SQL Server.  SQL Server 2005 has been engineered so that VSS backups are consistent.  So this is definitely a valid way to back up SQL Server databases.
Here is a white paper
on how the SQL Server 2005 SQL Writer works with VSS.
Microsoft® SQL Server™ 2005 provides
  support for creating snapshots from
  SQL Server data using Volume Shadow
  Copy Service (VSS). This is
  accomplished by providing a VSS
  compliant writer (the SQL writer) so
  that a third-party backup application
  can use the VSS framework to back up
  database files. This paper describes
  the SQL writer component and its role
  in the VSS snapshot creation and
  restore process for SQL Server
  databases. It also captures details on
  how to configure and use the SQL
  writer to work with backup
  applications in the context of the VSS
  framework.
Here is the MozyPro manual
(PDF), which describes how to restore SQL Server backups that were made using VSS.
That being said, if you don't trust this method, there is nothing stopping you from setting up a backup job and just having Mozy backup your *.bak files.


q: How can I get Direct3D to work over a Remote Desktop connection? I am using Windows XP Professional.

[A]
Maybe you already knew this but doesn't look like this is a supported scenario.
See
Remote Desktop Sharing Disables Direct3D Functionality
and
Is it too much to ask to have ONE good image display API in Windows?
You may want to look at WPF if you have a choice.


q: Is it possible to disable AJAX without disabling JavaScript completely?

[A]
No. AJAX is just a particular use of javascript.
If you could block the particular function call back to the server you might be able to do it, but you would probably have to edit your browser.
I assume you want to do this from the client end... Can you list some more specific goals? What is the expected outcome?


q:
How can I achieve a cool looking photo gallery page?  I don't know Flash, but can learn, and thought about a random collage that 'pulls out' a photo that you hover over.

It's for a photographer, so no thumbnails, grids, etc.

[A]
If you're looking for a tool that's pretty flexible and will support itself later on as you can just train the user to work with it check out
JAlbum
.
To work on integrating this yourself you can check out
AJAX ASP Photo Gallery
or something like
this one
.
If you're looking for a flash/flex based solution that they can just "plug-in" as a stand-alone product which incorporates some of the features you've described
StudioCloud
has a nice one that has a monthly fee...


q:
I'm reading Erica Sadun's iPhone Developer's Cookbook, and ran into a question.

She says in the book that the way to find the user's Documents directory is with the code:

[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];

but that seems slightly brittle, and dissimiliar to the normal Mac way of doing it, which would be:

NSSearchPathForDirectoriesInDomains(NSDocumentsDirectory, NSUserDomainMask, YES);

Are there any particular reasons to use one over the other?

[A]
Objc:
```
```
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)
```
```
Swift:
```
```
var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
```
```
You'll want the first element of the returned array.


q:
How can I read the status of the battery on my MacBookPro from my own application?

Googling has so far only revealed APIs for device drivers to handle power events - there's nothing about user-land processes accessing this information.

thanks.

[A]
You'll want to use IOKit for this, specifically the
IOPowerSources functions
.  You can use
```
IOPSCopyPowerSourcesInfo()
```
to get a blob, and
```
IOPSCopyPowerSourcesList()
```
to then extract a CFArray out of that, listing the power sources. Then use
```
IOPSGetPowerSourceDescription()
```
to pull out a dictionary (see
IOPSKeys.h
for the contents of the dictionary).


q: I'm especially interested in memory profiling, reducing the size of a compiled .swf, measuring network latency, etc.  Also, I'm focussed entirely on AS3.

[A]
FlexBuilder Pro definitely seems like a good option.  Downloading the trial now...
This article looks useful too:
http://flexblog.edchipman.ca/?p=7
I'm not actually concerned about measuring network latency, but I am concerned about measuring which parts of my app are slow because of latency, and which parts are slow because of boneheaded AS3.