Tuesday, April 5, 2011

How to add a property to a Table Adapter that can be bound to?

I have a database table TravelRequest that contains, amongst other things, the fields SignOffName and SignOffDate. I have a table adapter TravelRequestTable based on this table. I have a DetailsView control which uses this via an ObjectDataSource. Should be all fairly standard stuff.

What I want to do is add a property called SignOffNameDate to the table adapter that combines the two fields and be able to bind to it in the DetailsView control. I want to do it programmatically rather than adding another column in the SQL because dealing with null values is tricky and depends on some other business rules.

This is what I tried:

public partial class TravelRequestDS
    public partial class TravelRequestRow
     public string SignOffNameDate
      get { return CombineNameDate(SignOffName, SignOffDate); }

This property works fine when I access it programmatically, but when I try bind to it in my aspx page:

<asp:DetailsView ID="DetailsView_TravelRequest" runat="server" AutoGenerateRows="False"
    DataKeyNames="TravelRequestID" DataSourceID="ObjectDataSource_TravelRequest">
      <asp:BoundField DataField="SignOffNameDate"
       HeaderText="Sign Off" />

I get an System.Web.HttpException exception, "A field or property with the name 'SignOffNameDate' was not found on the selected data source."

Any ideas how I can do this? Is there an attribute I need to add to the property?

From stackoverflow
  • If you don't want to change your table structure, change the default method that loads data into your adapter (usually called Fill), most likely you are doing a Select * From [TravelRequest] or selecting the individual fields, so what you could do is change your TableAdapter query select statement to something like

    Select [YourCol1],[YourCol2], SignOffNameDate as Null From [TravelRequest]

    Modifying the default query, and selecting SignOffNameDate as null will give you access to set this value

    TallGuy : I'm not sure I fully understand your answer. By adding the dummy SignOffNameDate field in the SQL, the table adapter adds a property of that name in the generated code and I get a "The type 'TravelRequestDS.TravelRequestRow' already contains a definition for 'SignOffNameDate'" compiler error.
    TallGuy : Is there something else I can do to override the property?
    RandomNoob : are you still using the class in the original post? You no longer need it.
    TallGuy : I'm afraid I still don't follow you. I need to use my CombineNameDate method to *programmatically* combine the two fields. If I remove the class, how specify the SignOffNameDate property using this method?
    RandomNoob : ok let me take that back, to make things easy, why don't you select the fields you want to combine via the sql statement or is it something a little more complex than that, so instead of selecting null, could you select the two fields you need via sql and eliminate the need for you combine method?
    RandomNoob : For instance Select SignOffNameDate as [Field1] + ' ' + [Field2], I'm guessing a straight concat is wishful thinking or you wouldn't have asked this question in the first place
    RandomNoob : nevermind, I think I approached this in the completely wrong way and totally neglected the fact that you're using an objectdatasource, I'll ponder this one again, sorry for the confusion, I kept thinking SqlDataSource
  • If your objective is to display the combined result in a single non-editable field you can do it like this:

    <asp:DetailsView ID="DetailsView_TravelRequest" runat="server" AutoGenerateRows="False"
        DataKeyNames="TravelRequestID" DataSourceID="ObjectDataSource_TravelRequest">
                <asp:TemplateField HeaderText="Sign Off" SortExpression="SignOffDate">               
                            <asp:Label ID="Label1" runat="server" Text='<%# Bind("SignOffName") %>'></asp:Label>
                            <asp:Label ID="Label2" runat="server" Text='<%# Bind("SignOffDate") %>'></asp:Label>

Unable to set textarea width with CSS

I have attempted to use this CSS to set the width of my form elements:

input[type="text"], textarea { width:250px; }

If you look at this Firefox screenshot you'll see that the fields are not the same width. I get a similar effect in Safari.

alt text

Are there any workarounds?

UPDATE: Thanks for the info so far. I've now made sure padding/margin/border on both elements are set the same. I was still having the problem. The original CSS I posted was simplified... I was also setting the height of the textarea to 200px. When I remove the height styling, the widths match. Weird. That makes no sense.

Browser bug?

From stackoverflow
  • Maybe you have a user specific css overlay defined somewhere in your browser, because i just tested it and it works as expected: http://jsbin.com/exase/edit (Tested on windows. Maybe Apple native widgets have some quirk?)

  • Try border:0; or border: 1px solid #000;

  • This is probably caused by different default margins on the <input> and <textarea> elements. Try using something like this.

    input[type="text"], textarea { 
        padding: 0;
        margin: 0;
    derobert : Padding and margin do not add width.
    Andy Ford : well, margin doesn't.
  • Try removing padding and borders. Or try making them the same for both elements

    textarea {
        padding: 3px;
        border: none;


    textarea {
        padding: 0;
        border: 1px solid #ccc;

    INPUT and TEXTAREA elements often have some padding applied by the browser (varies by browser) and this can make things appear effectively wider than the assigned width.

Debugging successful but service not working after installation.

I used the following piece of code in the service to debug the service successfully by running the service as a console application and verified everything works fine.But later when I installed the service and started it as a windows application the service is running as indicated by the services console but it is not doing the job it has to.I want to know what went wrong in this scenario.Thanks.

static void Main() { System.ServiceProcess.ServiceBase[] ServicesToRun;

        if (Environment.UserInteractive)
            ListenerSVC service = new ListenerSVC();
            Console.WriteLine("Press any key to stop program");

            ServicesToRun = new System.ServiceProcess.ServiceBase[] { new ListenerSVC() };

From stackoverflow
  • Have you tried catching/logging any exceptions? The most likely cause is security (i.e. the service account not having access to some resource). There is also often an isue locating the .config file for a service (watch that if you are using config). Finally, for simplicity, try using a command arg just in case UserInteractive is reporting incorrectly - I tend to use "-c" for console/debug mode.

    kjayakum : I am logging status into the database and yes it says 'Access to Message Queuing System Denied'. I am trying to read messages from a private queue in my system using a listener service.
    kjayakum : I have turned off UAC and I have also added application manifest to elevate privileges. I am not aware of security needs specific to the message queuing system. I checked the message queue properties and I find that the security tab does not display any settings for running in WORKGROUP mode.

Formatted pluralize

I have a case where I need to use pluralize to properly spell something. However, I need to render the html like so:

<span>1</span> thing


<span>3</span> things

I could write a helper method, but I'm just making sure there isn't something in the box to do this.

From stackoverflow
  • This uses the Rails class TextHelper which uses Inflector to do the pluralization if needed.

    def pluralize_with_html(count, word)
      "<span>#{count}</span> #{TextHelper.pluralize(count, word)}"
    Tim Sullivan : This certainly works based on what I asked for, but I think the helper method I posted gives more flexibility to the designer in general. Thanks!
    Lolindrath : I'll have to invoke YAGNI on that comment and say to refactor if you find another use.
  • In the interim, I've created this helper method, because it looks like there isn't what I'm looking for:

    def pluralize_word(count, singular, plural = nil)
      ((count == 1 || count == '1') ? singular : (plural || singular.pluralize))

    It's essentially identical to the pluralize method, except that it removes the number from the front. This allows me to do this (haml):

    %span.label= things.size.to_s
    %description= pluralize_word(things.size, 'thing')

document.ready inside body tag

I have a web app that has a universal HTML header include, so I'd like to put page-specific scripts in each page instead of having it load for everything. I tried putting document.ready() near the end of the <body> of a page and it seems to be working fine. Are there any potential hazards to putting it there instead of inside the <head>?

From stackoverflow
  • None. Just make sure everything is loaded in the proper order.

  • Yahoo recommends putting all scripts at the end of your document for performance - http://developer.yahoo.com/performance/rules.html

    Matthew : I guess I could even put it between and ?
    bobince : Best not - there's not supposed to be anything in html other than head and body-or-frameset. A browser might choose not to execute the code; in any case it certainly wouldn't validate.

Is there a predefined class for 3 linked values like the Hashtable?

Is there a built in object that handles 3 linked values in a similar fashion to the hashtable? i.e. Key, Value1, Value2?

From stackoverflow
  • You could easily make one using a generic dictionary. Something like Dictionary<Key, KeyValuePair<Key, Value>>, or even Dictionary<Key, object[]>

    BenAlabaster : I thought about that - this library wasn't supposed to be heavy duty though so I was hoping not to have to build/implement anything extensive.
    Mike_G : Im not quite sure I understand. Dictionary and KeyValuePair are already implemented in .NET. You wouldnt have to build anything.
    BenAlabaster : Oops - I guess your whole text didn't post before I was commenting... yes, I see what you're getting at.
    Antony Perkov : I agree with Mike_G that this is probably the quickest way to implement what you want; but it probably won't yield the most maintainable code. In my experience, having a custom class as your "Value" with well named properties will be a lot clearer to people looking at your code for the first time.
    Mark Brackett : Don't like the object[] route, but +1 for KeyValuePair. There's a non generic Pair class somewhere in the BCL that I also use occasionally, but all I recall is that it's somewhere in one of the Control namespaces (WebControl, Control, ComponentModel or something...)
    Mike_G : Ya, object[] was just continue the example that the value in the dictionary could really be anything that can hold 2 values
  • I would have said generic dictionary too.

    If you didn't want to do anything extensive, just make a struct or some sort of tuple out of Value1, Value2 and make those the value of your dictionary's Key. Something like:

    Dictionary<Key, ThatTinyStructYouHadToCreate>

    Bad idea: If you didn't like that option, as far as "built-in" goes, a DataRow in a DataTable would give you that ability. While that's a very simple way to set it up, it'd also be a remarkably inefficient (as far as execution cost) way to go about it.

    bendewey : I was going to suggest this, nice.

Clojure read-line function problem

I'm trying to get console input in my Clojure program, but when it gives me this error when it gets to that part of the program.

Exception in thread "main" java.lang.ClassCastException:
clojure.lang.LineNumberingPushbackReader cannot be cast to java.io.BufferedReader

the 'read' function works, but it's not what I need. Here is the code I'm using.

(defn prompt-read [prompt]
  (print (format "%s: " prompt))
  (flush )


It is obviously just the version I'm using. It's the version included in the current sample code of Programming Clojure, I'll test out the current release version and see if that is the problem.

From stackoverflow
  • Hmm, it seems to work for me. What version of Clojure are you using and how are you calling prompt-read? Here's what I'm getting back (here goo is my response):

    user=> (defn prompt-read [prompt]
    (print (format "%s: " prompt))
    (flush )
    user=> (prompt-read "foo")
    foo: goo
    Rayne : Yes sir that was the problem! Thanks!
    Chris Bunch : Of course. Clojure's been changing a lot lately so I've run into a lot of similar problems between the first beta of the book and the current beta (but apparently this will calm down a bit soon).
  • The read-line problem was a known bug. It was fixed. Update your Clojure version.

    Rayne : I know, I was the one who reported that bug in the first place. I appreciate your enthusiasm but this answer was unnecessary.

add to TempData from non controller class

How do I add to the TempData dictionary from a non controller class?

From stackoverflow
  • To do so you'd need the current controller context, otherwise you cannot.

    ViewContext.Controller.TempData["whatever"] = whatever

  • Just don't do it :D. Everything needs to go through your controller, I know its a pain but that is the right way of doing it.

    Slee : I am using a strongly typed session state class, if a certain value does not exist I wasn't to add a message to the tempdata, so rather than repeat code on every single controller action that access this value I want to add the notification at that point.
  • You would have to pass the TempDataDictionary to the other class. I do this quite a bit and there is nothing wrong with it as long the other class is related to presentation (which it sounds like it is).

Having trouble initializing an SDL_Surface

I'm trying to set up something in SDL [in C++] where I can draw a one pixel big rectangle. I've got everything in my code working except my second SDL_Surface called rectangle. I'm having trouble initializing it. Here's the line where I try to initialize it:

rectangle = SDL_Surface(SDL_DOUBLEBUF | SDL_HWACCEL | 
                        SDL_SRCALPHA  | SDL_HWSURFACE,
                        screen->format, 1, 1, 16, NULL, clip_rect, 1);

Thank you for taking the time to read this and any answers you might choose to give.

From stackoverflow
  • I think that the main problem you are having is that there is no SDL_Surface function. To create a new surface, use SDL_CreateRGBSurface. Be sure to call SDL_FreeSurface on the returned surface after you are done with it or you will leak memory.

    Additionally, I am not sure why you are creating a surface for the rectangle. A cleaner way of drawing a solid-color rectangle is SDL_FillRect without creating a new surface.

    William : Yeah, that worked. Thank you very much.

What Backup Library/Code Do You Use For Your Dataset (Files On Disk)?

I'm implementing Backup functionality into my new (small) app, Oldaer. I've got standalone desktop files (rather than sitting in a SQL db).

Looking around, I decided on using a Clarion 3rd-Party Template that will package them into one file and then compress (huffman's) that one file. Restoring is just the reverse. Uncompress, unpack.

However, I'm not convinced this is ideal.

What Backup functionality do you implement for your dataset?

Of course, there's a lot more in "Backup/Restore" functionality. Location, Tracking/Archiving, Out-of-the-box Information (like better ways of letting the User know what was in the archive file). But that's another question.

From stackoverflow
  • SQL Replication, clustering, RAID 5

    Stu Andrews : Thanks tslib. Was kinda hoping for some static files, but I guess most folk work in SQL anyway.
    tsilb : Ahh. You still have RAID. My group backs up our physical data/files on an identical server off-site in a failover config.
  • Stu,

    Just been playing with uploading datasets to Amazon S3 using the NetTalk 3rd party libraries in Clarion. Seems to work a treat. I am working on keeping multiple 'versions' of the dataasets using the MetaTags functionality.

    Happy to dig out my code and discuss further if you need.

    Cheers, Devan

    Stu Andrews : Devan, Hey hey! Good to see another Clarionite on here :) Will take a squiz at Amazon S3. Sounds like a good online option.

Has anbody used Boo and can you comment on your experiences?

I'm looking for a groovy equivalent on .NET http://boo.codehaus.org/

So far Boo looks interesting, but it is statically typed, yet does include some of the metaprogramming features I'd be looking for.

Can anyone comment on the experience of using Boo and is it worth looking into for more than hobby purposes at a 1.0 Version?

Edit: Changed BOO to Boo

From stackoverflow
  • I've been using Boo quite a lot lately. It's very flexible and very powerful. The metaprogramming works well, but it's not nearly as easy to use as Nemerle's. In addition, the lack of arbitrary expression nesting (e.g. def foo = if(bar) match(baz) { ... } else 0;) makes certain things harder than it has to be, but that's not something you're going to miss unless you're coming from Nemerle, OCaml, Haskell, or something along those lines.

    Overall, I'd say give it a shot. I don't think you'll be disappointed.

  • I wrote a paper on it for my programming language class. I was really impressed with it. It's very fun, and they've started working on BooLangStudio. SharpDevelop also has some support for it.

    There are a lot of things that I liked about it. When BooLangStudio will be released with code complition, and boo compiler reaches 1.0 ( that means that the compiler will be written in pure boo :D ) I'll definitely be considering it over C#. It's awesome so you won't regret looking into it!

Embedding Quick Time movies in HTML Pages

I am trying to embed QuickTime movies into my HTML/ASPX pages but somehow they work on local machine but when i deploy them on my server they dont play at all. I tried all sorts of options but still unable to find a reason for that. anybody else have been though this issue ?

I did a quick research and find few resources but even though following them works on my local machine but not on production. I am wandering , do i need to setup some sort of streaming to just embed few videos files or what ?

and yeah i did follow the apple article too (who put the blame on simply internet explorer) while my firefox shows the same result. I got the image (startup) but no video as i click to play.

One video is of 11 MB while other is 50 MB. I renamed the files by removing all the spaces now and i can see the QuickTime plugin initiating but after a while the Question Mark is appearing on the QuickTime Logo. Mime type is also video/quicktime so which is correct.

From stackoverflow
  • How large are the videos? If you are not streaming the plugin may need to download the entire file before it can play, whereas locally it does not. That could cause a very long pause before the movie starts.

  • Point your browser directly to the movie's URL — not the containing page. See what error you get. Also, is the MIME type correct?

  • Actually the issue was not with my Page, The QuickTime movies require QuickTime (mov movies) and ITune (m4v movies)to be installed on Server. Hence after installing both softwares, the issues are resolved

  • Very interesting. I'm running IE8 with latest Quicktime. I pointed IE directly to the url of the movie...and after it loaded, it played. However, it will not stream and I see the question mark in the quicktime logo. Any suggestions?

Normalizing space characters in Prolog atoms

What is the best way to normalize whitespace characters (space, newline, tab) in a Prolog atom, e.g. in SWI-Prolog. I.e. I would like to have a rule:

normalize_space_in_atom(+Atom1, -Atom2)

such that Atom2

  • has any sequence of whitespace characters turned into a single space
  • starts with a non-space
  • ends with a non-space
From stackoverflow
  • SWI Prolog provides normalize_space/2, and so you could define your predicate as follows:

    normalize_space_in_atom(A1,A2) :- normalize_space(atom(A2),A1).

    I've tried this out with SWI Prolog 5.7.5 and it appears to work. You could add more error handling if you wish.

    Kaarel : Thanks, works in 5.6.61 as well. I can't believe I couldn't find it in the documentation.

Delphi 2009 classes / components to read/write file permissions

Does anyone have a set of classes / components that will work with Delphi 2009 (Unicode) to read and write NTFS file permissions?

There was a thing called "NTSet" - but they stopped development at Delphi 2006 about 3 years ago :-(

Any other takers??

Thanks! Marc

From stackoverflow
  • JCL has units to deal with file permissions, and they claim D2009 compatibility.

    Mick : I believe the best link would be to here: http://blog.delphi-jedi.net/security-library/
    Mick : Documentation for the above security library is here: http://jwscldoc.delphi-jedi.net/
    marc_s : Thanks - I'll see how that library lives up - looks promising!
  • Although not native Delphi, you could use SetACL. With that, you have 2 options. You can shell-out and call SetAcl.exe from your Delphi program, or you can use the SetACL.OCX and call it directly from your code.

    Of course, you'd need to distribute SetAcl.ocx with your application, but it works very very well.

    marc_s : As long as their are other ways, I'd definitely prefer a native Delphi way over OCX or shelling out to a EXE - but thanks anyway!
  • Colin Wilson's "NT low-level" component set wraps the APIs you need, and supports Delphi 2009 as well as earlier releases. However you may need to rely on the MS documentation and samples if you need detailed help to implement a specific operation. You can find the components (and others) at http://www.wilsonc.demon.co.uk/delphi.htm. They are freeware/donationware. I have found many uses for them over the years.

    gabr : Colin's stuff is high quality and extremely useful. +1

Are SQL stored procedures case sensitive?

for example...

ALTER PROCEDURE [dbo].[Reports_Dashboard_Get_Sav]   
    -- Add the parameters for the stored procedure here
    @startDate datetime,
    @endDate datetime,
    @companyID int=null

set @days=datediff(m,@startdate,@enddate)
if (@days)=0 
    set @days=1

This is not my code but if this is case sensitive then @days is not going to be calculated properly as the startDate/startdate and endDate/enddate variables don't match...

From stackoverflow
  • No. Not T-SQL at least...

  • As I recall, they are not case sensitive for the SQL commands themselves, I've routinely seen them written as lowercase. I'm pretty sure the rest is case-insensitive as well given that its an extension of the T-SQL spec.

  • They can be, depending on your database's collation. When you install SQL Server and choose your default collation, you'll notice that there's a "case sensitivity" checkbox. Certain collations are case sensitive and will affect your queries (and stored procedures).

    Worse still, many vendors don't test their products on servers with case sensitive collations, which leads to runtime errors.

    dbones : argh you beat me -- here is a link tho http://aspadvice.com/blogs/ssmith/archive/2007/09/30/Case-Sensitive-or-Insensitive-SQL-Query.aspx
    Michael Haren : Does that apply to variable names? Or just data?
    Russ Cam : I was surprised to find this out when we gained access to another database at work - not only were database objects case sensitive but so were queries against table data.
    Cade Roux : But your query won't run if it can't find the objects - it's not just going to silently insert NULLs or anything. Now it might not think a table exists, but in a LEFT JOIN, say, you aren't going to just get NULLs because a table is not in the right case, you'll get an error.
    Russ Cam : @Cade, that's true

Make a div fill the space


I'd like to put two columns on the side of the content div. The part I have problems with is that I want the columns being built from 3 parts. The top and bottom should have fixed heights, but the middle one would adjust depending on the content height. Look at the sample with one column:

* { border: 1px solid black;}
#contentWrapper     { width:450px; }
#leftColumn         { width:100px; float: left; }
#leftColumnTop      { width:100px; height:50px; background-color: gray; }
#leftColumnMiddle   { background-color: red; }
#leftColumnBottom   { width: 100px; height:50px; background-color: gray; }
#content            { width: 300px; float: left; }
#footer             { width: 400px; clear: both; }
<div id="contentWrapper">
<div id="leftColumn">
 <div id="leftColumnTop"> </div>
 <div id="leftColumnMiddle"> </div>
 <div id="leftColumnBottom"> </div>
<div id="content">content<br>
<div id="footer">footer text</div>

What I want is the #leftColumnBottom stick at the top of the footer and red #leftColumnMiddle to fill the space between top and bottom part.

From stackoverflow
  • try min-height for the one that needs to grow

    Phantom Watson : In case anyone still cares about Internet Explorer 6, min-height isn't supported by it for divs. It appears to be fully supported by the newest versions of all the major browsers, though, so disregard this unless if you're a huge stickler for browser compatibility.
  • This works in everything except IE6; for that you'll need a conditional comment and css expression to set a height instead of bottom on #leftColumnMiddle

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <style>* { border: 1px solid black;}
    #contentWrapper     { position: relative; float:left; width: 450px; }
    #leftColumnTop      { position: absolute; width: 100px; height: 50px; left: 0; background-color: gray; }
    #leftColumnMiddle   { position: absolute; width: 100px; top: 50px; bottom: 50px; left: 0; background-color: red; }
    #leftColumnBottom   { position: absolute; width: 100px; height: 50px; left: 0; bottom: 0; background-color: gray; }
    #content            { width: 300px; float: left; margin-left: 100px;}
    #footer             { width: 400px; clear: both; }
    <div id="contentWrapper">
        <div id="leftColumnTop"> </div>
        <div id="leftColumnMiddle"> </div>
        <div id="leftColumnBottom"> </div>
        <div id="content">content<br>
    <div id="footer">footer text</div>

    And to the commenter - it nearly worked, so that's why. ;)

    gnud : Just delete the damned answer, then =)
    ya23 : It seems to do the job, brilliant! Fortunately, I don't have to care about IE6 too much.
  • If you need both columns to be of equal height, and work in IE6, you basically have to hack.

    A solution I've used in the past involves setting up a fake margin/padding for one of the columns. This assumes that you know a upper limit of how large the columns can grow (could be in the magnitude of several thousand px's).

    This solution is outlined here.

    Quoting from the page I linked:

    The basic method works like this:
    1. Blocks which will act as columns must be wrapped in a container element
    2. Apply overflow: hidden to the container element
    3. Apply padding-bottom: $big_value [2] to the column blocks, where $big_value is a
    4. large enough value to guarantee that it's equal to or larger than the tallest column
    5. Apply margin-bottom: -$big_value to the column blocks

Uploading Rails Apps with MediaTemple

Any recommendations of a recent tutorial, or guide, on uploading Rails applications to a (gs) rails container?

I've followed a couple tutorials already, both of which haven't worked.

From stackoverflow
  • I used the mt-capistrano gem (from MT) and used this tutorial. It worked just fine for me.

    Clayton Bellmor : That's fairly out of date though. I've already had loads of difficulty implementing that method. Are you using the latest versions of rails, capistrano, etc?
    Bill : I'm using Rails 2.1 and Capistrano 2.5 with no difficulties. I still have to roll my db:migrate(s) manually b/c of some $PATH issues, but I like to see whats going on with my production server anyways.
  • I wrote a how-to a long time ago that someone (apparently) fixed up and got working. I was notified about the post with a pingback not very long ago. Perhaps it will help you get started:


  • Do you know if MediaTemple supports Passenger?

C#/asp.net; open a file write contents to a div, span, label, some kind of container.

I’d like to be able to open a text/html file and write its contents to a container, either an HTML div or an asp label would be fine. How do I go about doing this in the C# codefile for the page in question?

From stackoverflow
  • You just want to stream in the file and place the text into the Label.text field:

    lable1.text= System.IO.File.ReadAllText( path );
    IainMH : Great answer +1, but with a label, it's InnerText or InnerHtml.
    Joel Coehoorn : Yes: the .Text property will escape things like < for you. You could also use a literal control- that may be more what you really want.

ASP.NET Web Application - compiling .cs files

I guess I have been using the Web Site model ever since .NET 2.0 and never looked back. Now I'm using the Web Application mode on a few projects. How do you tell the compiler to compile .cs files in the project? I assume you can do this since the newer-MVC projects do it for the Controllers.

I have a class, RestRouteHandler, that implements the IRouteHandler interface but because I think the .cs file is not being compiled I can't use it in my Global.asax.

From stackoverflow
  • use the "Build" menu in Visual Studio

    tyndall : I do. Then I get this message: The type or namespace name 'RestRouteHandler' could not be found (are you missing a using directive or an assembly reference?)
    tyndall : The other weird thing... Is when I add a .cs file to my project. It comes in completely blank. No code. weird.
    Jason : are you missing a reference or using statement in your code? If your templates are empty it may be worth it to try reinstalling VS.NET and all of the Service Packs.
  • Right-click the .cs file in the Solution Explorer and click Properties. Set the "Build Action" to compile.

    tyndall : That's the ticket. Ran into this other day and couldn't remember that's how I fixed it. Thanks. +1 and answer.
    Jon Tackabury : No problem. I ran into this a few times as well after I converted some projects to Web Applications.

How did you get ASP.NET to output UTF-16 encoded text?

How did you get ASP.NET to output UTF-16 encoded text?

I serialize an object in .NET which by default is UTF-16 format. Now I want to send the string as an output response to an .ashx request.

I get the error: Switch from current encoding to specified encoding not supported. Error processing resource

How do I tell my website or page to use UTF-16 format.


Update: read both answers.

From stackoverflow
  • Change the Response.ContentEncoding property to System.Text.Encoding.Unicode?

  • In general: don't.

    Web pages as UTF-16 confuse many tools and make browsers behave in odd, unexpected ways. (Esp.: linked scripts, form submissions, proxies). UTF-16 can only be served safely as a binary object, so for web content stick to an encoding that is a superset of ASCII - the obvious choice being UTF-8.

    The error you quote is generally what you get when you try to read an XML file whose <?xml encoding="..."?> prolog clashes with the real encoding of the file. None of the superset-of-ASCII encodings ever clash because 'xml encoding' is ASCII and represented the same in all of them, but if you've put encoding="utf-16" in an XML file that's not saved as UTF-16, or you've not put it in when it is, then the parser can't cope with the logical impossibility.

    tyndall : Actually I am using the ToXml Extension Method from here: http://solidcoding.blogspot.com/2007/11/c-toxml-extension-method.html .Since System.String is stored internally as UTF-16 that is where my problem is. I will have to use a longer ToXml method that accounts 4 this and converts to UTF-8
    bobince : Perhaps XmlSerializer.Serialize(Stream, Object) onto a byte stream, rather than (TextWriter, Object) is what's required?
    tyndall : @bobince, that is what the examples I saw online showed. Oh well few extra lines of code. thats all.
    tyndall : Not exactly how I wrote it, but close enough: http://blog.newslacker.net/2008/02/net-xml-serialization.html and I used UTF8
    bobince : That example too is using the TextWriter. I haven't tried it, but it seems to me like the method accepting a Stream instead should be byte-oriented and hence not produce a spurious 'encoding="UTF-16"'.

OnClosing event is not being called when Close, X, button is pressed. Windows Mobile.

I am new to Windows Mobile and created an app that needs to do some clean up when a Form is closed. When I click on the Close in the ControlBox it does not call the OnClosing event. This works fine in regular windows but is not working with my Windows Mobile device.

Here is my code:

protected override void OnClosing(System.ComponentModel.CancelEventArgs e) { ... }

I have also tried this with no luck:

Form.Closing += new System.ComponentModel.CancelEventHandler(WindBaseForm_Closing);

I would appreciate any help you can give.

From stackoverflow
  • Correct. The (X) button in Windows Mobile is called the "Smart Minimize" button and only minimizes the Form. Set the Form's MinimizeBox property to false and it will change to (OK) which will close the Form (and raise the event).

    For the gory details as to why this happens, read this.

    Lasse V. Karlsen : This article, which I've read before, only shows that MS didn't really know how the other devices worked. Palm did in fact close every program when you switched, it just had a nice policy that said that every app should strive to save and restore the exact state upon relaunch.
    ctacke : Palm never really "closed" apps because they never actually "loaded" in the same way that CE apps load. Palm ran the PDBs in place, jumping from the OS to the app code directly. It was not a multitasking OS, so it's really hard to draw a parallel that a Windows-only dev would understand.
  • wow I had the exact same problem, thanks a lot for the explanation.


Finding unmatched records with SQL

I'm trying write a query to find records which don't have a matching record in another table.

For example, I have a two tables whose structures looks something like this:

    State | Product | Distributor | other fields
    CA    | P1      |  A          | xxxx
    OR    | P1      |  A          | xxxx
    OR    | P1      |  B          | xxxx
    OR    | P1      |  X          | xxxx
    WA    | P1      |  X          | xxxx
    VA    | P2      |  A          | xxxx

    State | Product | Version | other fields
    CA    | P1      |  1.0    | xxxx
    OR    | P1      |  1.5    | xxxx
    WA    | P1      |  1.0    | xxxx
    VA    | P2      |  1.2    | xxxx

(State/Product/Distributor together form the key for Table1. State/Product is the key for Table2)

I want to find all the State/Product/Version combinations which are Not using distributor X. (So the result in this example is CA-P1-1.0, and VA-P2-1.2.)

Any suggestions on a query to do this?

From stackoverflow
        Table2 T2
               Table1 T1
               T1.State = T2.State AND
               T1.Product = T2.Product AND
               T1.Distributor = 'X')

    Edit: Damn: beaten to it. This should be ANSI compliant though.

    Jonathan Leffler : This works on most SQL systems; EXCEPT won't work everywhere (though it is more elegant where it does work).
    Tomalak : Using "SELECT 1 FROM" in the sub-query (instead of "SELECT * FROM") may prevent an unnecessary table scan. Though I would expect the DBMS to be smart enough to figure it out on it's own, upon seeing "EXISTS".
    gbn : I have this with my SQL Server MVP colleague all the time :-) The * is expanded at compile time, bt collapses trivially, but not runtime he says. He showed me an article once. I saw Itzak Ben-Gan a while ago and he said the * is quicker. The choice is yours...
    Boofus McGoofus : Worked well. Thanks.
    Dems : When using EXISTS there should be no difference between SELECT * and SELECT 1.
  • select * from table1 where state not in (select state from table1 where distributor = 'X')

    Probably not the most clever but that should work.

    gbn : IN is not as good as EXISTS, and does not handle the composite key on state/product
  • In T-SQL:

    SELECT DISTINCT Table2.State, Table2.Product, Table2.Version
    FROM Table2 
      LEFT JOIN Table1 ON Table1.State = Table2.State AND Table1.Product = Table2.Product AND Table1.Distributor = 'X'
    WHERE Table1.Distributor IS NULL

    No subqueries required.

    Edit: As the comments indicate, the DISTINCT is not necessary. Thanks!

    HLGEM : I wouldn't use distinct, but otherwise this is what you want.
    gbn : The distinct will probably make the query less efficient, but never more efficient. It depends on the relative table row counts. The distcnt also forces an aggregate that sub query does not need.
  • SELECT DISTINCT t2.State, t2.Product, t2.Version
    FROM table2 t2
    JOIN table1 t1 ON t1.State = t2.State AND t1.Product = t2.Product
                    AND t1.Distributor <> 'X'
  • In Oracle:

    SELECT t2.State, t2.Product, t2.Version
    FROM Table2 t2, Table t1
    WHERE t1.State(+) = t2.State
      AND t1.Product(+) = t2.Product
      AND t1.Distributor(+) = :distributor
      AND t1.State IS NULL

Why does this work in Firefox but not IE?

           'display the left product image
           if intImagePos = 2 then
              response.write("<td class=""ProductImage"">" & vbcrlf)
              'show image
              if Len(objProduct.Image2) > 0 then
                 response.write("<a class=""thumbnail"" href=""javascript: void(0)"" onclick=""MM_openBrWindow('images/festool/KAPEXKS120-571287/KAPEXKS120-571287-Gallery/','scrollbars=no,resizable=no,width=840,height=580')""><img src=" & objProduct.Image1 & " border=""0""><br>See gallery of this product</a>")
                 response.write("<p>No Picture Available</p>")
              end if
           end if

Error code in IE is:

Line: 28 Char: 3 Error: Invalid argument. Code: 0

Line 28 is:

  var newWindow = window.open(theURL,winName,features+win_position);

Thanks for any help in solving this matter, I'm not a programmer at all and have no idea what I'm looking at, just copy and pasting and manipulating text to try and get stuff to work how I want.

From stackoverflow
  • This is just a guess, but I recall having a problem with window.open in ie where the winName variable had a space in it. Maybe put an alert(winName) before it to check.

    scunliffe : Quite likely... IE will fail if the window name has spaces or tabs http://webbugtrack.blogspot.com/2008/06/bug-289-popup-window-name-cant-have.html
  • You might want to watch the error in Firefox's javascript debugger:


    Firefox often fails silently on javascript errors. So it might not be an IE only issue.

  • The error is not in your server-side code. I'd look for the problem after the page is rendered.

  • Your call to MM_openBrWindow() only has two parameters, but it takes three. Try changing it to this:

    scunliffe : Doh! this is the issue, there is no window name.
    USteppin : This worked, thank you very much.

quaternion libraries in C/C++

Any good libraries for quaternion calculations in C/C++ ?

Side note: any good tutorials/examples? I've google it and been to the first few pages but maybe you have have some demos/labs from compsci or math courses you could/would share?


From stackoverflow
  • You could try with Boost - usually good place to start with. They have a dedicated sublibrary for that.

    As for the examples look at the documentation and the unit tests that come along with Boost.

  • DirectX has its own quaternion functions, as do several other 3D libraries.

    In my opinion, the best way to learn how quaternions work is to plow through the math yourself. The Wikipedia page on quaternions and conversion contain all the formulas you need. I wrote my own quaternion library from that :) (It's in Haskell, so I won't bother to post it.)

    Anonymous : Good idea with DirectX and graphics. Learning can produce some appealing visual effects.
    Brian Knoblauch : It's really not that hard to do yourself, if you can't find the libraries. I had no problem with it and my IT math training was very limited (computer science business degree, not pure science).
  • For documentation on quaternions, check out 3D graphics text books. They are simply matrices that produce the effect of 3D rotation using multiplication instead of computationally expensive trigonometry.

  • I'm a fan of the Irrlicht quaternion class. It is zlib licensed and is fairly easy to extract from Irrlicht:

  • There's Eigen, a templated library of math and geometry stuff used in Blender and by KDE programs, which has a slick Quaternion class defined in a single .h file.

    Info at http://eigen.tuxfamily.org/index.php?title=Main%5FPage and http://www.ohloh.net/p/5393

  • If you decide to roll your own, or actually want to understand the math behind the code (useful for debugging), I highly recommend Martin Baker's website. It looks primitive, but the explanations are thorough and easy to follow, and he also provides code in places.