q:
I am creating a mobile web application using asp.net. The application must support iPhone, Blackberry and Windows Mobile Platform. What are the low things which should be taken care of while developing this application. Is there any best practices list available for this?

Summary:

[A]
Can you add some more info? If you are developing a application for all those platforms, I would guess you are creating either some sort of web-services or just a "standard" web-application?
If it's just a standard web-application, I think it's a bit hard to ensure a good compatibility due to the fact that javascript, which is widely used in webapplications isn't always implemented in browsers for mobile phones.... Yes, if you have Opera, and not Pocket Internet Explorer, it get's a bit better. When it comes to Blackberry I'm not quite sure how well the browser performs.
Iphone on the other hand is probably "easy" to develop for, since it's default browser is probably good at javascript - just as Opera mini.
Also - Other graphical issues due to the fact that many Windows Mobile devices have a reather low resolution should also be taken in consideration, but this is eventually getting better with the new devices beeing released :) (As Touch HD, Omnia, Diamond etc)


q:
P1 and P2 are processes or nodes in a cluster. f1 and f2 are their flags. Supposing  strong memory model, and that both processes may be restarted at any moment, and that restarting a process clears it's flag, here's an algorithm that I came up with and couldn't yet break, but that bothers me for it's not theoretically proven and looks too simple compared with Peterson's.

P1 start:
set f1
if f2 set then clear f1, wait some, goto start
else enter critical section
do whatever
clear f1

P2 start:
set f2
if f1 set then clear f2, wait some, goto start
else enter critical section
do whatever
clear f2

Can anybody see a flow? Except may be that one of the processes may starve the other by quickly re-entering the section?

[A]
If the "if X set then clear Y" operation is not atomic, there's a potential race condition that could prevent either from getting inside the critical section. I've tried to outline the flow below:
```
```
P1: set f1
P2: set f2
P1: is f2 set?
P2: is f1 set?
P1: yes, clear f1
P2: yes, clear f2
P1: start wait
P2: start wait
P1: end wait
P2: end wait
P1: goto start
P2: goto start
```
```
This could potentially go on forever, until there's a difference in the allocation done by the task scheduler, or the wait times for the two P are different from one another.

s: huggingface

c: devops

d: intermediate


q:
I have two tables, movies and categories, and I want to get an ordered list by categoryID first and then by Name.

The movie table has three columns ID, Name and CategoryID.
The category table has two columns ID and Name.

I tried something like the following, but it didn't work.

var movies = _db.Movies.OrderBy( m => { m.CategoryID, m.Name })

[A]
This should work for you:
```
```
var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name)
```
```


q:
How do I send a cross-domain POST request via JavaScript?

Notes - it shouldn't refresh the page, and I need to grab and parse the response afterwards.

[A]
Create an iFrame,
put a form in it with Hidden inputs,
set the form's action to the URL,
Add iframe to document
submit the form
Pseudocode
```
```
var ifr = document.createElement('iframe');
 var frm = document.createElement('form');
 frm.setAttribute("action", "yoururl");
 frm.setAttribute("method", "post");

 // create hidden inputs, add them
 // not shown, but similar (create, setAttribute, appendChild)

 ifr.appendChild(frm);
 document.body.appendChild(ifr);
 frm.submit();
```
```
You probably want to style the iframe, to be hidden and absolutely positioned.  Not sure cross site posting will be allowed by the browser, but if so, this is how to do it.


q: I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?

[A]
Jauco posted a good solution in a comment, so I'm copying it here:
```
```
$(elem)
  .contents()
  .filter(function() {
    return this.nodeType === 3; //Node.TEXT_NODE
  });
```
```


q:
can i somehow compare two numbers in regex?
i want regex that is correct for 10-12, but incorrect for 12-10. I mean that 10 must be smaller than 12.
I want to do it in Javascript.

[A]
I wouldn't use regex for this.  I'd split the string on the operator, then compare the two resulting numbers based on what operator I found (I'm assuming
```
10+12
```
and
```
12+10
```
would both be legal).


q:
I'm trying to ensure a script remains running on a development server. It collates stats and provides a web service so it's supposed to persist, yet a few times a day, it dies off for unknown reasons. When we notice we just launch it again, but it's a pain in the rear and some users don't have permission (or the knowhow) to launch it up.

The programmer in me wants to spend a few hours getting to the bottom of the problem but the busy person in me thinks there must be an easy way to detect if an app is not running, and launch it again.

I know I could cron-script ps through grep:

ps -A | grep appname

But again, that's another hour of my life wasted on doing something that must already exist... Is there not a pre-made app that I can pass an executable (optionally with arguments) and that will keep a process running indefinitely?

In case it makes any difference, it's Ubuntu.

[A]
Monit
is perfect for this :)
You can write simple config files which tell monit to watch e.g. a TCP port, a PID file etc
monit will run a command you specify when the process it is monitoring is unavailable/using too much memory/is pegging the CPU for too long/etc. It will also pop out an email alert telling you what happened and whether it could do anything about it.
We use it to keep a load of our websites running while giving us early warning when something's going wrong.
-- Your faithful employee, Monit


q:
When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}.

Is there a way to access the same variable in Javascript (perhaps using the DOM, I don't know how Django makes the variables accessible)? I want to be able to lookup details using an AJAX lookup based on the values contained in the variables passed in.

[A]
The
```
{{variable}}
```
is substituted directly into the HTML. Do a view source; it isn't a "variable" or anything like it. It's just rendered text.
Having said that, you can put this kind of substitution into your JavaScript.
```
```
<script type="text/javascript">
   var a = "{{someDjangoVariable}}";
</script>
```
```
This gives you "dynamic" javascript.


q:
Since Terminal appeared I've saved as ~/mySrvr.term a modified stock .term file
which opens to execute an ssh to a remote server and to modify the appearance.
I have NOT been able to save "use option key as meta" for emacs-ery; there's no slot for it
in the term file and I'm reluctant to wrestle with a keyboard dictionary file.
Am I missing something simple?  How do I get option-as-meta to stick between sessions?

Thanks

[A]
Not sure if this helps, but when I go Shell -> Export Settings and save the file as a .terminal file, there are a few lines that save my option-as-meta preference:
```
```
<key>useOptionAsMetaKey</key>
<true/>
```
```
These lines are for a .terminal preference file, not for a .term (which is pretty hard to Google for) so they may not be what you're looking for.


q:
I have an IIS located on serverA

I have userA at locationA who has opened a content management system site, hosted on serverA.

One of the features of the system is that it allows the user to move a file to LocationB, all within the same network. Now when this move occurs and due to bandwidth restrictions, would this file move from LocationA to serverA to LocationB or is there a way for me to move the file from LocationA to LocationB without going through serverA, i.e using local memory on serverA

I am not using BITS at the moment.

[A]
That's entirely going to depend on how the CMS works - if it does an
```
scp
```
in the background, then the answer is yes - it skips the local machine.
If it uses http to transfer it to the user's machine then back out, the answer is "no".


q:
I have two Tables.

Order - With Columns OrderID, OrderStatusID

OrderStatus - With Columns OrderStatusID, Description

I have an Order Object which calls to the database and fills its properties for use in my code.  Right now I have access to Order.OrderStatusID, but in my application I really need access to the "Description" field.

How do you handle this elegantly with good OO design?

[A]
You can use a SQL select statement with a Join to the OrderStatus table, and include the columns yo want from each table ...
```
```
Select O.OrderId, O.OrderStatusId, S.Descriptiuon
From Order O
    Join OrderStatus S
        On S.OrderStatusId = O.OrderStatusId
Where OrderId = 23 -- or whatever
```
```


q:
Is there a way to read the properties inside an MSI file?

For example, given a MSI file named Testpackage.msi, I need to find

productName
PackageCode
version

This I am going to use it with WMI uninstall

string objPath = string.Format("Win32_Product.IdentifyingNumber='{0}', Name='{1}', Version='{2}'", "{AC9C1263-2BA8-4863-BE18-01232375CE42}", "testproduct", "10.0.0.0");

Using Orca is a great option, if this can be achieved programmatically. Then I can use this to generate automatic release notes. And in un-installing program too.

[A]
You can use
Microsoft's Orca.exe
.  Orca will allow you to open the MSI and edit/view all the tables in it. You will have to download the entire
Windows SDK
in order to get it, but thankfully that is free.
One alternative (which might be faster due to the download size of the SDK) is to use dark.exe from the
WiX project
.  Dark is a MSI decompiler, which will export everything into an XML file and collection of resources. The XML it outputs will have the information you are looking for.


q:
is there a managed code (without adding COM component or wrapped called to C++ routines) way to add integrated security to a C# Managed code assembly?

i.e. I want to write a client-server system where the server uses Remoting instead of IIS, but I want the client to automatically pass it's credentials to the server just like a browser does when communicating with an IIS server that has Integrated security enabled...

Can this be done? and if so, where is there some examples ?

[A]
When you say "remoting instead of IIS," what exactly do you mean? A remoting endpoint (the server end) is typically hosted in IIS since this gives you lots of stuff for free, like authentication, scaling through load balancing - especially for singlecall type objects - that is to say, you don't want to keep state for successive calls to the endpoint.
You can host a remoting endpoint using the http stack in a client app also in xp/sp2 and beyond utilising the http.sys driver directly (which is handleded automatically for you btw).
Regardless, for automatic logon with NTLM credentials, I suggest you host remoting in IIS, and use System.Net.CredentialCache.DefaultCredentials for the client's credentials your client app. This will pass the context credentials to the server app, presuming the current security zone (intranet/internet/trusted/etc) allows it.
-Oisin


q:
I'm wondering what good ways there would be make assertions about synchronization or something so that I could detect synchronization violations (while testing).

That would be used for example for the case that I'd have a class that is not thread-safe and that isn't going to be thread-safe. With some way I would have some assertion that would inform me (log or something) if some method(s) of it was called from multiple threads.

I'm longing for something similar that could be made for AWT dispatch thread with the following:

public static void checkDispatchThread() {
    if(!SwingUtilities.isEventDispatchThread()) {
        throw new RuntimeException("GUI change made outside AWT dispatch thread");
    }
}

I'd only want something more general. The problem description isn't so clear but I hope somebody has some good approaches =)

[A]
For the specific example you give, SwingLabs has some helper code to detect event thread violations and hangs.
https://swinghelper.dev.java.net/
A while back, I worked with the JProbe java profiling tools.  One of their tools (threadalyzer?) looked for thread sync violations.  Looking at their web page, I don't see a tool by that name or quite what I remember.  But you might want to take a look.
http://www.quest.com/jprobe/performance-home.aspx


q:
I've been putting together a small web form for our technicians to use from their phones out in the field.  However I'm having a lot of trouble getting things working using ASP.NET Mobile, and there seems to be few resources out there to help learn this stuff.  I'm also having trouble getting help.

So the thing is, do I really need to use the mobile controls?  The phones will all have web browsers, so I'm thinking if I'm careful with the interface I can get as good or better results than using the mobile controls.

The only thing I would like from the mobile controls is the PhoneCall control... so the follow up question would be: Can I get the functionality of the PhoneCall control without using it?

[A]
Use mobile controls has same adventages that web controls in web. Using Mobile Controls + Controls Adapters + WURFL helps to developing very fast to many devices.
Yes, you can use WTAI primitives of WML:
```
<a ref="wtai://wp/mc;34123456789">Call</a>
```


q:
I'm wondering why the assert keyword is so underused in Java? I've almost never seen them used, but I think they're a great idea. I certainly much prefer the brevity of:

assert param != null : "Param cannot be null";

to the verbosity of:

if (param == null) {
    throw new IllegalArgumentException("Param cannot be null");
}

My suspicion is that they're underused because

They arrived relatively late (Java 1.4), by which time many people had already established their Java programming style/habit

They are turned off at runtime by default

[A]
In fact they arrived in Java 1.4.
I think the main problem is that when you code in an environment where you do not manage JVM options directly by yourself like in
Eclipse
or J2EE servers (in both cases it is possible to change JVM options, but you need to deeply search to find where it can be done), it is easier (I mean it requires less effort) to use
```
if
```
and exceptions (or worse not to use anything).


q: In vb.net / winforms, how can a hashtable be bound to a drop down list or any other datasource-driven control?

[A]
Just use the dropdown lists's Datasource property
```
```
DropDownList dd = new DropDownList();
   Hashtable mycountries = New Hashtable();
   mycountries.Add("N","Norway");
   mycountries.Add("S","Sweden");
   mycountries.Add("F","France");
   mycountries.Add("I","Italy");
   dd.DataSource=mycountries;
   dd.DataValueField="Key";
   dd.DataTextField="Value";
   dd.DataBind();
```
```


q:
Question says it all really...

I have tried changing the "Allow non-admin users to run this program" setting on the property pages, and have also given the non-admin user in question what looks like the correct privileges in Component Services -> DCOM Config.

Is there anything else I can do ?

This is on Server2003 BTW.

Thanks

Matt

[A] I saw your question a few days ago, but didn't answer because all I have is something for you to try. I expected someone else with knowledgeable answer to respond, but since you still have no answers I'll tell you the little bit I know. When our tech support department installs our app onto a computer running XP or Vista they log in with an administrator account the first time they run the app. Apparently that allows what ever needs to happen with the ActiveX DLLs to work. After that the users can log in with their regular account and the app is still happy.


q:
Clearly separation of concerns is a desirable trait in our code and the first obvious step most people take is to separate data access from presentation. In my situation, LINQ To SQL is being used within data access objects for the data access.

My question is, where should the use of the entity object stop? To clarify, I could pass the entity objects up to the domain layer but I feel as though an entity object is more than just a data object - it's like passing a bit of the DAL up to the next layer too.

Let's say I have a UserDAL class, should it expose an entity User object to the domain when a method GetByID() is called, or should it spit out a plain data object purely for storing the data and nothing more? (seems like wasteful duplication in this case)

What have you guys done in this same situation? Is there an alternative method to this?

Hope that wasn't too vague.

Thanks a lot,

Martin.

[A]
I return IQueryable of POCOs from my DAL (which uses LINQ2SQL), so no Linq entity object ever leaves the DAL. These POCOs are returned to the service and UI layers, and are also used to pass data back into the DAL for processing. Linq handles this very well:
```
```
IQueryable<MyObjects.Product> products = from p in linqDataContext.Products
                                          select new MyObjects.Product //POCO
                                          {
                                              ProductID = p.ProductID
                                          };
 return products;
```
```


q:
Seeing as C# can't switch on a Type (which I gather wasn't added as a special case because is relationships mean that more than one distinct case might apply), is there a better way to simulate switching on type other than this?

void Foo(object o)
{
    if (o is A)
    {
        ((A)o).Hop();
    }
    else if (o is B)
    {
        ((B)o).Skip();
    }
    else
    {
        throw new ArgumentException("Unexpected type: " + o.GetType());
    }
}

[A]
One option is to have a dictionary from
```
Type
```
to
```
Action
```
(or some other delegate). Look up the action based on the type, and then execute it. I've used this for factories before now.


q:
I'm trying to have an XSLT that copies most of the tags but removes empty "<b/>" tags. That is, it should copy as-is "<b> </b>" or "<b>toto</b>" but completely remove "<b/>".

I think the template would look like :

<xsl:template match="b">
  <xsl:if test=".hasChildren()">
    <xsl:element name="b">
      <xsl:apply-templates/>
    </xsl:element>
  </xsl:if>
</xsl:template>

But of course, the "hasChildren()" part doesn't exist ... Any idea ?

[A]
I wonder if this will work?
```
```
<xsl:template match="b">
  <xsl:if test="b/text()">
    ...
```
```


q:
Is there anybody who has successfully accessed a Web service from an Oracle stored procedure?  If so, was it a Java stored procedure?  A PL/SQL stored procedure?

Is there any reason why I should not be trying to access a WS from a stored proc?

Here are a couple refs that I found so far

Database Web Services

Calling external Web Service from a Java Stored Procedure

..Just to clarify, this is for SOAP calls

[A]
First off, what sort of web service are you calling?  I am assuming either SOAP or REST.
For REST web services, UTL_HTTP is often more than sufficient, combined with a bit of XPath in a simple PL/SQL stored procedure.
For SOAP web services, it depends on how sophisticated you need (or want) to be.  You can certainly use XQuery to create an XML document that meets the spec for the web service, use UTL_HTTP to post the document and get the response, and then use some XPath to parse the response all in PL/SQL.  This is a relatively manual and relatively brute-force solution, but if you are talking about a handful of web services, it involves a minimum of infrastructure and the calls can get knocked together pretty quickly.
If you expect the calls to evolve over time or you expect there to be a number of procedures calling a number of web services, it probably makes sense to invest time in something like UTL_DBWS (this isn't something, though, that you generally get working in a couple hours).


q: I want to create a trace on a database server from my C# app, like what you do in SQL Server Profiler. I have found stored procedures (sys.sp_trace_create etc...) that dont seem to work for my SQL management studio. I was wondering if anyone could help with the coding, or where i would start to do this?!

[A]
Are you wanting this to be real-time, just like the Profiler itself? That'd be tough to do. You'd basically be re-creating the profiler.
If that is not a requirement, I would recommend simply calling the sp_trace_create stored procs that you found to start a server-side trace, then use your application to open up the files that this trace produces.
The EASIEST way to learn how this works is to run the SQL Profiler itself, set all the options you want, then click Run, and immediately click Stop. Then go to File, Export, Script Trace Definition, and choose the appropriate version.
This should give you a TSQL script that puts all the correct pieces together, including all the trace events, columns, etc.
More technical history of the profiler:
This old SQLMag article
has some history of the Profiler, which replaced an app called "SQL Trace" when SQL 7.0 was introduced.


q: I'm working with a WinForm app in C#, after I type something in a textbox I want to hit the Enter key but the textbox still has focus (flashing cursor is still in textbox), how can I achieve this?

[A]
The simple option is just to set the forms's AcceptButton to the button you want pressed (usually "OK" etc):
```
```
TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    Application.Run(new Form { AcceptButton = btn, Controls = { tb, btn } });
```
```
If this isn't an option, you can look at the KeyDown event etc, but that is more work...
```
```
TextBox tb = new TextBox();
    Button btn = new Button { Dock = DockStyle.Bottom };
    btn.Click += delegate { Debug.WriteLine("Submit: " + tb.Text); };
    tb.KeyDown += (sender,args) => {
        if (args.KeyCode == Keys.Return)
        {
            btn.PerformClick();
        }
    };
    Application.Run(new Form { Controls = { tb, btn } });
```
```


q:
i want the result of an equation rounded to the nearest integer.
e.g.

137 * (3/4) = 103

Consider the following incorrect code.

int width1 = 4;
int height1 = 3;

int width2 = 137;
int height2 = width2 * (height1 / width1);

What is the proper way to perform "integer" math in C#?

Do i really have to do:

int height2 = (int)Math.Round(
      (float)width2 * ((float)height1 / (float)width1)
   );

[A]
```
```
int height2 = (width2 * height1) / width1;
```
```


q:
Is there a way to turn off the automatic selection of the first row in the built-in DataGrid in Silverlight?

We build a lot of functionality based off the user selecting a row in a data grid.  The automatic firing of SelectionChanged when databinding or sorting is really causing us issues.  We have tried to put some guards around the selection, but can't seem get all problems covered.

For example, if you have  DataGrid in a tab of a TabControl that is not shown when loading the screen and the DataGrid has a binding to a property of the DataContext that is a list of objects.  The grid is not databound until the tab is shown.  Is there an event telling us that the grid is databinding?  Shouldn't the default behavior of databinding be not to select a row?

Thanks
Mike

[A]
Mike,
I have solved this problem by wrapping the windows control, and catching the selection changed event of the wrapped windows grid.
In your control, hook up the Loaded event of your control, and when it is loaded, set a boolean private member variable to true.  Then when you are catching the inner data grid's selection changed event, only raise your own selection changed event if you control is loaded.  When this is done, you can now go back to the OnApplyTemplate sub, and set your inner data grid's selected index to -1 and selected item to nothing.  Since the setting of the index and item will happen before your control is finished loading, the selection changed event will not fire. I have tried this in both a tabbed and non-tabbed environment, and it seems to work without issue.  Now on to a little bit harder problem, you may have noticed that when you sort the windows data grid (while it is data bound to an ItemsSource) it always selects the top item of the displayed data.  This will of course, fire the selection changed event, and move to an item that was not previously selected, and as far as I can see, shouldn't be selected. To handle this, you will have to do a little bit more tricky coding.  If you notice, when you catch the inner grid's selection changed event, and look at its selected item, there are only a few cases where the selected item is not set to anything, those are, when there is no longer an item selected (ie. the selection is cleared), or when (HINT) the columns are sorting.  When you are sorting, there are two events that fire, first is the de-selection of the item (SelectedItem is Nothing), and the second is the selection of the top item in the list (SelectedIndex 0).  Now, if you were to put a flag in the event handler for the inner grids selection changed event, and caught the fact that the item is nothing, you could keep track of the prior selected item, and then set the inner data grid's selected item to the previously selected item.
This solves the problem decently well, and as always there may be undesired results while wrapping a windows control, but as far as I can tell, this seems to be the only way to get around the first row being selected on load problem.  I can only imagine, however, that this is going to be fixed by M$ at some point.
I hope this helps,
Thanks,
Scott


q:
Everything I can find in linq for aggregation has a "group by" clause.  How would I write this query in LINQ?  I have a list of date-value pairs, and I want to take the average of the values:

SELECT AVG(MySuff.Value) AS AvgValue FROM MyStuff

[A]
morning Alan:
```
```
int count = (from a in myContext.MyStuff
            select a).Count();
```
```
Assuming myContext is the DataContext.
Note that is gives you immediate execution, which you may not want.
You could instead store the results of the query in a var:
```
```
var allResults = from a in myContext.MyStuff
                 select a;

//sometime later when needed
int count = allResults.Count(); // executes the SQL query now!
```
```


q:
im trying to kick off a Runnable classes run method however i keep getting a NullPointerException,  Im using WebSpheres commonj.workmanager to get an instance of executorService.this is the code im using.

executorService.execute(new Runnable() {
    public void run() {
        System.out.println("Inside run ()method..");
    }
});

ANY IDEAS?

[A]
Are you checking whether
```
executorService
```
is null before calling
```
execute()
```
? If not, it sounds like you need to check the WebSphere docs.


q:
Let's say I have a List object and an iterator for that list.

Now I sort the list with java.util.Collections.sort()

What happens to the iterator?

Is its behavior still defined and can it still be used?

If not, can I prevent destroying the iterators for the list?

I know, this problem could be circumvented by changing the program design, cloning the list for example, but I specificly want to know the "official" behavior of Java.

[A]
Iterators are generally invalid after
any
modification to their underlying collections, except via the iterator itself. (For instance,
```
ListIterator
```
allows for insertion and removal.)
I'd certainly expect any iterators to become invalidated after a sort though - and if they weren't, I'd have no idea what order to expect.


q:
I'm playing with this ActionScript which generates a random 'squiggle'.

Each time a 'squiggle' is placed, it appears within a sprite with a white background.

If I change the background colour of the flash file to pink for example, it would still show up as white.

Does anybody know how I might make the sprite background transparent? Thanks.

[A]
That is not an actual Sprite (Sprite is an AS3 datatype) it's just a MovieClip that's called 'sprite'. I see that in the code the squiggles are actually being drawn to a MovieClip called 'paintSurface', then when it's done a Bitmap of 'paintSurface' is captured via this line:
```
```
bitmapData.draw(paintSurface);
```
```
then it is attached to the 'sprite' MovieClip here:
```
```
sprite.attachBitmap(bitmapData, 3);
```
```
That is probably why you are getting the white background.
I assume the bitmap is being captured for the sake of processing speed.
Perhaps you could see what happens if you do not capture a bitmap, but instead just attach 'paintSurface' to 'sprite' instead.


q:
Currently reading quite a heavy WCF book. I have used it myself in production just the once, using tcp, worked a charm.
Anyway what are your opinions on this technology, is it here to stay, is it worth the time invested learning all the complex features etc etc?

[A]
I think it is here to stay.  It is easily configurable for moving endpoints, it seems robust and allows you to do (pretty much) everything you could do in web services and remoting without the overhead of separate implementations.
I can see where you are coming from, with MS's recent leaks about ongoing support for, and maintenance of  Linq to SQL, but I see WCF as a different beast altogether.  This is a technology that allows interoperability, as well as de-complixifying (I know this isn't a real word, but it should be) communications between systems.


q: What does the SQL Action keyword do?  Can I use this keyword in a trigger and determine if the trigger was called by an Insert, Delete or Update?

[A]
No, you can't use it for that. But you can look at the
Inserted and Deleted
tables to see what happened.
A vary basic example would go something like this:
```
```
If exists (select * from inserted) and exists (select * from deleted)
    --Update happened
If exists (select * from inserted)
    --Insert happened
If exists (select * from deleted)
    --Delete happened
Else
    --Nothing happened
```
```
Realistically, though, it just depends on what you need to do.  In some cases, you might just end up joining on these tables by primary key and do various things.
If you post more details in your question about what you're attempting, though, it'd be easier to give a more specific response.


q:
Ok, heres my issue: I have a JSF application and some JSP files. Let's say i have main.jsp which has a view and includes sub.jsp. This works fine. sub.jsp contains a subview. As a result all the ID's of the form elements in sub.jsp follow the form of 'subview:component'. Now suppose I'm using some ajax and want to fetch the jsp page sub.jsp and include it in a DIV somewhere. Now the ID's all are of the form 'component'. I don't know a way around this, and having to check for 2 different sets of IDs in my interactive javascript is a pain. Is there any way to get consistent IDs?

I've tried:
Removing the subview - (then the AJAX call will fail because no view is found)

and

h:form prependid=false - this only removes the form id, not the subview ids

[A]
AJAX is tricky to do with JSF. If the JSF framework you're using doesn't support it, you'll run into many view state problems.
I'm surprised an exception isn't thrown when you address
sub.jsp
directly - there should be no h:view in
sub.jsp
and without a UIViewRoot, I'm not sure how a UI tree would be created. If you have a h:view in
sub.jsp
, then you're putting two UIViewRoots into your UI tree - this is a bug. (The JSF component tree is roughly analogous to that of other Java widget kits like Swing or SWT.)
I suspect the problem you're observing is that you're submitting to a different view to the one that was originally rendered. Since the component tree is completely different, the clientIds will be generated from a different view root. You can read about how they are built in
this answer
.
In short, I do not think the mechanism you're using to update the client is a valid one.


q:
I am looking for good ideas for implementing a generic way to have a single line (or anonymous delegate) of code execute with a timeout.

TemperamentalClass tc = new TemperamentalClass();
tc.DoSomething();  // normally runs in 30 sec.  Want to error at 1 min

I'm looking for a solution that can elegantly be implemented in many places where my code interacts with temperamental code (that I can't change).

In addition, I would like to have the offending "timed out" code stopped from executing further if possible.

[A]
Well, you could do things with delegates (BeginInvoke, with a callback setting a flag - and the original code waiting for that flag or timeout) - but the problem is that it is very hard to shut down the running code. For example, killing (or pausing) a thread is dangerous... so I don't think there is an easy way to do this robustly.
I'll post this, but note it is not ideal - it doesn't stop the long-running task, and it doesn't clean up properly on failure.
```
```
static void Main()
    {
        DoWork(OK, 5000);
        DoWork(Nasty, 5000);
    }
    static void OK()
    {
        Thread.Sleep(1000);
    }
    static void Nasty()
    {
        Thread.Sleep(10000);
    }
    static void DoWork(Action action, int timeout)
    {
        ManualResetEvent evt = new ManualResetEvent(false);
        AsyncCallback cb = delegate {evt.Set();};
        IAsyncResult result = action.BeginInvoke(cb, null);
        if (evt.WaitOne(timeout))
        {
            action.EndInvoke(result);
        }
        else
        {
            throw new TimeoutException();
        }
    }
    static T DoWork<T>(Func<T> func, int timeout)
    {
        ManualResetEvent evt = new ManualResetEvent(false);
        AsyncCallback cb = delegate { evt.Set(); };
        IAsyncResult result = func.BeginInvoke(cb, null);
        if (evt.WaitOne(timeout))
        {
            return func.EndInvoke(result);
        }
        else
        {
            throw new TimeoutException();
        }
    }
```
```


q:
i'm a long-time newbie to c#, and this question may be too obvious, so please forgive if i'm "doing it wrong."

Using Visual Studio 2005 Pro, C#, SQL Server 2000 EE SP3.

I have a stored proc that takes one input param and returns several output params pertaining to that input. I am also calling it successfully, and String.Format-ing the outputs into a RichTextBox. I'd like to call this proc periodically and each time stick the output params into a DataGridView row, so the results accumulate over time.

What's the simplest/most elegant way to do get those parameters into the DataGridView? I'd prefer code instead of some GUI builder solution.

Am i overlooking some better approach, such as a more appropriate control?

Thanks!

[A]
```
```
//set up the datatable
DataTable dt = new DataTable("parms");
dt.Columns.Add("ParmName",typeof(string));
dt.Columns.Add("ParmValue",typeof(string));
//bind to a gui object
myDataGridView.DataSource = dt;

//do this after each sproc call
foreach (SqlParameter parm in cmd.Parameters)
{
    if (parm.Direction == ParameterDirection.Output)
    {
        //do something with parm.Value
        dt.Rows.Add(new object [] { parm.ParameterName,
            Convert.ToString(parm.Value) } );
    }
}
```
```


q: I am trying to monitor my outlook inbox so whenever new emails come in with attachments I  save the attachment to some other location. Can anyone help me out?

[A]
This is not a complete solution, but it describes some of the fundamental tools you'll be using in the Outlook API.
From
Access Outlook Emails with ASP.NET, C#
:
```
```
using Outlook;

 Outlook.Application oOutlook;
 Outlook.NameSpace oNs;
 Outlook.MAPIFolder oFldr;
 long iAttachCnt;

 try
 {
     oOutlook = new Outlook.Application();
     oNs = oOutlook.GetNamespace(”MAPI”);

     //getting mail folder from inbox
     oFldr = oNs.GetDefaultFolder(OlDefaultFolders.olFolderInbox);
     Response.Write(”Total Mail(s) in Inbox :” + oFldr.Items.Count + “
”);
     Response.Write(”Total Unread items = ” + oFldr.UnReadItemCount);
     foreach (Outlook.MailItem oMessage in oFldr.Items)
     {
         StringBuilder str = new StringBuilder();
         str.Append(”

Sender :	”);
         str.Append(oMessage.SenderEmailAddress.ToString() + “
”);
         //basic info about message
         str.Append(”
Date :	” + oMessage.SentOn.ToShortDateString() + “
”);
         if (oMessage.Subject != null)
         {
             str.Append(”
Subject :	” + oMessage.Subject.ToString() + “
”);
         }
         //reference and save all attachments

         iAttachCnt = oMessage.Attachments.Count;
         if (iAttachCnt > 0)
         {
             for (int i = 1; i <= iAttachCnt; i++)
             {
                 str.Append(”
Attachment(” + i.ToString() + “) :	” + oMessage.Attachments[i].FileName + “
”);
             }
         }
         str.Append(”

”);
         Response.Write(str.ToString());

     }

 }
 catch (System.Exception ex)
 {
     Response.Write(”Execption generated:” + ex.Message);
 }
 finally
 {
     GC.Collect();
     oFldr = null;
     oNs = null;
     oOutlook = null;

 }
```
```


q: What is the best way to convert word HTML to word XML? I cannot buy a tool so need something preferably XSLT which is free and works suitably with basic formatting like paragraphs, lists, bold and italic.

[A]
XSLT on its own won't do you any good if you want to retain any formatting from outside the XHTML file (for example, in external style sheets). Besides, Word has the ability to open (X)HTML files, and has for a while. It might not come out looking as good as the original, but it works.
In fact, if you have Word and some skill with VB Script, I believe that it is possible to write a script that opens a (X)HTML file, then saves it as WordML or plain old Word if you're using Word 2003 or older, or as .docx if you have 2007.


q:
Does anyone know tools like SpyStudio to hook processes?
The features I would like to have are:

log function calls on other processes

GUI

scriptable

opensource

I already looked at some tools like:

SpyStudio

Detours

DynInst

but none really fully satisfies me.

[A]
It likely uses the debugging API and places debug hooks at key points in the application to to trap events. You may even be able to do what you want using
ollydbg
.
EDIT: I just looked at the site and saw the demonstration videos and I would say that they almost certainly do this through the debugging API. They likely place breakpoints in the target at the desired function entry points. When a trap event fires, it looks like they use an RPC call to notify the user of their API and allow them to look at what happened and potentially modify some things. Sending back what to do next also in an RPC call. A nice design, but just a glorified debugger.


q:
Assuming I have a tree structure

UL
--LI
---INPUT (checkbox)

And I want to grab the checked inputs, I would select

$('ul li input:checked')

However, I want to select the checked inputs of a specific object $myUL that doesn't have an ID.

$myUL.children('li input:checked')

returns all li's since children filters immediate children - the checked filter has no impact.

Is there another way around this? Another descendant filter?

[A]
use
```
$myUL.find('li>input:checked')
```


q:
How can I start writing a plugin for Eclipse?

I've looked for documentation, but unfortunately there is very little or it's poor, so what articles can recommended?

[A]
There are some pretty good resources and tutorials on the main Eclipse and IBM's site. One of the best ways is to pick an open source plug-in that has some similar features to what you want to do and start to dissect it.
PDE Does Plug-ins
Plug-in development 101, Part 1: The fundamentals
Eclipse Plugins Exposed, Part 1: A First Glimpse
Developing Eclipse plug-ins


q:
Well, heres my scenario.

Client/Server winforms application with SQL Express as the DB. I need to be able to print invoice, packing slips etc..

i would like the customer to be able to modify the invoices. ie. be able to put their logo or change font sizes etc...basically format the display.

Things i have considered so far are.

1) Use a template engine (similar to codesmith or mygeneration) and use templates that output HTML. Then print the html page.

2) Use ReportViewer in local mode. I've heard that users can download a plugin for web dev express and edit the local report files. can anyone confirm this?

3) Use Reportviewer in remote mode.

I don't have much experience with ReportViewer so I'm not sure if i should use local or remote mode as well.

Those of you that have done this kind of thing before whats your recommendation?

[A]
After just completing a project with it, I would heartily recommend
iTextSharp
to create your invoices and other forms as PDFs. In addition to creating PDFs from scratch, you can also use it to fill in PDF forms and/or templates created with Acrobat (or even MS Office/OpenOffice). And it's free.
It's pretty easy to use in Windows apps or in ASP.Net applications. Most of the documentation and the books on it (
iText in Action
, for example) are about the original Java version,
iText
. However, there are tutorials and example code on the conversion process and, for the most part, all of the functions and libraries work the same in the .Net version, so adapting the book and reference code has been no problem.
I definitely learned the hard way that HTML and CSS are great for browsers (well, great except for the "every browser interprets it different" problem), but horrible for trying to generate consistent, attractive, and precise printed output and forms.


q:
Does anyone know if its possible to create a new property on an existing Entity Type which is based on 2 other properties concatenated together?

E.g. My Person Entity Type has these fields "ID", "Forename", "Surname", "DOB"

I want to create a new field called "Fullname" which is

Forenames + " " + Surname

So i end up with "ID", "Forename", "Surname", "DOB", "Fullname".

I know i can do this using Linq programmatically i.e.

var results = from p in db.People
select new {
ID = p.ID,
Forename = p.Forename,
Surname = p.Surname,
DOB = p.DOB,
Fullname = p.Forename+ " " + p.Surname
};

Then calling something like

var resultsAfterConcat = from q in results
where q.Fullname.Contains(value)
select q;

However i'd really like to use Linq to Entities to do this work for me at the Conceptual Model level.

[A]
Not yet, but maybe soon.  First, note that your suggested query will not work at all in LINQ to Entities, with or without the property, because, at present, it doesn't support Contains.  The new version of the Entity Framework in .NET 4.0, however, is supposed to support custom methods in LINQ to Entities queries.  You can see
a video about this from PDC
.  Essentially, you have to write the custom method twice; once in code, and once on your database (e.g., in a calculated field).  See the video for more information.


q:
In CFEclipse, I do a lot of double-clicking to select text. The standard behavior is to select all text within the nearest word boundaries. This is problematic when editing code where the original editor didn't use camel-case; for example, they wrote "myObject" as "my_object".

Is there a way to change the double-click selection behavior to include '_' as a valid word character?

[A]
On eclipse 3.4.1 Ganymede, it seems to select the nearest boundaries
including
the '_' (at least in the java file I am using)
What eclipse version are you using ?
This
blog
even reports that eclipse3.3 does select word as you are expecting it...
vs.


q:
I'm looking for an implementation of the LOGO programming language that supports 'dynaturtles' - animated turtles that can programmatically change shape, speed and direction as well as detect collisions with each other or other objects in the environment.

Back in the mists of time when the earth was new and 8 bit micros ruled supreme, Atari LOGO did this famously well.  One could create all sorts of small games and simulated environments using this technique very easily as that implementation of the language had a very well thought out, elegant syntax.

I know about LCSI's Microworlds but I'm looking for something I can use to get some friends and their kids involved in programming without breaking my budget.

[A]
Digging around a bit online, I've found
OpenStarLogo
. Though they don't specifically mention "dynaturtles" the docs do mention collision detection.  The site has code and documentation downloads.
From this
wikipedia article
, under the Implementations section, there is a PDF listing known current and antique implementations.  Some of these, such as
StarLogo TNG
and
Elica
have support for 3D objects.  These are definitely not like the LOGO programs I wrote as a kid...


q:
Say I have the following Objective-C class:

@interface Foo {
     int someNumber;
     NSString *someString;
}

and for reasons I won't get into here, I want to use KVC to update, in a generic fashion, the values for those variables:

[f setValue:object forKey:@"someNumber"];

or

[f setValue:object forKey:@"someString"];`

If object is a string and I'm updating the someNumber variable, it seems that I need to know to use an NSNumberFormatter to get an NSNumber and then Cocoa automatically converts that to an int inside setValue:forKey:.

Is there any way to avoid this custom code and have Cocoa infer the conversion to an int from a string, or do I need to catch this situation each time and handle it myself?

[A]
You should do the conversion yourself with a number formatter, it gives you finer control than anything that the framework might consider to be appropriate. It is also, probably, not a good idea to use a single instance of an object to update the values for your ivars.  More appropriately, you could perform your update based on the class of the object (providing you are not storing in an
```
id
```
by querying the runtime as to the class of the object by means of
```
object_getClassName
```
.  More information is available in the Objective-C 2.0 Runtime Reference.  But in general, you will likely find bugs in your code as a result of doing things that way.


q: I'm looking for a library or source code that provides guard methods such as checking for null arguments. Obviously this is rather simple to build, but I'm wondering if there are any out there for .NET already. A basic Google search didn't reveal much.

[A]
Given Microsoft's
Code Contracts
coming out with .NET 4.0 I'd try to find one which is mostly compatible, if possible - and if not, write it yourself. That way when you upgrade to .NET 4.0 (eventually) the migration will be easier.


q:
I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution.

def run():
    owd = os.getcwd()
    #first change dir to build_dir path
    os.chdir(testDir)
    #run jar from test directory
    os.system(cmd)
    #change dir back to original working directory (owd)

note: I think my code formatting is off - not sure why. My apologies in advance

[A]
You simply need to add the line:
```
```
os.chdir(owd)
```
```
Just a note this was also answered in your other
question
.


q:
I am working on an app for doing screen scraping of small portions of external web pages (not an entire page, just a small subset of it).

So I have the code working perfectly for scraping the html, but my problem is that I want to scrape not just the raw html, but also the CSS styles used to format the section of the page I am extracting, so I can display on a new page with it's original formatting intact.

If you are familiar with firebug, it is able to display which CSS styles are applicable to the specific subset of the page you have highlighted, so if I could figure out a way to do that, then I could just use those styles when displaying the content on my new page.  But I have no idea how to do this........

[A]
A good start would be the following: make a pass through the patch of HTML you plan to extract, collecting each element (and its ID/classes/inline styles) to an array. Grab the styles for those element IDs & classes from the page's stylesheets immediately.
Then, from the outermost element(s) in the target patch, work your way up through the rest of the elements in the DOM in a similar fashion, eventually all the way up to the body and HTML elements, comparing against your initial array and collecting any styles that weren't declared within the target patch or its applied styles.
You'll also want to check for any * declarations and grab those as well. Then, make sure when you're reapplying the styles to your eventual output you do so in the right order, as you collected them from low-to-high in the DOM hierarchy and they'll need to be reapplied high-to-low.


q:
For an ASP.NET application, what is the Best Practice implementation method for a custom swear word remover/replacer?

If this is a data table solution, is there free resource to get the data? (Similar to finding a public dictionary table that you can import to your system for spellchecking)

[A]
Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?
^_^
Also see
How do you implement a good profanity filter?
.


q:
I need to query Active Directory for a list of users whose password is about to expire.  The obvious (and easy) way to do this is with:

dsquery user -stalepwd n

The problem is that I need to add additional filters to only look for users who are in certain security groups.  This is hard to do with the "dsquery user" syntax that has the built-in -stalepwd option, so I've been using the "dsquery * -filter" option which allows you to use LDAP query syntax.  Unfortunately, while its relatively easy to do apply the other filters with an LDAP query, I'm having trouble filtering users who have a password age greater than n.

Does anyone know the syntax (or if it is even possible) to filter for old passwords using the "dsquery * -filter" method instead of the "dsquery user -stalepwd" method.

[A]
There are better tools than dsquery to use.
FindExpAcc
from joeware will do the same as stalepwd and allow a filter through its -f switch.
The filter would then look like:
```
```
&(objectCategory=user)(memberof=CN=User Group,OU=Test,DC=foo,dc=com)
```
```
Also check out adfind and admod tools from
joeware
which are more powerful than the command line query tools from Microsoft, but can be a little harder to learn.


q: What steps do I take? Any gotchas to be aware of or tips to enhance the IDE experience that are specific to SQL Server when using Emacs?

[A]
Connecting
To connect to a SQL Server database instance from Emacs:
```
```
M-x sql-ms RET
M-x sql-mode
```
```
You will be prompted for standard connection information specifically the following:
User
Password
Server
Database
For SQL Server Authentication, type in the necessary user and password info. However, if connecting via Windows Authentication, then press RETURN for both user and password leaving them blank.
Viewing Output Results
Note that to see the text of any output results in the *SQL* buffer, the 'go' statement should be called at some point. A couple of ways of doing this.
For example, this sql statement will execute but it will not show any result text in the  *SQL* buffer in its current format:
```
```
select 'foo' as bar
```
```
However, if a 'go' is appended to the end:
```
```
select 'foo' as bar
go
```
```
the following will be displayed in the *SQL* buffer:
```
```
bar
 -----
 foo

(1 row affected)
```
```
Alternatively, if you do not want to have 'go' statements littering the text of your SQL script then call 'go' on the fly to see all output results since the last time that the previous 'go' statement was sent to the sql process:
```
```
C-c C-s go RET
```
```
This is helpful if you need to view any error messages that might not initially show in the *SQL* buffer.


q:
In C# is there a technique using reflection to determine if a method has been added to a class as an extension method?

Given an extension method such as the one shown below is it possible to determine that Reverse() has been added to the string class?

public static class StringExtensions
{
    public static string Reverse(this string value)
    {
        char[] cArray = value.ToCharArray();
        Array.Reverse(cArray);
        return new string(cArray);
    }
}

We're looking for a mechanism to determine in unit testing that the extension method was appropriately added by the developer.  One reason to attempt this is that it is possible that a similar method would be added to the actual class by the developer and, if it was, the compiler will pick that method up.

[A]
You have to look in all the assemblies where the extension method may be defined.
Look for classes decorated with
```
ExtensionAttribute
```
, and then methods within that class which are
also
decorated with
```
ExtensionAttribute
```
. Then check the type of the first parameter to see if it matches the type you're interested in.
Here's some complete code. It could be more rigorous (it's not checking that the type isn't nested, or that there is at least one parameter) but it should give you a helping hand.
```
```
using System;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Linq;
using System.Collections.Generic;

public static class FirstExtensions
{
    public static void Foo(this string x) {}
    public static void Bar(string x) {} // Not an ext. method
    public static void Baz(this int x) {} // Not on string
}

public static class SecondExtensions
{
    public static void Quux(this string x) {}
}

public class Test
{
    static void Main()
    {
        Assembly thisAssembly = typeof(Test).Assembly;
        foreach (MethodInfo method in GetExtensionMethods(thisAssembly,
            typeof(string)))
        {
            Console.WriteLine(method);
        }
    }

    static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly,
        Type extendedType)
    {
        var query = from type in assembly.GetTypes()
                    where type.IsSealed && !type.IsGenericType && !type.IsNested
                    from method in type.GetMethods(BindingFlags.Static
                        | BindingFlags.Public | BindingFlags.NonPublic)
                    where method.IsDefined(typeof(ExtensionAttribute), false)
                    where method.GetParameters()[0].ParameterType == extendedType
                    select method;
        return query;
    }
}
```
```


q:
Is it possible to create an integer (or DataTime, etc) column in ListView? It is quite important, because I would like to properly sort the list according to this column.

The only way to add subItems to a ListViewItem I found are:

listviewitem.SubItems.Add("1");

I would like to avoid parsing these strings to get the int representation for every sort!

[A]
Rather than that you just add strings to the list and receive strings by using
```
.Text
```
property.
Example:
```
```
int a = 0;
listView1.Items.Add(a.ToString());
```
```
or
```
```
int a = Convert.ToInt32(listView1.Items[0].SubItems[0].Text);
```
```
You can do this same with
```
DataTime
```
and other datatypes, just by converting them to
```
String
```
type.
How you interpret the column containing i.e dates it fully depends of you.
Just implement your algorithm of sorting particular
```
ListView
```
column.


q:
I can query the AD and find all the IIS sites and their virtual directories, now I need to be able to update those home directories and save the changes.

After I fetch the directory entry I can display the site path using $site.Path, however setting it doesn't seem to have any effect.  It never changes the actual stored path.

I have tried $site.Path = <new path> and $site.Put( "Path", <new path> ) but neither have these seem to be affecting the stored path.

    $site = $iis.psbase.children |
        where {$_.keyType -eq "iiswebserver"} |
        where {$_.psbase.properties.servercomment -eq $siteConfig.name };

    $s = [ADSI]($site.psbase.path + "/ROOT");
    $s.Path
    # $s.Path = $siteConfig.path
    # $s.Put("Path", $siteConfig.path )
    $s.psbase.CommitChanges()

[A]
Ok, I tried this and it seems to work:
```
```
$s.psbase.properties.path[0] = $siteConfig.path
    $s.psbase.CommitChanges()
```
```
Is there a better cleaner way of handling this?


q:
I don't understand why one method would work and the other would throw a NoMethodError if they come from the same lib file.

# app/views/bunnies/show.html.erb
<% if logged_in? %>
  <%= current_user.login %> |
  <%= link_to 'Logout', logout_path %> |
  <% if authorized? %>
    <%= link_to 'Edit Details', edit_bunny_path(@broker) %> |
  <% end %>
  <%= link_to 'Back', bunnies_path %>
<% end %>

... throws a NoMethodError for authorized?.  If I comment that if block out, the page works fine (with logged_in?).

# lib/authenticated_system.rb
def logged_in?
  !!current_user
end

def authorized?
  current_user.login == "admin"
end

# app/controllers/application.rb
class ApplicationController < ActionController::Base
  include AuthenticatedSystem
end

What gives?

[A]
Right, so I still  don't understand why that wasn't working, but I have found an alternative solution.
(1) Leave authenticated_system.rb as is.
(2) Add a helper method to controllers/application.rb:
```
```
helper_method :is_admin?
def is_admin?
  if logged_in? && current_user.login == "admin"
    true
  else
    false
  end
end
```
```
(3) Use the helper method instead of
```
authorized?
```
.  If anyone would like to explain why the original code wasn't working, I'm all ears!
(Thanks to
this post
)


q:
I am compiling a legacy C code here and there is a lot of variables and struct members named "interface", but VC2008 express is complaining about these, do you know how to disable this?

I already changed settings to compile the code only as a C code, but no effect on this.

[A]
Do a
```
```
#define interface QQInterface
```
```
before your code (eg. in the header file), this way everywhere where the keyword interface is used, the compilers sees "QQInterface", which is not a keyword. If all code includes this define, you will not get compiler or linker errors.


q:
If I have the following setting in my app.config file.  It is a setting I need to make sure my WCF client can negotiate the default proxy server.

<system.net>
    <defaultProxy enabled="true" useDefaultCredentials="true"></defaultProxy>
</system.net>

Unfortunately, I can't add to the app.config file in my environment.  How do I ensure these settings by setting them at runtime?

[A]
Whatever the defined name of your executable (not a library dll) assembly is,  add a ".config" at the end...
so if your executable is to be
AcmeWidgets.EastCoast.MyApplicationName.exe
Then the app.config will get renamed to
AcmeWidgets.EastCoast.MyApplicationName.exe.config
However, I wouldn't recommend you attempt to dynamically change these settings (in the config file on disk)  at runtime...
instead, can you code your app so that it instead populates and uses static variables from these config settings... and then implement the dynamic "change the value" functionality so that it changes these static variables...
This way you can still "affect" the runtime behavior dynamically, but avoid the hassle of writing to the config file, and Ops management can manage the "default" values in the config file by editing it...


q:
I have an XML file and an XML schema in another file and I'd like to validate that my XML file adheres to the schema.  How do I do this in Python?

I'd prefer something using the standard library, but I can install a third-party package if necessary.

[A]
lxml provides etree.DTD
from the tests on
http://lxml.de/api/lxml.tests.test_dtd-pysrc.html
```
```
...
root = etree.XML(_bytes("<b/>"))
dtd = etree.DTD(BytesIO("<!ELEMENT b EMPTY>"))
self.assert_(dtd.validate(root))
```
```


q:
To implement data access code in our application we need some framework to wrap around jdbc (ORM is not our choice, because of scalability).

The coolest framework I used to work with is Spring-Jdbc. However, the policy of my company is to avoid external dependencies, especially spring, J2EE, etc.
So we are thinking about writing own handy-made jdbc framework, with functionality similar Spring-jdbc: row mapping, error handling, supporting features of java5, but without transaction support.

Does anyone have experience of writing such jdbc wrapper framework?
If anyone has experience of using other jdbc wrapper frameworks, please share your experience.

Thanks in advance.

[A] Spring-JDBC is fantastic.  Consider that for an open source project like Spring the down side of external dependency is minimized.  You can adopt the most stable version of Spring that satisfies your JDBC abstraction requirements and you know that you'll always be able to modify the source code yourselves if you ever run into an issue -- without depending on an external party.  You can also examine the implementation for any security concerns that your organization might have with code written by an external party.


q:
We're trying to send an image of a large SWF file to a server to have it mailed out and we're having a bit of trouble with transmission time.

The SWF is about 900px x 600px and restricted to AS2 so we've been using this Bitmap Exporter class. We've tried using several different ways to transmit the data; base10, base36 and base128 but none of them will send the file in any kind of timely manner.

Right now we're dealing with 60-120 seconds per image which isn't acceptable.

Has anyone any advice for dealing with either this class or another for sending large bitmap data to a server with flash?

Thank you for your time.

[A]
The reason you get such long upload times is that the image is barely compressed (or not at all depending on how the class is implemented). 900 by 600 pixels at 16 bpp (or whatever it now is flash uses) amounts to something like 1.5mb of raw data.
I'm doubtful that there are any useful compression libraries for AS2, but that
may
be a possible path.
The easiest way to make the image smaller on the client side would be lowering the resolution. Are you using the full resolution once it reaches the server? If not that might be a possible way.
(I guess you're aware that this would be way easier using AS3, then you could compress the whole image as a jpeg clientside without very much effort, but I guess the rest of your application is AS2 making that a somewhat moot point)


q:
My current project involves deploying an upgraded .exe file that runs as a Windows Service.  In order to overwrite the existing .exe with the new version, I currently need to:

Stop the service

Uninstall the service

Reboot the system (so Windows releases it's hold on the file)

Deploy the new .exe

Reinstall the service

Start the upgraded service.

I'd like to avoid the reboot, so that this can be a fully scripted/automated upgrade.

Is there any way to avoid rebooting?  Maybe a command-line tool that will force Windows to give up it's death grip on the old .exe?

[A]
Are you not able to stop the service before the update (and restart after the update) using the commands below?
```
```
net stop <service name>
net start <service name>
```
```
Whenever I'm testing/deploying a service I'm able to upload files without reinstalling as long as the service is stopped.  I'm not sure if the issue you are having is different.


q: What is the most direct and/or efficient way to convert a char[] into a CharSequence?

[A]
A
```
String
```
is a
```
CharSequence
```
.  So you can just create a new
```
String
```
given your
```
char[]
```
.
```
```
CharSequence seq = new String(arr);
```
```


q: I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?

[A]
You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript.  JSON is not only lighterweight but easier to make in javascript.  Check out
JSON-PHP
for parsing JSON.
You might want to take a look at
Creating JSON Data in PHP


q:
I'd like to write a plugin that does something with the currently edited file in Eclipse. But I'm not sure how to properly get the file's full path.

This is what I do now:

IFile file = (IFile) window.getActivePage().getActiveEditor.getEditorInput().
    getAdapter(IFile.class);

Now I have an IFile object, and I can retrieve it's path:

file.getFullPath().toOSString();

However this still only gives me the path relative to the workspace. How can I get the absolute path from that?

[A]
Looks like you want
```
IResource.getRawLocation()
```
.  That returns an
```
IPath
```
, which also has a
```
makeAbsolute()
```
method if you want to be doubly sure you've got an absolute path.


q: When issuing an HTTP DELETE request, the request URI should completely identify the resource to delete. However, is it allowable to add extra meta-data as part of the entity body of the request?

[A]
The spec
does not explicitly forbid or discourage it, so I would tend to say it is allowed.
Microsoft sees it the same way (I can hear murmuring in the audience), they state in the MSDN article about the
DELETE Method of ADO.NET Data Services Framework
:
If a DELETE request includes an entity body, the body is ignored [...]
Additionally here is what
RFC2616
(HTTP 1.1) has to say in regard to requests:
an
entity-body
is only present when a
message-body
is present (section 7.2)
the presence of a
message-body
is signaled by the inclusion of a
```
Content-Length
```
or
```
Transfer-Encoding
```
header (section 4.3)
a
message-body
must not be included when the specification of the request method does not allow sending an
entity-body
(section 4.3)
an
entity-body
is explicitly forbidden in TRACE requests only, all other request types are unrestricted (section 9, and 9.8 specifically)
For responses, this has been defined:
whether a
message-body
is included depends on both request method
and
response status (section 4.3)
a
message-body
is explicitly forbidden in responses to HEAD requests (section 9, and 9.4 specifically)
a
message-body
is explicitly forbidden in 1xx (informational), 204 (no content), and 304 (not modified) responses  (section 4.3)
all other responses include a message-body, though it may be of zero length  (section 4.3)


q:
Does anyone know a good tool that can be run on a page (for asp.net, for example) to help to minimize the footprint size of the page?

The page will have typical items: HTML, Javascript, etc.

I've heard of Javascript crunchers in the past, that will make the size of the code as compact as possible (and obfuscate it, I suppose).

The goal is to help optimize the page size (make it as small as possible for speed, without changing anything).

Is this possible?

[A]
Well, its not a automatic cleaner-upper, but I like
YSlow
for optimizing pages.  And the
YUI Compressor
can minify your javascript.
If you're really interested in javascript, the keyword is "minify".
Also, look at this question just posted:
HTML and stuff
Hope that helps!


q: What's the difference between java.lang.ref.WeakReference and java.lang.ref.SoftReference ?

[A]
Weak references are collected eagerly. If GC finds that an object is
weakly reachable (reachable only through weak references), it'll clear the
weak references to that object immediately. As such, they're good for
keeping a reference to an object for which your program also keeps
(strongly referenced) "associated information" somewere, like cached
reflection information about a class, or a wrapper for an object, etc.
Anything that makes no sense to keep after the object it is associated
with is GC-ed. When the weak reference gets cleared, it gets enqueued in a
reference queue that your code polls somewhere, and it discards the
associated objects as well. That is, you keep extra information about an
object, but that information is not needed once the object it refers to
goes away. Actually, in certain situations you can even subclass
WeakReference and keep the associated extra information about the object
in the fields of the WeakReference subclass. Another typical use of
WeakReference is in conjunction with Maps for keeping canonical instances.
SoftReferences on the other hand are good for caching external, recreatable resources
as the GC typically delays clearing them. It is guaranteed though that all
SoftReferences will get cleared before OutOfMemoryError is thrown, so they
theoretically can't cause an OOME[*].
Typical use case example is keeping a parsed form of a contents from a
file. You'd implement a system where you'd load a file, parse it, and keep
a SoftReference to the root object of the parsed representation. Next time
you need the file, you'll try to retrieve it through the SoftReference. If
you can retrieve it, you spared yourself another load/parse, and if the GC
cleared it in the meantime, you reload it. That way, you utilize free
memory for performance optimization, but don't risk an OOME.
Now for the [*]. Keeping a SoftReference can't cause an OOME in itself. If
on the other hand you mistakenly use SoftReference for a task a WeakReference is meant
to be used (namely, you keep information associated with an Object somehow
strongly referenced, and discard it when the Reference object gets
cleared), you can run into OOME as your code that polls the ReferenceQueue
and discards the associated objects might happen to not run in a timely
fashion.
So, the decision depends on usage
- if you're caching information that is expensive to construct, but
nonetheless reconstructible from other data, use soft references
- if you're keeping a reference to a canonical instance of some data, or
you want to have a reference to an object without "owning" it (thus
preventing it from being GC'd), use a weak reference.


q:
This is a design question and good practice question.  How do you structure your Java web development such that a lot of logic is not in the JSP file.  Should you use any of the JSP tags for if structures or loops.  I see a lot of code where the logic is hard to follow because of poorly designed JSP files.  And then when you want to output to a different format like a PDF or XML document, you can't do it because all the logic is in the JSP file.

Are there any tips or practices that you follow for Java Web development.

I am currently using a combination of Spring, Hibernate, Struts...and work with some Servlet code.

There are good practices associated with Java development.  Many of us that have worked a while know them.  What are some good practices for JSP development.

[A]
The easiest way to avoid placing logic in JSPs is simply to perform all that logic
before
forwarding a request to a JSP. The only logic you should need to do in a JSP is some basic looping (e.g. for creating HTML table rows), evaluating conditional statements, and data formatting.
All of this can be done without using scriptlet code (Java code) in the JSPs by using JSP tag libraries and EL. The most important tag library is
JSTL
. The JSTL tag library provides most of the logic you should ever need to perform in a view, though you may occasionally also use niche 3rd party tag libraries like
displaytag
which can reduce the amount of JSP code you need to write for specific tasks.


q:
I'm trying to put in an exception in my web.config so that one page does not require authentication.  However, it still redirects to the login page.

The question isn't how to setup the web.config.  Why?  Our system (for better or worse) has a bunch of instrumentation besides the web.config.  We have global.asax and custom HttpHandlers.  The code base isn't huge, but there's a lot of potential causes for the redirect.

What I do want to know is how to best determine the cause of the redirect.  Is there some way to find out what code triggered the redirect?

[A]
Have you tried turning on Tracing?  That may help.
How are you specifying the page doesn't require authentication, like:
```
```
<system.web>
...
</system.web>

<location path="NoAuthNeeded.aspx">
    <system.web>
        <authorization>
        <allow roles="*" />
        <allow roles="?" />
        </authorization>
    </system.web>
</location>
```
```


q:
Once it is compiled, is there a difference between:

delegate { x = 0; }

and

() => { x = 0 }

?

[A]
Short answer : no.
Longer answer that may not be relevant:
If you assign the lambda to a delegate type (such as
```
Func
```
or
```
Action
```
) you'll get an anonymous delegate.
If you assign the lambda to an Expression type, you'll get an expression tree instead of a anonymous delegate.  The expression tree can then be compiled to an anonymous delegate.
Edit:
Here's some links for Expressions.
System.Linq.Expression.Expression(TDelegate)
(start here).
Linq in-memory with delegates (such as System.Func) uses
System.Linq.Enumerable
.  Linq to SQL (and anything else) with expressions uses
System.Linq.Queryable
.  Check out the parameters on those methods.
An
Explanation from ScottGu
.  In a nutshell, Linq in-memory will produce some anonymous methods to resolve your query.  Linq to SQL will produce an expression tree that represents the query and then translate that tree into T-SQL.  Linq to Entities will produce an expression tree that represents the query and then translate that tree into platform appropriate SQL.


q: I'm getting quite a few errors in my code. Consequently, I would like to be able to minimize them at the outset or see as many errors as possible before code execution. Is this possible and if so, how can I do this?

[A]
Python provides a debugger which allows you to step through your code, inspect variables and manipulate them. Refer to
http://pythonconquerstheuniverse.wordpress.com/category/python-debugger/
which can take you over the steps...
Also check the python standard library reference for pdb
http://www.python.org/doc/2.5.2/lib/module-pdb.html


q:
In the Linux kernel, given the task_struct's mm I can access the process's list of vm_area_structs. Given these vm_area_structs, how do I get the struct pages which actually correspond to this vma?

I tried looking for functions in mm/memory.c and the like, but I was at a loss.

Edit: the idea is to find which pages in the vma are currently in memory and which are not. But I don't want someone telling me how to do this bit, as that's a small part of a homework assignment that I need to figure out on my own. But I can't seem to figure out how to find the pages that correspond to this vma. If I can find the pages, I figure I can check to see if they have a valid pfn or not.

[A]
From your comment to another answer (edit: the other answer seems to have been deleted), it seems you want to read from user space. The function to get the user space pages would be
```
get_user_pages()
```
, but that is most probably not what you want; you probably want
```
copy_from_user
```
/
```
copy_to_user
```
.


q: I've been given the task of working with SAML to implement an SSO solution between my company and a third party provider.  My only issue is that I can't seem to find how to implement SAML in C# 2.0.  I've been able to find a few examples for .Net 3.0 and 3.5, but none for 2.0 (and the classes they use don't appear to be available in 2.0).  Does anyone know of any oline examples using SAML and C# 2.0?

[A] Unless you can find a third party implementation, you are going to have to upgrade beyond v2.0. Probobly not what you want to hear, sorry...


q:
I need to do transactions (begin, commit or rollback), locks (select for update).
How can I do it in a document model db?

Edit:

The case is this:

I want to run an auctions site.

And I think how to direct purchase as well.

In a direct purchase I have to decrement the quantity field in the item record, but only if the quantity is greater than zero. That is why I need locks and transactions.

I don't know how to address that without locks and/or transactions.

Can I solve this with CouchDB?

[A]
No.  CouchDB uses an "optimistic concurrency" model.  In the simplest terms, this just means that you send a document version along with your update, and CouchDB rejects the change if the current document version doesn't match what you've sent.
It's deceptively simple, really.  You can reframe many normal transaction based scenarios for CouchDB. You do need to sort of throw out your RDBMS domain knowledge when learning CouchDB, though.  It's helpful to approach problems from a higher level, rather than attempting to mold Couch to a SQL based world.
Keeping track of inventory
The problem you outlined is primarily an inventory issue.  If you have a document describing an item, and it includes a field for "quantity available", you can handle concurrency issues like this:
Retrieve the document, take note of the
```
_rev
```
property that CouchDB sends along
Decrement the quantity field, if it's greater than zero
Send the updated document back, using the
```
_rev
```
property
If the
```
_rev
```
matches the currently stored number, be done!
If there's a conflict (when
```
_rev
```
doesn't match), retrieve the newest document version
In this instance, there are two possible failure scenarios to think about.  If the most recent document version has a quantity of 0, you handle it just like you would in a RDBMS and alert the user that they can't actually buy what they wanted to purchase.  If the most recent document version has a quantity greater than 0, you simply repeat the operation with the updated data, and start back at the beginning.  This forces you to do a bit more work than an RDBMS would, and could get a little annoying if there are frequent, conflicting updates.
Now, the answer I just gave presupposes that you're going to do things in CouchDB in much the same way that you would in an RDBMS.  I might approach this problem a bit differently:
I'd start with a "master product" document that includes all the descriptor data (name, picture, description, price, etc).  Then I'd add an "inventory ticket" document for each specific instance, with fields for
```
product_key
```
and
```
claimed_by
```
.  If you're selling a model of hammer, and have 20 of them to sell, you might have documents with keys like
```
hammer-1
```
,
```
hammer-2
```
, etc, to represent each available hammer.
Then, I'd create a view that gives me a list of available hammers, with a reduce function that lets me see a "total".  These are completely off the cuff, but should give you an idea of what a working view would look like.
Map
```
```
function(doc)
{
    if (doc.type == 'inventory_ticket' && doc.claimed_by == null ) {
        emit(doc.product_key, { 'inventory_ticket' :doc.id, '_rev' : doc._rev });
    }
}
```
```
This gives me a list of available "tickets", by product key.  I could grab a group of these when someone wants to buy a hammer, then iterate through sending updates (using the
```
id
```
and
```
_rev
```
) until I successfully claim one (previously claimed tickets will result in an update error).
Reduce
```
```
function (keys, values, combine) {
    return values.length;
}
```
```
This reduce function simply returns the total number of unclaimed
```
inventory_ticket
```
items, so you can tell how many "hammers" are available for purchase.
Caveats
This solution represents roughly 3.5 minutes of total thinking for the particular problem you've presented.  There may be better ways of doing this!  That said, it does substantially reduce conflicting updates, and cuts down on the need to respond to a conflict with a new update.  Under this model, you won't have multiple users attempting to change data in primary product entry.  At the very worst, you'll have multiple users attempting to claim a single ticket, and if you've grabbed several of those from your view, you simply move on to the next ticket and try again.
Reference:
https://wiki.apache.org/couchdb/Frequently_asked_questions#How_do_I_use_transactions_with_CouchDB.3F


q:
I am trying to call a Actionscript function from javascript but I am having problems in Internet Explorer.
I am using Swiff.remote in mootools 1.2.1 to call the actionscript function ie:

Swiff.remote(playSwf.toElement(), 'sendResult', result, plays, name);

This all works fine in FireFox, Safari and Opera but I'm getting an "unspecified" error in Internet Explorer 6 and 7.
I have tried using the bog standard:

window['flash'].sendResult(result, plays, name);

To no avail.

Thanks for any help.
Mark

[A]
I'm not familiar with the Swiff plugin, but you don't need a plugin to call flash functions from Javascript. It's even easier to do it natively.
From AS:
```
```
//1. calling javascript function from Flash.
ExternalInterface.call("sendData",tempStr);
// argument 1: javascript function, argument 2: data/variables to pass out.
//2. calling javascript function from Flash with recursion.
var returnValue:String = ExternalInterface.call("sendReturn",tempStr).toString();
//3. setting up a callback function for javascript
ExternalInterface.addCallback("callFlash",flashResponse);
// argument 1: function name called by javascript, argument 2: function on the Flash side.
// AS2 version looks like this : ExternalInterface.addCallback("callFlash",null,flashResponse);
```
```
From JS:
```
```
//1. javascript function as called from Flash.
function sendData(val){
    alert(val);
    document.flashForm.flashOutput.value = val;
}

//2. javascript function with recursion.
function sendReturn(val){
    var tempData = "Hello from JS";
    return tempData + ' :return';
}

//3. calling Flash function with javascript.
function sendToFlash(val){
    window['flash'].callFlash(val);
}
```
```


q:
I searched and found this question but did not like the answer.

Is there another way to get SVN to ignore config files that are checked in in-place (that you cannot check-in changed), but must be modified on your system.

This is a pretty severe failure of SVN, my first disappointment with the system actually.  What I'm hoping for is that someone out there figured out a trick, perhaps with branching just the config files onto a new branch while leaving everything else pointing at the original branch.  Perhaps modifying the .svn directory?

There must be a better solution then template/copy, that seems so unmaintainable.

[A]
After messing around for a few hours I think I have an answer.  Since it's my own question, I guess I'll make it community wiki...
I created a branch of the entire repository and pointed the "Config" type files at the new branch, then checked them in.
I'm not sure how this will play out, but it made the "Check everything in" stuff work correctly.  I think if I change one of those files it'll work fine, checking it into my local repository.
The only thing that could be annoying is if someone else changes a file that I have branched, I'm not sure how I'll identify the fact that I'm supposed to merge.


q:
I recently started facelets development, and a couple of days ago made my first useful custom tag. Now I would like to have auto-completion support in eclipse, like I have for standard taglibs like h, c and ui.

Is there any easy way (less than 30 min work) to enable tool support for custom tags?

I'm using eclipse 3.4 with jboss tools.

[A]
What version of Eclipse are you using?
My current version (Version: 3.4.0, Build id: I20080617-2000, with WTP)has autocompletion for any taglib added as a directive on my JSP page (even if the current JSP file does a
```
<%@ include file="..." %>
```
to the actual file with the taglib declarations in it), even the non-standard ones.
For example, Eclipse will autocomplete any
```
<form:blah>
```
tags for me if I have the following declaration:
```
```
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
```
```


q:
I have an existing application written in Perl. Now I need to integrate this application with OBI. The plan is having a button the user can click on to open OBI in an iframe. OBI resides on a different server from the running application.

Has anyone done this before, know what is the best practice for doing this, and what is the effort of doing this?

Another question is is it possible to add customizations to the OBI displayed in the iframe.?

[A]
There are two ways to address the problem that I know of and tried out.  According to your needs, one or the other might be more appropriate (or both, they're not mutually exclusive).  In both cases, the documentation is good and readily available.
The "Go URL"
The Go URL is documented more thoroughly in the Oracle Business Intelligence Presentation Services Administration Guide. It provides a quick and easy interface to the reports you've already defined, in the form of a URL.  All that's needed to get it running is to fill in a few query parameters to direct to the report you want.  You might need to include authentication tokens too.
Pros: very easy to try out.
Cons: harder to get security right.
The web services
The presentation server comes with a series of web services that enable a more programmatic way of querying your repository.  The functionality offered through this channel goes further: for example most catalog management, including report creation and editing is possible.  The full list fills a guide of its own: the Oracle Business Intelligence Web Services Guide.
Pros: better integration (i.e., no need for an IFRAME); easier to get the security right.
Cons: harder to setup; lots of XML; more advanced features (e.g. in-place drilldown) need an HTTP bridge that was a bitch to get right in my case.  The generated HTML might clash a bit with yours and require cleaning up, notably in the CSS.


q:
I'm executing several discrete queries in a single batch against SQL Server. For example:

update tableX set colA = 'freedom';

select lastName from customers;

insert into tableY (a,b,c) values (x,y,z);

Now, I want to capture the result in a DataSet (from select statement) which is easy enough to do...but how do I also capture the "meta" response from that command similar to the way Query Analyzer/SQL Mgt Studio does when it displays the "Messages" tab and diplays something similar to:

(1 Row affected)
(2 Rows Updated)

[A]
My suggestion would be to use the @@rowcount variable for this.  Usually, when I'm doing these kind of commands, if I want to trap both the potential error and the rows affected, I do
```
```
declare @rowsAffected int, @error int

select * from sometable
     select @rowsAffected = @@rowcount, @error = @@error

if @@error <> 0 goto errorCleanup
```
```


q: In Mootools, I'd just run if ($('target')) { ... }.  Does if ($('#target')) { ... } in jQuery work the same way?

[A]
no, jquery always returns a jquery object regardless if a selector was matched or not.
You need to use .length
```
```
if ( $('#someDiv').length ){

}
```
```


q:
I'd like to have my Eclipse plugin cause a URL to be opened by the users' default browser. This seems like pretty standard behavior, but I haven't been able to find any docs on how to do this.

Can anyone help?

[A]
Do you mean launch an external windows (IE, FireFox, ...) outside eclipse, or opening an internal "
Browser
" composite ?
Because on the internal side, the
org.eclipse.help.ui.internal.browser.embedded.EmbeddedBrowser
seems to be able to define any kind of major browser.
To open the default user's browser (as an internal or external window) is a preference defined in General/Web browser.


q:
I'm reloading a web page that has the following code:

<label for="showimage">Show Image</label>
<input id="showimage" name="showimage" type="checkbox" value="1" />

Even though the HTML stays sent to the browser is the same for each reload of the page, the checkbox always takes on the checked value when a reload was performed.  In other words, if the user checks the checkbox and reloads, the checkbox is still checked.

Is there some caching going on here?

Edit: I tried Gordon Bell's solution below and find that this is still happening even after removing the value="1".  Anything else I might be missing?

<label for="showimage">Show Image</label>
<input id="showimage" name="showimage" type="checkbox" />

[A]
Yes, I believe it is caching. I see this behaviour on Firefox for example (not Safari, for what that's worth :) ).
you can reload the page and bypass the cache (on Firefox) using
CTRL
-
SHIFT
-
R
and you'll see the check value doesn't carry (a normal
CTRL
-
R
will grab the info from the cache however)
edit
: I was able to disable this server side on Firefox, setting a cache control header:
```
```
Cache-Control: no-store
```
```
this seems to disable the "remember form values" feature of Firefox


q:
I'm trying to setup an alert to let me know via email (SMTP) when free disk space on one of my servers is less than a specified value. To do this I'm using PerfMon alerts, as described at MSFT Technet. I have the alert working and writing to the system log, but when I try to set it to 'Run Program' it fails. The log alert fires but the program fails.

The program I'm using is a small C# app I wrote to send an smtp email. I have tested the app independently from this server, running it manually and it works fine, without any user interaction (console app). But when I have it set to run via the alert trigger it fails.


q:
In linux, if I have a file I'm sharing with a group, and I put the file on a USB memory stick, for example, and copy it to a computer that doesn't have the same group or users, does the file have no permissions for anyone on that new computer?  What if I bring a linux file that only lets user X to read it to a windows machine?  Who gets to read it on the windows machine? since user X (and group) doesn't exist on that machine.

What kind of security do I get copying a linux file to another linux machine? how about to a windows machine?

What kind of security do I get copying a windows file to another windows machine?  how about to a linux machine?

Please let me know.

jbu

[A]
Regarding the USB key: generally, USB keys use one of the FAT family of filesystems; FAT doesn't support security at all, so as soon as you copy the file to it the security information is lost. So for your first question, anyone who has the USB key can read it on any computer from any user account. It is possible to format USB keys using another filesystem (for example, NTFS, which does support security); in that case, if the accounts (in Windows, at least, it must be a domain account or similar, just naming two accounts the same will not do it) do not exist on the target computer, only a user who can ignore filesystem permissions (such as root on *nix or Administrator on Windows) will be able to access the file.
For the second, I'm not 100% sure but I believe it depends on how you copy it; things like FTP and rcp generally don't copy permissions over, so I would assume that the file gets some kind of default permissions for the target directory, or a default built into the copy program, depending on what the copy program does.
For windows, to the best of my knowledge the security descriptor is initially inherited from the target folder; permissions are, again, not persisted across machines. It can be modified after the copy.
In general, except in specific environments that are designed to transfer permissions, I would assume that transferring any file from one computer to another resets the security permissions to a default (generally whatever a
new
file in that location would receive).


q:
I'm writing an HTTP Cache library for Java, and I'm trying to use that library in the same application which is started twice. I want to be able to share the cache between those instances.

What is the best solution for this? I also want to be able to write to that same storage, and it should be available for both instances.

Now I have a memory-based index of the files available to the cache, and this is not shareable over multiple VMs. It is serialized between startups, but this won't work for a shared cache.

According to the HTTP Spec, I can't just map files to URIs as there might be a variation of the same payload based on the request. I might, for instance, have a request that varies on the 'accept-language' header: In that case I would have a different file for each subsequent request which specifies a different language.

Any Ideas?

[A]
I think you should have a look at the
WebDav-Specifications
. It's an HTTP extension for sharing/editing/storing/versioning resources on a server. There exists an implementation as an
Apache module
, wich allows you a swift start using them.
So instead of implementing your own cache server implementation, you might be better off with a local Apache + mod-dav instance that is available to both of your applications.
Extra bonus: Since WebDav is a specified protocoll you get the interoperability with lots of tools for free.


q:
CodeIgniter allows access to POSTed data via:

$this->input->post('input_name');

where 'input_name' is the name of a form field. This works well for a static form where each input name in known ahead of time.

In my case, I am loading a collection of key/value pairs from the database. The form contains a text input for each key/value pair.

I am wondering, is there a way to get an array of posted data via the CodeIgniter api?

Thanks!

[A]
According to the documentation, no. I would suggest just using
```
array_keys($_POST)
```
to get the keys.


q: I am using a ResourceDictionary, but I would like to be able to look up the value or the key with the other item.  Each is always unique, so that is not a problem.  Is there a type that has this double sided lookup feature?

[A]
Not built in, but this is pretty easy to write.  I would probably implement IDictionary for this though...  You would then dump the ResourceDictionary into your custom type.
```
```
public class DoubleLookup<TKey, TValue>
{
  private IDictionary<TKey, TValue> keys;
  private IDictionary<TValue, TKey> values;

  //stuff...

  public void Add(TKey key, TValue value)
  {
    this.keys.Add(key, value);
    this.values.Add(value, key);
  }

  public TKey GetKeyFromValue(TValue value)
  {
    return this.values[value];
  }

  public TValue GetValueFromKey(TKey key)
  {
    return this.keys[key];
  }

}
```
```


q:
How can I center an image horizontally and aligned to the bottom of the container at the same time?

I have been able to center the image horizontally by its self. I have also been able to align the bottom of the container by its self. But I have not been able to do both at the same time.

Here is what I have:

.image_block {
    width: 175px;
    height: 175px;
    position: relative;
    margin: 0 auto;
}
.image_block a img {
position: absolute;
bottom: 0;
}

<div class="image_block">
    <a href="..."><img src="..." border="0"></a>
</div>

That code aligns the image to the bottom of the div. What do I need to add/change to make it also center the image horizontally inside the div? The image size is not known before hand but it will be 175x175 or less.

[A]
Remove the
```
position: relative;
```
line. I'm not sure why exactly but it fixes it for me.


q:
The following code works for me:

var webProxy = WebProxy.GetDefaultProxy();
webProxy.UseDefaultCredentials = true;
WebRequest.DefaultWebProxy = webProxy;

Unfortunately, WebProxy.GetDefaultProxy() is deprecated.  What else should I be doing?

(using app.config to set the defaultProxy settings is not allowed in my deployment)

[A]
From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.
The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.
If you wanted to use
different proxy settings
to the current user then you would need to code
```
```
WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);
```
```
or
```
```
WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);
```
```
You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call
```
webRequest.Proxy.GetProxy(new Uri("http://google.com.au"))
```
to see the actual details of the proxy server that would be used.
There seems to be some debate about whether you can set
```
webRequest.Proxy
```
or
```
WebRequest.DefaultWebProxy = null
```
to prevent the use of any proxy. This seems to work OK for me but you could set it to
```
new DefaultProxy()
```
with no parameters to get the required behaviour. Another thing to check is that if a
proxy element
exists in your applications config file, the .NET Framework will
NOT
use the proxy settings in Internet Explorer.
The MSDN Magazine article
Take the Burden Off Users with Automatic Configuration in .NET
gives further details of what is happening under the hood.