q: Does anybody know a good and free add-in for Visual Studio 2005 to get refactoring features in VB?

[A]
I could not recommend a free one but
ReSharper
will do the trick. If you're not planning to use it for commercial work it costs peanuts.


q:
What is the technical difference between a process and a thread?

I get the feeling a word like 'process' is overused and there are also hardware and software threads. How about light-weight processes in languages like Erlang? Is there a definitive reason to use one term over the other?

[A]
Both processes and threads are independent sequences of execution. The typical difference is that threads (of the same process) run in a shared memory space, while processes run in separate memory spaces.
I'm not sure what "hardware" vs "software" threads you might be referring to. Threads are an operating environment feature, rather than a CPU feature (though the CPU typically has operations that make threads efficient).
Erlang uses the term "process" because it does not expose a shared-memory multiprogramming model. Calling them "threads" would imply that they have shared memory.

s: huggingface

c: devops

d: intermediate


q:
Let's say I have a class

public class ItemController:Controller
{
    public ActionResult Login(int id)
    {
        return View("Hi", id);
    }
}

On a page that is not located at the Item folder, where ItemController resides, I want to create a link to the Login method. So which Html.ActionLink method I should use and what parameters should I pass?

Specifically, I am looking for the replacement of the method

Html.ActionLink(article.Title,
    new { controller = "Articles", action = "Details",
          id = article.ArticleID })

that has been retired in the recent ASP.NET MVC incarnation.

[A]
```
```
Html.ActionLink(article.Title, "Login/" + article.ArticleID, 'Item")
```
```


q:
I am working on writing a Highly Available agent for JBoss Application Server to run on Solaris Open HA Cluster. As I don't know much of the JBoss AS, can someone please tell me how can I probe the status of the application server?

I want to know the health of the application server, for example whether it is currently running or not.

[A]
Out of the box, JBoss has a JMX console that provides information about the modules loaded into the micro-kernel and the services that are running.  This application is usually available at
http://hostname:8080/jmx-console
, and you could conceivably use its presence or absence as an indicator of whether your JBoss server is running.
In the context of an HA cluster, you probably have a load balancing switch or other layer4-7 aware device in front of the nodes.  If you want to detect the status of each node in the cluster, you'll need to make sure your using the node's local IP address.
Of course, most of the processes that run in the micro-kernel are JMX enabled ... if you want to know the status of an individual process, just ask it!


q:
How would I set an image to come from a theme directory (my theme changes so I don't want to directly reference) I am sure this is possible but every example I find doesn't seem to work. They are usually along the lines of:

asp:image ID="Image1" runat="server" ImageUrl="~/Web/Mode1.jpg" /

where Web would be a sub directory in my themes folder. Suggesting the theme directory would be added at runtime.

[A]
Not sure if I understood your question right, but if you have an image in a skin file, such as the following, it will come by default from the theme folder:
```
```
<asp:Image runat="server" ImageUrl="filename.ext" />
```
```
If you want it to come from a subfolder Web of the theme folder, use a relative path:
```
```
<asp:Image runat="server" ImageUrl="Web/filename.ext" />
```
```
Your example specifies a subfolder of the application root directory:
```
```
<asp:image ID="Image1" runat="server" ImageUrl="~/Web/Mode1.jpg"/>
```
```
See
the MSDN page on themes and skins
.


q:
Does anybody have a keybinding scheme similar to VS 2005 available for Eclipse?

How to import it into preferences of Eclipse (I see only export button).

[A]
I don't have a VS2005 keybinding scheme as I personally prefer a Brief-style scheme.
However, to import "it", as far as I know (at least on Eclipse 3.4 Ganymede) use File -> Import -> General -> Preferences where "it" is a .prf file which has been saved out using File -> Export -> General -> Preferences.


q:
Here is the input (html, not xml):

... html content ...
<tag1> content for tag 1 </tag1>
<tag2> content for tag 2 </tag2>
<tag3> content for tag 3 </tag3>
... html content ...

I would like to get 3 matches, each with two groups. First group would contain the name of the tag and the second group would contain the inner text of the tag. There are just those three tags, so it doesn't need to be universal.

In other words:

match.Groups["name"] would be "tag1"
match.Groups["value"] would be "content for tag 2"

Any ideas?

[A]
Is the data proper xml, or does it just look like it?
If it is html, then the
HTML Agility Pack
is worth investigation - this provides a DOM (similar to XmlDocument) that you can use to query the data:
```
```
string input = @"...some html content  etc  ...
<user> hello mitch </user>
...some html content  etc  ...
<message> some html message bla </message>
...some html content  etc  ...";

            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(input);
            foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//user | //message"))
            {
                Console.WriteLine("{0}: {1}", node.Name, node.InnerText);
                // or node.InnerHtml to keep the formatting within the content
            }
```
```
This outputs:
```
```
user:  hello mitch
message:  some html message bla
```
```
If you want the formatting tags, then use .InnerHtml instead of .InnerText.
If it is xml, then to code with the full spectrum of xml, it would be better to use an xml parser. For small-to-mid size xml, loading it into a DOM such as XmlDocument would be fine - then query the nodes (for example, "//*"). For huge xml, XmlReader might be an option.
If the data doesn't have to worry about the full xml, then some simple regex shouldn't be too tricky... a simplified example (no attributes, no namespaces, no nested xml) might be:
```
```
string input = @"blah <tag1> content for tag 1 </tag1> blop
<tag2> content for tag 2 </tag2> bloop
<tag3> content for tag 3 </tag3> blip";

        const string pattern = @"<(\w+)>\s*([^<>]*)\s*</(\1)>";
        Console.WriteLine(Regex.IsMatch(input, pattern));
        foreach(Match match in Regex.Matches(input, pattern)) {
            Console.WriteLine("{0}: {1}", match.Groups[1], match.Groups[2]);
        }
```
```


q:
I collect statistics on IP addresses from where users visit my site and I have noticed what there are only two IP addresses presented, 172.16.16.1 and 172.16.16.248. The property I use to determine IP address is

Request.UserHostAddress

What could be a reason of IP address information losing? All the users are from around the world, so they cann't be behind only two proxies.

[A]
I assume you are behind a NAT/Reverse Proxy so I think you have to use:
```
```
Request.ServerVariables("REMOTE_ADDR")
```
```
Most likely 172.16.0.0/12 is your privat LAN where 172.16.16.248 is your own address and 172.16.16.1 the address of your router/proxy.


q:
I provide a web service to my organisation. i was wondering would anyone recommeding the use of apache cactus for setting up a testing framework or has anyone worked with any other web service frameworks that may be useful?

Thanks
Damien

[A]
As you are dealing with a web service you would not need to use Jakarta Cactus and could get away with writing plain old JUnit tests.
The tests would take two forms:
1. Does the underlying functionality work as expected?
This has nothing to do with the web service itself but the underlying functionality it provides. e.g. Does your Data access objects retrieve/process data correctly? Hopefully your web service interface and the underlying functionality are not tightly coupled.
2. Does the live web service (be it SOAP/REST/XMLRPC) function correctly?
In this case a good way to test this is to build a web service client and write tests to see whether this client works correctly against the web service. e.g. Use Axis/CXF/XFire to build the web service client and then write JUnit tests for the data it returns.
Also remember to target your testing towards what the end users of this web service will be using. If you have written a Java web service but it is being consumed by .Net clients then make sure you test the service against a .Net client. SOAP services are especially troublesome when it comes to consistent cross-platform behavior.


q:
I'd like to do the equivalent of the following in LINQ, but I can't figure out how:

IEnumerable<Item> items = GetItems();
items.ForEach(i => i.DoStuff());

What is the real syntax?

[A]
There is no ForEach extension for
```
IEnumerable
```
; only for
```
List<T>
```
. So you could do
```
```
items.ToList().ForEach(i => i.DoStuff());
```
```
Alternatively, write your own ForEach extension method:
```
```
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
    foreach(T item in enumeration)
    {
        action(item);
    }
}
```
```


q:
I'm trying to set up AutoHotkey macros for some common tasks, and I want the hotkeys to mimic Visual Studio's "two-step shortcut" behaviour - i.e. pressing Ctrl-K will enable "macro mode"; within macro mode, pressing certain keys will run a macro and then disable 'macro mode', and any other key will just disable macro mode.

Example - when typing a filename, I want to be able to insert today's date by tapping Ctrl-K, then pressing D.

Does anyone have a good example of a stateful AutoHotkey script that behaves like this?

[A]
This Autohotkey script, when you press
ctrl
+
k
, will wait for you to press a key and if you press
d
, it will input the current date.
```
```
^k::
Input Key, L1
FormatTime, Time, , yyyy-MM-dd
if Key = d
    Send %Time%
return
```
```


q:
I am programming a website in which users will have a number of settings, such as their choice of colour scheme, etc. I'm happy to store these as plain text files, and security is not an issue.

The way I currently see it is: there is a dictionary, where all the keys are users and the values are dictionaries with the users' settings in them.

For example, userdb["bob"]["colour_scheme"] would have the value "blue".

What is the best way to store it on file? Pickling the dictionary?

Are there better ways of doing what I am trying to do?

[A]
Using
cPickle
on the dictionary would be my choice. Dictionaries are a natural fit for these kind of data, so given your requirements I see no reason not to use them. That, unless you are thinking about reading them from non-python applications, in which case you'd have to use a language neutral text format. And even here you could get away with the pickle plus an export tool.


q:
What is the best way to count the time between two datetime values fetched from MySQL when I need to count only the time between hours 08:00:00-16:00:00.

For example if I have values 2008-10-13 18:00:00 and 2008-10-14 10:00:00 the time difference should be 02:00:00.

Can I do it with SQL or what is the best way to do it? I'm building a website and using PHP.

Thank you for your answers.

EDIT: The exact thing is that I'm trying to count the time a "ticket" has been in a specific state during working hours. The time could be like a couple weeks.

EDIT2: I have no problems counting the actual time difference, but substracting that off-time, 00:00:00-08:00:00 and 16:00:00-00:00:00 per day.

-Samuli


q:
If you had to make a case to a business about adopting or moving to an agile development methodology (like SCRUM or XP etc) what case would you make (how do you sell the concept)?

e.g.

How would you describe the concepts and benefits to a non-technical person?

If you have successfully done so, what was the winning argument/case/rationale?

Edit: The reason I ask is that a friend of mine (he is the solution architect at a firm) is currently trying to decide how to approach his management about exactly this topic, and I've given him what I can in terms of suggestions.  Curious especially to hear from those who have successfully made a case to move to an agile-aligned methdology.

[A]
Non-technical people are interested in projects done on time and within budget with good quality and which would satisfy their requirements at the time of the delivery. You should focus on how Agile helps to deliver those qualities.
It's sometimes quite difficult to sell Agile to a non-technical person for two reasons:
The concept of not trying to plan 100% ahead is not really intuitive
Quite a lot of people claim that they use Agile, fail miserably to deliver anything and give the great SDP a bad name
Talk about Agile process ability to handle changes.
It's usually easier if you work with the customer who already work with you. You could easily show them for example all of the change requests accumulated over the time and show how they affected the schedule and the costs of the project. You could then go into explaining how Agile process will help handling such cases.
Along the same line you could take the initial estimations done on a 'waterfall project' and compare them with real-life results.
I would also talk about the Agile approach to quality. Testing during iterations increase the quality considerably. Short iterations with immediate feedback are great help too, mention them.


q:
Is there a way to make sure a (large, 300K) background picture is always displayed first BEFORE any other content is shown on the page?

On the server we have access to PHP.

[A]
All the html content is served and parsed before it even starts to fetch the image, so you have a problem before you start.
You could circumvent this by programmatically hiding the content, and then triggering a "show" of it when the image is loaded.
ie:
```
```
<html>
  <body>
    <image here/>
    <div id="content" style="display:none;" >

    </div>
    <script type="psudocode">
     when(image.loaded){
          $("#content").show();
     }
    </script>
  </body>
</html>
```
```


[A]
I don't think there is an easy way out..
the best I can do in 5 minutes is flip the columns, select and Create an XY Scatter plot.
It still won't give you different dot colors for each employee or individual lines


q:
I always wondered what different methods Google Desktop Search is using so that it uses least CPU and memory while indexing a computer containing more 100,000 files on an average.

In just few hours it has indexed the whole system and I did not see it eating up my CPU, memory etc.

If any of you have done some research, please do share.

[A]
It doesn't...
I installed it on one computer, and quickly removed it because it was intrusive (although this can be probably configured) and hungry (particularly on a low end PC).
It is installed on a laptop near me right now, and if I compare it to a couple of small utilities I run permanently (SlickRun, CLCL, my AutoHotkey script...) it uses more than 10 times their CPU and 5 to 20 times their memory. Times two, since, for some reason, I have one instance running another, plus the ToolbarNotifier (less hungry).
Even Trend Micro anti-virus uses less memory and CPU.
Perhaps I will try it again when I will get a more modern PC with lot of memory, but right now I am happy enough with some grep utilities, even if they are slower.


q:
I want to sprintf() an unsigned long long value in visual C++ 6.0 (plain C).

char buf[1000]; //bad coding
unsigned __int64 l = 12345678;
char t1[6] = "test1";
char t2[6] = "test2";
sprintf(buf, "%lli, %s, %s", l, t1, t2);

gives the result

12345678, (null), test1

(watch that test2 is not printed)

and l = 123456789012345 it gives an exception handle

any suggestions?

[A]
Apparently, you did not assign
```
additionaltext
```
to the necessary
```
char *
```
(string). Note that the
```
long int
```
was processed, the comma was copied and only the
```
%s
```
generated
```
(null)
```
.


q:
Is there a way to have XAML properties scale along with the size of the uielements they belong to?

In essence, I have a control template that I have created too large for it's use/ mainly because I want to use the same control with different sizes. The problem is that I can set the control size to Auto (in the ControlTemplate), however the properties of the intrisic template elements aren't resized: eg StrokeThickness remains at 10 while it should become 1.

It works fine when I apply a ScaleTransform on the template, but that results in a control that's too small when it's actually used: the width/height=Auto resizes the control to the proper size and then the scaletransform is applied. So I'm stuff with a sort of nonscalable control.

I'm a bit new to WPF, so there might be a straightforward way to do this...

[A]
You could try to bind the width and height of the control inside the template to the width and height respectively of the templated control at runtime. Something like:
```
```
<Button>
    <Button.Template>
        <ControlTemplate TargetType={x:Type Button}>
            <Border Width="{TemplateBinding Property=ActualWidth}"
                    Height="{TemplateBinding Property=ActualHeight}">
                <ContentPresenter />
             </Border>
         </ControlTemplate>
    </Button.Template>
</Button>
```
```
Note that the binding sources are the
FrameworkElement.ActualWidth
and
FrameworkElement.ActualHeight
properties of the templated control. These properties contain the width and height of a control after it has been rendered, which can be different from what has been specified in the
Width
and
Height
properties. This is because the values are ultimately calculated at runtime taking into account the size of any parent controls in the visual tree.


q:
I want to get the full path of the running process (executable) without having root permission using C++ code. Can someone suggest a way to achieve this.

on Linux platforms i can do it by using following way.

char exepath[1024] = {0};
char procid[1024] = {0};
char exelink[1024] = {0};

sprintf(procid, "%u", getpid());

strcpy(exelink, "/proc/");
strcat(exelink, procid);
strcat(exelink, "/exe");

readlink(exelink, exepath, sizeof(exepath));

Here exepath gives us the full path of the  executable.

Similarly for windows we do it using

GetModuleFileName(NULL, exepath, sizeof(exepath));  /* get fullpath of the service */

Please help me how to do it on HP-UX since there is no /proc directory in HP-UX.

[A]
I have done this before in a general case.  The general idea is to grab argv[0], and do some processing on it:
```
```
int main( int argc, char** argv )
{
  string full_prog_path = argv[0];
  if ( full_prog_path[0] == "/" )
  {   // It was specified absolutely; no processing necessary.
  }
  else
  {
    string check_cwd = getcwd();
    check_cwd += argv[0];
    if ( FileExists( check_cwd ) )
    { // It was specified relatively.
      full_prog_path = check_cwd;
    }
    else
    { // Check through the path to find it
      string path = getenv( "PATH" );
      list<string> paths = path.split( ":" );
      foreach( test_path, paths )
      {
        if ( FileExists( test_path + argv[0] ) )
        { // We found the first path entry with the program
          full_prog_path = test_path + argv[0];
          break;
        }
      }
    }
  }

  cout << "Program path: " << full_prog_path << endl;

  return 0;
}
```
```
Obviously, this has some assumptions that might break at some point, but it should work for most cases.


q:
Using the PHP pack() function, I have converted a string into a binary hex representation:

$string = md5(time); // 32 character length
$packed = pack('H*', $string);

The H* formatting means "Hex string, high nibble first".

To unpack this in PHP, I would simply use the unpack() function with the H* format flag.

How would I unpack this data in Python?


q:
I have the following line of text

Reference=*\G{7B35DDAC-FFE2-4435-8A15-CF5C70F23459}#1.0#0#..\..\..\bin\App Components\AcmeFormEngine.dll#ACME Form Engine

and wish to grab the following as two separate capture groups:

AcmeFormEngine.dll
ACME Form Engine

Can anyone help?

[A]
```
```
using System.Text.RegularExpressions;

    Regex regex = new Regex(
    @"\\(?<filename>[\w\.]+)\#(?<comment>[\w ]+)$",
    RegexOptions.IgnoreCase
    | RegexOptions.Compiled
    );
```
```


q: I need a WiX 3 script to display to display only 2 dialogs: Welcome & Completed. Thats it no need for EULA, folder selection etc. All help appreciated.

[A]
All you need to do is add this in your WIX script, it will give you the WelcomeDlg before the installation and show the Installation progress, then the Exit Dialog.  Don't forget to add the WixUIExtension.dll to your references.
```
```
<UI Id="UserInterface">
  <Property Id="WIXUI_INSTALLDIR" Value="TARGETDIR" />
  <Property Id="WixUI_Mode" Value="Custom" />

  <TextStyle Id="WixUI_Font_Normal" FaceName="Tahoma" Size="8" />
  <TextStyle Id="WixUI_Font_Bigger" FaceName="Tahoma" Size="9" Bold="yes" />
  <TextStyle Id="WixUI_Font_Title"  FaceName="Tahoma" Size="9" Bold="yes" />

  <Property Id="DefaultUIFont" Value="WixUI_Font_Normal" />

  <DialogRef Id="ProgressDlg" />
  <DialogRef Id="ErrorDlg" />
  <DialogRef Id="FilesInUse" />
  <DialogRef Id="FatalError" />
  <DialogRef Id="UserExit" />

  <Publish Dialog="ExitDialog" Control="Finish" Event="EndDialog" Value="Return" Order="999">1</Publish>
  <Publish Dialog="WelcomeDlg" Control="Next" Event="EndDialog" Value="Return" Order="2"></Publish>

</UI>
<UIRef Id="WixUI_Common" />
```
```


q:
How do I split strings in J2ME in an effective way?

There is a StringTokenizer or String.split(String regex) in the standard edition (J2SE), but they are absent in the micro edition (J2ME, MIDP).

[A]
There is no built in method to split strings. You have to write it on your own using
```
String.indexOf()
```
and
```
String.substring()
```
.  Not hard.


q:
Large datasets, millions of records, need special programming to maintain speed in DBGrids.

I want to know if there are any ready-made components for Delphi (DBGrids) that do this automatically?

EDIT For Example: Some databases have features such as fetch 1st X records (eg 100 records). When I reach the bottom with scrolling, I want to auto fetch the next 100. Conversely when I reach the beginning, I want to fetch the previous 100. I know I can program this, but it sure is possible to propagate that feature to a DBGrid control where the DBGrid does the buffering. It will save quite a bit of programming - you simply have to set the "buffer size" so to speak.

[A]
NextGrid is light, fast and nice looking grid for Delphi
http://www.bergsoft.net/component/next-grid/features.htm
HANDLING LARGE AMOUNT OF CELLS WITHOUT LOOSING SPEED
NextGrid can handle very large amount
  of cells without losing speed. Speed
  of adding, modifying and deleting data
  doesn't depend of the amount of cells.
  In NextGrid demo you can see how fast
  NextGrid work with 100,000 rows and 10
  columns = 1,000,000 cells


q:
I'm creating a bunch of migrations, some of which are standard "create table" or "modify table" migrations, and some of which modify data.  I'm using my actual ActiveRecord models to modify the data, a la:

Blog.all.each do |blog|
  update_some_blog_attributes_to_match_new_schema
end

The problem is that if I load the Blog class, then modify the table, then use the Blog class again, the models have the old table definitions, and cannot save to the new table.  Is there a way to reload the classes and their attribute definitions so I can reuse them?

[A]
The answer is yes!
```
```
Blog.reset_column_information
```
```


q:
When using resources such as brushes, templates and styles in WPF, they can be specified either as StaticResources

<Rectangle Fill="{StaticResource MyBrush}" />

or as a DynamicResource

<ItemsControl ItemTemplate="{DynamicResource MyItemTemplate}"  />

Most of the times (always?), only one works and the other will throw exception during runtime. But I'd like to know why:

What is the main difference. Like memory or performance implications

Are there rules in WPF like "brushes are always static" and "templates are always dynamic" etc.?

I assume the choice between Static vs Dynamic isn't as arbitrary as it seems... but I fail to see the pattern.

[A]
A
StaticResource
will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.
A
DynamicResource
assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.


q:
I'm working on a system were a user can edit existing objects ("Filter" domain objects to be exact) through a GUI. As a UI hint, we only want to enable the save button if the user really modified something to the object. I was wondering if anyone had any experience with this problem and what the best way would be to approach this.

I was thinking about adding an isDirty() flag to the domain object. When a user starts editing a Filter, I would then make a copy, pass it to the GUI and let the user make modifications to the copy. A binding on the isDirty() flag would then enabled/disable the save button. On saving, the differences would then be merged into the original object and persisted.

Additionaly, I was thinking what would happen if a user undos the changes he made to an object. The isDirty() flag should then return false. So I guess the only way to achieve this is to keep the original value of each property inside the domain object.

Any ideas?

[A]
Correct!
Additionally,you can expose two methods:
BeginEdit - In this method, your mark your IsDirty Flag to True. Meaning you are doing modification. Call this method when you are about to make modifications
CancelEdit - In this method, reset the IsDirty Flag to False. Meaning you have arborted the edit process and reverted back to the original state. Call this method when cancelling any modifications made.
And once any modifications are persisted, you also reset the IsDirty Flag to False.
I hope this helps.


q:
We are trying to create some tests that reference an vendors custom grid.  Unfortunatly QTP only recognises it as a WinObject which is quite useless. We need to be able to navigate the grid and change cell values, double click on a cell(without using X,Y co-ordinates) etc.

Ideally we want to get QTP to understand that this object is a grid and treat it as one.

Any help would be greatly appreciated.

Thanks

Jon

[A]
What vendor?
I have a few suggestions:
Use key strokes to navigate the grid, rather than mouse clicks.  Ctrl-Home to set focus to the top-left cell, then use up, down, left, right to move around.  Use Enter keystroke to simulate double clicking.  Often you can use Ctrl-A, Ctrl-C to copy the contents of the grid to the system clipboard, and use the clipboard API to retrieve the data.
You may be able to programmatically get/set the grid properties using the .Object property.  .Object provides access to the underlying native properties and methods of the object, as opposed to the QTP methods and properties.  You could do something like the following pseudo-code to set focus to a cell and change the value.  Your code would differ depending on the vendor implementation.  Consult the vendor's documentation to find out what methods and properties you would be able to use.
```
WinObject("mygrid").Object.CurRow = 1
```
```
WinObject("mygrid").Object.CurCol = 1
```
```
WinObject("mygrid").Object.Value = "my new value"
```


q:
In CakePHP putting a querystring in the url doesn't cause it to be automatically parsed and split like it normally is when the controller is directly invoked.

For example:

$this->testAction('/testing/post?company=utCompany', array('return' => 'vars')) ;

will result in:

[url] => /testing/post?company=utCompany

While invoking the url directly via the web browser results in:

[url] => Array
    (
        [url] => testing/post
        [company] => utCompany
    )

Without editing the CakePHP source, is there some way to have the querystring split when running unit tests?

[A]
I have what is either a hack (i.e. may not work for future CakePHP releases) or an undocumented feature.
If the second testAction parameter includes an named array called 'url' then the values will be placed in the $this->params object in the controller. This gives us the same net result as when the controller is directly invoked.
```
```
$data = array ('company' => 'utCompany') ;

$result = $this->testAction('/testing/post', array
(
    'return' => 'vars',
    'method' => 'get',
    'url' => $data)
) ;
```
```
I'm satisfied with this method for what I need to do. I'll open the question to the community shortly so that it in the future a better answer can be provided.


q:
When indenting java code with annotations, vim insists on indenting like this:

@Test
    public void ...

I want the annotation to be in the same column as the method definition but I can't seem to find a way to tell vim to do that, except maybe using an indent expression but I'm not sure if I can use that together with regular cindent.

edit: The filetype plugin was already turned on I just got a bit confused about indenting plugins. The accepted answer may be a bit hackish but works for me as well.

[A]
Edit: I cannot delete my own answer because it has already been accepted, but
@pydave's answer
seems to be the better (more robust) solution.
You should probably be using the indentation file for the java FileType (instead of using cindent) by setting
```
filetype plugin indent on
```
.
That said, the indentation file coming with the Vim 7.1 from my linux distribution (looking at the current vim svn this is still true for 7.2) doesn't account for annotations yet. I therefore copied
```
/usr/share/vim/vim71/indent/java.vim
```
(see
https://vim.svn.sourceforge.net/svnroot/vim/branches/vim7.1/runtime/indent/java.vim
) to
```
~/.vim/indent/java.vim
```
and added the following lines right before the end:
```
```
let lnum = prevnonblank(v:lnum - 1)
let line = getline(lnum)
if line =~ '^\s*@.*$'
    let theIndent = indent(lnum)
endif
```
```
I'm not sure if this breaks any of the other indentations, but it works for me.


q: I am using tinyMCE as my text editor on my site and i want to reformat the text before saving it to my database (changing the &rsquo; tags into ' then in to &#39;). I cannot find a simple way of doing this using tinyMCe and using htmlentities() changes everything including <>. Any ideas?

[A]
You can user
```
strip_tags($str, $allowed_tags)
```
like below:
```
```
$txt = strip_tags($txt, '

');
```
```


q:
I am using Installshield 2008 Developer Edition and need to run SQL scripts against an existing SQL Server 2005 Express. When I do this without InstallShield, I would have to have some ODBC drivers installed for example.

How does InstallShield do this? Does it include some sort of driver? Or does it depend on preexisting drivers?

[A]
If you are having the database installed by Installshield as part of your installation, Installshield has all the information to simply use a connection string like this:
"Driver={SQL Native Client};Server=localhost;Database=newdatabase;Uid=proguser;Pwd=progpass;"
There is no need to create an ODBC connection to use a connection string like this, and Installshield makes the SQL Native Client a prerequisite  for SQL 2005 connected databases, so it is assured of having the correct driver available.


q:
its out of question that a dao will not hold any state.

however, for easiest access to the class, is it better to use prototype( = new every time) or singleton?

simple object creation is cheap for dao's.. it typically only holds a sessionfactory,
accessing the object from a list of singletons may be equally expensive.

clarfication: the focus of this question is, if there is a common convention to the scoping of daos.

[A]
If your question is about
architecture
, I'd go with scoping DAOs to the
Unit of Work
or Transaction you are doing. This
reduces
the potential for
cross-transaction pollution
and
threading-issues
.
If your question is about
performance
, then the answer lies within a
profiler
, which gives you
accurate
numbers for your particular
workload
.


q:
Context:
  So, I am attempting to build a ridiculously complex domain model.  Talking with the users, there are multiple ways the system will be used (For example: one way is from the perspective of the employee; another way is from the perspective of the employer).  In actuality, they are multiple applications reusing the core domain.

Question:
  Is it wrong to create the domain from multiple perspectives?  For instance, to build the domain as the business is run would mean creating all kinds of relationship classes that carry extra information about the entity and so on...  However, when running from a particular perspective, the picture is much clearer because most of the relationship classes can be rolled into their parent entity.

Ideas? Rebuttals? Am I completely off-base?

[A]
I don't think you should try and predefine the 'core domain' up front. Let it emerge over the development process. Additionally, anything that is not common to the 2 (or more) perspectives should not be in the 'core'.
For instance, build a portion of the system from the employeer perspective. This might prompt you to create entities like 'Project', 'Task', and 'Customer'. Then build a portion from the employeer perspective. This might prompt you to build new entities, and to reuse 'Project' and 'Task'. That's when I'd move 'Project' and 'Task' to the 'core library' shared by the rest of the system.
Sometimes you'll find common entities, but related in different ways. In that case the relationship should be injected by the context instead of being built-in with the entities themselves.


q: A beginner question, bear with me: I'm just wondering under what circumstances one should use a build tool like nant or msbuild? I'm working on a medium sized application (.net 3.0), every developer is doing his work and builds on his machine checking his code changes into the repository as he goes. Once we're all done, I'll get all the code from the repository, make a clean build on my machine and we deploy the binaries. Just out of curiosity, where comes the build tool in?

[A]
The short answer is always.
Each developer should be building using the build script before checking code in. The people building the release should be using the build script to build the release. Your buildbots should be using the build script to build and test the code that's been checked in.
Doing this allows all the developers, testers and buildbots to have a consistent, repeatable build. After all,
The F5 Key Is Not a Build Process
.


q:
I have deployed ASP.NET web site and ASP.NET web service on the same web server. Both of them require access to shared file.

How to implement/share lock that supports single writers and multiple readers? If somebody reads, nobody can write, but all still can read. If somebody writes, nobody can read/write.

[A]
to open file for writing with allowing other threads to read it use System.IO.File.Open method with System.IO.FileShare.Read. Ie.:
```
```
System.IO.File.Open("path.txt",System.IO.FileMode.OpenOrCreate,System.IO.FileAccess.ReadWrite,System.IO.FileShare.Read)
```
```
Other (reading) threads should use System.IO.FileAccess.Read
Signature of Open method:
```
```
public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share);
```
```
UPDATE
If you need all instances to ocasionally write to file. Use Mutex class to reserve file writing. Ie.:
```
```
Mutex mut = new Mutex("filename as mutex name");
    mut.WaitOne();
    //open file for write,
    //write to file
    //close file
    mut.ReleaseMutex();
```
```
Hope it helps.


q:
I have an application which uses a UDL file where the connection string specifies "Provider=SQLNCLI.1" which doesn't work on a specific machine because sqlncli.dll is not installed.

Another .Net app however, where the connection string is in app.config and does not specifically show the provider does worrk. The "Change Data Source" dialog in Visual Studio shows data provider as ".NET Framework Data Provider for SQL Server". This app works, even though sqlncli.dll is not installed.

Why?  What provider is it using? Does it somehow fall back to sqloledb.dll?

[A]
The SQL Server Native client is an independent data access API that was introduced in SQL Server 2005.
From MSDN
It also provides new functionality
  above and beyond that supplied by the
  Windows Data Access Components
  (Windows DAC, formerly Microsoft Data
  Access Components, or MDAC). SQL
  Server Native Client can be used to
  create new applications or enhance
  existing applications that need to
  take advantage of features introduced
  in SQL Server 2005, such as multiple
  active result sets (MARS),
  user-defined data types (UDT), query
  notifications, snapshot isolation, and
  XML data type support.
Read more about it and how it compares to MDAC/WDAC which is used by the ADO.Net SQL Server providers
here
.


q:
I ran accross a CSR file (Certificate Signing Request) and I need to extract some information from it.

There's a way to decode it using .NET Framework?

[A]
It's not .NET, but for interactive use, try the OpenSSL utilities. Specifically:
```
```
openssl req -text -in request.csr
```
```


q:
What's the easiest way to remove last row from the text file using SQL Server Integration Services?

Thanks.

[A]
Because SSIS is pipeline based, there's no good way to look ahead and know that a line is the last line.
However, depending on your actual goal, there are a number of ways to achieve this:
If the last row has some identifying
information, it can simply be
filtered out using the built-in
filter component.
You can create a custom component
which does buffer the pipeline a
little and leaves off the last row.
You can add a row counter, output
the file to a raw file and then read
the raw file, excluding the last row
using a filter


q: ASP.NET ASMX service occasionally throws exceptions. However, global.asax Application_Error method do not seem to catch them. The question is, how to configure global error handler to catch and log these exceptions?

[A]
Is it the ASMX or the AJAX JavaScript which is throwing the exception?
If it's the Javascript, you'll need to write exception handling into your JS, and then push that back to the server to be tracked in your error datastore--possibly via another call to your webservice.
If it's the ASMX then it's probably getting caught by your Application_Error, BUT as ASMX returns XML or JSON it won't necessarily get displayed on your UI unless you're looking for it.


q:
I have a large array in C (not C++ if that makes a difference). I want to initialize all members of the same value.

I could swear I once knew a simple way to do this. I could use memset() in my case, but isn't there a way to do this that is built right into the C syntax?

[A]
Unless that value is 0 (in which case you can omit some part of the initializer
and the corresponding elements will be initialized to 0), there's no easy way.
Don't overlook the obvious solution, though:
```
```
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };
```
```
Elements with missing values will be initialized to 0:
```
```
int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...
```
```
So this will initialize all elements to 0:
```
```
int myArray[10] = { 0 }; // all elements 0
```
```
In C++, an empty initialization list will also initialize every element to 0.
This is
not allowed
with C until C23:
```
```
int myArray[10] = {}; // all elements 0 in C++ and C23
```
```
Remember that objects with static storage duration will initialize to 0 if no
initializer is specified:
```
```
static int myArray[10]; // all elements 0
```
```
And that "0" doesn't necessarily mean "all-bits-zero", so using the above is
better and more portable than memset(). (Floating point values will be
initialized to +0, pointers to null value, etc.)


q:
I will be teaching a class sson, and I need to explain what factors should affect your decision of data access technology.
I am familiar with many data access methods like Typed Data Sets, Linq to SQL, Linq to Entities, .netTiers, LLBLGen, and custom calls with SQL connection objects and command objects.
Some of my clients will only allow stored procedures to be used, and they will NOT discuss anything else.
Some of my clients are NOT ready to install .NET 3.5 yet.
Some clients require a middle web service tier in any web application.
Most of the time I use Types Data Sets and Custom Web Services, or I use .netTiers with CodeSmith. What else should I be thinking about?

[A]
One important thing to remember is that a database is not necessarily just a backing data store for an application (in isolation).  Other applications and process could eventually require access to the database, especially in large or “enterprise” databases (or applications) and especially given enough time.
It’s important to consider:
ETL/Loads/Migration
External integration/synchronization (BizTalk/SSIS)
Reuse by other applications (particularly web sites, mobile applications etc)
Security/attack surface (is one approach less secure than another?)
Maintenance tasks
Availability  - will the database be in use 24/7?  Is one approach going to provide better availability than another, etc.
Also, some design consideration is in order.  Are you tuning for faster selects, or faster writes?  One data access design might perform better than another.
I’m not stating that there is a single silver bullet, but what I do caution is that any data access design pattern requires “big picture” thought - will it address today's concerns and what you can reasonably predict might be tomorrow's needs?
Also, will you be providing an external API or some framework for consistent data access?  Will it be exposed directly or indirectly?
There’s a place, I think, for both the Entity Framework/LINQ to SQL, traditional Stored Procedures and other tools like NHibernate (etc), but you should justify and rationalise the choice of technology first, and try to ensure it is appropriate for the present and future needs.
EDIT: Sorry, I forgot the big one: maintainability.  Some of the template driven solutions offer you some decent wins in being able to regenerate a DAL after schema changes, over others (like hand written stored procedures).  It's worth weighing up the productivity gains vs the disadvantages.


q:
I'm looking for a simple way to grab thumbnails of FLVs in ASP.NET, without having to change any permissions/settings on the server. Ideally, nothing is installed on the server machine, but if necessary, small tools such as FFmpeg are fine.

I've tried FFmpeg using the command-line tool with Process.Start, but the same command that works in a Windows Forms application and from the command prompt does not work in ASP.NET (presumably because of permissions).

I've also tried using TAO.FFmpeg, and it seems to be working most of the time, but fails randomly, and does not start working again until the machine is restarted. Even when I use the sample code (decoder.cs), it sometimes fails when I try to open multiple videos in a single request.

If this isn't possible in a clean/straightforward way, I'm open to other suggestions.

[A]
If you can embed Flash on a page, the easiest way to show a thumbnail of a FLV is to put a video object on the stage, attach a video to it through a NetStream in actionscript, and then put in an event handler to pause the move immediately after it starts playing.
For example, if you have a video object on the stage called "myVideo", and you're trying to show a thumbnail of "someVideo.flv", try this actionscript (2.0) code,
```
var connection_nc:NetConnection = new NetConnection();
connection_nc.connect(null);
var stream_ns:NetStream = new NetStream(connection_nc);
myVideo.attachVideo(stream_ns);
stream_ns.play("someVideo.flv");
stream_ns.seek(0);

stream_ns.onStatus = function(info)
{
    if(info.code = "NetStream.Play.Start")
    {

        stream_ns.pause();
    }
}
```
In terms of your ASPX talking to your Flash, you could pass the FLV video name to Flash via FlashVars so that your SWF would know what thumbnail to show.


q:
I am currently looking for a way to be notified when a child is added to the visual or logical children.

I am aware of the Visual::OnVisualChildrenChanged method, but it does not apply to me since I can't always inherit and override this function.  I am looking for an event.

So, is there a way for the owner of a FrameworkElement/Visual to be notified when a child is added?

[A]
I believe that
FrameworkElement.Loaded
and
FrameworkElement.Unloaded
are fired when the control is added to and removed from the Visual Tree, respectively. However, the few times that I was trying to do anything with them I wasn't able to get them to fire consistently (I was using Class Event Handlers at the time, so that might have something to do with it).


q:
I feel like a fool, but here goes:

public interface IHasErrorController{
  ErrorController ErrorController { get; set; }
}

public class DSErrorController: ErrorController{yadi yadi ya}

public class DSWebsiteController : Controller, IHasErrorController{
    public DSErrorController ErrorController { get; set; }
}

This gives me an error saying DSWebsiteController.ErrorController cannot implement IHasErrorController despite DSErrorController being inheritted from ErrorController.

Also, suggestions for a better naming so that the type ErrorController and the field Errorcontroller don't look the same are welcome (naming is hard).

[A]
C# (at the moment) has very little [co|contra]variance support; as such, the interface implementation must be an
exact
match, including the return type. To keep your concreate type on the class API, I would implement the interface explicitly - i.e. add:
```
```
ErrorController IHasErrorControlloer.ErrorController {
  get {return this.ErrorController;}
  set {this.ErrorController = (DSErrorController)value;}
}
```
```
Alternatively, simply change the type of the property to
```
ErrorController
```
- this may (or may not) give what you need.


q:
A strict equality operator will tell you if two object types are equal. However, is there a way to tell if two objects are equal, much like the hash code value in Java?

Stack Overflow question Is there any kind of hashCode function in JavaScript? is similar to this question, but requires a more academic answer. The scenario above demonstrates why it would be necessary to have one, and I'm wondering if there is any equivalent solution.

[A]
Depends on what you mean by equality. And therefore it is up to you, as the developer of the classes, to define their equality.
There's one case used sometimes, where two instances are considered 'equal' if they point to the same location in memory, but that is not always what you want. For instance, if I have a Person class, I might want to consider two Person objects 'equal' if they have the same Last Name, First Name, and Social Security Number (even if they point to different locations in memory).
On the other hand, we can't simply say that two objects are equal if the value of each of their members is the same, since, sometimes, you don't want that. In other words, for each class, it's up to the class developer to define what members make up the objects 'identity' and develop a proper equality operator (be it via overloading the == operator or an Equals method).
Saying that two objects are equal if they have the same hash is one way out. However you then have to wonder how the hash is calculated for each instance. Going back to the Person example above, we could use this system if the hash was calculated by looking at the values of the First Name, Last Name, and Social Security Number fields. On top of that, we are then relying on the quality of the hashing method (that's a huge topic on its own, but suffice it to say that not all hashes are created equal, and bad hashing methods can lead to
more
collisions, which in this case would return false matches).


q:
Is it possible to reference system environment variables (as opposed to Java system properties) in a log4j xml configuration file?

I'd like to be able to do something like:

<level value="${env.LOG_LEVEL}" />

and have it get that from the system environment variables, so I can avoid having to pass in so many things with -D parameters.

[A]
I tried to do that recently and couldn't get it to work. What I ended up doing is sending a variable at startup. So say you have an environment variable called $LOG_LEVEL:
```
```
<level value="${log_level}" />
```
```
and at startup...
```
```
java -Dlog_level=$LOG_LEVEL your_app
```
```


q:
We are using Linq To SQL with our own data context logic that executes the one linq query across multiple databases.  When we get the results back, we need the database for each of the rows.  So...

I want to have a property on my class that will return the database name (SQL Server, so DB_NAME()).  How can I do this in Linq To Sql?

Dave, thanks for the answer, but we have hundreds of databases and don't want to have to add views if possible.


q:
Using C#, does anyone know how to get the MarshalAsAttribute's Sizeconst value in runtime ?

Eg. I would like to retrieve the value of 10.

[StructLayout[LayoutKind.Sequential, Pack=1]
Class StructureToMarshalFrom
{
    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 10)]
    public byte[] _value1;
}

[A]
Yup, with reflection:
```
```
FieldInfo field = typeof(StructureToMarshalFrom).GetField("_value1");
object[] attributes = field.GetCustomAttributes(typeof(MarshalAsAttribute), false);
MarshalAsAttribute marshal = (MarshalAsAttribute) attributes[0];
int sizeConst = marshal.SizeConst;
```
```
(Untested, and obviously lacking rather a lot of error checking, but should work.)


q:
Let's say that I create a Sub (not a function) whose mission in life is to take the active cell (i.e. Selection) and set an adjacent cell to some value.  This works fine.

When you try to convert that Sub to a Function and try to evaluate it from from spreadsheet (i.e. setting it's formula to "=MyFunction()")  Excel will bark at the fact that you are trying to affect the value of the non-active cell, and simply force the function to return #VALUE without touching the adjacent cell.

Is it possible to turn off this protective behavior?  If not, what's a good way to get around it?  I am looking for something a competent developer could accomplish over a 1-2 week period, if possible.

Regards,
Alan.

Note: I am using 2002, so I would favor a solution that would work for that version.  Having that said, if future versions make this significantly easier, I'd like to know about it too.

[A]
I'm using Excel 2007, and it does not work. Excel mentions it creates a circular reference. I don't think you can alter other cells from a function, just return a value.
It's kind of functional programming, no side effects. If you could just alter other cells inside a function (used from a worksheet), then there's no way for Excel to know the order and what to recalculate if a cell changes.
This article
also contains a lot of information about how Excel does recalculation. But it never states that the other cells are frozen.
I don't know what you are trying to do, but, why don't you just place another function in the adjacent cell, that takes the first cell as a parameter?
Example:
```
```
Public Function Bar(r As Range) As Integer
  If r.Value = 2 Then
    Bar = 0
  Else
    Bar = 128
  End If
End Function
```
```


q:
Microsoft SQL Server and MySQL have an INFORMATION_SCHEMA table that I can query. However it does not exist in an MS Access database.

Is there an equivalent I can use?

[A]
Getting a list of tables:
```
```
SELECT
    Table_Name = Name,
FROM
    MSysObjects
WHERE
    (Left([Name],1)<>"~")
    AND (Left([Name],4) <> "MSys")
    AND ([Type] In (1, 4, 6))
ORDER BY
    Name
```
```


q:
I have a swing application that includes radio buttons on a form. I have the ButtonGroup, however, looking at the available methods, I can't seem to get the name of the selected JRadioButton. Here's what I can tell so far:

From ButtonGroup, I can perform a getSelection() to return the ButtonModel. From there, I can perform a getActionCommand, but that doesn't seem to always work.  I tried different tests and got unpredictable results.

Also from ButtonGroup, I can get an Enumeration from getElements().  However, then I would have to loop through each button just to check and see if it is the one selected.

Is there an easier way to find out which button has been selected?  I'm programing this in Java 1.3.1 and Swing.

[A]
I would just loop through your
```
JRadioButtons
```
and call
```
isSelected()
```
. If you really want to go from the
```
ButtonGroup
```
you can only get to the models. You could match the models to the buttons, but then if you have access to the buttons, why not use them directly?


q:
In my javascript experience, I found that is a very common task "searching the nearest ancestor of an element with some condition (tag name, class,...)".
Can the parents() method of jquery do the job? The order of returned elements of parents() is predictable? Is top-to-bottom or bottom-to-top?
For the moment I use this utility function:

function ancestor(elem, selector) {
  var $elem = $( elem ).parent();
  while( $elem.size() > 0 ) {
    if( $elem.is( selector ) )
    return $elem;
    else
       $elem = $elem.parent();
  }
  return null;
}

Can someone tell me if there is a clever way to do the job?

[A]
Edit
: Since jQuery 1.3, this has been built in as the
```
closest()
```
function. eg:
```
$('#foo').closest('.bar');
```
yep - parents() traverses up the tree.
```
```

```
```
```
$('#d').parents("div:first");
```
will select div b.


q:
Over the years I have slowly developed a regular expression that validates most email addresses correctly, assuming they don't use an IP address as the server part.

I use it in several PHP programs, and it works most of the time.  However, from time to time I get contacted by someone that is having trouble with a site that uses it, and I end up having to make some adjustment (most recently I realized that I wasn't allowing four-character TLDs).

What is the best regular expression you have or have seen for validating emails?

I've seen several solutions that use functions that use several shorter expressions, but I'd rather have one long complex expression in a simple function instead of several short expression in a more complex function.

[A]
I use
```
```
^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$
```
```
Which is the one used in ASP.NET by the RegularExpressionValidator.


q:
I just added xUnit to our test project (for the Asserts, we're still using MSTest as the framework) and immediately the test runs refused to execute any of the tests. This is the error message:

Failed to queue test run '{ .... }'
  Test run deployment issue: The
  location of the file or directory
  '...xUnit.dll' is not trusted.

[A]
It took me a few tries to find the answer in Google, so I'm putting it here in case anyone else runs into the same problem. A detailed description can be found at
this blog posting
.
Basically, the fix invovles right-clicking on the dll file (xunit.dll for example) in Windows Explorer, going to Properties, and clicking "Unblock" at the bottom of the tab next to the 'Security' text. It seems that Vista / Windows 2008 will automatically mark assemblies that come from other machines or the internet as unsafe.
As a couple commenters have mentioned, you may also need to restart Visual Studio for this to take effect.


q:
int l = strlen(s);

warning C4244: '=' : conversion from '__w64 int' to 'int', possible loss of data

I need to replace strlen with an inline function
int l = new_strlen(s);

But how do I portably get the result of the strlen into the int without a warning, and without using pragmas?  I can guarantee there aren't more than 2 billion characters in my string!

All the obvious things like reinterpret_cast, static_cast  also produce errors or warnings.

EDIT: Argh. a c-style cast: (int) does work. I had been convinced that it did not.

[A]
Cast it:
```
```
int i = (int) strlen(s);
```
```


q: Not of the site collection itself, but the individual SPWeb's.

[A]
You should take a look at this blog entry by Alexander Meijers :
Size of SPWeb based on its Folders and Files
It provides a clever way of finding the size of an SPWeb or SPFolder by iterating through his content.
```
```
private long GetWebSize(SPWeb web)
{
    long total = 0;

    foreach (SPFolder folder in web.Folders)
    {
        total += GetFolderSize(folder);
    }

    foreach (SPWeb subweb in web.Webs)
    {
        total += GetWebSize(subweb);
        subweb.Dispose();
    }

    return total;
}
```
```


q: For example, I am trying to get a min date, a max date, and a sum in different instances. I am trying to avoid hard coding a SQL string or looping through an IList to get these values.

[A]
For starters, instead of beginning your search at n / 2, start it at the square root of n. You'll get half of the factors, the other half being their complement.
eg:
```
```
n = 27
start at floor(sqrt(27)) = 5
is 5 a factor? no
is 4 a factor? no
is 3 a factor? yes. 27 / 3 = 9. 9 is also a factor.
is 2 a factor? no.
factors are 3 and 9.
```
```


q:
On my reading spree, I stumbled upon something called Intentional Programming.
I understood it somewhat, but I not fully. If anyone can explain it in better detail, please do. Is it being used in any real application?

[A]
It appears to be a method of programming that allows the programmer to expand what is actually in the language to more closely follow their original intent, rather than forcing the programmers intent into the constrained syntax of the language.
It explicitly mentions LISP as a language that supports this, so I'd suggest you read up on this great language :) LISP Macros are exactly what are described in the article, allowing you to indefinitely expand the language to cover almost anything you would care to express. (A fairly common outcome of large LISP systems is that you end up with a domain specific language that is very good for writing specific applications, i.e. writing a word processor ends up with a word processor specific language).
For your last part, yes LISP (and thus Intentional Programming) is used in some projects. Paul Graham is a great proponent of LISP, and other examples of it include the original Crash Bandicoot (a game object creation system was created in LISP for this, including a LISP PlayStation compiler)


q:
Why is the CheckBoxList removed from ASP.NET MVC preview release 5?

Currently I don't see any way in which I can create a list of checkboxes (with similar names but different id's) so people can select 0-1-more options from the list.

There is an CheckBoxList list present in the MVCContrib library, but it is deprecated. I can understand this for the other HtmlHelpers, but there does not seem to be a replacement for the CheckBoxList in preview 5.

I would like to create a very simple list like you see below, but what is the best way to do this using ASP.NET MVC preview release 5?

<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="goed"> goed
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="redelijk"> redelijk
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="matig"> matig
<INPUT TYPE="checkbox" NAME="Inhoud" VALUE="slecht"> slecht

[A]
A for loop in the view to generate the checkboxes
```
```
<% foreach(Inhoud i in ViewData["InhoudList"] as List<Inhoud>) { %>
  <input type="checkbox" name="Inhoud" value="<%= i.name %>" checked="checked" /> <%= i.name %>
<% } %>
```
```
Don't use
```
Html.Checkbox
```
, as that will generate two values for each item in the list (as it uses a hidden input for false values)


q:
I am working on a .NET application that displays multiple charts.  My users would like an easy way to say "take chart #3 and maximize it on my fourth monitor".

How can I determine the number of monitors so I can give them a selection of "monitor #1, monitor #2, etc"?  (Not every user has the same number of monitors.)

And once the user has selected a particular monitor, how can I use that information to position the chart they're trying to maximize?

[A]
The
Screen
class helps you a lot by finding the
available screens
.
When you "maximize" a form, the form will automatically maximize to the size of the Screen the form is in.
You can position it yourself, or let Windows take care of it, by just placing the form on the right "Screen", and maximizing it. Or use the
WorkingArea
of the screen, and fill that yourself.


q: I've heard people talking about "base 64 encoding" here and there.  What is it used for?

[A]
Base-64 encoding is a way of taking binary data and turning it into text so that it's more easily transmitted in things like e-mail and HTML form data.
http://en.wikipedia.org/wiki/Base64


q:
I have a strange issue: I am using SPContext.Current.Web in a .aspx page, but at the end, I get a "Trying to use an SPWeb object that has been closed or disposed and is no longer valid." error message.

From what I see, SPContext.Current.Web is Disposed by someone, but I have no idea where. I just wonder: With Visual Studio 2005's Debugger, can I somehow see where/who disposed an Object? As I neither create nor have the source code, setting breakpoints is a problem.

What would be a good approach for finding out who disposes a given object where, without just randomly commenting out lines?

(Note: The Issue has been resolve, but the question itself also applies outside of Sharepoint)

[A]
Check if this helps:
Add a new breakpoint using
Debug > New Breakpoint > Break at Function... (Ctrl+B)
.
Enter
Microsoft.SharePoint.SPWeb.Dispose
in the Function edit box.
Dismiss the dialog box that says that Intellisense could not find the specified location.
Run under the debugger.
When the breakpoint is hit you can see on the call stack who called the Dispose method. Hopefully for some of the times the breakpoint is hit one stack frame is in your source code.
If a dialog appears saying that
There is no source code available for the current location
when the breakpoint is hit dismiss it.
Note:
Because I do not have SharePoint installed I have tested this with
```
System.IO.StreamReader.Dispose
```
but I am guessing that this should also work for SPContext.Current.Web. Drop a note on this.


q:
I've done this a million times ... setting up a developer work station.

Is there a best practices, or installation checklist for installing Microsoft development software on a work station? What about applying updates and/or service packs?  Is there a specific order for doing this, in hopes of minimizing any install issues.

Our current software library consists of:

Visual Studio 2003

Visual Studio 2008

SQL Server 2005

Microsoft Office 2007

We do use some other tools, but I usually hold off on installing them once I get a good build from Microsoft ... whether a good build is possible or not is another topic! =)

Also, do you use any software like Ghost to create images of work station?  Some easy way to restore your work station.

[A]
I tend to go in chronological order. The oldest software to the most recent.
In your case I would do something like
Office 2007 (I usually install office first)
VS2003
Install VS2003 updates through Microsoft update
SQL Server 2005
Install SQL Server 2005 through Microsoft Update
And so on...
When the setup is over and the machine is configured I do a full base image with
Acronis True Image
.


q:
I need to create a database table to store different changelog/auditing
(when something was added, deleted, modified, etc). I don't need to store particularly detailed info, so I was thinking something along the lines of:

id (for the event)

user that triggered it

event name

event description

timestamp of the event

Am I missing something here? Obviously, I can keep improving the design, although I don't plan on making it complicated (creating other tables for event types or stuff like that is out of the question since it's a complication for my need).

[A]
There are many ways to do this.  My favorite way is:
Add a
```
mod_user
```
field to your source table (the one you want to log).
Create a log table that contains the fields you want to log, plus a
```
log_datetime
```
and
```
seq_num
```
field.
```
seq_num
```
is the primary key.
Build a trigger on the source table that inserts the current record into the log table whenever any monitored field is changed.
Now you've got a record of every change and who made it.


q:
I need to add multiple empty divs to a container element using jQuery.

At the moment I am generating a string containing the empty html using a loop

divstr = '<div></div><div></div>...<div></div>';

and then injecting that into my container:

$('#container').html(divstr);

Is there a more elegant way to insert multiple, identical elements?

I'm hoping to find something that wouldn't break chaining but wouldn't bring the browser to its knees. A chainable .repeat() plugin?

[A]
You can use a regular loop with the Jquery
append
function.
```
```
for(i=0;i<10; i++){
    $('#container').append("

");
}
```
```


q:
I am using wordpress and use custom permalink structure: /%category%/%postname%/

My problem is that a decent number of people link to the site without including the trailing slash in the URL, so users get a 404 page.

I'm using the default .htaccess file that comes with wordpress because no solution I've tried has worked. I've tried using the Redirection plugin, with no success.

I'd gladly link to the site, but I don't want it to be construed as self-promotion. If you ask, I'll provide a link.

Could anyone help me find a plugin or provide some .htaccess entries to help resolve this?

Thanks very much!

[A]
Use:
```
```
/%category%/%postname%(/?)
```
```
in your .htaccess file.
The question mark denotes an optional character sequence.


q:
For the past 2 years-(ish) I've been using Maven2 for my build/continuous integration solution.  I used Ant a bit before that but really didn't get a lot of experience with it.  Now I've taken a new job and the team I'm on now uses Ant.

What I'm wondering about is this:

In Maven we had directory conventions for seperating our java source and files and java test files (JUnit tests).  It looked like this:

Project-
  -src/main/java
  -src/test/java

This way your tests are separate from your source/production code and won't be built/deployed as such.

Going over the Ant documentation I don't really see any convention for this. Am I missing something?  Is there a similar convention in Ant?

[A]
My experience with ant -- which is our primary build tool for Java source, so make of this what you will -- is that there are no such
formal
conventions.  Many source projects I've seen organize things in a similar manner; JBoss uses <module>/src/main for sources, etc...  Ant just uses whatever conventions you want, which makes it an ideal tool to integrate into a larger project building framework.
At any rate, the Maven conventions work just fine for Ant, so if you've already got them in place, just re-use the same structures.  Not only is it easier for you to keep track of where things are, when you use a familiar structure, but if you ever decide to mavenize the project, you'll already be set.


q:
I'd like to do something like this:

Dim Foo as String = "a,b,c,d,e"
Dim Boo as List(of String) = Foo.Split(","c)

Of course Foo.Split returns a one-dimensional array of String, not a generic List. Is there a way to do this without iterating through the array to turn it into a generic List?

[A]
If you use Linq, you can use the ToList() extension method
```
```
Dim strings As List<string> = string_variable.Split().ToList<string>();
```
```


q:
Our WinForms application has been reported to occasionally just close on its own.  It neither shows our own crash error submit dialog nor Windows' error submit dialog, it just closes and is gone, often when the person was afk and not doing anything with the application.  It seems to be a semi-rare occurrence, maybe like 2-3 times a month, and it's happened to more than one person.  I have no idea where to start with getting a repro case or where to begin tracking this down.

C#
.NET 2.0
Reported cases are on Win XP

Anyone have any ideas?

[A]
Exceptions will cause an app to "disappear". Check the Event logs to see if anything was there.
Check task manager to see if the process is still present when the window disappears. I have had explorer crash and fail to redraw the window until it was Alt-Tabbed or Switched-To (from task manager).
Dont put it past the users to conveniently forget they are closing the app. You may want to put some logging logic in the app to log user initiated closures. Next time it "disappears" you can check for any log entries.


q:
Can some one post an example of using syslog outputter for log4r, I am currently using stdout but want to log to syslog.

mylog = Logger.new 'mylog'
mylog.outputters = Outputter.stdout
mylog.info "Starting up."

raj

Thanks also to the following blog posts.

Angrez's blog: Log4r - Usage and Examples

ProgrammingStuff: Log4r

[A]
Kind of lame answering my own question, but I found answer to this and adding it for later searches.
For some reason I need to require log4r/outputter/syslogoutputter explicitly other wise SyslogOutputter would cause "uninitialized constant SyslogOutputter (NameError)" error. Other outputters do not seem to have this problem.
```
```
require 'rubygems'
require 'log4r'
require 'log4r/outputter/syslogoutputter'
mylog = Logger.new 'mylog'
mylog.outputters = SyslogOutputter.new("f1", :ident => "myscript")
mylog.info "Starting up."
```
```
raj


q: In MySQL, how do I get a list of all foreign key constraints pointing to a particular table? a particular column? This is the same thing as this Oracle question, but for MySQL.

[A]
If you use InnoDB and defined FK's you could query the information_schema database e.g.:
```
```
SELECT * FROM information_schema.TABLE_CONSTRAINTS
WHERE information_schema.TABLE_CONSTRAINTS.CONSTRAINT_TYPE = 'FOREIGN KEY'
AND information_schema.TABLE_CONSTRAINTS.TABLE_SCHEMA = 'myschema'
AND information_schema.TABLE_CONSTRAINTS.TABLE_NAME = 'mytable';
```
```


q:
We are using Linq To SQL with our own data context logic that executes the one linq query across multiple databases. When we get the results back, we need the database for each of the rows. So...

I want to have a property on my class that will return the database name (SQL Server, so DB_NAME()). How can I do this in Linq To Sql?

NOTE: We have hundreds of databases and do not want to put views in each db.  The return should come back as just another property on each row of the return result set.

[A]
How are you iterating through the different databases? Could you just include information from the context in the query? For example:
```
```
Dim results = _
    From x In myContext.MyTables _
    Select x, info = myContext.Connection.ConnectionString
```
```


q: I can't find documentation for it, even on MSDN...

[A]
Some reasoning here:
http://www.tech-archive.net/Archive/VC/microsoft.public.vc.language/2005-08/msg00589.html


q:
Does Geronimo provides a standalone transaction manager?
And if it does, is it possible to use it in Tomcat?

[A]
Apache OpenEJB
is embedded implementation of Geronimo EJB container that includes Transaction Manager. OpenEJB can be embedded into Tomcat which is one of its intended usages.


q:
In ASP.NET, I'm looking for a way to audit a user leaving my application. To be specific, I'd like to insert a 'logout' record in an audit table in SQL Server when the user's session is abandoned/destroyed for any reason (not necessarily because of a call to session.abandon)

I have a 'SessionHelper' class that manages the session setters/getters.

I've tried posting back in Session_End in Global.asax, but it never fired this event even after the timeout expired.

I've tried overriding 'finalize' in the SessionHelper class and doing it there when the class is destroyed, but it did not fire that event either.

I'd try implementing IDisposable in the SessionHelper, but I don't know where to call it so that it always gets called.

What is the proper way to audit a user leaving your ASP.NET application?

Thank you!

[A]
Note sure about the "proper way" but here's how I've done it in the past.
Have a "is active" date-Time stamp associated with the user record in the database. Everytime the user accesses a page, that is updated to the current time. If someone hasn't accessed the page in say 15 minutes, then that user is recorded as a "logout" event, and the timestamp is set to NULL.


q:
I have a Java applet that runs inside a forms-authenticated aspx page. In the .NET 1.1 version of my site, the applet has access to the session cookie and is able to retrieve a file from the server, but in the .NET 2.0 version it fails to authenticate.

I have seen a couple of forum posts elsewhere that state that 2.0 sets cookies to HttpOnly by default, but the solutions given haven't worked for me so far. I also read somewhere that 2.0 may be discriminating based on user-agent.

Does anyone have any experience or insight into this?

[A]
Filip's answer isn't entirely correct. I ran a program to sniff the HTTP headers on my workstation, and the Java applet does in fact present the ASP.NET authentication ticket in some circumstances - just not reliably enough for my needs.
Eventually I did find a solution to this, but it didn't entirely solve my problem. You can add an entry to the web.config in .NET 2.0:
```
<httpCookies httpOnlyCookies="false" />
```
; but this didn't work for all my users.
The long term solution turned out to be modifying the Java applet so that it doesn't need to retrieve anything from the web server.


q:
I'm currently logging via the simplest of methods within my servlet using Tomcat.  I use the ServletConfig.getServletContext().log to record activity.  This writes to the localhost.YYYY-MM-DD.log in $TOMCAT_HOME/logs.

I don't want to get away from the simplicity of this logging mechanism unless absolutely necessary.  But I would like to name my log file.  Rather than "localhost".YYYY-MM-DD.log, is there a way to have it write to "myAppName".YYYY-MM-DD.log.  I know I could create my own mechanism, but again, I looking for simplicity here.

I'm hoping to stay away from a complete framework like Log4j.


q: How do I concatenate two std::vectors?

[A]
I would use the
insert function
, something like:
```
```
vector<int> a, b;
//fill with data
b.insert(b.end(), a.begin(), a.end());
```
```


q: I have a one-dimensional array of strings in JavaScript that I'd like to turn into a comma-separated list. Is there a simple way in garden-variety JavaScript (or jQuery) to turn that into a comma-separated list? (I know how to iterate through the array and build the string myself by concatenation if that's the only way.)

[A]
The
Array.prototype.join()
method:
```
```
var arr = ["Zero", "One", "Two"];

document.write(arr.join(", "));
```
```


q:
I have to preface this with the fact that I love jQuery as a JavaScript language extension and YUI as a rich set of free controls.  So here is my question, is there going to be any problems down the line if I mix jQuery and YUI together in an MVC app I am working on.

I want to use jQuery for the heavy lifting on the DOM and I want to use YUI for the rich user control set.  This is an internal application and will never see the light of day outside of the organization I work for.

If anybody has experience with mixing these two frameworks I would love to hear what your experience has been.

[A]
Speaking from some experience in developing a small tool myself, I've used YUI's rich control set with Prototype for DOM manipulation in the past and experienced no issues. Admittedly, this was a small tool that didn't use a wide array of the controls.
Even so, I'm always hesitant to use multiple frameworks on my web projects; however, if you're only using jQuery's DOM functionality and YUI's control functionality, then I think you're fine - there's not really a conflict of interest there. Plus, with jQuery's noConflict() mode and YUI's namespacing, the two frameworks really shouldn't trump one another.


q:
I have an ASP.NET web page with a Login control on it.  When I hit Enter, the Login button doesn't fire; instead the page submits, doing nothing.

The standard solution to this that I've found online is to enclose the Login control in a Panel, then set the Panel default button.  But apparently that doesn't work so well if the page has a master page.  I've tried setting the default button in code with control.ID, control.ClientID, and control.UniqueID, and in each case I get:

The DefaultButton of panelName must be the ID of a control of type IButtonControl.

I'm sure there's a way to do this with JavaScript, but I'd really like to do it with plain old C# code if possible.  Is it possible?

[A]
you have to add something like this in page load...
```
```
txtPassword.Attributes.Add("onKeyPress", "javascript:if (event.keyCode == 13) __doPostBack('" + lnkSubmit.UniqueID + "','')")
```
```
the password textbox has an onKeyPress attribute added that will force a doPostBack on the submit button if the "Enter" key is pressed. This simulates clicking the submit button.


q: I have a user interface that requires placing some round buttons in a C# project with some data behind them. The buttons are System.Windows.Forms.buttons and I have used a GIF image with transparency to create them.  However, the transparent areas aren't transparent.  I've looked for references online but haven't found any suggestions for how to do this properly.  There's some mention of doing it in Visual Studio 2008 but I need to keep this project in 2005. Any help or suggestion is appreciated.

[A]
I'm pretty sure you need to use PNGs with WinForms to get image transparency. I know I've used them successfully.
EDIT: When I used the PNGs, I was overlaying them with the Image control onto the Form1.BackgroundImage; I wasn't using them in buttons.
I think your best bet is to switch from using a button control to using an image control. You might also try changing the button style to flat (I think it was flat, maybe one of the other styles) and seeing if you can get the effect you want that way.


q:
ASPX Code

<asp:RadioButtonList ID="rbServer" runat="server" >
   <asp:ListItem Value=<%=ServerDeveloper%>> Developer </asp:ListItemv
   <asp:ListItem Value="dev.ahsvendor.com"> dev.test.com</asp:ListItem>
   <asp:ListItem Value="staging.ahsvendor.com"> staging.test.com</asp:ListItem>
</asp:RadioButtonList>

ASPX.CS - Codebehind

const string ServerDeveloper = "developer";

ASPX Error: Code blocks are not supported in this context.

Question: So what is the correct way to tie an dropdown/radio buttion/... ASPX value to a constant that is shared with the CodeBehind code?

I know that I could do rbServer.Add.Item("developer") [from the CodeBehind], but is there  a way to achieve it from the Presentation side of things?

[A]
Would it be:
```
rbServer.Items.Add(ServerDeveloper)
```
Ok, so since you want to do it from presentation...It is possible, but horribly ugly:
```
<div>
<% rbServer.Items.Add(new ListItem("Dev", ServerDeveloper)); %>
<asp:RadioButtonList ID="rbServer" runat="server">
    <asp:ListItem Value="Blah">Blah</asp:ListItem>
</asp:RadioButtonList>
</div>
```
Note that the code block has to be
above
the markup - if you put it below, it doesn't seem to work. Note also that the const will have to be protected in order for the page to access it. This feels terribly like a hack to me, but there it is.


q:
Ok, strange setup, strange question. We've got a Client and an Admin web application for our SaaS app, running on asp.net-2.0/iis-6. The Admin application can change options displayed on the Client application. When those options are saved in the Admin we call a Webservice on the Client, from the Admin, to flush our cache of the options for that specific account.

Recently we started giving our Client application >1 Worker Processes, thus causing the cache of options to only be cleared on 1 of the currently running Worker Processes.

So, I obviously have other avenues of fixing this problem (however input is appreciated), but my question is: is there any way to target/iterate through each Worker Processes via a web request?


q:
I have a format file where I want one of the columns to be "group".  I'm auto-generating the format file and a client wants to upload a file with "group" as one of the columns.  I could restrict it so they can't use SQL keywords, but then I need a function to determine if a column name is a SQL keyword, so I'd like to support the user being able to name their clients however they want.  I'm wondering if this is possible.  I tried using brackets, but that didn't appear to work.  My file looks like:

8.0
1
1 SQLCHAR 0 0 "\r\n" 1  [group] SQL_Latin1_General_CP1_CI_AS

[A]
I tested this out several different ways on SQL 2005 SP2 (target databases in both compatibility modes 80 and 90) and it works OK for me using the SQL 2005 version of bcp.
However, I also tested it with the SQL 2000 version of bcp, and that failed with
```
```
Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'group'.
```
```
which I guess is what you're getting.
Are you able to upgrade the system where you're running bcp to use the SQL 2005 client tools?
If you believe that you have already upgraded, check your PATH environment variable to confirm that
```
```
C:\Program Files\Microsoft SQL Server\90\Tools\binn\
```
```
(adjusted for your installation) appears before
```
```
C:\Program Files\Microsoft SQL Server\80\Tools\BINN
```
```
otherwise the SQL 2000 command line tools will be used in preference to the SQL 2005


q:
Hey right now I'm using jQuery and I have some global variables to hold a bit of preloaded ajax stuff (preloaded to make pages come up nice and fast):

$.get("content.py?pageName=viewer", function(data)
    {viewer = data;});
$.get("content.py?pageName=artists", function(data)
    {artists = data;});
$.get("content.py?pageName=instores", function(data)
    {instores = data;});
$.get("content.py?pageName=specs", function(data)
    {specs = data;});
$.get("content.py?pageName=about", function(data)
    {about = data;});

As you can see, we have a huge violation of the DRY principle, but... I don't really see a way to fix it... any ideas?

maybe an array?

[A]
You can avoid eval using new Function:
```
```
var names = ['viewer', 'artists', 'instores', 'specs', 'about'];
for (var i = 0; i < names.length; i++)
   $.get("content.py?pageName=" + names[i], new Function('data', names[i] + ' = data;'));
```
```
It's not a lot better though tbh


q:
i have the following script

import getopt, sys
opts, args = getopt.getopt(sys.argv[1:], "h:s")
for key,value in opts:
    print key, "=>", value

if i name this getopt.py and run it doesn't work as it tries to import itself

is there a way around this, so i can keep this filename but specify on import that i want the standard python lib and not this file?

Solution based on Vinko's answer:

import sys
sys.path.reverse()
from getopt import getopt

opts, args = getopt(sys.argv[1:], "h:s")

for key,value in opts:
    print key, "=>", value

[A]
```
```
import getopt as bettername
```
```
This should allow you to call getopt as bettername.


q:
I'm automating Outlook and I need to control who the email appears to be from. The users will have two or more Accounts set up in Outlook and I need to be able to select which account to send the email from. Any ideas?

Needs to be supported on Outlook 2003 and above. I'm using Delphi 2006 to code this, but that doesn't really matter.


q:
The project is poorly defined: we are to write educational software for CS 111 Computer Programming I students focusing on functions. We have 6 student developers with various backgrounds working in Flex. The project has a duration of about 7 weeks. We have very limited face time (30 min per week) and very limited work time (<8 hours per developer per week). We have limited access to the customers (professor of our course, professor of CS 111, students in CS 111).

Our toolset includes Flex Builder, Subversion, and TRAC.

What methodology is best for this project and why? Alternately, what features should be gathered from various methodologies to better suit this situation?

[A]
What makes you think any methodology would be successful under these circumstances -- little communication, more requirements than time, and lack of access to customers?
That being said, I would focus on incremental delivery (each iteration should have some few working features), unit testing (all tests pass before check in), tagging of incremental releases (the ability to go back to a working release), and pairing of strong team members with weaker team members to boost the overall productivity of the team.  Consider devoting one strong member of the team to integration testing.
Incremental delivery is most important.  Showing a working demo of less than what was asked for is always better than showing a non-working prototype.


q: How to hide the default toolbar and to disallow the default context menu of the DocumentViewer control?

[A]
You can prevent the default context menu from appearing by handling the
```
ContextMenuOpening
```
event, and setting
```
ContextMenuEventArgs.Handled
```
to true.
As for the toolbar, I'm not sure - maybe you could somehow change the default style of the DocumentView to not include the toolbar? I haven't ever done much with styles, but that is probably where I'd start looking.


q:
Is there a cross database platform way to get the primary key of the record you have just inserted?

I noted that this answer says that you can get it by Calling SELECT LAST_INSERT_ID() and I think that you can call SELECT @@IDENTITY AS 'Identity'; is there a common way to do this accross databases in jdbc?

If not how would you suggest I implement this for a piece of code that could access any of SQL Server, MySQL and Oracle?

[A]
Copied from my code:
```
```
pInsertOid = connection.prepareStatement(INSERT_OID_SQL, Statement.RETURN_GENERATED_KEYS);
```
```
where pInsertOid is a prepared statement.
you can then obtain the key:
```
```
// fill in the prepared statement and
pInsertOid.executeUpdate();
ResultSet rs = pInsertOid.getGeneratedKeys();
if (rs.next()) {
  int newId = rs.getInt(1);
  oid.setId(newId);
}
```
```
Hope this gives you a good starting point.


q: I want something that can check if a string is "SELECT", "INSERT", etc.  I'm just curious if this exists.

[A]
why not start with
this stored procedure
and modify it to suit your needs, possibly even convert it to Java using the hashmap as Steve suggested.
Personally I like the idea of a stored procedure because different databases may have different keywords so it seems elegant to have the database pass judgement


q:
Under Windows Server 2003, Enterprise Edition, SP2 (/3GB switch not enabled)

As I understand it, and I may be wrong, the maximum addressable memory for a process is 4GB.

Is that 2GB of private bytes and 2GB of virtual bytes?

Do you get "out of memory" errors when the private byte limit or virtual byte limit is reached?

[A]
Mark Russinovich started a series of posts on this..
Pushing the Limits of Windows: Physical Memory
While 4GB is the licensed limit for 32-bit client SKUs, the effective limit is actually lower and dependent on the system's chipset and connected devices. The reason is that the physical address map includes not only RAM, but device memory as well, and x86 and x64 systems map all device memory below the 4GB address boundary to remain compatible with 32-bit operating systems that don't know how to handle addresses larger than 4GB. If a system has 4GB RAM and devices, like video, audio and network adapters, that implement windows into their device memory that sum to 500MB, 500MB of the 4GB of RAM will reside above the 4GB address boundary.


q:
I'm living in nightmares because of this situation, I have a HttpWebRequest.GetResponse that keeps on giving me a ThreadAbortException, that causes the whole app to go down.

How can I avoid that, or at least handle it, would using Thread.ResetAbort() be useful in such a case?

To explain more here is a rough code sample:

HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://someurl.com/");
HttpWebResponse resp = req.GetResponse();

now the last line above throws the ThreadAbortException, it might be because the request timed out which is fine, but I don't want to get a ThreadAbortException inside my ASP.NET 2.0 app because it kills it. The ThreadAborException can't be caught with try/catch, the only way to handle it is using Thread.ResetAbort() which has its own bad effects too, it will keep the thread alive and god only knows for how long.

[A]
I had this problem with using Response. Check out this article for some workarounds.
http://support.microsoft.com/kb/312629
Also take a look at this MSDN documentation in the section for WebException and Remarks.
http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.getresponse.aspx
This exception can be caught... If you are having trouble detecting the right one, you should try catching a general exception (system.Exception) and from there the stack trace should tell you the specific type (HttpException, WebException, etc) to actually catch.


q: Is it possible using a server side XML parser to have it create an HTML blob that is then included in an existing HTML page?

[A]
Is the existing HTML page already being served by the same server? If so, then yes - arguably that's a rough description of what almost all web frameworks do, to a greater or lesser extent: insert some dynamic content within a static template.
Which bit are you concerned about?


q:
Often times I need a collection of non-sequential objects with numeric identifiers. I like using the KeyedCollection for this, but I think there's a serious drawback. If you use an int for the key, you can no longer access members of the collection by their index (collection[index] is now really collection[key]). Is this a serious enough problem to avoid using the int as the key? What would a preferable alternative be? (maybe int.ToString()?)

I've done this before without any major problems, but recently I hit a nasty snag where XML serialization against a KeyedCollection does not work if the key is an int, due to a bug in .NET.

[A]
It might be best to add a
```
GetById(int)
```
method to a collection type.
```
Collection<T>
```
can be used instead if you don't need any other key for accessing the contained objects:
```
```
public class FooCollection : Collection<Foo>
 { Dictionary<int,Foo> dict = new Dictionary<int,Foo>();

   public Foo GetById(int id) { return dict[id]; }

   public bool Contains(int id) { return  dict.Containskey(id);}

   protected override void InsertItem(Foo f)
    { dict[f.Id] = f;
      base.InsertItem(f);
    }

   protected override void ClearItems()
    { dict.Clear();
      base.ClearItems();
    }

   protected override void RemoveItem(int index)
    { dict.Remove(base.Items[index].Id);
      base.RemoveItem(index);
    }

   protected override void SetItem(int index, Foo item)
    { dict.Remove(base.Items[index].Id);
      dict[item.Id] = item;
      base.SetItem(index, item);
    }
 }

 }
```
```


q:
I am attempting to create a Clipboard stack in C#.  Clipboard data is stored in System.Windows.Forms.DataObject objects. I wanted to store each clipboard entry (IDataObject) directly in a Generic list. Due to the way Bitmaps (seem to be) stored I am thinking I need to perform a deep copy first before I add it to the list.

I attempted to use Binary serialization (see below) to create a deep copy but since System.Windows.Forms.DataObject is not marked as serializable the serialization step fails. Any ideas?

public IDataObject GetClipboardData()
{
    MemoryStream memoryStream = new MemoryStream();
    BinaryFormatter binaryFormatter = new BinaryFormatter();
    binaryFormatter.Serialize(memoryStream, Clipboard.GetDataObject());
    memoryStream.Position = 0;
    return (IDataObject) binaryFormatter.Deserialize(memoryStream);
}

[A]
I wrote the code below for another question and maybe it could come in useful for you in this scenario:
```
```
public static class GhettoSerializer
    {
            // you could make this a factory method if your type
            // has a constructor that appeals to you (i.e. default
            // parameterless constructor)
            public static void Initialize<T>(T instance, IDictionary<string, object> values)
            {
                    var props = typeof(T).GetProperties();

                    // my approach does nothing to handle rare properties with array indexers
                    var matches = props.Join(
                            values,
                            pi => pi.Name,
                            kvp => kvp.Key,
                            (property, kvp) =>
                                    new {
                                            Set = new Action<object,object,object[]>(property.SetValue),
                                            kvp.Value
                                    }
                    );

                    foreach (var match in matches)
                            match.Set(instance, match.Value, null);
            }
            public static IDictionary<string, object> Serialize<T>(T instance)
            {
                    var props = typeof(T).GetProperties();

                    var ret = new Dictionary<string, object>();

                    foreach (var property in props)
                    {
                            if (!property.CanWrite || !property.CanRead)
                                    continue;
                            ret.Add(property.Name, property.GetValue(instance, null));
                    }

                    return ret;
            }
    }
```
```
However I don't think this will be the final solution to your problem though it may give you a place to start.


q:
I'm trying to create a QTVR movie via QTKit, and I've got all the frames in the movie.  However, setting the attributes necessary doesn't seem to be having any effect.  For example:

NSNumber *val = [NSNumber numberWithBool:YES];
[fMovie setAttribute:val forKey:QTMovieIsInteractiveAttribute];

val = [NSNumber numberWithBool:NO];
[fMovie setAttribute:val forKey:QTMovieIsLinearAttribute];

If I then get the value of these attributes, they come up as NO and YES, respectively.  The movie is editable, so I can't understand what I'm doing wrong here.  How can I ensure that the attributes will actually change?

[A]
What I do when I want to export a Quicktime movie is something like the following:
```
```
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithBool:YES], QTMovieExport,
    [exportSettings objectForKey: @"subtype"], QTMovieExportType,
    [exportSettings objectForKey: @"manufacturer"], QTMovieExportManufacturer,
    [exportSettings objectForKey: @"settings"], QTMovieExportSettings,
  nil];

BOOL didSucceed = [movie writeToFile: tmpFileName withAttributes:dictionary error: &error];
```
```


q:
I use Visual Studio to do a lot of my coding. I find the open containing folder feature quite helpful. But I don't want the folder to be "opened" by the windows explorer, instead I want to "explore" the folder -- you know, get the nice little frame showing me all the other folders on the left hand side. Does anyone know how to do this?

Thank you,
Rohit


q: I need to open a Microsoft Word 2003 file and change its file properties.  Such as changing the Subject in the Summary Tab.

[A]
I can think of 2 ways to do this:
Use the Microsoft Office APIs. You
will have to reference them in your
project, and you will need the
Primary Interop Assemblies
.
Convert the file to the Word 2003
XML format and change that value in
the XML document. Here is the MSDN
documentation on the document
properties:
http://msdn.microsoft.com/en-us/library/aa223625(office.11).aspx
I would go with the second option if you can, because that way you don't have to depend on Word being installed on the system.


q: How can I encrypt and decrypt a string in C#?

[A]
Here is an example using RSA.
Important:
There is a limit to the size of data you can encrypt with the RSA encryption,
```
KeySize - MinimumPadding
```
.
e.g. 256 bytes (assuming 2048 bit key) - 42 bytes (min OEAP padding) = 214 bytes (max plaintext size)
Replace your_rsa_key with your RSA key.
```
```
var provider = new System.Security.Cryptography.RSACryptoServiceProvider();
provider.ImportParameters(your_rsa_key);

var encryptedBytes = provider.Encrypt(
    System.Text.Encoding.UTF8.GetBytes("Hello World!"), true);

string decryptedTest = System.Text.Encoding.UTF8.GetString(
    provider.Decrypt(encryptedBytes, true));
```
```
For more info, visit
MSDN - RSACryptoServiceProvider


q:
I'm looking at setting up a small company that hosts flash-based websites for artist portfolios.  The customer control panel would be django-powered, and would provide the interface for uploading their images, managing galleries, selling prints, etc.

Seeing as the majority of traffic to the hosted sites would end up at their top level domain, this would result in only static media hits (the HTML page with the embedded flash movie), I could set up lighttpd or nginx to handle those requests, and pass the django stuff back to apache/mod_whatever.

Seems as if I could set this all up on one box, with the django sites framework keeping each site's admin separate.

I'm not much of a server admin. Are there any gotchas I'm not seeing?

[A]
Maybe. I don't think the built-in admin interface is really designed to corral admins into their own sites. The
```
sites
```
framework is more suited to publish the same content on multiple sites, not to constrain users to one site or another. You'd be better off writing your own admin interface that enforces those separations.
As far as serving content goes, it seems like you could serve up a common (static) Flash file that uses a dynamic XML file to fill in content. If you use Django to generate the XML, that would give you the dynamic content you need.