q:
Greetings,

I have data stored on mysql with delimiter "," in 1 table.
I have rows and column stored on database too.
Now i have to output the data using rows and column number stored on database to draw the table.

Rows and column number are user input, so it may varies.

Let say, there is number 3 on column and 3 on rows.

I need to do it like display like,

|___d1__|___d2__|___d3__|
|___d4__|___d5__|___d6__|
|___d7__|___d8__|___d9__|

Where d1-d9 would be the data stored on mysql database with delimiter "," in one table.

Thanks for helping me.

[A]
assuming that user set table size for 2 rows and 3 columns and makes some input fot 6 cells, data which will go to database will be
2,3,d1,d2,d3,d4,d5,d6
when you will fetch data from cell and make explode on fetched string you will get 1 dimension array with 8 elements
$r = $e[0] rows
$c = $e[1] cols
$e[2-7] data
wrtite openning < table > tag
two loops, one in another,
first one will generate code for start of row
wrtite openning < tr > tag
inside one will genereate code for row.
write opening < td > tag
write data $e[1 + position calulated from inside and outside loops]
write closing < td > tag
end of inside loop
wrtite closing < tr > tag
end of outside loop
wrtite closing < table > tag
It should give you the idea


q: Are these two terms interchangeable?

[A]
CIL is the term used in the
CLI Standard
. MSIL is (I suppose) CIL created by MS tools. Effectively they are synonymous.
Brad Abrams says this.

s: huggingface

c: devops

d: intermediate


q:
What I would like to do is have VS2008, when I open a code file, collapse all members of the classes/interfaces in the file by default (including, crucially, any XML documentation and comments).

I do not want to use regions, at all.

I would also like to be able to use the ctrl+m, ctrl+l chord to toggle all member outlining (for example, if everything is collapsed, I would like it to expand all of the members, but not the comments or XML documentation).

Possible?  How?

[A]
Yes to part 1.
Unsure about part 2.
To have VS2008 automatically open files in a Collapsed state you'll need to create an addin to run the "Edit.CollapsetoDefinition" when each document opens.
This isn't overly tricky - The difficult parts seems to be the that you have to run the code a few milliseconds after the document is actually opened so you need to use the threed pool to do that.
Create an Addin project for VS2008.
Add this code (see following) to the end of the OnConnection Method of the Connect class.
```
```
switch (connectMode)
    {
        case ext_ConnectMode.ext_cm_UISetup:
        case ext_ConnectMode.ext_cm_Startup:
            //Do nothing OnStartup will be called once IDE is initialised.
            break;
        case ext_ConnectMode.ext_cm_AfterStartup:
            //The addin was started post startup so we need to call its initialisation manually
            InitialiseHandlers();
            break;
    }
```
```
Add this method to the Connect class
```
```
private void InitialiseHandlers()
    {
        this._openHandler = new OnOpenHandler(_applicationObject);
    }
```
```
Add a call to InitialiseHandlers() to the OnStartupComplete method of the Connect class.
```
```
public void OnStartupComplete(ref Array custom)
    {
        InitialiseHandlers();
    }
```
```
Add this class to the project.
```
```
using System;
    using System.Collections.Generic;
    using System.Text;
    using EnvDTE80;
    using EnvDTE;
    using System.Threading;

    namespace Collapser
    {
        internal class OnOpenHandler
        {
            DTE2 _application = null;
            EnvDTE.Events events = null;
            EnvDTE.DocumentEvents docEvents = null;

            internal OnOpenHandler(DTE2 application)
            {
                _application = application;
                events = _application.Events;
                docEvents = events.get_DocumentEvents(null);
                docEvents.DocumentOpened +=new _dispDocumentEvents_DocumentOpenedEventHandler(OnOpenHandler_DocumentOpened);
            }

            void OnOpenHandler_DocumentOpened(EnvDTE.Document document)
            {
                if (_application.Debugger.CurrentMode != dbgDebugMode.dbgBreakMode)
                {
                    ThreadPool.QueueUserWorkItem(new WaitCallback(Collapse));
                }
            }

            private void Collapse(object o)
            {
                System.Threading.Thread.Sleep(150);
                _application.ExecuteCommand("Edit.CollapsetoDefinitions", "");
            }
        }
    }
```
```
And now all opened files should be fully collapsed.


q:
Helo!

Is this possible to use string value of one node which tells what type of field is presented in another node using LINQ to XML?

For example:

<node>
  <name>nodeName</name>
  <type>string</type>
</node>
<node>
  <name>0</name>
  <type>bool</type>
</node>
<node>
  <name>42</name>
  <type>int</type>
</node>

Thanks in advance

[A]
Well, you won't get a nice statically typed API given that the type information is only known at execution time - but you could easily write an extension method on XElement which looks for the appropriate subelements and returns
```
System.Object
```
. For instance (untested):
```
```
public static object ParseValue(this XElement element)
{
    XElement name = element.Element("name");
    XElement type = element.Element("type");
    // Insert error handling here :)

    switch (type.Value)
    {
        case "int":
            return int.Parse(name.Value);
        case "string":
            return name.Value;
        case "bool":
            return name.Value == "1"; // Or whatever
        default:
            throw new ArgumentException("Unknown element type " + type.Value);
    }
}
```
```
It's not how I'd design a data format, but if it's being thrust upon you...


q:
For example, I make extensive use of the session in my ASP.NET application but have heard somewhere that objects stored in session can be removed by the system where server memory runs low. Is this true? Is there any session 'callback' functionality to allow you to re-populate scavenged objects?

More generally, what other potential problems of using session state are there, and what are the suggested best practices for dealing with them?

[A]
Sorry, I don't know about the removal of items from session state, but in response to your general question, the most important question is whether you anticipate running your web app on just one web server machine or many.
Typically, you are keeping the session state in the memory of one single machine.  Your load balancer that fronts your multiple web servers must be configured to make things "sticky", so that the same user keeps being routed to the same machine.
Alternatively, you could store session state in a central location, including SQL Server, but then you pay the performance hit for the network and IO interaction with SQL Server.  You give up the speed of local, in memory state.
Since session state is 20 minutes by default, if you need more than that, but your hosting company won't let you override it, you would have to have some ajax or hidden iframe javascript code running in your web pages that would ping the server every (less than) 20 minutes to keep the session aliv


q:
I am currently building an application using ASP.NET MVC.  The data entry pages are fairly easy to code, I just make the Model for the page of the type of my business object:

namespace MyNameSpace.Web.Views.ProjectEdit
{
    public partial class MyView : ViewPage<Project>
    {
    }
}

Where I am struggling is figuring out the best way to implement a dashboard like interface, with stand-alone parts, using ASP.NET MVC, where the Model for each part would be different? I'm assuming that each part would be an MVC user control.

Also, how could I make it so each part is testable?

[A]
I think that user controls is probably the way to go.  I'm not sure what the concern is about testability.  You should be able to test that your controller is providing the right view data -- since you'll have several models each of these will probably be stored in a separate view data item, rather than aggregating them in a single model.  Aggregating in a single model is also possible, although probably more brittle.  Each control would just need to check for a particular view data item, rather than being specific to a particular model.  You could approximate the model variable on each view page by doing:
```
```
<% MyUserControlModel model = ViewData["MyUserControlModel"]
         as MyUserControlModel; %>

   Name: <%= model.Name %>

   Count: <%$ model.Count %>

```
```
If you need to test your view, then you're probably already using Selenium or some other web testing framework.  I don't think that these would care how the page was constructed and you should be able to construct your tests pretty much like you always do.


q:
I would like to add custom tooltips to emacs.
More specifically, whenever I hover on a symbol (function/variable) name
with my mouse of I would like to see a tooltip with the symbol's definition.
I know that I can find this kind of info with a tool like cscope but I have no idea how
to attach the output of cscope to a tooltip.
does anyone have a partial (how to link a callback to a tooltip in emacs in general) or
a full (how do I actually link the output of cscope to a tooltip) solution to this?

Thanks,
Nir

[A]
Your Emacs installation should include the
Elisp reference manual
(if not, download it now - you're going to need it when developing your mode). To access it, go to Info (C-h i) and look for a node labeled "Elisp", sometimes in a separate "Emacs" menu. Type
```
i
```
for index and
```
tooltip
```
to look for information on tooltips. You should find node
32.19.4 Properties with Special Meanings
, which tells you that the content of the
```
help-echo
```
property is a string that is the tooltip content, or a function that can construct the tooltip dynamically. Explore the manual around that node to find out more about text properties and how to set them.
Here's a simple example:
```
```
(insert (propertize "foo\n" 'help-echo "Tooltip!"))
```
```
Type this into your
```
*scratch*
```
buffer and press
```
C-j
```
to run the code. Then point your mouse at the word "foo" and you should see the tooltip.


q:
HI I got this coursework question to solve.

This is the question:

Design a program to simulate vehicles at an intersection.

Assume that there is one lane going in each of four directions, with stoplights facing each direction. Vary the arrival time of vehicles randomly in each direction and set up a regular frequency of the light changes. Run your direction and set up a regular frequency of the light changes. Run your simulation for a set period of time to view the "behaviour" of the intersection.

Coursework Requirement:

Should be coded in java

Use of proper data structures

If any one has any clue of how to do it, please help; I have no idea.

[A]
Read
about
queues
you have to use to simulate each traffic light.
Each randomly generated car going in each lane will get pushed into the corresponding queue and then popped out of it when the light is green, and keep popping cars as long as (hint: you need to simulate time as well (subhint: look into finite state machines)) the light is green, of course. You process each queue in order.


q: i need to check whether the user clicking the browser Refresh button and redirect to error page. Can we do this in javascript or any server side methods in ASP.net

[A]
If you give each link you present a unique ID (e.g. a GUID) in the URL as a parameter, then you can keep track of all the requests you've processed. (You could clear out "old" requests if you don't mind the mechanism not working if someone leaves a browser open for a few days and then hitting refresh.) The first time you see a GUID, write it into the table. If you see it again, redirect to an error page.
It's pretty ugly though, and users could just edit the URL to change the GUID slightly. (You could fix this last flaw by recording the GUID when you
generate
it, and update the table to indicate when it's been
used
.)
In general, users expect to be able to refresh the page though - particularly for GET requests (even though most users wouldn't know what that means). Why do you want to do this?


q: It's 5 button clicks to get eclipse to create a deployable war file for my eclipse project, I figure there's probably some eclipse command line option to do the same thing, so I can just write it into a script, but I'm not seeing it.

[A]
Use the
Ant
```
war
```
task
, set up a relevant build file and you can just hit the "external tools" button to execute it.


q:
If I have the following code:

MyType<int> anInstance = new MyType<int>();
Type type = anInstance.GetType();

How can I find out which type argument(s) "anInstance" was instantiated with, by looking at the type variable? Is it possible?

[A]
Use
Type.GetGenericArguments
. For example:
```
```
using System;
using System.Collections.Generic;

public class Test
{
    static void Main()
    {
        var dict = new Dictionary<string, int>();

        Type type = dict.GetType();
        Console.WriteLine("Type arguments:");
        foreach (Type arg in type.GetGenericArguments())
        {
            Console.WriteLine("  {0}", arg);
        }
    }
}
```
```
Output:
```
```
Type arguments:
  System.String
  System.Int32
```
```


q:
If anyone is trying to do agile, i am trying to figure out a way to use JIRA / Greenhopper for this.  We are a global dev team so the distributed nature is crucial here.

We were initially using Scrumworks but the team complained that they had duplicate information in JIRA and scrumworks all the time and thought it was redundant.

We got Greenhopper and thought that would solve our problems but the problems that i have with this are:

No User story concept in JIRA

Greenhopper too "task" focused without aggregation at the user story level.

Has anyone successfully done this in JIRA or should we look at moving back to other tools like scrumworks and just use JIRA for bugs raised by our support team.

[A]
You can add your own Issue types in JIRA.
Just add a type called User Story.
Then make sure to enable your sub-tasks feature in JIRA.
You will then be able to explode your stories int multiple Subtasks.
The integration of the subtasks is pretty nice if you reuse the Ranking feature.
See:
http://www.greenpeppersoftware.com/confluence/display/GH/PLANNING+BOARD#PLANNINGBOARD-ordering
You will then be able to
1) Estimate your Stories in Story points
2) Prioritize your issues (with the ranking field)
3) Explode your stories in multiple subtasks that you will estimate in hours.
You should post your questions on the GreenHopper forum, might have more and quicker answers.
http://www.greenpeppersoftware.com/site/forums/list.page
Cheers,


q: for VS 2005 is there a max number of projects that will cause performance issues.  We have now up to 25 projects and growing.  Should we making these binary referenced or are we breaking out our application logic into too many different projects.  Seems to start to be a big performance issue lately.

[A]
Having too many DLL files can cost you at run-time so I would recommend that you try to minimize the amount of projects. Creating several solutions is also an option but try to make the solutions independent of each other so that you don't have to debug and implement new features across several solutions - that can be cumbersome.
Take a look at this article:
Project anti-pattern: Many projects in a Visual Studio Solution File
.


q:
In this query:

SELECT COUNT(*) AS UserCount, Company.* FROM Company
LEFT JOIN User
ON User.CompanyId = Company.Id
WHERE Company.CanAccessSystem= true
AND(User.CanAccessSystem IS null OR User.CanAccessSystem = true)
GROUP BY Company.Id

I want to query a list of companies that can access a particular system as well as the number of users who can access the system inside the company.

This query works for all cases except for one very important one.  If a company can access a the system but none of the users can, the Company disappears completely from the query (i.e.: Users.CanAccessSystem = false).  In that case, I just want the UserCount = 0.

Example From Companies that Can Access the System:

Users   Company Name
1       WidgetWorks
3       WidgetCompany
0       WidgesRUs

This system is on MySQL

Query Edit: Fixed a Typo "ON User.CompanyId = Company.Id"

[A]
You should be counting the number of users for whom User.CanAccessSystem is true. Think of something like
```
```
count(case when User.CanAccessSystem then true end)
```
```
The case expression will return NULL in case User.CanAccessSystem is false (default), and
```
count(expr)
```
counts the number of items for which the expression is not null.
So... This?
```
```
SELECT COUNT(case when User.CanAccessSystem then true end) AS UserCount, Company.*
FROM Company LEFT JOIN User
ON Company.id = user.companyId   -- I had to guess, this seems to be missing in your query
WHERE Company.CanAccessSystem= true
GROUP BY Company.Id
```
```
p.s. I used LEFT JOIN instead of INNER JOIN in order not to exclude companies without users.


q:
I've been working with jQuery for a pair of weeks and I've noticed it works fine with objects that are in the original HTML document, but when I generate a new element using jQuery the library doesn't get any of its events.

Let's say I try to run something like this:

$('.whatever').click(function() {
  alert("ALERT!");
});

If the HTML does have something like this:

<span class="whatever">Whatever</span>

Then clicking on the word Whatever gets me a nice alert.

But if the span element is added dynamically using jQuery, nothing happens when clicking on it.

Is there a way to make jQuery work with those elements, somehow?

[A]
You need to rebind it.
```
```
function bindme(){
    $('.whatever').click(function(){
        alert('binded');
    });
};

bindme();

//function that will generate something

function foo(){
   $('.whatever').val('oryt');
   bindme();//rebind itagain
}
```
```


q:
Should operations that could take some time be performed in a constructor or should the object be constructed and then initialised later.

For example when constructing an object that represents a directory structure should the population of the object and its children be done in the constructor. Clearly, a directory can contain directories and which in turn can contain directories and so on.

What is the elegant solution to this?

[A]
You usually do not want the constructor to do any computation.  Someone else using the code will not expect that it does more than basic set-up.
For a directory tree like you're talking about, the "elegant" solution is probably not to build a full tree when the object is constructed.  Instead, build it on demand.  Someone using your object may not really care what is in sub-directories, so start out by just having your constructor list the first level, and then if someone wants to descend into a specific directory, then build that portion of the tree when they request it.


q:
There's a HTML:

<div class="test">
<ul>
    <li>Item 1</li>
    <li>Item 2</li>
</ul>
</div>

And a bit of JS:

$(document).ready(function() {
    // do stuff when DOM is ready
    $(".test ul").append('<li>Foo</li>');
});

Why does it add nothing, but if I remove html from append's argument string,

.append('Foo')

it works - but that's not the point - new text is added as anonymous block, not li item as I wanted.

Anu suggestions?

edit:
Argh, I've found the problem. I modified a file saved from Firefox's "Save page" option, the extension was .xhtml - and here's the problem. I renamed it and it works fine.

Thanks :)

[A]
adding actual HTML from JavaScript is rather ugly, have you tried something like this:
```
```
var li=document.createElement("li");
li.appendChild(document.createTextNode("Dupa"));
$(".text ul").appendChild(li);
```
```
?


q:
I'd like to mark a method as deprecated, so the people using it can easily check their code and catch up. In Java you set @Deprecated and everybody knows what this means.

So is there a preferred way (or even tools) to mark and check for deprecations in Ruby?

[A]
You do have
```
libdeprecated-ruby
```
(2010-2012, not available anymore on rubygem in 2015)
A small library intended to aid developers working with deprecated code.
The idea comes from the '
```
D
```
' programming language, where developers can mark certain code as deprecated, and then allow/disallow the ability to execute deprecated code.
```
```
require 'lib/deprecated.rb'
require 'test/unit'

# this class is used to test the deprecate functionality
class DummyClass
  def monkey
    return true
  end

  deprecate :monkey
end

# we want exceptions for testing here.
Deprecate.set_action(:throw)

class DeprecateTest < Test::Unit::TestCase
  def test_set_action

    assert_raise(DeprecatedError) { raise StandardError.new unless DummyClass.new.monkey }

    Deprecate.set_action(proc { |msg| raise DeprecatedError.new("#{msg} is deprecated.") })

    assert_raise(DeprecatedError) { raise StandardError.new unless DummyClass.new.monkey }

    # set to warn and make sure our return values are getting through.
    Deprecate.set_action(:warn)

    assert_nothing_raised(DeprecatedError) { raise StandardError.new unless DummyClass.new.monkey }
  end
end
```
```


q:
I have a visual studio solution with the following projects:

UI

DataAccess

BusiessLogic

BusinessObjects

I now have a bunch of code that generates reports that are sent out via email or saved as csv files.

These ReportGenerators classes take in business objects and output either files or strings.

which project would you put them in?  I am leaning toward an answer but wanted to see what others thought?

[A]
I would create a separate reporting project. It doesn't belong in the UI (I assume they run in the background) - it is effectively a 'reporting logic' layer.
If you think about how you might want to support reportng, you may want a backend service but you might want to expose the data via a web service as well in the future. If you need to provide users a front-end reporting facility you plug into the reporting logic as you would a normal UI -> Logic -> Data Access architecture.
Also, if you separate your reporting code out you are then free to extract it to a dedicated reporting tier in the future.


q: I know postgres has a datatype for storing geographical coordinates. But I'm looking for a RDBMS agnostic solution. Currently I'm using Decimal(25,20) in MySQL. I may be using this data to lookup these locations based on a given distance from a given location later. Which would be the best approach to store this kind of data?

[A]
The standard is
here
. Although it's too much for a simple use case such as yours, it may give you some ideas about why it may actually be best to go and use some OGC compliant packages many databases have nowadays, even
MySQL
.
Failing that, and assuming you will implement the algorithms for distance calculations, any floating point number that has the precision you need will work.


q:
When comparing two objects (of the same type), it makes sense to have a compare function which takes another instance of the same class. If I implement this as a virtual function in the base class, then the signature of the function has to reference the base class in derived classes also. What is the elegant way to tackle this? Should the Compare not be virtual?

class A
{
    A();
    ~A();
    virtual int Compare(A Other);
}

class B: A
{
    B();
    ~B();
    int Compare(A Other);
}

class C: A
{
    C();
    ~C();
    int Compare(A Other);
}

[A]
If you mean that the Compare() in class B or C should always be passed an object of class B or C, no matter what the signature says, you can work with pointers to instances instead of instances, and try to downcast the pointer in the method's code using something like
```
```
int B::Compare(A *ptr)
{
   other = dynamic_cast <B*> (ptr);
   if(other)
      ...  // Ok, it was a pointer to B
}
```
```
(Such an overloading would be necessary only for those derived classes that add to the state of their parent something that influences the comparison.)


q:
What are some C++ related idioms, misconceptions, and gotchas that you've learnt from experience?

An example:

class A
{
  public:
  char s[1024];
  char *p;

  A::A()
  {
    p = s;
  }

  void changeS() const
  {
    p[0] = 'a';
  }

};

Even know changeS is a const member function, it is changing the value of the object.  So a const member function only means that it will treat all variables as const, and it does not mean that it will actually keep all members const.  (why? the const keyword on the member function treats char *p;  as char * const p;  And not as const char *p;

Which therefore means that p can't point to something else.   And not that you can't change p's data.

[A]
I've liked this since the time i've discovered it in some code:
```
```
assert(condition || !"Something has gone wrong!");
```
```
or if you don't have a condition at hand, you can just do
```
```
assert(!"Something has gone wrong!");
```
```
The following is attributed to
@Josh
(see comments). It uses the
comma operator
instead:
```
```
assert(("Something has gone wrong!", condition));
```
```


q: I have noticed that GhostDoc hasn't been updated in a long while.  So I am curious if there is a plug-in for Resharper or CodeRush that will accomplish the same thing?  Or even if this type of functionality is built in to one of the tools that would be great too.

[A]
GhostDoc is working just fine, so I guess there is no need to be updated (unless some new features will be added). Also, it does not conflict with Resharper in any way (for me, at least).
Edit:
Since everybody seems to happily use GhostDoc (based on my Google search), I doubt anyone will reinvent the wheel, unless it suffers from the not-invented-here sindrom.
EDIT
Well, a new version was released:
SubMain acquires GhostDoc, releases new version, integrates it with CodeIt.Right


q:
Maybe this is an easy question, maybe not.  I have a select box where I hardcode with width. Say 120px.

<select style="width: 120px">
  <option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>
  <option>ABC</option>
</select>

I want to be able to show the second option so that the user can see the full length of the text.

Like everything else.  This works fine in Firefox, but doesn't work with Internet Explorer6.

[A]
If you have the option pre-existing in a fixed-with
```
<select>
```
, and you don't want to change the width programmatically, you could be out of luck unless you get a little creative.
You could try and set the
```
title
```
attribute to each option. This is non-standard HTML (if you care for this minor infraction here), but IE (and Firefox as well) will display the entire text in a mouse popup on mouse hover.
You could use JavaScript to show the text in some positioned DIV when the user selects something. IMHO this is the
not-so-nice
way to do it, because it requires JavaScript on to work at all, and it works only
after
something has been selected -  before there is a change in value no events fire for the select box.
You don't use a select box at all, but
implement its functionality using other markup and CSS
. Not my favorite but I wanted to mention it.
If you are adding a long option later through JavaScript, look here:
How to update HTML “select” box dynamically in IE


q: I have a large amount of rows in the database from which I need to create an XML document. I am using hibernate 3. The basic list() method in Criteria and Query interfaces looks dangerous: I quess it pretty much has to read all the records into memory even if I only iterate over them. Or is there some lazy loading magic? If not, I seem to have two options left: using scroll() or iterate() from Query (scroll is also present in Criteria). iterate doesn't look all that great either if I want to have minimal SQL roundtrips: "The first SQL query returns identifiers only". So am I right, do I have to use scroll() for this?

[A]
Use the setMaxResults() method on Criteria.
```
```
Criteria crit = sess.createCriteria(Cat.class);
crit.setMaxResults(maxResults);
crit.setFirstResult(firstResultIndex);
List cats = crit.list();
```
```
http://hibernate.org/hib_docs/v3/reference/en/html/querycriteria.html
http://www.hibernate.org/hib_docs/v3/api/org/hibernate/Criteria.html


q:
Is it possible to catch an recycle event in the global.asax?

I know Application_End will be triggered but is there a way to know that it was triggered by a recycle of the application pool?

thx, Lieven Cardoen aka Johlero

[A]
I've never tried this myself, but you could try to attach an event handler to the ProcessExit event of the AppDomain.
```
```
...
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnExit);
...

void OnExit(object sender, EventArgs e) {
    // do something
}
```
```
I hope this helps!


q:
When I create a New Project of type ASP.Net MVC Web Application, I expect the dialog for unit test applications to show up, but it does not. I cannot find the Unit Test App among the product types I can create either. How do I set up my VS so that the dialog shows up?

I have installed Visual Studio 2008, .Net Framework 3.5 SP1 and ASP.Net MVC Framework (Beta).

[A]
As @MrJavaGuy says, you need to install at least the Professional, not Express, version of VS2008.  Alternatively, you can install nUnit and/or TestDriven.Net and get unit testing capabilities.  Info on nUnit can be found at
http://www.nunit.org/
and TestDriven.Net at
http://www.testdriven.net/
.  I recommend TestDriven.Net even if you have the testing capabilities of Visual Studio baked in.


q:
For a newcomer to .NET Web Development and programming in general, who chooses C# as there preferred language?

Is it better to learn C# first, without trying to apply it to web development? It seems most literature for C# uses Console or Windows Forms as a learning platform. So would that be the best direction?

Or should you practice in web development and try to learn C# alongside?

[A]
You need to understand the fundamentals of C# in order to develop anything useful, be it an ASP.NET website, windows client or web service.
I would start with some good tutorials around the basics of types, classes, methods, events and so on to get to grips with C#. C# Station has some good introductory tutorials
here
.
To develop web specific skills, start with HTML and CSS.
Then look at how the ASP.NET platform integrates both the C# (application code) and the HTML and CSS (presentational code).
And good luck!


q:
Is there any way to import a database backup from 2005 into 2008 express edition. What I've had to resort to is doing a script the database, then import all the data through DTS. Whenever I tried to import straight from a backup file it says something about not being to import into a new version of sql server or I'll get the below error.

title: Microsoft SQL Server Management Studio

Specified cast is not valid. (SqlManagerUI)

[A]
SQL 2005 backups should be restored on 2008 without problem (have done that myself many times). What exact error message did you got about versions?
The other error (Specified cast is not valid) seems to be Management Studio error, not server error. Have you full rights on 2008 server?
Look at this question -
any-reason-to-have-sql-server-2005-and-2008-installed-on-same-machine
- there are talked both about restoring SQL2005 backups and about attaching SQL2005 data files.
(Of course you cannot attach production databases. To attach non-production databases just detach them, make file level copy of these and attach copies to new server. Orginal files need to attach to original server too :))


q:
What's the best way to merge 2 or more dictionaries (Dictionary<T1,T2>) in C#?
(3.0 features like LINQ are fine).

I'm thinking of a method signature along the lines of:

public static Dictionary<TKey,TValue>
                 Merge<TKey,TValue>(Dictionary<TKey,TValue>[] dictionaries);

or

public static Dictionary<TKey,TValue>
                 Merge<TKey,TValue>(IEnumerable<Dictionary<TKey,TValue>> dictionaries);

EDIT: Got a cool solution from JaredPar and Jon Skeet, but I was thinking of something that handles duplicate keys. In case of collision, it doesn't matter which value is saved to the dict as long as it's consistent.

[A]
The trivial solution would be:
```
```
using System.Collections.Generic;
...
public static Dictionary<TKey, TValue>
    Merge<TKey,TValue>(IEnumerable<Dictionary<TKey, TValue>> dictionaries)
{
    var result = new Dictionary<TKey, TValue>();
    foreach (var dict in dictionaries)
        foreach (var x in dict)
            result[x.Key] = x.Value;
    return result;
}
```
```


q: Could some one point to articles / books on how to create good flow chart diagrams?

[A]
Tutorial
here
.
Also get a copy of Microsoft
Visio
.


q:
I have a delegate, say:

public delegate void MyDelegate();

I have an event, say:

public MyDelegate MyEvent;

While invoking the event I am receiving an error message:

"MyEvent += expected ....."

How do I resolve this?

[A]
You can only invoke the event from within the class where you declared it. In any other place, you can only add or remove handlers from the event delegate via the operators
```
+=
```
and
```
-=
```
, hence the error message.


q:
I have this piece of code:

$("#faq").click(function () {
    var url = $.get("faq", { pagina: "page" });
    alert(url);
});

On "faq" responds to a Servlet that sets an attribute on the request

....
request.setAttribute("pageFAQ", pageFAQ);
....

After the get jQuery prints [object XmlHttpRequest].

I would like to access to the attribute set in the Servlet but I don't know how to do it.

[A]
I'm not sure that a servlet request attribute is shared with the client.
You can get hold of the response text in jQuery like so:
```
```
$("#faq").click(function () {
  $.get(
    "faq",
    { pagina: "page" },
    function(data) {    // callback function, executed on GET success
      alert(data);
    }
  );
});
```
```
All you need to do is let your servlet return some text.


q:
Given 2 file revisions I want to know how many lines were added/modified/deleted.
I want to have this information for the entire repository of thousand of files.
Please point me to a script or tool as I am a total svn newbie

I am working on windows

Sample output

File~NewRevision~OldRevision~Added~Modified~Deleted

file1.c~#11~#10~1~2~0

file1.c~#2~#1~2~2~0

[A]
Subversion has a very nice diff tool integrated within it.  I would use a command such as:
```
```
svn diff -rOldRevision:NewRevision URL
```
```
where URL is the URL of your repository (for instance,
http://www.mycode.org/svn/trunk
).  This won't format the diff output in the form you are looking for, but it will show how each file has been changed between the two revision numbers.
For your formatting, you could use a grep to count how many additions and subtractions occur in each file.
Hope this helps!


q: How could I create iPhone applications using the .NET development environment?

[A]
As far as I know, Apple does not support the Microsoft .Net development environment.
At most you could hope for is installing
mono
on a
jailbroken
iphone. Not that I condone this and you do so at your own risk.
IPhone applications are developed using Objective C or Ruby.


q:
In ARM assembly immediates are encoded by an 8-bit rotated value which means we can only encode

(0-256)^2n.

Now my problem is that I want to clear the upper 16-bits of r0 and replace it with the half-word stored r1. But because of the limited range of the immediates I have to do: -

bic r0, r0, #0xff000000
bic r0, r0, #0x00ff0000
add r0, r0, r1, LSL #16

Is it possible to do replace the 2 bic instructions with a single instruction? 0xffff0000 is unencodable. Perhaps I should be using another logical operation to clear the upper 16-bits?

Thanks

EDIT: Sorry I forgot to say that the top 16-bits of r1 is empty, and I'm using an ARM7TDMI

[A]
If you can clear the whole thing, you could
```
xor
```
it with itself.
If you need to retain the bottom half, might you be able to left-shift the register 8 bits and back? That may be same number of instructions, though.


q:
I'm trying to create a WPF application where I can drag an image around.

Currently I have an image placed in the center of the window, and I'm thinking of using the three mouseevents MouseDown, MouseMove and MouseUp to calculate the new position when dragging the image.

Are there any other good ideas on how to do this? I'm totally new to WPF so my mindset is still in the Windows Forms world.

As far as I can see I need to use a

in order to have absolute positioning available.

[A]
ok, here's an attached property "behaviour" that you can use to make any element draggable provided it's on a canvas:
```
```
public class DraggableExtender : DependencyObject
{
    // This is the dependency property we're exposing - we'll
    // access this as DraggableExtender.CanDrag="true"/"false"
    public static readonly DependencyProperty CanDragProperty =
        DependencyProperty.RegisterAttached("CanDrag",
        typeof(bool),
        typeof(DraggableExtender),
        new UIPropertyMetadata(false, OnChangeCanDragProperty));

    // The expected static setter
    public static void SetCanDrag(UIElement element, bool o)
    {
        element.SetValue(CanDragProperty, o);
    }

    // the expected static getter
    public static bool GetCanDrag(UIElement element)
    {
        return (bool) element.GetValue(CanDragProperty);
    }

    // This is triggered when the CanDrag property is set. We'll
    // simply check the element is a UI element and that it is
    // within a canvas. If it is, we'll hook into the mouse events
    private static void OnChangeCanDragProperty(DependencyObject d,
              DependencyPropertyChangedEventArgs e)
    {
        UIElement element = d as UIElement;
        if (element == null) return;

        if (e.NewValue != e.OldValue)
        {
            if ((bool)e.NewValue)
            {
                element.PreviewMouseDown += element_PreviewMouseDown;
                element.PreviewMouseUp += element_PreviewMouseUp;
                element.PreviewMouseMove += element_PreviewMouseMove;
            }
            else
            {
                element.PreviewMouseDown -= element_PreviewMouseDown;
                element.PreviewMouseUp -= element_PreviewMouseUp;
                element.PreviewMouseMove -= element_PreviewMouseMove;
            }
        }
    }

    // Determine if we're presently dragging
    private static bool _isDragging = false;
    // The offset from the top, left of the item being dragged
    // and the original mouse down
    private static Point _offset;

    // This is triggered when the mouse button is pressed
    // on the element being hooked
    static void element_PreviewMouseDown(object sender,
            System.Windows.Input.MouseButtonEventArgs e)
    {
        // Ensure it's a framework element as we'll need to
        // get access to the visual tree
        FrameworkElement element = sender as FrameworkElement;
        if (element == null) return;

        // start dragging and get the offset of the mouse
        // relative to the element
        _isDragging = true;
        _offset = e.GetPosition(element);
    }

    // This is triggered when the mouse is moved over the element
    private static void element_PreviewMouseMove(object sender,
              MouseEventArgs e)
    {
        // If we're not dragging, don't bother - also validate the element
        if (!_isDragging) return;

        FrameworkElement element = sender as FrameworkElement;
        if (element == null) return;

        Canvas canvas = element.Parent as Canvas;
        if( canvas == null ) return;

        // Get the position of the mouse relative to the canvas
        Point mousePoint = e.GetPosition(canvas);

        // Offset the mouse position by the original offset position
        mousePoint.Offset(-_offset.X, -_offset.Y);

        // Move the element on the canvas
        element.SetValue(Canvas.LeftProperty, mousePoint.X);
        element.SetValue(Canvas.TopProperty, mousePoint.Y);
    }

    // this is triggered when the mouse is released
    private static void element_PreviewMouseUp(object sender,
            MouseButtonEventArgs e)
    {
        _isDragging = false;
    }

}
```
```
You can then use this in your XAML by importing the namespace your class is contained in (something like this:)
```
```
<Window x:Class="WPFFunWithDragging.Window1"
        xmlns:local="clr-namespace:WPFFunWithDragging" .. >
```
```
And then you can just set DraggableExtender.CanDrag="true" on elements to drag around:
```
```
<Canvas>
    <Image Source="Garden.jpg"
           Width="50"
           Canvas.Left="10" Canvas.Top="10"
           local:DraggableExtender.CanDrag="true"/>
</Canvas>
```
```
Hope this is of some use :)


q:
I'm looking for an open-source SGML parser written in plain C. This is to parse bona-fide SGML, not malformed stuff.

Any ideas?

[A]
This came up on a fast Google search (
sgml c parser
):
http://www.w3.org/Library/src/SGML.html
. Does that help?
Or perhaps this one:
http://www.math.utah.edu/pub/sgml/sgmls/


q:
I'm working on an assignment that is telling me to assume that I have a singly linked list with a header and tail nodes.  It wants me to insert an item y before position p.  Can anybody please look over my code and tell me if I'm on the right track?  If not, can you provide me with any tips or pointers (no pun intended)?

tmp = new Node();
tmp.element = p.element;
tmp.next = p.next;
p.element = y;
p.next = tmp;

I think I may be wrong because I do not utilize the header and tail nodes at all even though they are specifically mentioned in the description of the problem.  I was thinking of writing a while loop to traverse the list until it found p and tackle the problem that way but that wouldn't be constant-time, would it?

[A]
Just write it down if you get stuck with an algorithm:
```
```
// First we have a pointer to a node containing element (elm)
// with possible a next element.
// Graphically drawn as:
// p -> [elm] -> ???

tmp = new Node();
// A new node is created. Variable tmp points to the new node which
// currently has no value.
// p   -> [elm] -> ???
// tmp -> [?]

tmp.element = p.element;

// The new node now has the same element as the original.
// p   -> [elm] -> ???
// tmp -> [elm]

tmp.next = p.next;

// The new node now has the same next node as the original.
// p   -> [elm] -> ???
// tmp -> [elm] -> ???

p.element = y;

// The original node now contains the element y.
// p   -> [y] -> ???
// tmp -> [elm] -> ???

p.next = tmp;

// The new node is now the next node from the following.
// p   -> [y] -> [elm] -> ???
// tmp -> [elm] -> ???
```
```
You have the required effect, but it can be more efficient and I bet you can now find out yourself.
It is more clear to write something like:
```
```
tmp = new Node();
tmp.element = y;
tmp.next = p;
p = tmp;
```
```
Which of course does not work if p is not mutable. But your algorithm fails if p == NULL.
But what I meant to say, is, if you have problems with an algorithm, just write the effects out. Especially with trees and linked lists, you need to be sure all pointers are pointing to the righ direction, else you get a big mess.


q:
Suppose that I have a <div> that I wish to center in the browser's display (viewport). To do so, I need to calculate the width and height of the <div> element.

What should I use? Please include information on browser compatibility.

[A]
NOTE
:
this answer was written in 2008. At the time the best cross-browser solution for most people really was to use jQuery. I'm leaving the answer here for posterity and, if you're using jQuery, this is a good way to do it. If you're using some other framework or pure JavaScript the accepted answer is probably the way to go.
As of jQuery 1.2.6 you can use one of the core
CSS functions
,
```
height
```
and
```
width
```
(or
```
outerHeight
```
and
```
outerWidth
```
, as appropriate).
```
```
var height = $("#myDiv").height();
var width = $("#myDiv").width();

var docHeight = $(document).height();
var docWidth = $(document).width();
```
```


q: Has anyone able to assign multiple users to a sharepoint workflow task using the CreateTask activity?

[A]
What version? WSS V3 or MOSS?
Is the "Create Task" bound to the Task List? If so then only one person at a time. Unless you have an AD group with a bunch of people or you modify the list to include SharePoint groups in the assigned to field.


q:
I want to use svn command line with beyond compare and get the following output

Text Compare
Produced: 11/16/2008 11:45:34 AM

SourceFile,CompareFile,IOriginal,IAdded,IDeleted,IChanged,UOriginal,UAdded,UDeleted,UChanged
"E:\Downloads\eeli\eel\1.c","E:\Downloads\eeli\eel\2.c",967,192,501,270,368,113,205,89

What is the exact commandline?

[A]
Put this in (for example) c:\bin\bcsvn.bat
```
```
@REM To configure this as the Subversion diff command, add these lines to
@REM    c:\Documents and Settings\username\Application Data\Subversion\config:
@REM
@REM [helpers]
@REM diff-cmd = c:\bin\bcsvn.bat
@REM
@"C:\Progra~1\Beyond~1\bcomp.exe" "%6" /title1=%3 "%7" /title2=%5
@exit 0
```
```
You'll might have to fix up the path to bcomp.exe.


q:
How can I change the master volume level? Using this code

[DllImport ("winmm.dll")]
public static extern int waveOutSetVolume (IntPtr hwo, uint dwVolume);

waveOutSetVolume (IntPtr.Zero, (((uint)uint.MaxValue & 0x0000ffff) | ((uint)uint.MaxValue << 16)));

I can set the wave volume but if the master volume is too low this won't have any effect.

Thanks for any help.

[A]
For the master volume (for Vista and above), that would be:
ISimpleAudioVolume::SetMasterVolume
As explained
here
, you may refer to the section:
Core Audio APIs in Windows Vista
for more.
This call is not a Media Foundation call but a WASAPI (Windows Audio Session API) call:
 ISimpleAudioVolume::SetMasterVolume (The SetMasterVolume method sets the master volume level for the audio session.)
This may be difficult however to make the UI of the Media Center reflect the new sound level set by that call, as this
thread illustrates
it.
For windows Xp, you can study this
script
and maybe
this other script
.
Audio Library
might also be of interest.
There is also this old
Audio Project
which hasa master volume part:
```
```
BOOL CVolumeDlg::amdInitialize()
{
    ASSERT(m_hMixer == NULL);

    // get the number of mixer devices present in the system
    m_nNumMixers = ::mixerGetNumDevs();

    m_hMixer = NULL;
    ::ZeroMemory(&m_mxcaps, sizeof(MIXERCAPS));

    m_strDstLineName.Empty();
    m_strVolumeControlName.Empty();
    m_dwMinimum = 0;
    m_dwMaximum = 0;
    m_dwVolumeControlID = 0;

    // open the first mixer
    // A "mapper" for audio mixer devices does not currently exist.
    if (m_nNumMixers != 0)
    {
        if (::mixerOpen(&m_hMixer,
                        0,
                        reinterpret_cast<DWORD>(this->GetSafeHwnd()),
                        NULL,
                        MIXER_OBJECTF_MIXER | CALLBACK_WINDOW)
            != MMSYSERR_NOERROR)
        {
            return FALSE;
        }

        if (::mixerGetDevCaps(reinterpret_cast<UINT>(m_hMixer),
                              &m_mxcaps, sizeof(MIXERCAPS))
            != MMSYSERR_NOERROR)
        {
            return FALSE;
        }
    }

    return TRUE;
}

BOOL CVolumeDlg::amdUninitialize()
{
    BOOL bSucc = TRUE;

    if (m_hMixer != NULL)
    {
        bSucc = (::mixerClose(m_hMixer) == MMSYSERR_NOERROR);
        m_hMixer = NULL;
    }

    return bSucc;
}

BOOL CVolumeDlg::amdGetMasterVolumeControl()
{
    if (m_hMixer == NULL)
    {
        return FALSE;
    }

    // get dwLineID
    MIXERLINE mxl;
    mxl.cbStruct = sizeof(MIXERLINE);
    mxl.dwComponentType = MIXERLINE_COMPONENTTYPE_DST_SPEAKERS;
    if (::mixerGetLineInfo(reinterpret_cast<HMIXEROBJ>(m_hMixer),
                           &mxl,
                           MIXER_OBJECTF_HMIXER |
                           MIXER_GETLINEINFOF_COMPONENTTYPE)
        != MMSYSERR_NOERROR)
    {
        return FALSE;
    }

    // get dwControlID
    MIXERCONTROL mxc;
    MIXERLINECONTROLS mxlc;
    mxlc.cbStruct = sizeof(MIXERLINECONTROLS);
    mxlc.dwLineID = mxl.dwLineID;
    mxlc.dwControlType = MIXERCONTROL_CONTROLTYPE_VOLUME;
    mxlc.cControls = 1;
    mxlc.cbmxctrl = sizeof(MIXERCONTROL);
    mxlc.pamxctrl = &mxc;
    if (::mixerGetLineControls(reinterpret_cast<HMIXEROBJ>(m_hMixer),
                               &mxlc,
                               MIXER_OBJECTF_HMIXER |
                               MIXER_GETLINECONTROLSF_ONEBYTYPE)
        != MMSYSERR_NOERROR)
    {
        return FALSE;
    }

    // store dwControlID
    m_strDstLineName = mxl.szName;
    m_strVolumeControlName = mxc.szName;
    m_dwMinimum = mxc.Bounds.dwMinimum;
    m_dwMaximum = mxc.Bounds.dwMaximum;
    m_dwVolumeControlID = mxc.dwControlID;

    return TRUE;
}

BOOL CVolumeDlg::amdGetMasterVolumeValue(DWORD &dwVal) const
{
    if (m_hMixer == NULL)
    {
        return FALSE;
    }

    MIXERCONTROLDETAILS_UNSIGNED mxcdVolume;
    MIXERCONTROLDETAILS mxcd;
    mxcd.cbStruct = sizeof(MIXERCONTROLDETAILS);
    mxcd.dwControlID = m_dwVolumeControlID;
    mxcd.cChannels = 1;
    mxcd.cMultipleItems = 0;
    mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
    mxcd.paDetails = &mxcdVolume;
    if (::mixerGetControlDetails(reinterpret_cast<HMIXEROBJ>(m_hMixer),
                                 &mxcd,
                                 MIXER_OBJECTF_HMIXER |
                                 MIXER_GETCONTROLDETAILSF_VALUE)
        != MMSYSERR_NOERROR)
    {
        return FALSE;
    }

    dwVal = mxcdVolume.dwValue;

    return TRUE;
}

BOOL CVolumeDlg::amdSetMasterVolumeValue(DWORD dwVal) const
{
    if (m_hMixer == NULL)
    {
        return FALSE;
    }

    MIXERCONTROLDETAILS_UNSIGNED mxcdVolume = { dwVal };
    MIXERCONTROLDETAILS mxcd;
    mxcd.cbStruct = sizeof(MIXERCONTROLDETAILS);
    mxcd.dwControlID = m_dwVolumeControlID;
    mxcd.cChannels = 1;
    mxcd.cMultipleItems = 0;
    mxcd.cbDetails = sizeof(MIXERCONTROLDETAILS_UNSIGNED);
    mxcd.paDetails = &mxcdVolume;
    if (::mixerSetControlDetails(reinterpret_cast<HMIXEROBJ>(m_hMixer),
                                 &mxcd,
                                 MIXER_OBJECTF_HMIXER |
                                 MIXER_SETCONTROLDETAILSF_VALUE)
        != MMSYSERR_NOERROR)
    {
        return FALSE;
    }

    return TRUE;
}
```
```


q:
Python provides the "*" operator for unpacking a list of tuples and giving them to a function as arguments, like so:

args = [3, 6]
range(*args)            # call with arguments unpacked from a list

This is equivalent to:

range(3, 6)

Does anyone know if there is a way to achieve this in PHP? Some googling for variations of "PHP Unpack" hasn't immediately turned up anything.. perhaps it's called something different in PHP?

[A]
You can use
```
call_user_func_array()
```
to achieve that:
```
call_user_func_array("range", $args);
```
to use your example.


q: I have a TDbGrid, and I can easily tell how many columns are in it at runtime with the FieldCount property, but there doesn't seem to be a corresponding RowCount property to display how many records are being displayed.  How can I find this out?

[A]
You could try:
```
```
DBGrid1.DataSource.DataSet.RecordCount
```
```
Maybe there are better solutions. But this worked for me.


q:
I am trying to create a sidebar for a site that will allow a user to select an item from a drop down menu and show an RSS Feed. The feed will change depending on which item is selected from the list. I am not sure how to acomplish this, but my first thought was to use z-index and show/hide layers. I have one layer and the menu set up, but it will not allow me to change the feed displayed when a different menu item is selected. Does anyone know how I can acomplish this?

I have a live preview up of what I have gotten done so far. It's located on the site, CHUD,

[A]
This uses jQuery and jFeed plugin to replace the contents of a DIV based on a dropdown selection.
```
```
// load first feed on document load
$(document).ready(
    function() {
       load_feed( $('select#feedSelect')[0], 'feedDiv' ) ); // pick first
    }
);

function load_feed( ctl, contentArea )  // load based on select
{
   var content = $('#' + contentArea )[0]; //pick first

   content.html( 'Loading feed, please wait...' );

   var feedUrl = ctl.options[ctl.selectedIndex].value;

   $.getFeed( { url: feedUrl,
        function(feed) {
           content.html( '' );
           content.append( '
' + feed.title + '
' );
           feed.items.each(
              function(i,item) {
                  content.append( '
'
                                     + feed.title
                                     + '
' );
                  content.append( '
' + feed.description + '
' );
              }
           );
         }
     });
 }
```
```
HTML
```
```

   <select id=feedSelect onchange="load_feed(this,'feedDiv');" >
      <option value='url-to-first-feed' text='First Feed' selected=true />
      <option value='url-to-second-feed' text='Second Feed' />
      ...
   </select>

```
```


q: Does anyone know of a good YAML Parser for PHP? If so, what are the pros and cons of this library?

[A]
The
symfony framework
makes very heavy use of YAML, this
blog post by Grégoire Hubert
demonstrates using their YAML library in a non-symfony project.


q:
These days, more languages are using unicode, which is a good thing. But it also presents a danger. In the past there where troubles distinguising between 1 and l and 0 and O. But now we have a complete new range of similar characters.

For example:

ì, î, ï, ı, ι, ί, ׀ ,أ ,آ, ỉ, ﺃ

With these, it is not that difficult to create some very hard to find bugs.

At my work, we have decided to stay with the ANSI characters for identifiers. Is there anybody out there using unicode identifiers and what are the experiences?

[A]
Besides the similar character bugs you mention and the technical issues that might arise when using different editors (w/BOM, wo/BOM, different encodings in the same file by copy pasting which is only a problem when there are actually characters that cannot be encoded in ASCII and so on), I find that it's not worth using Unicode characters in identifiers. English has become the lingua franca of development and you should stick to it while writing code.
This I find particularly true for code that may be seen anywhere in the world by any developer (open source, or code that is sold along with the product).


q:
I added the ModalPopupExtender to an existing ASP.NET application. At runtime I get the following error

Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: BC32206: Indirect reference is being made to assembly System.Web.Extensions version 3.5.0.0, which contains 'AjaxControlToolkit.ModalPopupExtender'. This Project references a prior version of System.Web.Extensions version 1.0.61025.0. To use 'AjaxControlToolkit.ModalPopupExtender', you must replace the reference to System.Web.Extensions with version 3.5.0.0 or higher.

Source Error:

Line 29:

Line 30:

Line 31:

How do I fix this.

[A]
You're trying to compile a .NET 3.5 application with a reference to a .NET 1.1 module.  Make sure you have the .NET 3.5 framework installed, and if you do, make sure you're trying to build it in .NET 3.5.
You may also want to see
this post
.


q:
One of my Websites is on a Shared Hosting Provider, running either .net 2.0 or .net 3.0, but not 3.5 SP1.

I wonder if it would be possible to still use 3.5 SP1 by simply deploying all the 3.5 assemblies into the /bin Folder, since technically it's all still the 2.0 CLR.

I know that if my Host ever updates I have to remove them or else weird stuff can happen, and that I am driving into Unsupported-Territory at full speed, but is there any really big road sign that says "DON'T DO IT!" or even "That is not possible because of X"?

Primary reason is because I want to use ASP.net MVC and possibly ADO.net Entity Framework, but I do not want to make a contract with yet another Hosting provider.

Thanks!

[A]
I'm pretty sure you can't do this, but googling on the following blogs may get you the definitive answer:
ScottGu
ScottHa
BradA
The problems would be, I think:
You want to load system.dll. Where does it look? does the GAC take precidence? (I think it does), therefore you get 2.0. So you have system.dll v2.0, and you try to use a DLL (eg system.web.mvc) which is bound to system.dll v3.5, but is only in you /bin.... it should explode loudly, not having the same contracts and the like.
Personally, I wouldn't try it, especially on production. But if you can take the site down for a while, give it a go. Worst case, you have to delete the files and re-upload the old site.
YMMV :)


q:
I'm looking for a consistent way to structure my use of formatting strings throughout a large web application, and I'm looking for recommendations or best practices on which way to go.

Up until now I've had a static class that does some common formatting e.g.

Formatting.FormatCurrency

Formatting.FormatBookingReference

I'm not convinced that this is the way to go though, I'd prefer to use the standard way of formatting strings within .NET directly and use:

amount.ToString("c")

reference.ToString("000000")

Id use IFormattable and ICustomFormatter for some of our more complicated data structures, but I'm struggling what to do about the more simple existing objects that we need to format (in this case Int32 but also DateTime).

Do I simply define constants for "c" and "000000" and use them consistently around the whole web app or is there a more standard way to do it?

[A]
One option is to use a helper class with extension methods like
```
```
public static class MyWebAppExtensions
{
    public static string FormatCurrency(this decimal d)
    {
        return d.ToString("c");
    }
}
```
```
Then anywhere you have a decimal value you do
```
```
Decimal d = 100.25;
string s = d.FormatCurrency();
```
```


q: Is there any way to show two editing windows in visual studio? I would like to look at two source files at the same time but I must be missing the option to do that.

[A]
Another easy option is to open two documents, then just click and drag the tab for one of the documents and drop it on the document itself. This will display a menu that lets you move the document to a new vertical or horizontal tab group.
I find this to be the easiest and quickest way to do this.
You didn't ask in the question, but if you want to edit
one
document in two windows, you can grab the small area above the scrollbar and drag it down. You will now have your document open in two scrollable areas. Great for working on two sections at once.


q:
These are some questions for any developer whose made the jump from Java to .Net:

If you could go back to the start of your switched, what would you do to make the transition easier?

Any books you would recommend?

How is .Net compared to Java EE?  Anything that totally bugs you?

And the most important, do you regret making the jump?

[A]
Don't think of it as a switch.  If you learn a new language like C#, you're not trading in all the knowledge you have in Java.  It takes several months until you skills in other languages start to degrade.  Try it out and see if it's for you.  Java will be there for several more years if you change your mind.  :)
I would recommend (and repeatedly have recommended)
Head First C#
as your first .NET book.  The whole series is really beyond compare, IMHO.


q:
I need to set my process to run under 'nobody', I've found os.setuid(), but how do I find uid if I have login?

I've found out that uids are in /etc/passwd, but maybe there is a more pythonic way than scanning /etc/passwd. Anybody?

[A]
You might want to have a look at the
pwd
module in the python stdlib, for example:
```
```
import pwd
pw = pwd.getpwnam("nobody")
uid = pw.pw_uid
```
```
it uses /etc/passwd (well, technically it uses the posix C API, so I suppose it might work on an OS if it didn't use /etc/passwd but exposed the needed functions) but is cleaner than parsing it manually


q:
I have a winforms projects and we use the command pattern.  We are trying to clean up our directory structure and make it consistent.

We are trying to decide if we should have a root commands folder or not. What do you think is better for a directory structure?

Project

--Commands

----AddCommand

----SubtractCommand

----InsertCommand

----DeleteCommand

or

Project

--Calculation

----AddCommand

----SubtractCommand

--Database

----InsertCommand

----DeleteCommand

[A]
Personally I like the second option but I think that you could also do something like this:
```
```
Project
-Commands
--Calculation
----AddCommand
----SubtractCommand
--Database
----InsertCommand
----DeleteCommand
```
```
Just my 2 cents


q:
I was just wondering if there is any difference between the two different new object initializers or is it just syntactic sugar.

So  is:

Dim _StreamReader as New Streamreader(mystream)

and different to:

Dim _StreamReader as Streamreader = new streamreader(mystream)

Is there any difference under the hood? or are they both the same?  Which one do you prefer to use?

[A]
I'm not a VB guy, but as far as I can tell they're equivalent. According to
MSDN's description of the Dim statement
:
If you do not specify datatype, the
  variable takes the data type of
  initializer. If neither datatype nor
  initializer is present, by default,
  the data type is Object Data Type. If
  you specify both datatype and
  initializer, the data type of
  initializer must be convertible to
  datatype.
I won't pass comment on preference, as I don't use VB (except when answering statements).


q:
I have an enumeration: ENUM( 'alpha', 'beta', 'gamma', 'delta', 'omega' )

If I sort my table by this column I get them in the correct order defined above.

However, I can't find a way to select a subset of these, e.g. everything before delta. Using WHERE status < 'delta' only returns alpha and beta, not gamma. It seems MySQL uses a string comparison, not enum index comparison.

I could use the index numbers - i.e. WHERE status < 4 - but it's a bit of a code smell (magic numbers) and may break if I insert new values into the enumeration.

[A]
You can use
```
FIELD(column, "string1", "string2", ...)
```
to find rows with any particular subset of possible
```
ENUM
```
values.
```
```
SELECT * FROM `table` WHERE FIELD(`enum_column`, "alpha", "delta", "et cetera");
```
```
If you want to use the range version, you can use
```
FIND_IN_SET("needle", "hay,stack")
```
to return the index but you'll have to extract the ENUM list out of the table definition first with another query.


q:
I'm currently considering the use of Reflection classes (ReflectionClass and ReflectionMethod mainly) in my own MVC web framework, because I need to automatically instanciate controller classes and invoke their methods without any required configuration ("convention over configuration" approach).

I'm concerned about performance, even though I think that database requests are likely to be bigger bottlenecks than the actual PHP code.

So, I'm wondering if anyone has any good or bad experience with PHP 5 Reflection from a performance point of view.

Besides, I'd be curious to know if any one of the popular PHP frameworks (CI, Cake, Symfony, etc.) actually use Reflection.

[A]
Don't be concerned. Install
Xdebug
and be sure where the bottleneck is.
There is cost to using reflection, but whether that matters depends on what you're doing. If you implement controller/request dispatcher using Reflection, then it's just one use per request. Absolutely negligible.
If you implement your ORM layer using reflection, use it for every object or even every access to a property, and create hundreds or thousands objects, then it might be costly.


q:
Sorry for the newb question.  I'm still learning programming.  So I'm using C++, and I need to do something like this:

int n;
do {
    n = get_data();
    if(n != -1)
        send(n);
} while(n != -1);

This is just a sketch.  Anyway it doesn't feel real elegant.  I have to have my test twice.  I could just test once and set a flag, but that doesn't feel real elegant either since I have to check the flag twice.  It just seems like there should be a way to do this more easily, since it's so easy what I want to do.

[A]
Howabout using
break
:
```
```
int n;
while(1) {
    n = get_data();
    if(n == -1)
        break;
    send(n);
}
```
```
This way you only test once, and quit immediately if get_data doesn't return what you want.


q:
I'm using django and when users go to www.website.com/ I want to point them to the index view.

Right now I'm doing this:

(r'^$', 'ideas.idea.views.index'),

However, it's not working. I'm assuming my regular expression is wrong. Can anyone help me out? I've looked at python regular expressions but they didn't help me.

[A]
What you have should work (it does for me).  Make sure it's in the top
```
urls.py
```
, and it should also be at the top of the list.


q:
I'm interested in measuring and improving (where necessary) my team's SQL-92 skills. Can anyone recommend an appropriate on-line course and/or examination?

Ideally it would be vendor-neutral, but it could also be MSSQL/Oracle specific, as long as the proprietary bits were flagged as such.


q:
What is the best way to block certain input keys from being used in a TextBox with out blocking special keystrokes such as Ctrl-V/Ctrl-C?

For example, only allowing the user to enter a subset of characters or numerics such as  A or B or C and nothing else.

[A]
You could use the TextChanged event for the textbox.
```
```
private void txtInput_TextChanged(object sender, EventArgs e)
    {
        if (txtInput.Text.ToUpper() == "A" || txtInput.Text.ToUpper() == "B")
        {
            //invalid entry logic here
        }
    }
```
```


q: I would like to set up a localhost server to test my site on in sql server 2005. I just installed sql server 2005 and I have never set up a database in this before. There is a login screen and I tried everything and it will not let me log into anything. What are the steps I need to do to get this to work. Thanks

[A]
Assumptions:
sql2005 is installed on your localhost
u can connect to it via Query analyzer or Sql Server Management Studio?
when the login prompt starts up, u have two options for authentication ->  Windows authentication or Sql Server Authentication.
If those assumptions are all correct, then try connecting via the Windows Authentication option. If that fails, then try the Sql Server Authentation and use the username 'sa' (no quotes), password leave empty.
does that work? also, post some links to screenshots so we can see exactly what you see, to help you further.


q:
I'm getting an exception which says "Access Denied" when the users permissions are sufficient, how do I catch an exception and check for "Access Denied" so that I can show the user a friendlier "Sorry Access Denied" message?

Thanks
Beginner :-)

[A]
If you are using a try catch block...
```
```
try
{
    //error occurs
}
catch (Exception ex)
{
    MessageBox.show(ex.Message);
}
```
```
Obviously that is pretty crappy error handling, but it shows that the Exception object contains the error string.  You can narrow down the handling of different exceptions by catching different exception types.
```
```
Try
{
    //error occurs
}
catch (AccessDeniedException ex)
{
    MessageBox.show(ex.Message);
}
catch (FieldAccessException)
{

}
// etc...
```
```


q:
What's a good algorithm to solve this problem?

I have three groups of people - group A, group B, and group C. There are the same number of people in each group. They each have a list of people in the other groups that they're willing to work with. I want to group all these people together in groups of 3 (one from A, one from B, and one from C) such that everyone in a group wants to work with the other people in their group.

How can I find these groups in a fast way? If there's no way to make everyone happy, then the algorithm should first make as many groups have three people who want to work with each other, and then make as many people in the other groups happy.

One final point: people agree on who they want to work with (if person x wants to work with person y, then y also wants to work with x). If you could also give a big-O of the running time of your algorithm, that'd be great!

[A]
This is like the stable marriage problem, but with 3 parties instead of two.
Have a look at efficient solutions for former problem (bi-partite graph matching) and adapt them to your needs.
http://en.wikipedia.org/wiki/Stable_marriage_problem
One adaptation could be to first build working pairs from groups A and B only. Then these pairs have to be paired with a worker from group C each. Let the pairs only prefer workers which both members of the pair agree on (given their lists). Note that this will only give a local optimum.
An optimal solution to k-partite matching is NP-hard to find:
http://www.math.tau.ac.il/~safra/PapersAndTalks/k-DM.ps
See this paper for a non-optimal solution to the k-partite matching problem:
http://books.google.com/books?id=wqs31L1MF4IC&pg=PA309&lpg=PA309&dq=k-partite+matching&source=bl&ots=kgBuvi7ym_&sig=j3Y-nyo51y8qp0-HwToyUlkao4A&hl=de&sa=X&oi=book_result&resnum=1&ct=result
I'm sure you can find others on Google yourself now that you know the terms to search for. I don't know if there is an efficient algorithm giving the optimal solution for k=3.


q: I have a MySQL table that will only have one row. What should my statement be for the first time I insert to this row, and for subsequent updates? I tried an insert where the primary key equals 1, but this doesn't account for the first time around when no row exists yet.

[A]
```
```
INSERT INTO table(col1,col2,col3) VALUES(val1,val2,val3) ON DUPLICATE KEY UPDATE col1 = val1, col2 = val2, col3 = val3;
```
```


q: I also want to save the font size in my .emacs file.

[A]
Press Shift and the first mouse button.  You can change the font size in the following way:
This website
has more detail.


q:
The application de-serializes a stream into dynamically allocated objects and then keeps base type pointers in a linked list (i.e. abstract factory).  It's too slow.  Profiling says all the time is spent in operator new.

Notes: The application already uses a custom memory allocator that does pooling.  The compiler is VC++ 6.0 and the code uses the old RogueWave collections rather than the STL.

The only idea I have right now is to introduce Object Pooling.  I'd maintain large collections of pre-allocated objects for each type and re-use them.  But this will be a lot of work in this old code, and I'm not yet sure there's enough re-use that it would even help.  I was hoping someone smarter than me has an idea.

[A]
I'll assume that most allocations relate to the list of objects you're talking about. If you're actually allocating a bunch of other objects as part of the parsing that's too slow, then you need more information to optimize.
I don't know anything about the RogueWave collections, but if their linked list allocates an external node, then you should be able to halve the number of allocations by using an intrusive list - write your own container if necessary. This assumes that you don't need to put the same objects on multiple lists at once (or in the same list more than once).
If your app is multi-threaded, then the memory allocator will likely be doing some synchronization. But if you can arrange for these objects to be freed in the same thread they're allocated, then they could be allocated off a per-thread heap by overloading operator new. This might be faster: synchronization isn't necessarily all that slow provided there isn't contention, but it takes more time than none, and if other threads in your process are allocating at the same time then there will be contention.
For even more limited use-cases, if you find that you allocate a whole load of these things and then always free them all at once when you're done with the list, you can write an even faster "gc-style" allocator.
Operator new/delete would call functions like these (and size might be a constant rather than a parameter, if there's only one class you use the pool for):
```
```
char *alloc(POOL *pool, size_t size) {
    // if size is a parameter, and may be a non-multiple the max alignment
    // requirement on your system, and you want this to work in general:
    // size = (size + MAX_ALIGNMENT - 1) % ALIGNMENT;
    char *block = pool.current;
    char *next = block + size;
    if (next > pool.limit) throw std::bad_alloc();
    pool.current = next;
    return block;
}

void free(char *block) {
    return;
}

void freeAll(POOL *pool) {
    pool.current = pool.start;
    return;
}
```
```
This should ensure that operator new takes trivial time compared with what you spend parsing the objects you're creating. But it does require the application to identify the times at which it should create, destroy, and clear pools, and to to use a suitable new operator taking the pool pointer as a parameter, so it's not a drop-in replacement.


q:
We have a project page which consists of users' files, multimedia stuff, etc and we want to allow the user to export all this out into a single zip file. We're using unix and mysql to store all of these currently and our primary goal is to minimize load/performance time from all the processing and compiling all the files into a zip file.

My idea was to cache the zip file into a temp dir and keep all the CRC checksum for each files in the zip into a separate text file. Each time the user tries to do an export I will first check through each file's CRC and compare it to the list before adding or removing files from the zip file.

But my other concern is also the space that the zip file will be occupying as we might have a lot of users.

IMHO, this is probably the dumbest way possible to do this,
so can any of you guys please suggest a better way to deal with this problem?

thanks
~codeNoobian

[A]
If bandwidth/download speed is not a concern, I recommend you use an uncompressed tar file. TAR is a very simple format, so it will be easy to write code to update sections of it when a few of the files have changed.  Also, leaving it uncompressed will be a huge win on server CPU time.
Of course, leaving it uncompressed will take a lot of storage space on your server.  But since it is uncompressed, it might remove the need for you to keep a cache copy of the file at all, if you can build it fast enough you can just build it on the fly as needed.  Then you don't have to worry about storing CRCs and updating the TAR, either.


q:
I am using the following servlet-mapping in my web.xml file:

<servlet>
    <servlet-name>PostController</servlet-name>
    <servlet-class>com.webcodei.controller.PostController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>PostController</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>

To do some kind of a search. ex:
 http://www.myweb.com/The search string here

But the problem is that CSS, JS and Images are treated like a search request.

There are any patterns that strip out *.css, *.js, *.gif and etc, so the requests don't need to pass through my controller?

Thank you so much, bye bye!

[A]
Two options come to mind:
1) Typically, in web app like this, the "action" URLs that are handled by a servlet, are given either a sub-directory like "
```
/actions/*
```
" or are given an extension like "
```
*.action
```
" or "
```
*.do
```
" (this is what Struts does). This way it's clear which URLs are intended for the servlet. This is more of an inclusive solution, rather than the exclusive one you're asking for, but I don't think what you want is possible.
2) The slightly more adventurous option is to set up your web app server behind an apache install that serves up the images, css, etc as flat files, sending only everything else onto the app server. Typically, this is done to take the load off your app server. It would require you to copy all these files to a separete directory for apache to handle.


q:
How does the data go from the MVC to the browser and back again?   Does it use Microsoft's own technology like ASMX or WCF or something completely different?

This sounds like MVC is using a ASMX Web Service they are using but I can't seem to find any documentation which gives the real answer.

[A]
AJAX requests are performed in the page using normal HTTP request/response. That is, in javascript the client will create a AJAX request object, send it off to a URL and it gets back a string. If that string is json, it can be eval'd and become a live javascript object.
The philosophy of MVC is that
all
http requests go through controllers. WCF is only for other types of web services that where the client doesn't consume html-json-css-etc.
You can return JSON from a controller action using the Json(object model) method on System.Web.Mvc.Controller.
for example
```
```
ActionResult MyAction() {
    return Json(new { success=false, for_lunch="mmm, chicken"});
}
```
```
That will return the json your webpage can consume.
So, that leaves the question - how does the browser call the MyAction for the json?
Several posts exist on this topic, and the first one i could find that did this was
this post
.
Hope that helps


q:
I have a few model classes with basic one-to-many relationships.  For example, a book has many recipes, and each recipe has many ingredients:

class Book(models.Model):
    name = models.CharField(max_length=64)

class Recipe(models.Model):
    book = models.ForeignKey(Book)
    name = models.CharField(max_length=64)

class Ingredient(models.Model):
    text = models.CharField(max_length=128)
    recipe = models.ForeignKey(Recipe)

I'd like a flat list of all ingredients in all recipes from a particular book.  What's the best way to express this in Python?

If I was using LINQ, I might write something like this:

var allIngredients = from recipe in book.Recipes
                     from ingredient in recipe.Ingredients
                     select ingredient;

[A]
To print each recipe and its ingredients:
```
```
mybook = Book.objects.get(name="Jason's Cookbook")
for recipe in mybook.recipe_set.all():
    print recipe.name
    for ingredient in recipe.ingredients:
        print ingredient.text
```
```
And if you just want to get a list of all ingredient objects:
```
```
mybook = Book.objects.get(name="Jason's Cookbook")
ingredient_list = []
for recipe in mybook.recipe_set.all():
    for ingredient in recipe.ingredients:
        ingredient_list.append(ingredient)
```
```
Documentation
.


q:
I've explored python for several years, but now I'm slowly learning how to work with c.  Using the python documentation, I learned how to extend my python programs with some c, since this seemed like the logical way to start playing with it.  My question now is how to distribute a program like this.

I suppose the heart of my question is how to compile things.  I can do this easily on my own machine (gentoo), but a binary distribution like Ubuntu probably doesn't have a compiler available by default.  Plus, I have a few friends who are mac users.  My instinct says that I can't just compile with my own machine and then run it on another.  Anyone know what I can do, or some online resources for learning things like this?

[A]
Please read up on distutils.  Specifically, the section on
Extension Modules
.
Making assumptions about compilers is bad policy; your instinct may not have all the facts.  You could do some marketplace survey -- ask what they can handle regarding source distribution of extension modules.
It's relatively easy to create the proper distutils
```
setup.py
```
and see who can run it and who can't.
Built binary distributions are pretty common.  Perhaps you can sign up some users will help create binary distributions -- with OS-native installers -- for some considerations.


q:
When working with window handles, is it good enough to use the plain IntPtr or should I subclass SafeHandle?

Are there any significant pros/cons?

Thanks.

[A]
That depends :)
If the handle is returned in such a way that you must eventually call a version of ::CloseHandle on them then you should always subclass SafeHandle.  SafeHandle makes the strongest guarantee possible in the .Net Framework that a handle will be freed.  Not freeing an IntPtr will lead to a resource leak.  Enough resource leaks will eventually lead to a program crash.
If the handle doesn't need to be freed then passing around IntPtr is sufficient.


q:
I have a ComboBox bound to an ObservableCollection of decimals.  What is the correct way to apply our currency converter to the items?

Edit:

a) I have an existing currency converter that I must use
b) .NET 3.0

Do I need to template the items?

[A]
Use
StringFormat
in the Binding expression like
```
```
<TextBox Text="{Binding Path=Value, StringFormat=Amount: {0:C}}"/>
```
```
See this
blog for more details.
A
ValueConverter
is another way - StringFormat doesnt work on .NET3.0 it needs WPF3.5 SP1.


q: Where can I find either literature or video demonstration of unit testing applications using VB.NET? As a novice/hobbyist programmer I would like to build a solid foundation in developing applications using the unit testing methodology.

[A]
If it helps any, you may want to learn C# if you plan on staying in the .NET world and ever plan to use .NET professionally.  I've answered why
here
.  Now, on to your question: O'Reilly and Associates had an
article on this very subject
recently (if by 2005 you mean recent, but for our purposes, we can call it recent).  You may also want to learn
Nunit
, which is a unit testing framework for .NET.
As far as Books:
Open Source .NET Development
- Covers Nunit.
eXtreme .NET: Introducing eXtreme Programming Techniques to .NET Developers
Test Driven Development in Microsoft.NET
That should get you started.  I don't know whether the code examples are in VB or C#, but if you have a
Safari online
subscription (which I highly recommend), you'll be able to browse these books without dropping money on them.


[A]
In PHP and C++ you can use the printf() function
```
```
printf("$%01.2f", $money);
```
```


q:
What are some of the ways you have implemented models in the Zend Framework?

I have seen the basic class User extends Zend_Db_Table_Abstract and then putting calls to that in your controllers:

$foo = new User;

$foo->fetchAll()

but what about more sophisticated uses? The Quickstart section of the documentation offers such an example but I still feel like I'm not getting a "best use" example for models in Zend Framework. Any interesting implementations out there?

EDIT: I should clarify (in response to CMS's comment)... I know about doing more complicated selects. I was interested in overall approaches to the Model concept and concrete examples of how others have implemented them (basically, the stuff the manual leaves out and the stuff that basic how-to's gloss over)

[A]
You can do more complicated queries, check the
Advanced usage
section in the
```
Zend_Db_Table
```
manual page.
```
```
$select = $table->select();
$select->from($table,
              array('COUNT(reported_by) as `count`', 'reported_by'))
       ->where('bug_status = ?', 'NEW')
       ->group('reported_by');
```
```


q:
I have a table like this:

<table>
    <tfoot>
        <tr><td>footer</td></tr>
    </tfoot>
    <tbody>
        <tr><td>Body 1</td></tr>
        <tr><td>Body 1</td></tr>
        <tr><td>Body 1</td></tr>
    </tbody>
    <tbody>
        <tr><td>Body 2</td></tr>
        <tr><td>Body 2</td></tr>
        <tr><td>Body 2</td></tr>
    </tbody>
    <tbody>
        <tr><td>Body 3</td></tr>
        <tr><td>Body 3</td></tr>
        <tr><td>Body 3</td></tr>
    </tbody>
</table>

I'd like to put some spacing between each tbody element, but padding and margin have no effect. Any ideas?

[A]
Try this, if you don't mind not having borders.
```
```

footer

Body 1

Body 1

Body 1

Body 2

Body 2

Body 2

Body 3

Body 3

Body 3

```
```


q:
I have a project that I have been working on for a while, just one of those little pet projects that I would like to one day release to open source.

Now I started the project about 12 months ago but I was only working on it lightly, I have just started to concentrate a lot more of my time on it(almost every night).

Because it is a framework like application I sometimes struggle with a sense of direction due to the fact I don't have anything driving my design decisions and I sometimes end up making features that are hard to use or even find.  I have been reading about how to do TDD and thought maybe this will help me with some of the problems that I am having.

So the question is do you think it's a good idea to start using TDD on a project that doesn't already use it.

EDIT: I have just added a bit to clarify what I mean by struggle with a "sense of direction", it properly wasn't the best thing to say without clarification.

[A]
In my opinion, it's never too late to adopt a better practice - or to drop a worse one - so I'd say "Yes, you should start".
However ... (there's always a "but") ...
... one of the biggest gains of TDD is that it impacts on your design, encouraging you to keep reponsibilties separate, interactions clean and so on.
At this point in your project, you may find it difficult to get tests written for some aspects of your framework. Don't give up though, even if you can't test some areas, your quality will be the better for the areas you can test, and your skills will improve for the experience.


q:
I have a JSF form that needs to upload a file via an icon click (i.e. without showing the textfield/browse button of the file upload component).

Is it possible to trigger the file-open dialog and uploading functionality of the upload component via some other component type?


q:
I have a winforms app and i want to keep track of every time a user clicks certain buttons, etc as well as other actions.  What is the best way for me to keep track of this information and then put it together so i can run metrics on most used features, etc.

This is a winforms app and I have users around the world.

[A]
I'd try something like this:
```
```
// execute this method once all forms have been created
    public static void HookButtons()
    {
         foreach( Form f in Application.OpenForms )
         {
              EnumerateControls( f.Controls );
         }
    }

    public static void EnumerateControls( ICollection controls )
    {
        foreach( Control ctrl in controls )
        {
            if( ctrl.Controls.Count > 0 )
            {
                EnumerateControls( ctrl.Controls );
            }

            if( ctrl is ButtonBase )
            {
                ctrl.MouseClick +=new MouseEventHandler( ctrl_MouseClick );
            }
        }

    }

    static void ctrl_MouseClick( object sender, MouseEventArgs e )
    {
        ButtonBase clicked = ((ButtonBase)sender);

        // do something with the click information here
    }
```
```


q: Is there an equivalant to Environment.NewLine in DotNet for a Tab character?

[A]
NewLine is on the Environment class because the new line specification varies between platforms:
It's "\r\n" for non-Unix platforms and "\n" for Unix platforms. However tab is always "\t".


q: I need to create an empty .mdb file, so that I can then run ADO commands on it (not ADO.NET). Is there a way to create an empty mdb using ADO?

[A]
Here are some code snippets that work:
```
```
string sADOProvider = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";

        ADOX.CatalogClass cat = new ADOX.CatalogClass();

        string sCreate = MainForm.sADOProvider + sFullPath;

        cat.Create(sCreate);

        // The point of this code is to unlock the access file after we
        // create it.   You can tell it is unlocked if the .ldb file disappears.
        System.Runtime.InteropServices.Marshal.ReleaseComObject(cat);
        cat = null;
        GC.Collect();
```
```


q:
I am working on an application that will be used as an extensible framework for other applications.

One of the fundamental classes is called Node, and Nodes have Content. The SQL tables look like this:

TABLE Node ( NodeId int, .... etc )

TABLE NodeContentRelationship ( NodeId int, ContentType string, ContentId int)

It will be up to the developers extending the application to create their own content types.

Clearly this is bad from a relationship-database point of view as it is not possible to add a foreign key relationship to NodeContentRelationship.ContentId, even though it is a foreign key column.

However, the solution is quite simple and powerful so I am reluctant to change it.

What do you think - am I in for a world of pain down the track?

[A]
Beware the
Inner Platform Effect
.
If you're trying to build an 'extensible framework' which allows developers to store data of different 'content types' and relate them to each other in a generic fashion, you may find that others have already
solved
this
problem
.


q: As prescribed by Yahoo!, gzip'ng files would make your websites load faster. The problem? I don't know how :p

[A]
http://www.webcodingtech.com/php/gzip-compression.php
Or if you have Apache, try
http://www.askapache.com/htaccess/apache-speed-compression.html
Some hosting services have an option in the control panel.  It's not always possible, though, so if you're having difficulty, post back with more details about your platform.


q:
I'm dealing with an Oracle DBA at the moment, who has sent me some profiling he's done. One of the terms in his report is 'Buffer Gets', any idea what this actually means? My guess is bytes retrieved from a buffer, but I have no idea really. Here is some sample output:

  Buffer Gets    Executions  Gets per Exec  %Total Time (s)  Time (s) Hash Value
--------------- ------------ -------------- ------ -------- --------- ----------
    137,948,100       31,495        4,380.0   98.4  6980.57   6873.46 4212400674
Module: JDBC Thin Client
SELECT fieldOne, fieldTwo, fieldThree, fieldFour, fieldFive FROM TableExample
WHERE fieldOne = 'example'

It would also be handy to know what 'Gets per Exec' means, as I guess they are related? I'm a programmer, but not a DBA.

[A]
Oracle storage is arranged into blocks of a given size (e.g. 8k).  Tables and indexes are made up of a series of blocks on the disk.  When these blocks are in memory they occupy a buffer.
When Oracle requires a block it does a
buffer get
.  First it checks to see if it already has the block it needs in memory.  If so, the in-memory version is used.  If it does not have the block in memory then it will read it from disk into memory.
So a buffer get represents the number of times Oracle had to access a block.  The reads could have been satisfied either from memory (the buffers) or have resulted in a physical IO.
Since physical IO is so expensive (compared to memory or CPU) one approach to tuning is to concentrate on reduction in buffer gets which is assumed will flow on to reduce physical IO.


q:
In the application that I am working on, the logging facility makes use of sprintf to format the text that gets written to file. So, something like:

char buffer[512];
sprintf(buffer, ... );

This sometimes causes problems when the message that gets sent in becomes too big for the manually allocated buffer.

Is there a way to get sprintf behaviour without having to manually allocate memory like this?

EDIT: while sprintf is a C operation, I'm looking for C++ type solutions (if there are any!) for me to get this sort of behaviour...

[A]
"the logging facility makes use of sprintf to format the text that gets written to file"
```
fprintf()
```
does not impose any size limit. If you can write the text directly to file, do so!
I assume there is some intermediate processing step, however. If you know how much space you need, you can use
```
malloc()
```
to allocate that much space.
One technique at times like these is to allocate a reasonable-size buffer (that will be large enough 99% of the time) and if it's not big enough, break the data into chunks that you process one by one.


q:
When using call_user_func_array() I want to pass a parameter by reference.  How would I do this.  For example

function toBeCalled( &$parameter ) {
    //...Do Something...
}

$changingVar = 'passThis';
$parameters = array( $changingVar );
call_user_func_array( 'toBeCalled', $parameters );

[A]
To pass by reference using
```
call_user_func_array()
```
, the parameter in the array must be a reference - it does not depend on the function definition whether or not it is passed by reference.  For example, this would work:
```
```
function toBeCalled( &$parameter ) {
    //...Do Something...
}

$changingVar = 'passThis';
$parameters = array( &$changingVar );
call_user_func_array( 'toBeCalled', $parameters );
```
```
See the notes on the
```
call_user_func_array()
```
function documentation
for more information.


q:
Using google's Protocul Buffers, I have a service already written in Java which has its own data structures already. I'd like to use pb to delivering messages and I'm looking for a way to serialize the existing data structures that I have in Java to pb.
I can start by defining all the data structures in pb from scratch, which is probably the right way to go but I'm too lazy.
So, say I have a Person class in Java (or other supported languages) or a Plane class which has tens of attributes in it, is there a way to serialize that class to pb? Can I have a pb attribute of type Plane? (when Plane is not a pb, it's a Java class)

[A]
No, you can't. Fields in protobuf messages are always the primitives (numbers, strings and byte arrays, basically), protobuf enums (which are generated as Java enums) or protobuf messages - and repeated versions of all of those, of course.
You could potentially write a tool which used reflection to create a .proto file from a Java class, but I suspect you'd find it quicker just to do it by hand. In particular, if you
did
use reflection you'd want to make sure that the fields were always generated with the same name, to maintain compatibility. One thing you
could
do is annotate the Java classes and write code to generate the .proto file based on those annotations - or even potentially serialize directly to proto format using the annotations. Personally I'd recommend creating the .proto file in
some
way rather than effectively rewriting the PB project - otherwise there's a significant risk of introducing bugs where there's already thoroughly tested code.
If you
do
create an annotation system, I'm sure Kenton Varda (and the rest of the PB community) would be interested in seeing it.


q:
I have a very tricky situation (for my standards) in hand. I have a script that needs to read a script variable name from ConfigParser. For example, I need to read

self.post.id

from a .cfg file and use it as a variable in the script. How do I achieve this?

I suppose I was unclear in my query. The .cfg file looks something like:

[head]
test: me
some variable : self.post.id

This self.post.id is to be replaced at the run time, taking values from the script.

[A]
test.ini:
```
```
[head]
var: self.post.id
```
```
python:
```
```
import ConfigParser

class Test:
  def __init__(self):
      self.post = TestPost(5)
  def getPost(self):
      config = ConfigParser.ConfigParser()
      config.read('/path/to/test.ini')
      newvar = config.get('head', 'var')
      print eval(newvar)

class TestPost:
  def __init__(self, id):
      self.id = id

test = Test()
test.getPost()   # prints 5
```
```


q: I have a sharepoint event handler which I want to activate for a single list, not all the lists in the site. How do I go about this?

[A]
Just that list or that list in each site ?
I have been testing the code that run when the event happens and I have used a
nice little tool
from u2u, which allows me to add or remove event handlers per list.
This MSDN article
is a nice primer.


q:
How do I convert a string to the variable name in Python?

For example, if the program contains a object named self.post that contains a variable named, I want to do something like:

somefunction("self.post.id") = |Value of self.post.id|

[A]
As referenced in Stack Overflow question
Inplace substitution from ConfigParser
, you're looking for
```
eval()
```
:
```
```
print eval('self.post.id') # Prints the value of self.post.id
```
```


q:
I am a COM object written in ATL that is used from a C++ application, and I want to pass an array of BYTEs between the two.  My experience of COM/IDL so far is limited to passing simple types (BSTRs, LONGs, etc.).

Is there a relatively easy way to have the COM object pass an array to the caller?  For example, I want to pass a raw image (TIFF) instead of messing with temporary files.

[A]
Check out using
safearrays
. Here's some example code:
The safearray is returned as a pointer to a VARIANT
```
```
[id(1), helpstring("LogCache")] HRESULT LogCache([out,retval] VARIANT* logCache);
```
```
Safearrays are pretty easy to use. Here's some example code which is a cache of the latest 1000 log messages of some application:
```
```
safearray_t<bstr_t> m_logCache;
   ...
   if (m_logCache.size() > 1000)
   {
       m_logCache.pop_back();
   }

   m_logCache.push_front(Msg.str(), 0);

    variant_t LogCache()
    {
        if (!m_logCache.is_empty())
        {
            variant_t cache(m_logCache);
            return cache;
        }
    }
```
```
Note that the syntax in your case is almost certainly going to be different since I'm using the
comet COM library
, but the ideas/concepts are the same.


q:
When we write in a Javascript expression :

expression < <%=variableJsp%>

the double "<" seems to be a problem and the JSP is not interpreted ?

Is it a fault of the other servers that should not accept this type of expression ? Or WebSphere that bugs ?

[A]
I find it generally a bad idea to inline javascript on jsp pages.Your problem is only one of the reasons to make javascript functions external.
Although I do not know websphere, this has happened to me on other containers.
If you insist on keeping it inline, you can probably use
```
```
expression < <%=variableJsp%>
```
```