q:
Does anyone have any T4 example Templates (or links to same) that can be used to generate a Webservice?

I'm thinking of the fact that I guess the Webservice is not just the Vb or Cs field but also requires an appropriate asmx file.

I'm really not sure how to achieve this

[A]
Oleg Sych: How to generate multiple outputs from single T4 template
; create another method that generates your asmx - should be pretty simple, as it's one line - and renders it to a file.
T4 Toolbox
also has some methods that are helpful for this.  Oleg Sych's site also has other articles that will guide you through it, particularly these:
T4 Toolbox
Creating a complex code generator


q: Is there a name meaning "not a singleton"?

s: huggingface

c: devops

d: intermediate


q:
How do I get the type of a generic typed class within the class?

An example:

I build a generic typed collection implementing ICollection< T>. Within I have methods like

    public void Add(T item){
        ...
    }

    public void Add(IEnumerable<T> enumItems){
        ...
    }

How can I ask within the method for the given type T?

The reason for my question is: If object is used as T the collection uses Add(object item) instead of Add(IEnumerable<object> enumItems) even if the parameter is IEnumerable. So in the first case it would add the whole enumerable collection as one object instead of multiple objects of the enumerable collection.

So i need something like

if (T is object) {
    // Check for IEnumerable
}

but of course that cannot work in C#. Suggestions?

Thank you very much!

Michael

[A]
You can use:
```
typeof(T)
```
```
```
if (typeof(T) == typeof(object) ) {
    // Check for IEnumerable
}
```
```


q:
I have a comma separated list of strings like the one below.

a,b   ,c ,d, ,      , , ,e, f,g,h  .

I want to write a regular expression that will replace the empty values i.e., strings that contain only white spaces to 'NA'. So the result should be

a,b   ,c ,d,NA,NA,NA,NA,e, f,g,h  .

I tried using ",\s+," to search but it skips the alternate empty strings and results in

a,b   ,c ,d,NA,      ,NA, ,e, f,g,h  .

What's the correct regex to use here ?

[A]
```
(?<=,)\s+(?=,)
```
This is a lookbehind for a comma, then whitespace, then a lookahead for a comma


q:
I keep reading that, in C, using pointer arithmetic is generally faster than subscripting for array access. Is this true even with modern (supposedly-optimizing) compilers?

If so, is this still the case as I begin to move away from learning C into Objective-C and Cocoa on Macs?

Which is the preferred coding style for array access, in both C and Objective-C? Which is considered (by professionals of their respective languages) more legible, more "correct" (for lack of a better term)?

[A]
You need to understand the reason behind this claim. Have you ever questioned yourself why it is faster? Let's compare some code:
```
```
int i;
int a[20];

// Init all values to zero
memset(a, 0, sizeof(a));
for (i = 0; i < 20; i++) {
    printf("Value of %d is %d\n", i, a[i]);
}
```
```
They are all zero, what a surprise :-P The question is, what means
```
a[i]
```
actually in low level machine code? It means
Take the address of
```
a
```
in memory.
Add
```
i
```
times the size of a single item of
```
a
```
to that address (int usually is four bytes).
Fetch the value from that address.
So each time you fetch a value from
```
a
```
, the base address of
```
a
```
is added to the result of the multiplication of
```
i
```
by four. If you just dereference a pointer, step 1. and 2. don't need to be performed, only step 3.
Consider the code below.
```
```
int i;
int a[20];
int * b;

memset(a, 0, sizeof(a));
b = a;
for (i = 0; i < 20; i++) {
    printf("Value of %d is %d\n", i, *b);
    b++;
}
```
```
This code
might
be faster... but even if it is, the difference is tiny. Why might it be faster? "*b" is the same as step 3. of above. However, "b++" is not the same as step 1. and step 2. "b++" will increase the pointer by 4.
(
important for newbies
: running
```
++
```
on a pointer will not increase the
pointer one byte in memory! It will
increase the pointer by as many bytes
in memory as the data it points to is
in size. It points to an
```
int
```
and the
```
int
```
is four bytes on my machine, so b++
increases b by four!)
Okay, but why might it be faster? Because adding four to a pointer is faster than multiplying
```
i
```
by four and adding that to a pointer. You have an addition in either case, but in the second one, you have no multiplication (you avoid the CPU time needed for one multiplication). Considering the speed of modern CPUs, even if the array was 1 mio elements, I wonder if you could really benchmark a difference, though.
That a modern compiler can optimize either one to be equally fast is something you can check by looking at the assembly output it produces. You do so by passing the "-S" option (capital S) to GCC.
Here's the code of first C code (optimization level
```
-Os
```
has been used, which means optimize for code size and speed, but don't do speed optimizations that will increase code size noticeably, unlike
```
-O2
```
and much unlike
```
-O3
```
):
```
```
_main:
    pushl   %ebp
    movl    %esp, %ebp
    pushl   %edi
    pushl   %esi
    pushl   %ebx
    subl    $108, %esp
    call    ___i686.get_pc_thunk.bx
"L00000000001$pb":
    leal    -104(%ebp), %eax
    movl    $80, 8(%esp)
    movl    $0, 4(%esp)
    movl    %eax, (%esp)
    call    L_memset$stub
    xorl    %esi, %esi
    leal    LC0-"L00000000001$pb"(%ebx), %edi
L2:
    movl    -104(%ebp,%esi,4), %eax
    movl    %eax, 8(%esp)
    movl    %esi, 4(%esp)
    movl    %edi, (%esp)
    call    L_printf$stub
    addl    $1, %esi
    cmpl    $20, %esi
    jne L2
    addl    $108, %esp
    popl    %ebx
    popl    %esi
    popl    %edi
    popl    %ebp
    ret
```
```
Same with the second code:
```
```
_main:
    pushl   %ebp
    movl    %esp, %ebp
    pushl   %edi
    pushl   %esi
    pushl   %ebx
    subl    $124, %esp
    call    ___i686.get_pc_thunk.bx
"L00000000001$pb":
    leal    -104(%ebp), %eax
    movl    %eax, -108(%ebp)
    movl    $80, 8(%esp)
    movl    $0, 4(%esp)
    movl    %eax, (%esp)
    call    L_memset$stub
    xorl    %esi, %esi
    leal    LC0-"L00000000001$pb"(%ebx), %edi
L2:
    movl    -108(%ebp), %edx
    movl    (%edx,%esi,4), %eax
    movl    %eax, 8(%esp)
    movl    %esi, 4(%esp)
    movl    %edi, (%esp)
    call    L_printf$stub
    addl    $1, %esi
    cmpl    $20, %esi
    jne L2
    addl    $124, %esp
    popl    %ebx
    popl    %esi
    popl    %edi
    popl    %ebp
    ret
```
```
Well, it's different, that's for sure. The 104 and 108 number difference comes of the variable
```
b
```
(in the first code there was one variable less on stack, now we have one more, changing stack addresses). The real code difference in the
```
for
```
loop is
```
```
movl    -104(%ebp,%esi,4), %eax
```
```
compared to
```
```
movl    -108(%ebp), %edx
movl    (%edx,%esi,4), %eax
```
```
Actually to me it rather looks like the first approach is faster(!), since it issues one CPU machine code to perform all the work (the CPU does it all for us), instead of having two machine codes. On the other hand, the two assembly commands below might have a lower runtime altogether than the one above.
As a closing word, I'd say depending on your compiler and the CPU capabilities (what commands CPUs offer to access memory in what way), the result might be either way. Either one might be faster/slower. You cannot say for sure unless you limit yourself exactly to one compiler (meaning also one version) and one specific CPU. As CPUs can do more and more in a single assembly command (ages ago, a compiler really had to manually fetch the address, multiply
```
i
```
by four and add both together before fetching the value), statements that used to be an absolute truth ages ago are nowadays more and more questionable. Also who knows how CPUs work internally? Above I compare one assembly instructions to two other ones.
I can see that the number of instructions is different and the time such an instruction needs can be different as well. Also how much memory these instructions needs in their machine presentation (they need to be transferred from memory to CPU cache after all) is different. However modern CPUs don't execute instructions the way you feed them. They split big instructions (often referred to as CISC) into small sub-instructions (often referred to as RISC), which also allows them to better optimize program flow for speed internally. In fact, the first, single instruction and the two other instructions below might result in the
same set of sub-instructions
, in which case there is no measurable speed difference whatsoever.
Regarding Objective-C, it is just C with extensions. So everything that holds true for C will hold true for Objective-C as well in terms of pointers and arrays. If you use Objects on the other hand (for example, an
```
NSArray
```
or
```
NSMutableArray
```
), this is a completely different beast. However in that case you must access these arrays with methods anyway, there is no pointer/array access to choose from.


q:
What is the best way to do GUIs in Clojure?

Is there an example of some functional Swing or SWT wrapper?
Or some integration with JavaFX declarative GUI description which could be easily wrapped to s-expressions using some macrology?

Any tutorials?

[A]
From this
page
:
```
```
(import '(javax.swing JFrame JButton JOptionPane)) ;'
(import '(java.awt.event ActionListener))          ;'

(let [frame (JFrame. "Hello Swing")
     button (JButton. "Click Me")]
 (.addActionListener button
   (proxy [ActionListener] []
     (actionPerformed [evt]
       (JOptionPane/showMessageDialog  nil,
          (str "<html>Hello from <b>Clojure</b>. Button "
               (.getActionCommand evt) " clicked.")))))

 (.. frame getContentPane (add button))

 (doto frame
   (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
   .pack
   (.setVisible true)))

print("code sample");
```
```
And, of course, it would be worth looking at the
interoperability
section of clojure's website.


q:
I am trying to get data from my server, used RemoteObject to accomplish it.
When I run the application on my localhost it works great but when iam using it on my server i get a Channel.Security.Error(Security Error accessing URL).

On the server side logs there is a mention about cross domain .
77.127.194.4 - - [23/Oct/2008 21:15:11] "GET /crossdomain.xml HTTP/1.1" 501

Any one encountered the same problem ? any idea ?

[A]
One thing you didn't list, that are used commonly to detect bad crawlers.
Hit speed, good web crawlers will break their hits up so they don't deluge a site with requests.  Bad ones will do one of three things:
hit sequential links one after the other
hit sequential links in some paralell sequence (2 or more at a time.)
hit sequential links at a fixed interval
Also, some offline browsing programs will slurp up a number of pages, I'm not sure what kind of threshold you'd want to use, to start blocking by IP address.
This method will also catch mirroring programs like fmirror or wget.
If the bot randomizes the time interval, you could check to see if the links are traversed in a sequential or depth-first manner, or you can see if the bot is traversing a huge amount of text (as in words to read) in a too-short period of time.  Some sites limit the number of requests per hour, also.
Actually, I heard an idea somewhere, I don't remember where, that if a user gets too much data, in terms of kilobytes, they can be presented with a captcha asking them to prove they aren't a bot.  I've never seen that implemented though.
Update on Hiding Links
As far as hiding links goes, you can put a div under another, with CSS (placing it first in the draw order) and possibly setting the z-order.  A bot could not ignore that, without parsing all your javascript to see if it is a menu.  To some extent, links inside invisible DIV elements also can't be ignored without the bot parsing all the javascript.
Taking that idea to completion, uncalled javascript which could potentially show the hidden elements would possilby fool a subset of javascript parsing bots.  And, it is not a lot of work to implement.


q:
I have an abstract generic class BLL<T> where T : BusinessObject. I need to open an assembly that contains a set of concrete BLL classes, and return the tuples (businessObjectType, concreteBLLType) inside a Dictionary. There is the part of the method I could do until now, but I'm having problems to discover T.

protected override Dictionary<Type, Type> DefineBLLs()
{
   string bllsAssembly = ConfigurationManager.AppSettings["BLLsAssembly"];

   Type[] types = LoadAssembly(bllsAssembly);

   Dictionary<Type, Type> bllsTypes = new Dictionary<Type, Type>();

   foreach (Type type in types)
   {
     if (type.IsSubclassOf(typeof(BLL<>)))
        /* how to know T in the situation below? */
        bllsTypes.Add(??businessObjectType (T)??, type);
   }

   return bllsTypes;
}

[A]
So the concrete classes will be closed rather than generic? Here's a short program which demonstrates what I
think
you're after...
```
```
using System;
using System.Reflection;

public abstract class Base<T>
{
}

public class Concrete : Base<string>
{
}

class Test
{
    static void Main()
    {
        Type type = typeof(Concrete);
        Type baseType = type.BaseType;
        Type typeOfT = baseType.GetGenericArguments()[0]; // Only one arg
        Console.WriteLine(typeOfT.Name); // Prints String
    }
}
```
```
Note that here I'm
assuming
that we only need to go up one level to get to the appropriate base type, and that the concrete class
will
be closed. You'd want to put more checks into your real code, of course, but I suspect it was the call to
GetGenericArguments
that you were missing.


q:
I'm writing a C Shell program that will be doing su or sudo or ssh. They all want their passwords in console input (the TTY) rather than stdin or the command line.

Does anybody know a solution?

Setting up password-less sudo is not an option.

expect could be an option, but it's not present on my stripped-down system.

[A]
Take a look at
```
expect
```
linux utility.
It allows you to send output to stdio based on simple pattern matching on stdin.


q:
I have 3 divs where only one is visible by default, they each contain information about a product. Below this divs is a list of 3 images which are images of the products. By default of course the 1st list item is selected and has class="selected". When a different product image is clicks then class="selected" moves to that list item and the div above it changes to hidden and the div containing the other product information needs to appear.

I have searched all over the place for a plugin which can do what I want, they are all limited in some way which stops me doing from doing it.

[A]
Consider the following code:
```
```

description 1

description 2

description 3

```
```
This should get you pretty close.  You need to define the relationship between your images and divs...  so I added a 'desc' attribute to the images.  The extra 'prodImg' class on the images allows you to ensure that only those images are being wired up for this type of swap in and out behavior.


q:
In all honesty, I think the answer is "no;" however, I want to get a second opinion. Basically, I need one micro-controller device to send a steady signal to another one, but the communicate between them is using RS232. So I think that I have to create/update the communication messages to get it to do what I want.

What do you think?

[A]
You should be able to set something like DTR (Data Terminal Ready), pin 20, or DSR (Data Set Ready), pin 6, high and keep it there as your steady-state signal. This is how modems/terminals detect that there is a device on the other end that is ready to communicate.  It all depends on what level of access you have to the hardware through your driver.
[EDIT] This doesn't involve sending data, although you could still do that using TX/RX, pins 2 & 3.
RS-232 Reference
on wikipedia


q: Since many years a GUI-standard are the menu-bars of applications with menus popping up, if you click or hover an entry in the menu-bar. Some websites implement this feature too, but they are using Javascript, as far as  I can see. For different reasons Javascript can be a problem, so the question: Is this possible to implement without Javascript, only using HTML and CSS?

[A]
You can use the pseudoclass :hover to get an hover effect.
```
```
a:link {
 color: blue;
}

a:hover {
  color: red;
}
```
```
I can give a more extensive example but not right now (need to get the kids to the dentist).


q:
I have created a .NET DLL which makes some methods COM visible.

One method is problematic. It looks like this:

bool Foo(byte[] a, ref byte[] b, string c, ref string d)

VB6 gives a compile error when I attempt to call the method:

Function or interface marked as
  restricted, or the function uses an
  Automation type not supported in
  Visual Basic.

I read that array parameters must be passed by reference, so I altered the first parameter in the signature:

bool Foo(ref byte[] a, ref byte[] b, string c, ref string d)

VB6 still gives the same compile error.

How might I alter the signature to be compatible with VB6?

[A]
Try
```
```
[ComVisible(true)]
bool Foo([In] ref byte[] a, [In] ref byte[] b, string c, ref string d)
```
```


q:
I'm running Python 2.6 on Unix and when I run the interactive prompt (SQLite is supposed to be preinstalled) I get:

[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>

How do I resolve this?

[A]
```
```
import sqlite3
```
```
sqlite3
- DB-API 2.0 interface for SQLite databases.
You are missing the
```
.so
```
(shared object) - probably an installation step. In my Linux python installation,
```
_sqlite3
```
is at:
```
```
${somewhere}/lib/python2.6/lib-dynload/_sqlite3.so
```
```


q: I want to print the full length of a C-string in GDB.  By default it's being abbreviated, how do I force GDB to print the whole string?

[A]
```
```
set print elements 0
```
```
From the GDB manual
:
```
set print elements
```
```
number-of-elements
```
Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the
```
set print elements
```
command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200.
Setting
number-of-elements
to zero means that the printing is unlimited
.


q: So what is the easiest way to accomplish this?

[A]
Path of least resistance is to download
Tortoise
, which supports this out of the box.
From their features page:
Can create a graph of
  all revisions/commits. You can then
  easily see where you created a
  tag/branch or modified a file/folder
  Graphs of commit statistics of the
  project Easy comparing of two branches
  or tags


q: I have to override Add method of "Controls" property of myControl that is extended from a Panel control of windows. For that i extended ControlCollection class into MyControlCollection where i overriden its Add method. Now i declared a Controls property of MyControlCollection type to hide panel's Controls property. When i am accessing this.Controls.Add(control), it refers to overriden Add method. But if i drags and drops a control on myControl the behaviour is of base type's Add method. Can any body suggest the cause and remedy for this problem? Thanks in advance.

[A]
The cause is that the designer is calling Control.Controls rather than accessing your separate collection. To be honest, your solution sounds like it's destined to cause trouble - hiding members usually does.
What are you trying to achieve, exactly? It doesn't look like there's a nice event to hook into in
```
ControlCollection
```
but there may be a different way of tackling the problem.
EDIT: I've just seen that
```
Control
```
has a
```
ControlAdded
```
event - would subscribing to that be enough for you?


q: Is it possible to enable a second monitor programatically and extend the Windows Desktop onto it in C#? It needs to do the equivalent of turning on the checkbox in the image below.

[A]
I don't have the full answer here but I am almost sure that you will have to call out of .Net to do this.  You will have to use Pinvoke to call an unmanaged dll.  A great resource for this is pinvoke.net.
I did a quick search and found
http://www.pinvoke.net/default.aspx/user32/ChangeDisplaySettings.html
which probably isn't exactly what you want but you will probably find it somewhere on pinvoke.net


q:
I am trying to make our SQL Server Integration Services packages as portable as possible and the one thing that is preventing that is that the path to the config is always an absolute path, which makes testing and deployment a headache. Are there any suggestions for making this more manageble?

Another issue is when another developer gets the package out of source control the path is specific to the developers machine.

[A]
If you are trying to execute your packages using Visual Studio then the configuration file path will be hardcoded in there. So if you move your project around you'll need to change the path in the package settings. To avoid this you could use the Environment variable option to store the configuration file path. Then you'll only need to change that.
For testing and deployment however you should probably use the dtexec utility to execute your packages. Make some batch files for that. Preferably one for each different environment. Here the configuration file path can be relative.
```
```
dtexec /File Package.dtsx /Conf configuration.dtsConfig
```
```
This is if you're packages are on file system. You can also store them in SQL Server. You can also store your configuration in SQL Server which may provide flexibility.


q: I need to display a small (15x15 pixel) animation in a Flex app.  I have it FLV format, but it could be converted to somthing else.  I'd prefer to have the file embedded in the app (it's only 8k in size).  I've seen posts about displaying animated GIFs using third-party code which would be OK, but is there a way to do this with the native Flex libs.  I also realize that FLVs can be displayed in Video objects but only if they are external files.

[A]
It is a lot easier converting it into a SWF and displaying it in an
```
Image
```
control.
SWFTools
can convert animated GIF into SWF file, small enough to be embedded in your app.


q: I'm trying to write a small app that monitors how much power is left in a notebook battery and I'd like to know which Win32 function I could use to accomplish that.

[A]
For Vista and up you can use
RegisterPowerSettingNotification
For earlier functions see the
Power Management Functions
in this section of the MSDN page "Power Management Functions: Windows Server 2003 and Earlier"
You can see example code of the Vista method on
codeproject
.


q:
I have a number of custom controls that I am trying to enable designer support for. The signature looks something like the following:

[ToolboxData("<{0}:MyDropDownList runat=\"server\" CustomProp="123"></{0}:MyDropDownList>")]
public class MyDropDownList: DropDownList
{
   ... code here
}

This works fine, but when I drag a control onto the page from the toolbox, the TagPrefix that gets added is "cc1":

<%@ Register Assembly="DBMClientPortal.Controls" Namespace="DBMClientPortal.Controls"
    TagPrefix="cc1" %>

Obviously it is somewhat irrelevant what that TagPrefix is... it works as it stands, but I figured I must be able to change it somehow and curiosity got the better of me...

Anyone know how to define what the TagPrefix will be set to when dragging a custom control onto a page in visual studio?

Thanks,
Max

[A]
It looks something like this:
```
```
[assembly:TagPrefix("MyControls","RequiredTextBox")]
```
```
and
here's
some more info about it.


q:
I'm writing tests for a business method that invokes some DAO classes to perform operations over a database.

This method, firstly retrieves a JDBC connection from a DataSource object, The same connection is passed to all DAO instances, so I can use it to control the transaction. So, if everything works properly, I must invoke commit() over the connection object.

I would like to test if the commit() is invoked, so I've thought to create an expectation (I'm using JMock) that checks that. But since the Connection class isn't a direct neighbour from my Business class, I don't know how to do this.

Someone knows how to overcome this? There is some JMock facility for this, or some alternative design that allows to overcome this?

Thanks

[A]
You need to mock
```
DataSource
```
and
```
Connection
```
so that your mock
```
DataSource
```
returns your mock
```
Connection
```
. And yes, this kind of thing ends up becoming a real pain...


q:
I need to access a network resource on which only a given Domain Account has access.
I am using the LogonUser call, but get a "User does not have required priviliege" exception, as the web application is running with the asp.net account and it does not have adequate permissions to make this call.

Is there a way to get around it?
Changing the identity or permissions of the ASP.Net account is not an option as this is a production machine with many projects running.
Is there a better way to achieve this?

Using Asp.Net 2.0, Forms Authentication.

Kind Regards.

[A]
You could add an
```
```
<identity impersonate="true" userName=""/>
```
```
tag to your web.config but that might not be ideal as you probably don't want to run the entire site as that user...
Can you map the network share as a local drive with the DomainName & Password... and then pull files to the website via the mapped drive ?
```
```
NET USE Z: \\SERVER\Share password /USER:DOMAIN\Username /PERSISTENT:YES
```
```


q:
I have a very simple jQuery Datepicker calendar:

$(document).ready(function(){
    $("#date_pretty").datepicker({
    });
});

and of course in the HTML...

<input type="text" size="10" value="" id="date_pretty"/>

Today's date is nicely highlighted for the user when they bring up the calendar, but how do I get jQuery to pre-populate the textbox itself with today's date on page load, without the user doing anything?  99% of the time, the today's date default will be what they want.

[A]
```
```
var myDate = new Date();
var prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +
        myDate.getFullYear();
$("#date_pretty").val(prettyDate);
```
```
seemed to work, but there might be a better way out there..


q:
What is the best practice for writing a rather large wcf service, containing a lot of OperationContracts and DataContracts?

How would I separate functional areas into several contracts, would it be best to create an endpoint for each functional area?

Is there any way to keep the source for the different parts apart, but still use only one service for all of them?

Where do I get good information how to plan the contracts, what to include, how to split...?

[A]
That's been a big question surrounding services since their inception. SOA done successfully is SOA planned to the extent you're talking about. Having said that, I've always leaned more toward splitting services out, but using them in a composite manner. That is, several endpoints when you have several contracts, but most of them are only consumed by a few endpoints that are consumed by non-service callers. (wow, that was a mouthful, did it even make sense?)
Also, I would advise to have as few contracts as possible. Too many contracts can lead to poor manageability. Good contract design will help limit the number of endpoints and service calls. Removing OO concepts from contract design is one way of doing so. Contract design is a massive topic in itself, but suffice it to say that through good contract planning (up front), comes good service design.
Maarten Mullender
writes a great blog
on WCF design, and is a must read. There are also some great SOA/WCF books emerging as well.
Some good books:
Pro WCF: Practical Microsoft SOA Implementation
Programming WCF


q:
I have heard that closures could be introduced in the next Java standard that is scheduled to be released somewhere around next summer.

What would this syntax look like?

I read somewhere that introducing closures in java is a bigger change than generic was in java 5. Is this true? pros and cons?

(By now we definitely know that closures not will be included in the next Java release)

OR

edit: http://puredanger.com/tech/2009/11/18/closures-after-all/ :D

edit2: Re-thinking JDK7: http://blogs.oracle.com/mr/entry/rethinking_jdk7

edit3: There’s not a moment to lose!: http://blogs.oracle.com/mr/entry/quartet

[A]
Have a look at
http://www.javac.info/
.
It seems like this is how it would look:
```
```
boolean even = { int x => x % 2 == 0 }.invoke(15);
```
```
where the
```
{ int x => x % 2 == 0 }
```
bit is the closure.


q: Does Eclipse have a feature that lets you search a project to find all calls to deprecated methods?

[A]
You can set the compiler to generate errors or warnings (your choice) for any usage of deprecated API.
Preferences -> Java -> Compiler -> Errors/Warnings ->
Deprecated and restricted API
section.
Then, each use of a deprecated method or API will show up as an error/warning in the Problems view.


q: In my experience it seems that most people will tell you that it is unwise to force a garbage collection but in some cases where you are working with large objects that don't always get collected in the 0 generation but where memory is an issue, is it ok to force the collect?  Is there a best practice out there for doing so?

[A]
I've learned to not try to outsmart the garbage collection.  With that said, I just stick to using
```
using
```
keyword when dealing with unmanaged resources like file I/O or database connections.


q:
All the PHP files in my workspace are encoded in Unicode (UTF-8, no BOM). I often duplicate an existing source file to use as a base for a new script. Invariably (with Path Finder or the original Finder), OS X will convert the encoding of the duplicate file to Western (Mac OS Roman).

Is there any way to make OS X behave and not convert the text encoding when duplicating a text file? Or make it use a specific text encoding (other than Western!) by default for all files with .php extension?

[A]
I highly doubt that the "conversion" you're seeing is an actual difference in the two copies of the file.  OS X doesn't store any sort of encoding value for a file's content, so it's much more likely that it's whatever tool you're using to view/edit your files that's interpreting the content differently, whether it be Xcode, TextWrangler, or whatever other editor you're using.  Doing a straight copy of the file, whether it be from the Finder, Path Finder, or the command line, won't ever change the actual data in the file in the process of copying.
UTF-8 and Mac OS Roman are actually the same if you don't have any characters above 0x7f, so it's very possible that a valid UTF-8 file with no BOM could be interpreted as a Mac OS Roman file.  In any case, I would look into whatever program it is that's showing you that encoding to find the solution, not the file copying procedure of OS X itself.


q:
Ok

I'm working on a little project at the moment, the Report expects an int but the ReportParameter class only lets me have a value that's a string or a string[]

How can I pass an int?

thanks

dan

[A]
You can call the method
```
GetReportParameters()
```
which will return a
```
ReportParameter[]
```
array. If you iterate through each parameter and look at its Type property it will indicate if it is an
```
int
```
. The Type property is an
```
enum
```
of type
```
ParameterTypeEnum
```
and would be
```
ParameterTypeEnum.Integer
```
for an
```
int
```
.


q:
I had a VBA project in outlook with a few email macros - but after a PC crash they are all gone and all I see is a fresh 'Project1' when I hit Alt+F11

I'm not a VBA programmer, but had a collection of handy macros for email sorting etc. I would not like to have to code them again. Anyone know where the code files should be on the filesystem so that I might rescue the code?

[A]
This page
has some really good insight on where Outlook keeps all its stuff. It suggests the following:
All Outlook macros are stored in a single file named VbaProject.otm in the user's %appdata%\Microsoft\Outlook folder, which will be a hidden folder on most systems.
Now, the problem is that if you do not see them now, then you probably won't be able to restore them from that location: there is probably either an "empty" project there or no project at all, but if that folder is being backed up, you might be able to restore it.
Moving forward, you might consider exporting your macros periodically in case this happens again, either through the VBA IDE (right-click and select Export File...) or using one of the tools mentioned in the linked article (like the
Office Profile Wizard
).


q:
i have a data access layer which returns data from stored procedures. If i bind this to a gridview control in asp.net 2.0, the users then have an option of filtering on that data select list where in they can choose the conditional clause of

like

=

or

and

Once the result is returned, I do not want to hit the Db again with the filters applied.

I have an option to use .net 3.5 if the need be. i looked at this:
http://weblogs.asp.net/jgaylord/archive/2006/05/31/Filter-A-GridView-After-The-Initial-Bind.aspx

and not sure of its efficiency.


q:
I use an anonymous object to pass my Html Attributes to some helper methods.
If the consumer didn't add an ID attribute, I want to add it in my helper method.

How can I add an attribute to this anonymous object?

[A]
I assume you mean anonymous types here, e.g.
```
new { Name1=value1, Name2=value2}
```
etc. If so, you're out of luck - anonymous types are normal types in that they're fixed, compiled code. They just happen to be autogenerated.
What you
could
do is write
```
new { old.Name1, old.Name2, ID=myId }
```
but I don't know if that's really what you want. Some more details on the situation (including code samples) would be ideal.
Alternatively, you could create a container object which
always
had an ID and whatever other object contained the rest of the properties.


q:
This question is about App domains and Sessions. Is it possible to have IIS run each User Session in a seperate App Domain. If Yes, Could you please let me settings in the config file that affect this.

Regards,
Anil.


q: I was wondering if the C# project setting "Allow unsafe code" applies only to unsafe C# code in  the project itself, or is it necessary to set this option when linking in a native C++ DLL? What about linking in a managed DLL that itself links to a native DLL? What does this option really do, under the hood?

[A]
It allows you to use the "unsafe" block.
```
```
unsafe(...)
{
}
```
```


q:
I am trying to detect Blackberry user agents in my app, which works fine in my development version. But nothing happens when I redeploy the app in production.

application_helper.rb

  def blackberry_user_agent?
    request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(Blackberry)/]
  end

application.html.erb

<% if blackberry_user_agent? -%>
<div class="message">
<p>Using a Blackberry? <a href="http://mobile.site.ca/">Use the mobile optimized version</a>.</p>
</div>

I've tried clearing the cache using rake tmp:cache:clear and restarted mongrel a few times. Apparently the HTTP_USER_AGENT is coming back nil in production. I am using Nginx with a mongrel cluster.

[A]
Are you using Apache or nginx in front of your mongrel(s)?
Are you logging the user_agent? This is from my nginx.conf:
```
```
log_format main '$remote_addr - $remote_user [$time_local] $request '
                  '"$status" $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "http_x_forwarded_for"';
```
```


q:
I would like to create a link between a winMo device and a server, so that they can pass information back and forth to each other. I actually don't really know where to start, I've had SOAP, RPC and creating a TCP link suggested to me. If someone could provide a link to an example that would be great.

Thanks!

Thanks for the responses. Updates:

It's not critical that the server initiate the communications, I could have the mobile device poll the server

timing is not ultra critical

I would prefer that it uses some open standard, if I wanted to also communicate with a palm device as well for example.

I had the idea that webservices were one way, unless the mobile device runs a server also?!

[A]
Your best bet is to set up an ASP.NET web service on the server, and then have your PDA application talk to it.
You can also use the web service to talk back to the PDA.  Essentially, the PDA has to initially call the web service and pass in a delegate method that the server then calls when it needs to talk to the PDA.  I do not recommend this latter method, especially in an environment where the PDA is not continuously connected to the network.  It's usually better to have the PDA initiate each contact with the server.


q:
Let's say you have a aspx page that does not rely on session, but does rely on viewstate for persistance between postbacks.

If a user is accessing this page, and leaves for a long lunch, will viewstate still be valid when he returns?

[A]
No ViewState is kept as part of the PostBack process.  You can, however,
override
the Page class's  SavePageStateToPersistenceMedium() and LoadPageStateFromPersistenceMedium(), to implement that behavior if desired.  For more information read
Understanding the ASP.NET ViewState
.
Note that
Page
ViewState is stored in the Session so if your Session expires, the ViewState will be lost.  I wouldn't say this is ViewState expiring, but yes, it will be destroyed after Session timeout.


q:
What are the best algorithms (and explanations) for representing and rotating the pieces of a tetris game?  I always find the piece rotation and representation schemes confusing.

Most tetris games seem to use a naive "remake the array of blocks" at each rotation:

http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=tetris

However, some use pre-built encoded numbers and bit shifting to represent each piece:

http://www.codeplex.com/wintris

Is there a method to do this using mathematics (not sure that would work on a cell based board)?

[A]
There is a limited amount of shapes, so I would use a fixed table and no calculation. That saves time.
But there are rotation algorithms.
Chose a centerpoint and rotate pi/2.
If a block of a piece starts at (1,2) it moves clockwise to (2,-1) and (-1,-2) and (-1, 2).
Apply this for each block and the piece is rotated.
Each x is the previous y and each y - the previous x. Which gives the following matrix:
```
```
[  0   1 ]
[ -1   0 ]
```
```
For counterclockwise rotation, use:
```
```
[  0  -1 ]
[  1   0 ]
```
```


q:
I know the statement:

create table xyz_new as select * from xyz;

Which copies the structure and the data, but what if I just want the structure?

[A]
Using sql developer select the table and click on the DDL tab
You can use that code to create a new table with no data when you run it in a sql worksheet
sqldeveloper is a free to use app from oracle.
If the table has sequences or triggers the ddl will sometimes generate those for you too. You just have to be careful what order you make them in and know when to turn the triggers on or off.


q:
The Microsoft unit testing framework has suddenly gone on strike.

When I try to run tests in VS2008, I get a dialog with the message "VSTestHost.exe has stopped working".

I have Visual Studio Team System 2008 (version 9.0.30729.1 SP) running on Vista with all updates applied.

The "Problem reports and solutions" suggests that I "Upgrade to the latest retail version of Visual Studio Team Edition for Software Testers" which is not right.

I have tried rebooting.

I have tried "devenv /resetuserdata"

These made no difference.

I'd like to go back to MbUnit based on this nonsense, but that's not my choice.

Any suggestions on how to fix this?

[A]
I have found the issue that I was asking about, and it was my fault. I had coded a stack overflow: I refactored some code into an extension method, renamed it to match the Linq extension method that it called, and so  it just called it self recursively.
The lessons to learn from this:
1:
"select" isn't broken
.
I was too quick to blame the framework, due to its bad reputation.
2:
But it did have a pathologically general and entirely misleading error message.
In cases where the error message is that bad, a good debugging technique is to try to pin down what does and what doesn't cause the error. In my case, the breakthrough came as soon as I noticed that it wasn't "the test run" that was failing, it was only runs containing Sql database tests - domain object and mock repository test could run just fine, so there had to be something about the code that it was running. And that the debugger would step into the tests. I had assumed from the calamitous errors that it wasn't even getting that far.


q: Is there a way to create a blank solution, or some type of file-based project solution within Visual Studio so that I can point to a root folder, and have all of the sub-folders and files in that root, show up in my solution explorer? I realize I can create a blank solution and then add the individual items manually by add > existing item, however, this does not keep the folder structure intact, and, well, it would take forever if I have a lot of folders/files.

[A]
You can also create the blank solution and then click the second-from-the-right icon at the top of the solution explorer (it looks like three files with one "cut out").  Once you click that button to show the files in the solution directory that are not in a project, you can select all the files (with shift-click) and then right-click on your selection and select "Include In Project."
Also note you can select multiple files in the "Add Existing..." file window with shift- or control-click.


q:
Im currently using ie as an active x com thing on wxWidgets and was wanting to know if there is any easy way to change the user agent that will always work.

Atm im changing the header but this only works when i manually load the link (i.e. call setUrl)

[A]
The only way that will "always work," so far as I've been able to find, is
changing the user-agent string in the registry
. That will, of course, affect
every
web browser instance running on that machine.
You might also try a Google search on
```
DISPID_AMBIENT_USERAGENT
```
. From
this Microsoft page
:
MSHTML will also ask for a new user
  agent via
```
DISPID_AMBIENT_USERAGENT
```
when navigating to clicked hyperlinks.
  This ambient property can be
  overridden, but it is not used when
  programmatically calling the Navigate
  method; it will also not cause the
  userAgent property of the DOM's
  navigator object or clientInformation
  behavior to be altered - this property
  will always reflect Internet
  Explorer's own UserAgent string.
I'm not familiar with the MSHTML component, so I'm not certain that's helpful.
I hope that at least gives you a place to start. :-)


q:
I have a WinForms app with an input textbox, button, and a multiline output textbox.
A root path is entered in the textbox.  Button click calls a function to recursively check all subdirectories for some proper directory naming validation check.
The results are output into the multiline textbox.

If the recursive work is done in a separate class, I have two options:

Keep track of improper directories in a class property(e.g. ArrayList),return the ArrayList when done, and update the output textbox with all results.

Pass in ByRef the output textbox and update/refresh it for each improper directory.
Even though 1 & 2 are single-threaded, with 2, I would at least get my results updated per directory.

If the recursive work is done in the presentation layer and the validation is done in a separate class, I can multithread.

Which is a cleaner way?

[A]
You don't need to pass the TextBox ByRef.  It's already a reference object.  Passing it ByRef would only have an effect if you planned to assign a different or new TextBox to the reference.
If you're going to do the work in a separate class, it seems as simple as passing in the contents of the TextBox as a string, and getting the results back as a string or a set of strings (array or
```
List<string>
```
or the like).  This is better than passing in the TextBox in case someday you decide to use a different kind of control to store this information.


q:
What are my validation options with .net mvc?

Do any of them have a nice validation summary like webforms did?

[A]
You can use a MVC html validation summary,see this blog
http://blog.maartenballiauw.be/post/2008/08/29/Form-validation-with-ASPNET-MVC-preview-5.aspx


q: Does anyone know if there is a debug visualiser for this yet along the same lines and the linq to SQL debug visualiser?

[A]
There isn't one that I'm aware of at the moment (hope to be shown otherwise by other answers here), but Julie Lerman has a post
"An extension method for visualizing ObjectStateEntries"
where she walks through creating a debug tool that pops up a WinForm for inspecting the state of entities via their EntityKey.
Not quite a visualizer, but seriously handy when you need to tease apart ObjectStateEntries to debug change tracking scenarios.


q:
I need to create at runtime instances of a class that uses generics, like class<T>, without knowing previously the type T they will have, I would like to do something like that:

public Dictionary<Type, object> GenerateLists(List<Type> types)
{
    Dictionary<Type, object> lists = new Dictionary<Type, object>();

    foreach (Type type in types)
    {
        lists.Add(type, new List<type>()); /* this new List<type>() doesn't work */
    }

    return lists;
}

...but I can't. I think it is not possible to write in C# inside the generic brackets a type variable. Is there another way to do it?

[A]
You can't do it like that - the point of generics is mostly
compile-time
type-safety - but you can do it with reflection:
```
```
public Dictionary<Type, object> GenerateLists(List<Type> types)
{
    Dictionary<Type, object> lists = new Dictionary<Type, object>();

    foreach (Type type in types)
    {
        Type genericList = typeof(List<>).MakeGenericType(type);
        lists.Add(type, Activator.CreateInstance(genericList));
    }

    return lists;
}
```
```


q: How can I find the index in a string that matches a boost regex?

[A]
Use the
```
position
```
member function of the
```
match_results
```
:
```
```
int find_match_offset(std::string const& string_to_search,
                      boost::regex const& expression)
{
    boost::smatch results;
    if(boost::regex_match(string_to_search,results,expression))
    {
        return results.position()
    }
    return -1;
}
```
```


q:
Anyone got a ready made function that will take an XML string and return a correctly indented string?

eg

<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>

and will return nicely formatted String in return after inserting linebreaks and tabs or spaces?

[A]
Using
OmniXML
:
```
```
program TestIndentXML;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  OmniXML,
  OmniXMLUtils;

function IndentXML(const xml: string): string;
var
  xmlDoc: IXMLDocument;
begin
  Result := '';
  xmlDoc := CreateXMLDoc;
  if not XMLLoadFromAnsiString(xmlDoc, xml) then
    Exit;
  Result := XMLSaveToAnsiString(xmlDoc, ofIndent);
end;

begin
  Writeln(IndentXML('<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>'));
  Readln;
end.
```
```
The code fragment above is released to public domain.


q:
How do I pass a parameter from a page's useBean in JSP to a servlet in Java? I have some data in a form that gets passed no problem with a submit button, but no way to send anything else. Please help? Here is my code:

<input name = "deleteGameButton" type = "submit" value = "Delete"
 onclick = "submitToServlet('DeleteGameServlet');">

Here is the corresponding javascript:

 function submitToServlet(newAction)
 {
   document.userGameForm.action = newAction;
 }

I'd like the servlet to have access to userBean

 <jsp:useBean id = "userBean" scope = "session" class = "org.project.User" />

[A]
You kind of mess things here.
onclick() is Javascript and executed on client side. It has no (direct) way to update session-scoped bean. That bean is left on server-side, and was used when the HTML page was
generated
. To pass parameters back to servlet you need to use good old form fields, and submit the form.
Add more fields to the form, set their values before submit, then submit.
In Servlet call request.getParameter("name");
P.S. To automate this kind of things
USE STRUTS
. :-) Struts does exactly what you want: before passing the parameters to action, it populates the bean with those parameters. Transparently.


q: I have a string containing a date, and another string containing the date format of the first string. Is there a function that I can call to convert that date into something like a SYSTEMTIME structure? Basically, I'd like the opposite of GetDateFormat().

[A]
No, but you can write a function that will convert the date format string into a
```
sscanf
```
format string and series of variables.  Then copy the data from the variables to the
```
SYSTEMTIME
```
structure and you're all set.
It's not trivial, but it is probably the most flexible arrangement if you must support many different date formats.


q:
I am creating a WordML document from an xml file whose elements sometimes contain html-formatted text.

<w:p>
  <w:r>
    <w:t> html formatted content is in here taken from xml file! </w:t>
  </w:r>
</w:p>

This is how my templates are sort of set up.  I have a recursive call-template function that does text replacement against the source xml content.  When it comes across a "<b>" tag, I output a string in CDATA containing "</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>" to close the current run and start up a new run with bold formatting enabled.  when it gets to a "</b>" tag, it replaces it with the following CDATA string "</w:t></w:r><w:r><w:t>".

What I'd like to do is use XSL to close the run tag and start a new run without using CDATA string inserts.  Is this possible?

[A]
I can most probably help you if only I understood your problem... Is the html in a CDATA section or is it parsed as part of the input doc (and thus well-formed XML)?
Since you talk about 'text replacement' I'll assume that you treat the 'html formatted content' as a single string (CDATA) and therefor need a recursive call-template function to perform string replacement. The only way you're going to be able to use an XSL matching template to do what you're doing now is to make the html part of the parsed document (your input document). In such a case you could just match the
```
b
```
tag and replace it with the appropriate output (again: this assumes that it can always be parsed as valid XML). Your problem now has shifted... since (if I understood your problem correctly) what you're trying to do is close the
```
w:t
```
and
```
w:r
```
elements and then 'reopen' them... this is hard because it's (as you probably suspect) very hard to do this nicely in XSLT (you cannot just create an element in template A and then close it in template B). You'll have to start messing with unescaped output etc. to make this happen. I now I've made a lot of assumptions but here is a small example to help you on your way:
input.xml
```
```
<doc xmlns:w="urn:schemas-microsoft-com:office:word">
<w:p>
  <w:r>
    <w:t>before<b>bold</b>after</w:t>
  </w:r>
</w:p>
</doc>
```
```
convert_html.xsl
```
```
<xsl:template match="@*|node()">
  <xsl:copy>
    <xsl:apply-templates select="@*|node()"/>
  </xsl:copy>
</xsl:template>

<xsl:template match="/doc/w:p/w:r/w:t//b">
  <xsl:value-of select="'</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>'" disable-output-escaping="yes" />
  <xsl:apply-templates select="@*|node()"/>
  <xsl:value-of select="'</w:t></w:r><w:r><w:t>'" disable-output-escaping="yes" />
</xsl:template>
```
```
Now running
```
```
xalan input.xml convert_html.xsl
```
```
produces
```
```
<?xml version="1.0" encoding="UTF-8"?><doc xmlns:w="urn:schemas-microsoft-com:office:word">
<w:p>
  <w:r>
    <w:t>before</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>bold</w:t></w:r><w:r><w:t>after</w:t>
  </w:r>
</w:p>
</doc>
```
```
which I guess is what you wanted.
Hope this helps you somewhat.


q:
How do you create an application shortcut (.lnk file) in C# or using the .NET framework?

The result would be a .lnk file to the specified application or URL.

[A]
It's not as simple as I'd have liked, but there is a great class call
ShellLink.cs
at
vbAccelerator
This code uses interop, but does not rely on WSH.
Using this class, the code to create the shortcut is:
```
```
private static void configStep_addShortcutToStartupGroup()
{
    using (ShellLink shortcut = new ShellLink())
    {
        shortcut.Target = Application.ExecutablePath;
        shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
        shortcut.Description = "My Shorcut Name Here";
        shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
        shortcut.Save(STARTUP_SHORTCUT_FILEPATH);
    }
}
```
```


q: Are pipes considered dangerous to use in Windows, from a security standpoint?

[A] If you are concerned about network sniffing, I suppose they could be since I don't think that pipes between systems are encrypted.  I don't know exactly how they are implemented in Windows, but I would expect that pipes between processes/threads on the same machine would be implemented with shared memory and not let traffic leak outside the box.  If you need secure communication between systems, I'd go with secure sockets.


q:
Possible Duplicate:

  Reference: Comparing PHP's print and echo

Is there any major and fundamental difference between these two functions in PHP?

[A]
From:
http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40
Speed.  There is a difference between the two, but speed-wise it
should be irrelevant which one you use.  echo is marginally faster
since it doesn't set a return value if you really want to get down to the
nitty gritty.
Expression.
```
print()
```
behaves like a function in that you can do:
```
$ret = print "Hello World"
```
; And
```
$ret
```
will be
```
1
```
.  That means that print
can be used as part of a more complex expression where echo cannot.  An
example from the PHP Manual:
```
```
$b ? print "true" : print "false";
```
```
print is also part of the precedence table which it needs to be if it
is to be used within a complex expression. It is just about at the bottom
of the precedence list though.  Only
```
,
```
```
AND
```
```
OR
```
```
XOR
```
are lower.
Parameter(s).  The grammar is:
```
echo expression [, expression[,
expression] ... ]
```
But
```
echo ( expression, expression )
```
is not valid.
This would be valid:
```
echo ("howdy"),("partner")
```
; the same as:
```
echo
"howdy","partner"
```
; (Putting the brackets in that simple example
serves
no purpose since there is no operator precedence issue with a single
term like that.)
So, echo without parentheses can take multiple parameters, which get
concatenated:
```
```
echo  "and a ", 1, 2, 3;   // comma-separated without parentheses
   echo ("and a 123");        // just one parameter with parentheses
```
```
```
print()
```
can only take one parameter:
```
```
print ("and a 123");
   print  "and a 123";
```
```


q:
I'm trying to come up with a Java regex that will match a filename only if it has a valid extension. For example it should match "foo.bar" and "foo.b", but neither "foo." nor "foo".

I've written the following test program

public static void main(String[] args) {
  Pattern fileExtensionPattern = Pattern.compile("\\.\\w+\\z");

  boolean one = fileExtensionPattern.matcher("foo.bar").matches();
  boolean two = fileExtensionPattern.matcher("foo.b").matches();
  boolean three = fileExtensionPattern.matcher("foo.").matches();
  boolean four = fileExtensionPattern.matcher("foo").matches();

  System.out.println(one + " " + two + " " + three + " " + four);
}

I expect this to print "true true false false", but instead it prints false for all 4 cases. Where am I going wrong?

Cheers,
Don

[A]
The
Matcher.matches()
function tries to match the pattern against the entire input.  Thus, you have to add
```
.*
```
to the beginning of your regex (and the
```
\\Z
```
at the end is superfluous, too), or use the
find()
method.


q:
I'm using Chris Pederick's Firefox addon "Web Developer 1.1.6". I get this warning when hitting a certain web page on my site:

Unknown property 'MozOpacity'. Declaration dropped.

What does this mean and how can I fix this on my site?

[A]
Are you using
```
mozopacity
```
in your CSS stylesheet? This might be spelled wrong and is thus triggering an error.
You might be looking for
```
-moz-opacity
```
which has been dropped as of Firefox 3.0.


q:
When overriding the MembershipProvider and calling it directly, is there a way to fill the NameValueCollection config parameter of the Initialize method without manually looking through the config file for the settings?

Obviously this Initialize is being called by asp.net and the config is being filled somewhere. I have implemented my own MembershipProvider and it works fine through the build in controls.
I would like to create a new instance of my provider and make a call to it directly, but I don't really want to parse the .config for the MembershipProvider, it's connection string name and then the connection string if it's already being done somewhere.

[A]
Not sure why you want to create a new one, but if you create it yourself, you'll need to read the web config and get the values yourself to pass to Initialize() as this is done outside the class.  I'm sure, though, that there is already a section handler for this section so it should be just a matter of doing:
```
```
MembershipSection section  = WebConfigurationManager.GetSection("membership");
```
```
Then find your provider and accessing its properties to construct the NameValueCollection.  I don't think you will have to write any code to parse the configuration section.
Here is the
MembershipSection
documentation at MSDN.  Drill down from there.


q:
I don´t know why, but my form isn´t calling Form_Load event when it loads.

Any ideas why this might be happening?

[A]
Do you have the event handler set up?
Ultimately, there is going to be a line of code that looks something like this:
```
```
this.Load += new System.EventHandler(this.Form1_Load);
```
```
That might be something you code yourself, or is generated by double-clicking the Load event for the form from within Visual Studio.


q:
I'm new to Windows programming and after reading the Petzold book I wonder:

is it still good practice to use the TCHAR type and the _T() function to declare strings or if I should just use the wchar_t and L"" strings in new code?

I will target only Windows 2000 and up and my code will be i18n from the start up.

[A]
Yes, absolutely; at least for the _T macro.  I'm not so sure about the wide-character stuff, though.
The reason being is to better support WinCE or other non-standard Windows platforms.  If you're 100% certain that your code will remain on NT, then you can probably just use regular C-string declarations.  However, it's best to tend towards the more flexible approach, as it's much easier to #define that macro away on a non-windows platform in comparison to going through thousands of lines of code and adding it everywhere in case you need to port some library to windows mobile.


q:
Disclaimer: I've solved the problem using Expressions from System.Linq.Expressions, but I'm still looking for a better/easier way.

Consider the following situation :

var query =
    from c in db.Customers
    where (c.ContactFirstName.Contains("BlackListed") ||
           c.ContactLastName.Contains("BlackListed")  ||
           c.Address.Contains("BlackListed"))
    select c;

The columns/attributes that need to be checked against the blacklisted term are only available to me at runtime. How do I generate this dynamic where clause?

An additional complication is that the Queryable collection (db.Customers above) is typed to a Queryable of the base class of 'Customer' (say 'Person'), and therefore writing c.Address as above is not an option.

[A]
```
```
var query = from C in db.Customers select c;

if (seachFirstName)
         query = query.Where(c=>c.ContactFirstname.Contains("Blacklisted"));

if (seachLastName)
         query = query.Where(c=>c.ContactLastname.Contains("Blacklisted"));

if (seachAddress)
         query = query.Where(c=>c.Address.Contains("Blacklisted"));
```
```
Note that they aren't mutually exclusive.


q:
I'm exploring the iPhone SDK and want to create and use a UI component like the figure below. A rounded table with cells in which each cell can have some label text, maybe an input text field and an action button that would take it to the next screen. The table should not be screen filling.

But... I can't figure out how to do it or find example code. The 'Table View' always seems to result in a screen filling table and although the 'Table View Cell' looks like what I need I can't find any good examples. I'm sure it's all not that hard, but I just can't find it. Any tips, pointers are appreciated.

(This figure is just an example of the sort of UI component I'm looking for, I'm not build something related to flight tracking...)

Table like component http://gerodt.homeip.net/table_ui_component.png

Gero

[A]
Try looking at the "5_CustomTableViewCell" project of the
TableViewSuite
code sample from Apple. It should how to create custom subclasses of UITableViewCell.
The short answer is, as alluded to above, you'll want to subclass UITableViewCell and add your custom UI elements to it. For the example you provided, you'd want two different types of cells; one with a label (in light blue) and content (in black) for 4 of your cells, and then a more complex one with additional text on the right.


q:
I have a string which is like this:

this is [bracket test] "and quotes test "

I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:

['this','is','bracket test','and quotes test ']

[A]
Here's a simplistic solution that works with your test input:
```
```
import re
re.findall('\[[^\]]*\]|\"[^\"]*\"|\S+',s)
```
```
This will return any code that matches either
a open bracket followed by zero or more non-close-bracket characters followed by a close bracket,
a double-quote followed by zero or more non-quote characters followed by a quote,
any group of non-whitespace characters
This works with your example, but might fail for many real-world strings you may encounter. For example, you didn't say what you expect with unbalanced brackets or quotes,or how you want single quotes or escape characters to work. For simple cases, though, the above might be good enough.


q: Can I setup a custom MIME type through ASP.NET or some .NET code?  I need to register the Silverlight XAML and XAP MIME types in IIS 6.

[A]
To add to the master mime type list:
```
```
using (DirectoryEntry mimeMap = new DirectoryEntry("IIS://Localhost/MimeMap"))
{
    PropertyValueCollection propValues = mimeMap.Properties["MimeMap"];

    IISOle.MimeMapClass newMimeType = new IISOle.MimeMapClass();
    newMimeType.Extension = extension; // string - .xap
    newMimeType.MimeType = mimeType;   // string - application/x-silverlight-app

    propValues.Add(newMimeType);
    mimeMap.CommitChanges();
}
```
```
Add a reference to :
'System.DirectoryServices' on the .NET add references tab
'Active DS IIS Namespace Provider' on the COM add references tab.
To configure a mime type for a specific site, change ..
```
'IIS://Localhost/MimeMap'
```
to
```
'IIS://Localhost/W3SVC/[iisnumber]/root'
```
...replacing
```
'[iisnumber]'
```
with the IISNumber of the website.


q:
How do I make vi-Vim never use tabs (converting spaces to tabs, bad!), makes the tab key == 4 spaces, and automatically indent code after curly brace blocks like Emacs does?

Also, how do I save these settings so I never have to input them again?

I've seen other questions related to this, but it always seems to be a little off from what I want.

[A]
As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your
```
.vimrc
```
):
```
```
filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab
```
```
In your [.vimrc:][1] file:
```
```
set smartindent
set tabstop=4
set shiftwidth=4
set expandtab
```
```
The help files take a bit of time to get used to, but the more you read, the better Vim gets:
```
```
:help smartindent
```
```
Even better, you can embed these settings in your source for portability:
```
```
:help auto-setting
```
```
To see your current settings:
```
```
:set all
```
```
As
graywh
points out in the comments, smartindent has been replaced by cindent which "Works more cleverly", although still mainly for languages with C-like syntax:
```
```
:help C-indenting
```
```


q:
In Eclipse, under Windows -> Preference -> Java -> Code Style, you can define code templates for comments and code, and you can setup a code formatter.

I'm wondering if it is possible in Eclipse to have these setting take affect every time I save a source file.  Basically, instead of me highlighting everything and pressing Ctrl+Shift+F, I want Eclipse to be responsible for making sure my code is formatted properly.

Is this possible and how do you set it up?

Note On Using the Auto-Format:  It's probably best to choose "Format Edited Lines" as merging changes becomes very difficult when you reformat a whole file that is in source control already that was not formatted properly. Already did this to a co-worker.

[A]
Under
Preferences
, choose
Java
-->
Editor
-->
Save Actions
.  Check the
Perform the selected actions on save
, and check the
Format source code
box.
This may or may not be available in previous versions of Eclipse.  I know it works in:
```
```
Version: 3.3.3.r33x_r20080129-_19UEl7Ezk_gXF1kouft<br>
Build id: M20080221-1800
```
```


q:
I have been tasked to optimize some sql queries at work. Everything I have found points to using Explain Plan to identify problem areas. The problem I can not find out exactly what explain plan is telling me. You get Cost, Cardinality, and bytes.

What do this indicate, and how should I be using this as a guide. Are low numbers better? High better? Any input would be greatly appreciated.

Or if you have a better way to go about optimizing a query, I would be interested.

[A]
You get more than that actually depending on what you are doing. Check out this
explain plan
page. I'm assuming a little bit here that you are using Oracle and know how to run the script to display the plan output. What may be more important to start with is looking at the left hand side for the use of a particular index or not and how that index is being utilized. You should see things like "(Full)", "(By Index Rowid)", etc if you are doing joins. The cost would be the next thing to look at with lower costs being better and you will notice that if you are doing a join that is not using an index you may get a very large cost. You may also want to read details about the
explain plan columns
.


q:
I work on a lot of Asian Language localization projects, and am looking for a powerful text editor with the following features:

1) Unicode support
2) Find in Files
3) Replace in Files
4) Regular expressions
5) Multiline find/replace
6) Built-in diff

I am currently using NotePad++, but it doesn't really support unicode in its find-in-files tool, which is a deal-breaker. EmEditor looks promising, but it doesn't have multi-line find/replace.

Anyone working with Chinese, Japanese, or Korean files have a text editor that they like, free or commercial?

[A]
Ultraedit
is my favorite text editor and it is advertised as having good Unicode support
http://www.ultraedit.com/support/tutorials_power_tips/ultraedit/unicode.html
.
It has the find / replace / regex features you're looking for as well as almost every other feature I have ever needed.


q: I have a custom control that inherits from WebControl and implements IValidator, but I also want to have a property for ValidationGroup.  From research, it appears I need to inherit from BaseValidator to do so.  Can anybody provide a successfull example from a ASP.Net custom control that implements both BaseValidator and IValidator?


q:
I would like to redirect www.example.com to example.com. The following htaccess code makes this happen:

RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

But, is there a way to do this in a generic fashion without hardcoding the domain name?

[A]
Try this:
```
```
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ %{HTTP_HOST}$1 [C]
RewriteRule ^www\.(.*)$ http://$1 [L,R=301]
```
```
If the host starts with www, we stick the whole host onto the start of the URL, then take off the "www."


q:
Is it possible to serialize and deserialize a class in C++?

I've been using Java for 3 years now, and serialization / deserialization is fairly trivial in that language. Does C++ have similar features? Are there native libraries that handle serialization?

An example would be helpful.

[A]
The
```
Boost::serialization
```
library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it,
here
.
The only native way to do it is to use streams. That's essentially all the
```
Boost::serialization
```
library does, it extends the stream method by setting up a framework to write objects to a text-like format and read them from the same format.
For built-in types, or your own types with
```
operator<<
```
and
```
operator>>
```
properly defined, that's fairly simple; see
the C++ FAQ
for more information.


q:
Is it possible to use an ocx (ActiveX Control) on a winform (probably adding it programatically) without first having the ocx registered with regsrv32?

What I'm trying to achieve is to enable xcopy installation. I've had the "AxInterop..dll" and "Interop..dll" file generated from my dev machine.

I've seen the possibility of calling a COM dll without first registering it (ProSysLib, according to the author, but I haven't tested it yet), since ocx is also COM based, thus I assume that there must be some way to do that as well.

[A]
Yes, this can be done.  You must assume your application will only be deployed on Windows XP (or Windows Server 2003) or later, and then you can use what is called 'registration free COM' to make this happen.
Essentially what you do is create a manifest file for the ActiveX control DLL so the Windows loader & COM DLL's know what its registration is without having to put that in the registry.
A walkthrough of what to do is in this article on MSDN:
Registration-Free Activation of COM Components: A Walkthrough
"Step 6" and "Step 7" in that article contain
everything
you will need.
I just tried this out on one of my own C# programs that uses a Microsoft ActiveX grid control (the old "MS Flex Grid") and it works just fine. Make sure you create a manifest file for both your application and the COM DLL, and substitute the appropriate GUIDs in the right places. You may need to use OLEVIEW to dig out the right IDs to use from the ActiveX DLL if you don't have them handy.


q:
The TIBCO EMS user's guide (pg 292) says:

The backup server will work indefinitely to either A) become the
  primary server or B) reconnect to the primary server. It also says
  clients may receive fail-over notification when the switch is successful (see also TIBCO EMS .NET reference pg 220).

I have some questions spinning off of these facts...

What kind of errors occur on the client side while the servers are attempting fail-over/reconnect?

What is the appropriate response from the client?

Get new Connection objects from the ConnectionFactory until one works?

Wait for fail-over notification? (are current Connection instances fixed at this time? or do I need to get a new instance?)

I hope the scenario is clear, any related information or advice would be appreciated too.

[A]
I can at least answer #1 above.
If you have enabled Tibems.SetExceptionOnFTSwitch(true); and have set up an exception handler to capture the messages the server sends to the client, you will see the following:
For single-server, non-fault tolerant connection failures:
"Connection has been terminated".
For fault-tolerant connection failures:
"Connection has performed fault-tolerant switch to "
If you attempt to publish while the connection is down, a TIBCO.EMS.IllegalStateException is thrown with the "Producer is closed" message.
for #2 above, I think the answer is to allow the EMS library to handle as much as possible.  Once we got the EMS reconnect functionality to work, it gracefully tried to reconnect until the server became available again and once it reconnected, it was like there was never a problem.  The only gotcha is probably if you try to publish a message before the ems connection is back.  This is where the exception handler comes in, Once notified that you are in failover mode, you can adjust exception handling on the publisher side to suppress the error until the connection is back.  The thing I don't know is how do you tell when you've exhausted all reconnect attempts.
Anyway, Seems like our two worlds are closely related when it comes to EMS - hope our findings (based on your comments on my questions) help you.


q:
I would really love to push for TDD development inside the shop I'm working in. Lots of the seniors over there didn't work with unit testing or did unit testing that was hitting the database.

I would love to bring some good arguments, books for training, possible coach to ease the transition.

[A]
I have found that it is often very hard to push TDD from the developer up. What I tend to do is talk about the benefits of TDD as much as possible and wherever possible, introduce elements of TDD myself bit by bit.
If they don't mind, start a new project with unit tests in it (managers seldom mind more test coverage) and start developing that way yourself. Slowly show the rest of your team the benefits and try to win some converts. Once you have a few other developers on your side, start pushing management for some training.
You could also offer to run some lunch-n-learns about it for the other developers. Teaching is the best way of learning and your will hopefully gain allies. If you are lucky, you can talk your boss into buying the pizza for the lunch-n-learn and everyone benefits.


q:
The situation is as follows: I've got 2 models: 'Action' and 'User'. These models refer to the tables 'actions' and 'users', respectively.

My action table contains a column user_id. At this moment, I need an overview of all actions, and the users to which they are assigned to. When i use $action->fetchAll(), I only have the user ID, so I want to be able to join the data from the user model, preferably without making a call to findDependentRowset().

I thought about creating custom fetchAll(), fetchRow() and find() methods in my model, but this would break default behaviour.

What is the best way to solve this issue? Any help would be greatly appreciated.

[A]
You could always make a view in your database that does the join for you.
```
```
CREATE OR REPLACE VIEW VwAction AS
SELECT [columns]
  FROM action
  LEFT JOIN user
    ON user.id = action.user_id
```
```
Then just use
```
```
$vwAction->fetchAll();
```
```
Just remember that views in MySQL are read-only (assuming this is MySQL)


q:
I was checking out the TIBCO GI the other day and I was impressed.

Has anyone used it extensively?

What are your thoughts?

What drawbacks did you encounter?

Is it suitable for Internet or only Intranet apps?

I appreciate any input you can shed on this.

[A]
Yes, I have used it pretty extensively, here are some of my thoughts. Will add to them as the occur.
I don't rate the approach of implementing the IDE in the framework itself (it runs in a browser window). There are many, many quirks and it can lead to a very frustrating experience. I normally develop all of the JS, XML etc in Intellij Idea using the Javascript debug window to run the IDE itself. After working on a file, it has to be reloaded in the IDE, but its still much more efficient.
Using the IDE, an entire application can be layed out relatively quickly.
There is a pretty steep learning curve. The API is extensive and the community forums aren't great when you do run into problems.
Much of the GUI painting is done using inline style attributes, making them difficult to skin and get the overall application looking exactly how you might want. If is for this reason that I think GI is more suited to intranet apps than publicly available ones.
GI uses a 'dual DOM' approach, holding it's own internal representation of each on-screen element. This can make it difficult to fully integrate other frameworks such as JQuery etc.
As RIAD environments go, I think it is awesome. I find that doing things the GI way is an order of two faster than going down the request/response route.
I really like the enforced separation of presentation and business logic.
The JS extensions they put in, like introspective package, interface and class definitions are quite clever and very useful.


q:
I have a winforms application, that why someone clicks on a button I need to open up IE to a specific URL.

When someone closes the winforms app, I then need to close IE.

Is this possible? If yes, how?

[A]
It would be possible to do that, but it might be a better idea to simply embed Internet Explorer into your application using the WebBrowser control. That way when you close the website you have no chance of closing the whole window when your website opened in a new tab in an existing IE window.
Edit:
If you're going to do it anyway,  look at the
MSDN page on System.Diagnostics.Process.Close


q:
This is a follow on to this question.  I am trying to avoid using the x509 certificate method as that makes my client installs more complex.  If basicHttpBinding is not the only option, where are some samples of other binding methods.

My clients are on .Net 2.0, I don't have access to System.ServiceModel namespace as that didn't come out until 3.0.

Update: To be clear,
           clients: .Net 2.0,
           web service: .net3.5/WCF

[A]
You could require SSL + Username/Password with basicHttp.
First the below is what your client would use in .NET 2.0 to auth w/ your WCF service.
```
```
Dim client As WebServiceClient = New WebServiceClient("basicHttpWebService")
client.ClientCredentials.UserName.UserName = "username"
client.ClientCredentials.UserName.Password = "password"
```
```
Next, a sample config for your WCF service to require SSL + Membership provider credentials
```
```
<bindings>
            <basicHttpBinding>
                <binding name="basicHttp">
                    <security mode="TransportWithMessageCredential">
                        <transport/>
                        <message clientCredentialType="UserName"/>
                    </security>
                </binding>
            </basicHttpBinding>
        </bindings>
        <behaviors>
            <serviceBehaviors>
                <behavior name="NorthwindBehavior">
                    <serviceMetadata httpGetEnabled="true"/>
                    <serviceAuthorization principalPermissionMode="UseAspNetRoles"/>
                    <serviceCredentials>
                        <userNameAuthentication userNamePasswordValidationMode="MembershipProvider"/>
                    </serviceCredentials>
                </behavior>
            </serviceBehaviors>
        </behaviors>
```
```
The only thing I'm not sure about is that to use the first section in the client app you might need the WCF/WPF extensions CTP installed because I typically right click and "add service reference" instead of the ASMX "add web reference" - if so this extension for VS2005 does require .NET 3.0 to be installed.  But with a simple "add web reference" you should still be able enter a username/password ... I just don't know what this vb/c# would look like ...


q:
I'm new to CakePHP but I've been though their FAQs and guides to no avail.  This is so simple that I just must not be thinking straight:

How can I access a parameter sent through the URL within my view files?

Example: http://example.com/view/6

How would I take that parameter ("6") and cycle it through the controller to another view page?

If that's too complex for a quick answer, how can I reference the 6 within the view page itself?  The 6 in this situation is the "Id" value in my database, and I need to set it as the "parent" -

Thanks

[A]
The URL, as you have it, will call the 6() method of your ViewController, which is not a valid method name. You may have to play with your routes to make that work.
If you don't want to configure your routes, you'll need the controller in the URL, like so:
```
```
http://example.com/thinger/view/6
```
```
which will call
```
thingerControllerObject->view("6")
```
. If you want "/view/" to go to a different method, edit the routes. See:
Cake controllers
Cake routes


q: If I accidentally closed the scratch buffer in Emacs, how do I create a new scratch buffer?

[A]
C-x b
```
*scratch*
```
RET y RET with iswitchb-mode enabled.
Just C-x b
```
*scratch*
```
RET otherwise.


q:
What is the best way to check for the existence of a session variable in ASP.NET C#?

I like to use String.IsNullOrEmpty() works for strings and wondered if there was a similar method for Session.  Currently the only way I know of is:

 var session;
 if (Session["variable"] != null)
 {
     session = Session["variable"].ToString();
 }
 else
 {
     session = "set this";
     Session["variable"] = session;
 }

[A]
That is pretty much how you do it.  However, there is a shorter syntax you can use.
```
```
sSession = (string)Session["variable"] ?? "set this";
```
```
This is saying if the session variables is null, set sSession to "set this"


q:
Scenario - I need to access an HTML template to generate a e-mail from my Business Logic Layer.  It is a class library contains a sub folder that contains the file.  When I tried the following code in a unit test:

string FilePath = string.Format(@"{0}\templates\MyFile.htm", Environment.CurrentDirectory);
string FilePath1 = string.Format(@"{0}\templates\MyFile.htm", System.AppDomain.CurrentDomain.BaseDirectory);

It was using the C:\WINNT\system32\ or the ASP.NET Temporary Folder directory.

What is the best to access this file without having to use an app.config or web.config file?

[This is using a WCF Service]

[A]
You're running this from an ASP.Net app right? Use
```
Server.MapPath()
```
instead.
Also take a look at
```
System.IO.Path.Combine()
```
for concatenating paths.
[Edit]
Since you can't use
```
System.Web
```
, try this:
```
```
System.Reflection.Assembly.GetExecutingAssembly().Location
```
```
Or
```
GetEntryAssembly()
```
.


q: Scaffolding, what is it?  Is it a Rails-only thing?

[A]
From
Wikipedia
:
Scaffolding is a meta-programming
  method of building database-backed
  software applications. It is a
  technique supported by some
  model-view-controller frameworks, in
  which the programmer may write a
  specification that describes how the
  application database may be used. The
  compiler uses this specification to
  generate code that the application can
  use to create, read, update and delete
  database entries, effectively treating
  the template as a "scaffold" on which
  to build a more powerful application.


q:
What Makes a Good Unit Test? says that a test should test only one thing. What is the benefit from that?

Wouldn't it be better to write a bit bigger tests that test bigger block of code? Investigating a test failure is anyway hard and I don't see help to it from smaller tests.

Edit: The word unit is not that important. Let's say I consider the unit a bit bigger. That is not the issue here. The real question is why make a test or more for all methods as few tests that cover many methods is simpler.

An example: A list class. Why should I make separate tests for addition and removal? A one test that first adds then removes sounds simpler.

[A]
Testing only one thing will isolate that one thing and prove whether or not it works. That is the idea with unit testing. Nothing wrong with tests that test more than one thing, but that is generally referred to as integration testing. They both have merits, based on context.
To use an example, if your bedside lamp doesn't turn on, and you replace the bulb and switch the extension cord, you don't know which change fixed the issue. Should have done unit testing, and separated your concerns to isolate the problem.
Update: I read this article and linked articles and I gotta say, I'm shook:
https://techbeacon.com/app-dev-testing/no-1-unit-testing-best-practice-stop-doing-it
There is substance here and it gets the mental juices flowing. But I reckon that it jibes with the original sentiment that we should be doing the test that context demands. I suppose I'd just append that to say that we need to get closer to knowing for sure the benefits of different testing on a system and less of a cross-your-fingers approach. Measurments/quantifications and all that good stuff.


q:
I'm relatively new to Nant, what i'd like to do is have a task that creates a new Website and AppPool in IIS6

is there a way to do this in Nant?

Essentially the task would need to set all the appropriate properties including the correct version of the .net Framework

Ideally i'd also like to check if the site is already present in IIS.

[A]
You can do this from the command line using ADSUTIL, you can find more information here:
http://blogs.msdn.com/david.wang/archive/2007/12/12/howto-create-custom-application-pool-by-commandline.aspx
To do this in Nant you can use the exec task.
How are you planning on deploying your application?  Do you need this just for local installation?  There may be a better solution if you can give us some more details.


q:
I am trying to create a route with a Username...

So the URL would be mydomain.com/abrudtkhul (abrudtkhul being the username)

My application will have public profiles based on usernames (Ex: http://delicious.com/abrudtkuhl). I want to replicate this URL scheme.

How can I structure this in ASP.Net MVC? I am using Membership/Roles Providers too.

[A]
You could have a route that looks like:
```
```
{username}
```
```
with the defaults of
```
```
Controller = "Users"
```
```
For the finished product of:
```
```
routes.MapRoute(
                    "Users",
                    "{username}",
                    new { controller = "Users" }
```
```
So that the Username is the only url parameter, the MVC assumes it passes it to the users controller.


q: Can it be done or the only way is to configure it on IIS?

[A]
You edit generally the Global.asax file's Session_Start method and set
Session.TimeOut
to whatever you want.  You can do this anywhere else in your code too.


q: Can you do ajax on ASP.net webform without using ajax toolkit? (Please post a example link)

[A]
yes... see my example in this post
AJAX - How to Pass value back to server
This can perform much better than ASP.NET ajax, but does take longer to code.


q:
I am building a Flex Application that calls a .aspx page on the same webserver which builds a PDF report using SQL Reporting Services. When the report is built it prompts the user to open or save the PDF.

We are trying to find a way to display a Progress Bar to let the user know that the report they requested is being built, and then destroy the Progress Bar once the report is finished being built.

I've tried opening a new window using JavaScript and trying to catch when the window closes, as well as trying XMLHTTPRequest, but nothing to seems to work.

Does anyone have any suggestions?

[A]
There are 2 options:
Use the
```
FileReference
```
class in Flex to programmatically invoke your aspx file. You will be able to track the progress of the call from within Flex by listening to its events. But the users can only save the PDF, not open it.
Have an intermediate HTML page that displays a loading icon and then refresh itself to your PDF generating ASPX page. Encode your aspx url along with parameters etc and set it as a parameter to this intermediate page so it knows what to load.


q: I need to replace the standard Overflow function in a ToolStrip to a "More..." button which would then pop up a menu with the overflowed items. Does anyone have any ideas about how to accomplish this?

[A]
You can trap the paint event on the button by calling
```
```
toolStrip1.OverflowButton.Paint += new PaintEventHandler(OverflowButton_Paint);
```
```
Which in theory should allow you to make it say "More...", but I was unable to set the width of the Overflow Button to be anything but the (narrow) default width.
Also, another idea was that you can trap
```
VisibleChanged
```
on the OverflowButton then manually inject a split button into the toolstrip.  The tricky part is figuring out where to put that button.


q:
I'm currently on chapter 4 of Real World Haskell, and I'm trying to wrap my head around implementing foldl in terms of foldr.

(Here's their code:)

myFoldl :: (a -> b -> a) -> a -> [b] -> a

myFoldl f z xs = foldr step id xs z
    where step x g a = g (f a x)

I thought I'd try to implement zip using the same technique, but I don't seem to be making any progress. Is it even possible?

[A]
I found a way using quite similar method to yours:
```
```
myzip = foldr step (const []) :: [a] -> [b] -> [(a,b)]
    where step a f (b:bs) = (a,b):(f bs)
          step a f [] = []
```
```


q:
I'm trying to add parameters to an objectDataSource at runtime like this:

        Parameter objCustomerParameter = new Parameter("CustomerID", DbType.String, customerID);
        Parameter objGPDatabaseParameter = new Parameter("Database", DbType.String, gpDatabase);

        //set up object data source parameters
        objCustomer.SelectParameters["CustomerID"] = objCustomerParameter;
        objCustomer.SelectParameters["Database"] = objGPDatabaseParameter;

At what point in the objectDataSource lifecycle should these parameters be added (what event)?  Also, some values are coming from a master page property (which loads after the page_load of the page containing the objectDataSource).

[A]
Add as early as possible; at the
```
PreInit
```
event.  This is part of initialization so should be done there.
See the
ASP.NET Page Life Cycle Overview
for more information.


q:
How can I Submit an InfoPath form to a SharePoint library AND to an email box at the same time when the user hits SUBMIT?

I need my form to be approved by several users in a particular order; then re-submitted to the SharePoint site, and to another email box so that the next approver can see the approvals, and approve their own, then submit it and have it drop onto Sharepoint again, etc.

The email chain works (the form as an attachment), and the approvals show, but the form doesn't get updated on the SharePoint Form library.

[A] Sorry for asking but have you considered using a workflow rather then emails? I'm not sure whether the basic workflows in WSS 3.0 will cater for your senario but the MOSS workflow should be more than adequate.


q:
What is the best way to make trailing slashes not matter in the latest version of Routes (1.10)? I currently am using the clearly non-DRY:

map.connect('/logs/', controller='logs', action='logs')
map.connect('/logs', controller='logs', action='logs')

I think that turning minimization on would do the trick, but am under the impression that it was disabled in the newer versions of Routes for a reason. Unfortunately documentation doesn't seem to have caught up with Routes development, so I can't find any good resources to go to. Any ideas?

[A]
There are two possible ways to solve this:
Do it entirely in pylons
.
Add an htaccess rule to rewrite the trailing slash
.
Personally I don't like the trailing slash, because if you have a uri like:
http://example.com/people
You should be able to get the same data in xml format by going to:
http://example.com/people.xml


q:
I am curious to do what happens when you edit a post on this site.

I am using wmd for my markdown editor, of course when I goto edit, I get the HTML it generated not the markdown like on stackoverflow.  Now, is there a way I can store both?  or is it reliable enough to simply convert the HTML back to markdown to show in the wmd editor?

Thanks!

[A]
Look at the
```
optionsExample.html
```
in your WMD distribution. There's an option to send the result to the server as Markdown.


q:
I am having the worst luck with this. We bought a template to update our own website (don't have enough time to start our own from scratch!) but when I make simple changes in the Flash CS4 native file and re-export the swf, it doesn't work correctly!

I am wondering if anyone has run across the same problems with a Template Monster Flash website template.

Thanks.


q:
Derik Whitaker posted an article a couple of days ago that hit a point that I've been curious about for some time: should business logic exist in controllers?

So far all the ASP.NET MVC demos I've seen put repository access and business logic in the controller.  Some even throw validation in there as well.  This results in fairly large, bloated controllers.  Is this really the way to use the MVC framework?  It seems that this is just going to end up with a lot of duplicated code and logic spread out across different controllers.

[A]
Business logic should really be in the model.  You should be aiming for fat models, skinny controllers.
For example, instead of having:
```
```
public interface IOrderService{
    int CalculateTotal(Order order);
}
```
```
I would rather have:
```
```
public class Order{
    int CalculateTotal(ITaxService service){...}
}
```
```
This assumes that tax is calculate by an external service, and requires your model to know about interfaces to your external services.
This would make your controller look something like:
```
```
public class OrdersController{
    public OrdersController(ITaxService taxService, IOrdersRepository ordersRepository){...}

    public void Show(int id){
        ViewData["OrderTotal"] = ordersRepository.LoadOrder(id).CalculateTotal(taxService);
    }
}
```
```
Or something like that.


q: Can JQuery and YUI live together w/o any conflicts?

[A]
Yes.  They live in different namespaces, plus jQuery has a
noConflict option
.


q: In Silverlight how can I launch / navigate to another page?

[A]
```
```
System.Windows.Browser.HtmlPage.Window.Navigate(
   new Uri( "http://www.google.com" ),
   "_blank"
   );
```
```
You can leave out the target ("_blank") if you just want to navigate within your current browser window.


q:
I wonder why no browser out there has such simple but essential feature. Am I missing something? Is there a technical reason?

I'm tired of all those javascript/flash/java hacks out there ...

[A]
You have to post back to upload a file, regardless of whether or not you are being "sneaky" about it (using hidden iframes, for example); the browser's own progress bar (usually down in the status bar) is the file upload progress bar in that sense, although not exactly.
It's just that you can't easily use that data for yourself, so you have to approximate it with a lot of client-to-server communication tricks.


q:
I want to hold a bunch of const char pointers into an std::set container [1].  std::set template requires a comparator functor, and the standard C++ library offers std::less, but its implementation is based on comparing the two keys directly, which is not standard for pointers.

I know I can define my own functor and implement the operator() by casting the pointers to integers and comparing them, but is there a cleaner, 'standard' way of doing it?

Please do not suggest creating std::strings - it is a waste of time and space.  The strings are static, so they can be compared for (in)equality based on their address.

1: The pointers are to static strings, so there is no problem with their lifetimes - they won't go away.

[A]
Depending on how big a "bunch" is, I would be inclined to store a corresponding bunch of
```
std::string
```
s in the set. That way you won't have to write any extra glue code.


q:
Today I had a discussion with a colleague about nested functions in Javascript:

function a() {
   function b() {
      alert('boo')
   }
   var c = 'Bound to local call object.'
   d = 'Bound to global object.'
}

In this example, trials point out that b is not reachable outside the body of a, much like c is. However, d is - after executing a(). Looking for the exact definition of this behaviour in the ECMAScript v.3 standard , I didn't find the exact wording I was looking for; what Sec.13 p.71 does not say, is which object the function object created by the function declaration statement is to be bound to. Am I missing something?

[A]
As I understand it, these are equivalent as far as scoping is concerned:
```
```
function a() { ... }
```
```
and
```
```
var a = function() { ... }
```
```


q: I've searched around a bit in the small amount of iPhone/iPod Touch development information available and couldn't find anything for or against.  Can an application find out information about currently playing song on iPhone/iPod Touch?  Since the music can continue to play while you are in 3rd party applications, is there a function or library that will give you information about what is playing? (Track, Artist, Album, etc.)  I know generally that applications are sand-boxed but thought maybe there was a way.