Saturday, April 30, 2011

Variable for img src=

Hi there, I have a question. Firstly, I am not going to pretend that I know what I am talking about here. I am a newbie to http and JavaScript.

I think my question may be answered in this post http://stackoverflow.com/questions/116967/img-src-tags-and-javascript but I thought I would explain the exact thing I am trying to achieve in case there is an easier way.

I have a webpage, I want to display an image on it. Only thing is, the image is coming from an automated system monitor, the image is automatically generated each day and placed in a new directory depending on date.

e.g. On April 4 = "http://host/partition/2009/apr/04/cpu.gif"
e.g. On April 5 = "http://host/partition/2009/apr/05/cpu.gif"

To facilitate this, I have created some basic JavaScript to give me the date in the format I need it. I have all that working. Now I just want to use that variable I created to show the image. I have the JavaScript code stored in a function called displaydate() If I do this <script language="JavaScript"> displaydate() </script> I see "http://host/partition/2009/apr/05/cpu.gif" and that is correct.

Now how do I display this on the site correctly?

 <a href="displaydate()"><img src="displaydate()" </a></td>    //This does not work. I am just adding it to show where I have been heading.

P.S. I have read a lot of pages on this and been trying a lot of things, but have had no luck so far. Any help, would be much appreciated.

From stackoverflow
  • Yes, that page probably does answer your question. Basically, you want this javascript:

    <script type="text/javascript">
    document.getElementById('image').src = "yourpicture.png";
    </script>
    

    Except you want to replace the "yourpicture.png" with the function you wrote to generate the correct path to the image on disk, so...

    <script type="text/javascript">
    document.getElementById('image').src = displaydate();
    </script>
    

    Of course, you might need to modify this a bit for your own uses, the getElementById will take as an argument whatever the id attribute of your < img > tag is. You probably want to execute the above javascript after your page has loaded, i.e.:

    <html>
    <head>
    <script type="text/javascript">
    function load()
    {
    document.getElementById('image').src = displaydate();
    }
    
    function displaydate()
    {
    //your displaydate() function here
    }
    </script>
    </head>
    
    <body onload="load()">
    
    <img src="nothing.jpg" id="image" name="image"/>
    </body>
    </html>
    
    Brett Bender : Welcome, just made another edit that i actually tested and it worked for me. Hopefully you can get yours working. Good luck!
  • Hi again. I have added the code, but am still having some issues. I am clearly missing something.

    Here is script I am working with.

    The output I get is, a new page with text written on it. http://host1/Shared/2009/Apr/21/cpu_abs.gif

    That's not what I am after. I want to show that picture, not display that text. Also I do get an error when I launch the page, "Line 15 permission denied". Line 15 is this: document.getElementById('image').src = displaydate();

    If I debug, I get another error: Microsoft JScript runtime error: 'document.getElementById(...)' is null or not an object

    Any help much appreciated. I am out of my depth here, but keen to learn.

        <html>
    <head>
    <meta http-equiv="Content-Language" content="en-au">
    <meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
    <title>Infrastructure Dash Board </title>
    <meta name="description" content="Infrastructure Dash Board ">
    <script type=text/javascript> // The time out value is set at 60,000 milli-seconds (or 60 seconds) 
    setTimeout(' document.location=document.location' ,60000); 
    </script> 
    
    <script type=text/javascript>
    function load()
    {
    document.getElementById('image').src = displaydate();
    }
             function displaydate()
             {
             var now = new Date();
             var months = new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
             var day = ((now.getDate()<10) ? "0" : "")+ now.getDate();
             var month = months[now.getMonth()]
             var year = [now.getYear()]
             document.write("http://host1/Shared/" + year + "/" + month + "/" + day + "/cpu_abs.gif");
             }
            </script> 
    </head>
    
    <body onload="load()">
    
         <img src="nothing.jpg" id="image" name="image" width="600" height="251"></a></td>
    
    </body>
    </html>
    
  • You should just need to change this line

    document.write("http://host1/Shared/" + year + "/" + month + "/" + day + "/cpu_abs.gif");
    

    to

    return "http://host1/Shared/" + year + "/" + month + "/" + day + "/cpu_abs.gif";
    

Serialize an arbitary string to XML in .NET

What is the best way to serialize an arbitary string (into an XML attribute or XML node) to a XML stream so that the XML stays valid (special characters, newlines etc. must be encoded somehow).

From stackoverflow
  • I would simply use either a DOM (such as XmlDocument or XDocument), or for huge files, XmlWriter:

            XDocument xdoc = new XDocument(new XElement("xml", "a < b & c"));
            Console.WriteLine(xdoc.ToString());
    
            XmlDocument xmldoc = new XmlDocument();
            XmlElement root = xmldoc.CreateElement("xml");
            xmldoc.AppendChild(root).InnerText = "a < b & c";
            Console.WriteLine(xmldoc.OuterXml);
    
            StringBuilder sb = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.OmitXmlDeclaration = true;
            using (XmlWriter xw = XmlWriter.Create(sb, settings))
            {
                xw.WriteElementString("xml", "a < b & c");
            }
            Console.WriteLine(sb);
    
  • Isn't that exactly what CDATA is meant to be used for in XML? All you need to watch out for is that your data doesn't contain "]]>", or that you escape them somehow using the time-honored C technique:

    Encoding:
        '\' becomes '\\'
        ']' becomes '\]'
    Decoding:
        '\]' becomes ']'
        '\\' becomes '\'
    

Vista Remote Desktop connection timeout setting?

Hi all,

I'm running Windows Vista Business 64 bit. I'm having trouble with session timeout/logout.

If I leave my PC on overnight with apps open but locked, they are all there the next day as I expect.

If I leave my PC on then use Remote Desktop via the VPN to access my desktop from home, I get the applications I left open also. I use the apps and disconnect the session. However, when I come back in in the morning all the apps are gone and it appears as if a logout has occurred.

Does anyone know of a setting to change this? It looks like if I use remote desktop and then leave it for a period of time the session is logged out.

Thanks for any help Chris

From stackoverflow
  • At least on the server side you can tweak it like this:

    Administrative tools -> Terminal Services Configuration -> Connections -> RDP-tcp (right click -> properties) -> Sessions-tab -> check "override user settings" -> Idle Session Limit, set to your desire

have this php query also show an html link

can this code snippet be modified to reveal html coding?

<?php $_option = $this->getOption() ?>
<?php echo  $this->htmlEscape($_option->getTitle()) ?>

it is showing a title but in that title i have an href:

<a href="http://link" target="otherwindow">link</a>

instead of it appearing as a link it just shows me the code. i'd like it to be a clickable link.

possible?

From stackoverflow
  • Yes, just remove the $this->htmlEscape() and leave the $_option->getTitle()

    The escape function is to provide just the functionality of not being able to use (or inject) html commands or javascript.

Only one top level element is allowed in an XML document

hi guys, Following is the code for inserting new nodes in an xml file .

Dim fleStream As New FileStream("C:\mailing.xml", FileMode.Append, FileAccess.Write,FileShare.ReadWrite)
Dim stmWriter As New StreamWriter(fleStream)
Dim writer As New XmlTextWriter(stmWriter)
Dim currNode As XmlNode
Dim doc As New XmlDocument

doc.LoadXml(("<XMLFile>" + " <EMail></EMail>" + "</XMLFile>"))
'doc.Load("C:\mailing.xml") '
Dim docFrag As XmlDocumentFragment = doc.CreateDocumentFragment()
docFrag.InnerXml = "<From><Address>" + txtFrom.Text + " </Address></From>"
currNode = doc.DocumentElement.FirstChild.AppendChild(docFrag)
currNode.InsertAfter(docFrag, currNode.LastChild)

docFrag.InnerXml = "<Receipient> <To>" + txtTo.Text + " </To></Receipient>"
currNode = doc.DocumentElement.FirstChild.FirstChild.AppendChild(docFrag)
currNode.InsertAfter(docFrag, currNode.LastChild)

docFrag.InnerXml = "<Subject>" + txtSubject.Text + "</Subject>"
currNode = doc.DocumentElement.FirstChild.AppendChild(docFrag)
currNode.InsertAfter(docFrag, currNode.LastChild)

docFrag.InnerXml = "<Body>" + txtBody.Text + "</Body>"
currNode = doc.DocumentElement.FirstChild.AppendChild(docFrag)
currNode.InsertAfter(docFrag, currNode.LastChild)

doc.Save(writer)
'doc.Save("C:\xmlmailfile.xml") '
writer.Flush()
stmWriter.Flush()
stmWriter.Close()

By executing this i cant able to view the result in IE,an error msg comes as "The XML page cannot be displayed

Cannot view XML input using XSL style sheet.

Only one top level element is allowed in an XML document. Error processing resource 'file:///C:/mailing.xml'. Line 2, Posi...

asdasd@qwe.com

When i open the xml file the datas are entered,Can anyone help me to solve the pblm.What modifications are to be done in my code?

From stackoverflow
  • Open it in Notepad and see what the output is, and from there see what the error really is, and post it here if you need more help.

  • Well, this is quite normal. An XML document must have a root element that is not duplicated. You have already asked the related question here and originally here. Jon Skeet quite succinctly explained this to you already.

    If there is an issue in understanding, you should consider reading up on XML or doing some research, instead of asking the same question repeatedly because most people will not realize that you have already received excellent answers to the problem.

    If you keep doing the same thing you've already done, you should not expect different results.

How to design html pages which renders properly in windows while staying in Linux?

I usually prefer linux for programming( i program in django on Ubuntu). But often i need to design html pages which renders properly in Windows and Linux?

How iam currently doing the above is

  1. Design (Fix) html page in linux

  2. Reboot to windows check whether the design is proper or not. if not reboot to linux repeat step1 ,step2

i felt the above process is tedious. Is there any easier way to do this?

From stackoverflow
  • You could use a virtual machine to host your Windows installation, if you have a Windows license (which I'm guessing you do by the fact you reboot into Windows), and the RAM to keep a virtualized instance of XP or whatever Windows you use to test.

    Using VMWare or VirtualBox you could set up a shared folder so both the virtual instance and Linux can look at the same file to test the website locally.

    Rama Vadakattu : Any good pointers which illustrates the above.
    Stijn Sanders : Xen or QEmu may get you started a little smoother on linux than VMWare or VirtualBox, but all four should be able to get the work done.
  • If a website is being correctly displayed doesn't depend much on the operating system. It mainly depends on the webbrowser and its engine.

    A webpage being rendered in FF 3.0 on Linux will look exactly as on a windows machine.

    Some suggestions if your browser doesn't support Linux by default:

    Rama Vadakattu : it also depends on operating system.In ubuntu the rendering of a web page is slightly different from rendering of web page in windows.
    Rama Vadakattu : These online renderer's can't render local files.We need to move the files to some hosting servers in order to see via BroswerShots, netrenderer
    Simucal : Rendering on different OS's is NOT the same. SO has looked like garbage on certain flavors of linux for while, using the same version FF.
  • There is a great free service called BrowserShots that you can provide a link to which will take screenshots of a site in multiple browsers and OS's. It supports the Linux, Windows, OS X and BSD operating systems, and a large number of major and minor browser (including several versions of each).

    There's also IEs4Linux which will use Wine to install Internet Explorer within Linux. This solution isn't perfect though, as the rendering isn't exact and it can be difficult to install (and get working) any plugins beyond flash. Also, IE 7 & 8 aren't officially supported yet.

    Other Options:

    • For environments with multiple devs, create one server with several virtualized windows installs with different versions. Devs can use remote desktop to test sites on the local network.
    • If you have a 2nd machine handy, install windows on it and a kvm switch to test on this system.
  • Use as many browser platforms for testing as you can under Linux: Firefox, Opera, Konqueror. If you pages work in these browsers, test in IE using BrowserShots or Wine.

    voyager : The problem is when you have to test JS too. Furthermore, if it works under FF, Opera and Konqueror, it's likely it will work with anything you throw at it AS LONG AS IT IS NOT IE. IE gives you NO guaranties.
  • as Adviced by many people here:

    i advice using virtual machines, if you have a server at hand or even better multiple servers you could try and install vmware server version 2.0 so that you and other people can use the same (virtual) machine for testing.

    also it is true that most of the free browsers look the same on diferend Operating systems but bare in mind that some operating systems are lacking fonts you might want, this will make a huge diference.

    with that in mind i advice go virtual an go for a good and free selution vmware server

  • Just to add to what people have said about Virtual Machines, you need to know how to make your django test server available to them. To do this, I use:

    python manage.py runserver 192.168.1.xx:80

    where xx is your local IP address. Then you can browse the site as you're making it, both from virtual boxes running on your Linux host and from other machines on your local network.

Copy Database Sructure of Mysql Database.

I am using MySql 5.1 Database.

I have created a Project database. (Temnplate Database)

and want to Create a copy of the same database from the Application, every time, User Creates A new Project.

How can I copy and Create a New Database of same structure.??

What is the Command to do so???

Thanks a Lot for Help.

From stackoverflow
  • Dump the database with the -d option.

    To create a new copy, do a "create database new-database-name; use new-data-base-name;", then run the dump file as a sql script.

    Ashok Gupta : How can I do the same?? can we copy n create a new structure with single command??
    tpdi : No. In fact the dump file will issue one command per structure (table, view, sp, index, etc.).
  • If you only want to copy the table structure etc. from one db to the other you can use this single bash line:

    mysqldump -u user -ppass -d olddb | mysql -u user -ppass -Dnewdb
    

    The new database must exist already. The -d flag in the mysqldump command prevents copying of data.

Is the ANTLR parser generator best for a C++ app with constrained memory?

I'm looking for a good parser generator that I can use to read a custom text-file format in our large commercial app. Currently this particular file format is read with a handmade recursive parser but the format has grown and complexified to the point where that approach has become unmanageable.

It seems like the ultimate solution would be to build a proper grammar for this format and then use a real parser generator like yacc to read it, but I'm having trouble deciding which such generator to use or even if they're worth the trouble at all. I've looked at ANTLR and Spirit, but our project has specific constraints beyond earlier answers that make me wonder if they're as appropriate for us. In particular, I need:

  • A parser that generates C or C++ code with MSVC. ANTLR 3 doesn't support C++; it claims to generate straight C but the docs on getting it to actually work are sort of confusing.
  • Severely constrained memory usage. Memory is at a huge premium in our app and even tiny leaks are fatal. I need to be able to override the parser's memory allocator to use our custom malloc(), or at the very least I need to give it a contiguous pool from which it draws all its memory (and which I can deallocate en bloc afterwards). I can spare about 200kb for the parser executable itself, but whatever dynamic heap it allocates in parsing has to get freed afterwards.
  • Good performance. This is less critical but we ought to be able to parse 100kb of text in no more than a second on a 3ghz processor.
  • Must be GPL-free. We can't use GNU code.

I like ANTLRworks' IDE and debugging tools, but it looks like getting its C target to actually work with our app will be a huge undertaking. Before I embark on that palaver, is ANTLR the right tool for this job?

The text format in question looks something like:

attribute "FluxCapacitance"  real constant

asset DeLorean
{
    //comment foo bar baz
    model "delorean.mdl"
    animation "gullwing.anm"
    references "Marty"
    loadonce
}

template TimeMachine
{
    attribute FluxCapacitance 10      
    asset DeLorean
}
From stackoverflow
  • ANTLR parsers, and in fact any parser built with something LALR or the like, tend to be big. Do you have an actual grammar for this? It looks like it might be most readily parsed with a hand-written recursive-descent parser, but it's not much of a sample.

    Oops, my mistake, as ANTLR apparently generates recursive-descent. Still, I've had problems with ANTLR generating big parsers.

    Crashworks : It's only a tiny sample -- we do have a hand written parser for the current format, but it's become so complicated that maintenance and adding new features is an abject nightmare. I'm wondering whether parsing it with ANTLR would be easier, or harder still. I've built an LR grammar for our format in ANTLRworks and it seems to syntax-check okay, but the next huge step would be to actually hook up C actions and link it into our program.
    Charlie Martin : How big is the generated parser? The ugly part is usually the parser structure itself.
    Charlie Martin : You know, you just convinced me to move teh ANTLR book up my to-read stack. ANTLR v3 might solve some of the problems I was seeing in 2005-2006.
  • We use Boost Spirit successfully in our application. The Boost license is a very liberal one, so there is no problem using it in commercial applications.

    Quote from the documentation:

    Spirit is an object-oriented recursive-descent parser generator framework implemented using template meta-programming techniques. Expression templates allow us to approximate the syntax of Extended Backus-Normal Form (EBNF) completely in C++. The Spirit framework enables a target grammar to be written exclusively in C++. Inline EBNF grammar specifications can mix freely with other C++ code and, thanks to the generative power of C++ templates, are immediately executable. In retrospect, conventional compiler-compilers or parser-generators have to perform an additional translation step from the source EBNF code to C or C++ code.

  • Then why don't you use flex/yacc? It generates C code,can be run from MSVC, was developped with efficiency in mind, can have malloc overriden (google for yymalloc), they are themselves GPL, but the resulting code (the code you use in your project) AFAIK not.

    Or use a hand-made parser.

  • ANTLR 3 doesn't support C++; it claims to generate straight C but the docs on getting it to actually work are sort of confusing.

    It does generate C, and furthermore, it works with Visual Studio and C++. I know this because I've done it before and submitted a patch to get it to work with stdcall.

    Memory is at a huge premium in our app and even tiny leaks are fatal. I need to be able to override the parser's memory allocator to use our custom malloc(), or at the very least I need to give it a contiguous pool from which it draws all its memory (and which I can deallocate en bloc afterwards). I can spare about 200kb for the parser executable itself, but whatever dynamic heap it allocates in parsing has to get freed afterwards.

    The antlr3c runtime, last time I checked does not have a memory leak, and uses the Memory pool paradigm which you describe. However, it does have one shortcoming in the API which the author refuses to change, which is that if you request the string of a node, it will create a new copy each time until you free the entire parser.

    I have no comment on the ease of using a custom malloc, but it does have a macro to define what malloc function to use in the entire project.

    As for the executable size, my compilation was about 100 kb in size including a small interpreter.

    My suggestion to you is to keep learning ANTLR, because it still fits your requirements and you probably need to sacrifice a little more time before it will start working for you.

  • Realistically, if your grammar is relatively small, and doesn't contain many ambiguities or parsing complexities then it shouldn't matter if you use a recursive descent parser or a shift-reduce parser.

    I would say look at ANTLR and Spirit, also look at Flex and Bison. There are other, less known parsers like Coco/R (contains generators for a lot of languages, including C++) also.

    Crashworks : Bison's no good; we must be GPL-free.
  • A hand-coded recursive descent parser is actually quite fast and can be very compact. The only downside is you have to be careful to code essentally LL(1) grammars.

    You can hand code such parsers as plain recursive C code. If you are really tight on space, you can define a parsing virtual machine, and build a tiny C interpreter to run it. I used to build BASIC interpreters this way back the 70s.

    The ideas came from a 1964 paper on metacompilers by Val Schorre, who shows how to build complete compilers in 10 pages Shorres tiny parser generator that does pretty good recursive descent parsers. A site describing this paper and showing precisely how to build such parsers can be found at http://www.bayfronttechnologies.com/metaii.html

How do I test to see if a variable exists in a ColdFusion struct?

I would like to test:

<cfif Exists(MyStruct["mittens"])>
</cfif>

If the "mittens" key doesn't exist in MyStruct, what will it return? 0, or ""??

What should replace Exists function?

UPDATE

I tried,

<cfif IsDefined(MyStruct.mittens)>

Which also throws the error

Element Mittens is undefined in MyStruct.

From stackoverflow
  • Found the answer here

    It's StructKeyExists

    Tomalak : IsDefined would work as well, but it's slower.
    Dan Cramer : The reason IsDefined wasn't working for you as typed was the missing double quotes. Instead of looking for the 'mittens' struct key, it was trying to dereference the mittens key to see check for existance. That's why you were still getting the error
  • To test for key existence, I recommend:

    <cfif StructKeyExists(MyStruct, "mittens")>
    
    <!--- or --->
    
    <cfset key = "mittens">
    <cfif StructKeyExists(MyStruct, key)>
    

    Behind the scenes this calls the containsKey() method of the java.util.map the ColdFusion struct is based on. This is arguably the fastest method of finding out if a key exists.

    The alternative is:

    <cfif IsDefined("MyStruct.mittens")>
    
    <!--- or --->
    
    <cfset key = "mittens">
    <cfif IsDefined("MyStruct.#key#")>
    

    Behind the scenes this calls Eval() on the passed string (or so I believe) and tells you if the result is a variable reference. In comparison this is slower than StructKeyExists(). On the plus side: You can test for a sub-key in a nested structure in one call:

    <cfif IsDefined("MyStruct.with.some.deeply.nested.key")>
    

Export a Table of Contents to Word

Hey Can any One help me ?

I am creating a table in C# using HtmlTextRender and i am getting the innertext and the css is not working in that when i show it in Ms Word and also i am getting Table Lines and td tr lines.

Thanks in advance :)

Kishh

From stackoverflow
  • Are you using a linked stylesheet (class=) or embedding the css in the table (style=) ?

Error conerned with web.config

hi guys, Following is the error coming while executing.

Server Error in '/' Application.

Configuration Error Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message: It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS.

Source Error:

Line 22:     <customErrors mode="RemoteOnly"/>
Line 23:    
Line 24:     <authentication mode="Forms">
Line 25:       <forms loginUrl="Default.aspx" protection="Validation" timeout="300" />
Line 26:     </authentication>

Source File: D:\slnAllForKids\slnAllForKids\Allforkids\allforkids\web.config Line: 24

Following is my web.config

<?xml version="1.0"?><configuration>
  <configSections>
    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
      <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
          <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
        <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
          <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
          <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
          <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
        </sectionGroup>
      </sectionGroup>
    </sectionGroup>
  </configSections>
  <connectionStrings>
    <add name="AllForKidsConnectionString" connectionString="Data Source=GRAPHIX\SQLEXPRESS;Initial Catalog=AllForKidsData;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>


    <customErrors mode="RemoteOnly"/>

    <authentication mode="Forms">
      <forms loginUrl="Default.aspx" protection="Validation" timeout="300"/>
    </authentication>
    <authorization>
      <allow users="*"/>
    </authorization>


     <compilation  debug="false">
      <assemblies>
        <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
       <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
       <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/></assemblies></compilation></system.web>
  <system.web>
    <pages styleSheetTheme="Kids1">
      <controls>
        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      </controls>
    </pages>
    <!--
          Set compilation debug="true" to insert debugging
          symbols into the compiled page. Because this
          affects performance, set this value to true only
          during development.
    -->


    <httpHandlers>
      <remove verb="*" path="*.asmx"/>
      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
    </httpHandlers>

    <httpModules>
      <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </httpModules>
  </system.web>


  <system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules>
      <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </modules>
    <handlers>
      <remove name="WebServiceHandlerFactory-Integrated"/>
      <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
      <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
    </handlers>
  </system.webServer>
</configuration>

What correction i hve to make to correct this error

From stackoverflow
  • Did you create a virtual application for your site in IIS?

  • This has to do with your Application Setup in IIS

    You need to mark the virtual directory as an Application.

    for IIS 6,

    • Right click the virtual directory containing your application,
    • go to properties
    • go to the Virtual Directory Tab
    • Application Settings Section
    • Click "Create" Default Application
  • I reckon the clue is in the error message:

    "This error can be caused by a virtual directory not being configured as an application in IIS."

    You need to configure the virtual directory as an application in IIS.

GStrings in Python

Groovy has a concept of GStrings. I can write code like this:

def greeting = 'Hello World'
println """This is my first program ${greeting}"""

I can access the value of a variable from within the String.

How can I do this in Python?

-- Thanks

From stackoverflow
  • d = {'greeting': 'Hello World'}
    print "This is my first program %(greeting)s" % d
    
  • You can't exactly...

    I think the closest you can really get is using standard %-based substitution, e.g:

    greeting = "Hello World"
    print "This is my first program %s" % greeting
    

    Having said that, there are some fancy new classes as of Python 2.6 which can do this in different ways: check out the string documentation for 2.6, specifically from section 8.1.2 onwards to find out more.

  • If your trying to do templating you might want to look into Cheetah. It lets you do exactly what your talking about, same syntax and all.

    http://www.cheetahtemplate.org/

  • In Python 2.6+ you can do:

    "My name is {0}".format('Fred')
    

    Check out PEP 3101.

  • In Python, you have to explicitely pass a dictionary of possible variables, you cannot access arbitrary "outside" variables from within a string. But, you can use the locals() function that returns a dictionary with all variables of the local scope.

    For the actual replacement, there are many ways to do it (how unpythonic!):

    greeting = "Hello World"
    
    # Use this in versions prior to 2.6:
    print("My first programm; %(greeting)s" % locals())
    
    # Since Python 2.6, the recommended example is:
    print("My first program; {greeting}".format(**locals()))
    
    # Works in 2.x and 3.x:
    from string import Template
    print(Template("My first programm; $greeting").substitute(locals()))
    
    unwind : Note that the parens with print are a 3.0 newness; before print was a keyword, in 3.0 it's just a function like any other, so it needs the parens. This is why you see examples without them, in other answers.
    Parag : print("My first program; {greeting}".format(**locals())) This last line gives me an error: AttributeError: 'str' object has no attribute 'format'
    Carl Meyer : That's because you're not on 3.0 - the last example is 3.0-only. The preferred option in Python 2.x is the first example.
    Carl Meyer : Ferdinand - please add Python version clarifications to your answer. Python 2.x is still much more widely used than 3.0.
    Ferdinand Beyer : @Carl: Thanks for the comment. I added the version hint -- note that str.format() is actually available since 2.6.
    endolith : Note that the s in %(greeting)s is for "string", not for making 'greeting' plural. ;)

migrating data from VSS to SVN

How do i migrate my data from VSS to SubVersion??

From stackoverflow
  • It depends on whether you want to take the VSS Meta Data with you.

    If yes, have a look at PowerAdmin or Vss2SVN on Tigris

    If no, just to a search of the Code Folders on your machine to remove all .scc & .vss files and then dump that code into your SVN Repo in the standard way.

    EDIT: Looks like Vss2SVN Development on Tigris has been parked.

  • there's a better migration tool on Codeplex, called (imaginatively) VSS2SVN. It works very well, and keeps your history.

WAMP: How to show warning messages in browser?

Dear all,

I have a WAMP installation on my machine and I am developing a PHP website in that. Can anyone tell me what settings to be changed in order to show all errors / warning messages in the browser?

Thanks in advance

From stackoverflow
  • Find your php.ini file, scroll down while reading the comments. There is a global setting for enabling/disabling error output. Change it accordingly. Restart your Apache.

  • First click on the wamp icon in the task panel. Then click on the 'PHP' folder followed by the 'PHP settings' folder. Make sure 'expose PHP' and 'display errors' are both checked. You can set other error settings like 'track errors' and 'display startup errors' as well.

  • Open your php.ini and search for the option error_reporting.

    Change it to E_ALL & ~E_NOTICE.

    That will show all errors and warnings, but no notices.

    Personally I always use E_ALL on my development machines because often the notices are signs to potential code problems.

    Pim Jager : I would indeed leave notices on. It's nice to know when your using undefined variables since they usually mean you've made a typo.
  • You need to set both error_reporting and display_errors. These can be set in php.ini, in Apache (if you're using PHP as an Apache module) or during run-time, though if you set it during run-time then it won't effect some types of errors, such as parse errors.

    For portability - that is, if you want to set this in the application - try setting them in an .htaccess:

    # note: PHP constants such as E_ALL can't be used when setting it in Apache
    php_value error_reporting 2147483647
    
    php_flag display_errors on
    

    Alternatively you could set these in httpd.conf

    display_errors makes sure that all reported errors are actually output to the browser (on a live server, it's typical to log them to a file instead). error_reporting specifies which types errors should be logged/displayed.

    For a live server, it's generally a good idea to not to display errors publicly (but you may still want to log them). Either way, it's still a good idea to set error_reporting to a more inclusive value (2147483647 being the most inclusive value possible now and for the future according to the PHP docs) because ignoring errors is generally a bad idea.

Resizing a control in WPF.

I have a set of user controls in my wpf form and want to give ability to user to resize them. Whenever a user clicks on a control total 8 boundary rectangles should appear and then by dragging any of them, the user must be able to resize the control. Please help me on this.

From stackoverflow

Windows Mobile Synchronization Error

Hi guys,

I am new to Windows Mobile development and have been investigating methods to synchronize data between PDA's running WM6 and a SQL Server 2005 Database. After some research I decided to go with Windows Synchronization Services.

I started by looking at the sample: SyncServicesForDevicesSample

I downloaded and installed all the prerequisite software outlined in the readme including:

  • Visual Studio 2008 Professional SP1
  • SQL Server Compact 3.5 Service Pack 1 (SP1)
  • Synchronization Services for ADO.NET 1.0 (devices)

When I load the sample I noted that the System.Data.SqlServerCe.dll reference in the "GBADeviceClient" project was missing, so I linked it to the version in C:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Devices which was 3.5.5386.0.

When I run the project I get the following error message:

File or assembly name 'System.Data.SqlServerCe, Version=3.5.1.0, Culture=neutral, PublicKeyToken=3BE235DF1C8D2AD3', or one of its dependencies, was not found.

When I look on the emulator (Remove Programs) I have the following software installed:

  • Sync Services for ADO.NET 1.0
  • Microsoft .Net CF 3.5 EN-String R...
  • SQLServerCompact 3.5 Toos EN
  • SQLServerCompact 3.5 Repl
  • SQLServerCompact 3.5 Core Microsoft
  • .NET CF 3.5

So the wrong file version is being called on the PDA...how do I reference the 'correct' version?

Alternatively, is there an easier way to synchronise a subset of data (about 10 tables, where most of those are lookup lists only) from a SQL Server 2005 database?

Thanks in advance.

From stackoverflow
  • Check again if you have the SQL Server Compact 3.5 SP1 for Windows Mobile installed (download here). My dll has the version 3.5.5692.0

    After installing the SP1, you better uninstall the previous version from the emulator and deploy your application again to install the latest version.

Python + PHP + Lighttpd?

I've set up a few web servers in my day, but I'm not sure how they work internally. I'm setting up a new environment for myself and I'm interested in configuring my lighttpd server to support both PHP and Python. Is this possible?

From stackoverflow
  • Yes, this is possible. Here you can find a sample configuration.

    fastcgi.server = (
    ".php" => ((
    "bin-path" => "/usr/bin/php5-cgi",
    "socket" => "/tmp/php.socket"
    )),
    "django.fcgi" => (
    "main" => (
    "host" => "127.0.0.1",
    "port" => 9090, #set the port numbers to what-eva you want
    ),
    ),
    "admin.fcgi" => (
    "admin" => (
    "host" => "127.0.0.1",
    "port" => 9091,
    )
    )
    )
    
  • You can also enable Lighty to use .pl, .py and .php as 'cgi' by enabling mod_cgi and setting it up. The default configs are on the Lighty website. However, this will have the benefits and problems of running an independent cgi process. If you are only experiencing light traffic, performance shouldn't be an issue.

One line if in VB .NET

Is it possible to do one line if statement in VB .NET? If so, how?

From stackoverflow
  • Just add Then:

    If A = 1 Then A = 2
    

    or:

    If A = 1 Then _
        A = 2
    
  • It's actually pretty simple..

    If CONDITION Then ..INSERT CODE HERE..
    
    codeape : And the Else part?
    Joey : You just put Else at the end.
  • Or

    IIf(CONDITION, TRUE_ACTION, FALSE_ACTION)
    
    peSHIr : And this is an expression, while the question asked for a statement. ;-)
  • You can use the IIf function too:

    CheckIt = IIf(TestMe > 1000, "Large", "Small")
    
  • Use IF().

    Dim Result = IF(expression,<true return>,<false return>)
    

    SEE ALSO:

  • Be careful with the IIf opertor though - it is not always short-circuited and both the true and false expressions are evaluated.

  • At the risk of causing some cringing by purests and c# programmers, you can use multiple statements and else in a one-line if statement in VB. In this example, y ends up 3 and not 7.

    i = 1
    If i = 1 Then x = 3 : y = 3 Else x = 7 : y = 7
    
    hamlin11 : Why go half way??? i = 1 : if i = 1 Then x = 3 : y = 3 Else x = 7 : y = 7

LaTex for .NET

I am using ItextSharp to generate PDF. Part of our output, we have a lot of math related content. Maybe we can use some kind of Latex library to feed the result to ItextSharp to produce PDF. I have been googling for a while now but found nothing. Do you know if there is a latex library for .NET exists?

Also, do you know if ItextSharp can handle this without this Latex help?

From stackoverflow
  • Your best bet may be to roll your own.

    It might be as simple as making a basic template, and then doing:

    1. Insert expression into template.
    2. Compile with pdflatex.
    3. Insert resulting pdf into your document.

    As another option, you could look at the source for other applications that do this. Mediawiki (the software behind wikipedia) springs to mind – it can use a LaTeX backend to generate maths formulae, and it's open-source so you can see how they did it.

    Jouni K. Seppänen : See also the TeX-like engine of Matplotlib - it is written in Python, and although Matplotlib uses Numpy and other extensions so you can't directly use it in IronPython, it would likely be a fairly easy project to make the math rendering engine a standalone library. I think there was once going to be a GSoC project to do exactly this, but the student got a real job at the last moment.
    Jouni K. Seppänen : Hey, there's a new project with the same goal accepted for GSoC 2009! I'll edit my answer to link to it.
  • It probably doesn't exist yet, but it shouldn't be an impossibly big project to compile TeX for C#. The original TeX was written in a version of Pascal, which is nowadays automatically translated into C by web2c. So it would just be a "small matter of programming" to make web2c produce C#, and to translate the supporting libraries (kpathsea, and whatever parts of pdftex you need - probably not nearly all of it) to be compatible.

    Apart from that, there seems to be a GSoC project to extract the math rendering engine of Matplotlib into a separate library. Assuming that the library will be pure Python, you could use it via IronPython. So if you can wait until the end of the summer, that might be just what you need.

  • The GSoC project owner got back to me on the new project to externalize Mathtext to a new python library called MathTex.

    He said that his work depends on a library called FT2FONT which is a wrapper around a C++ library. It would be trivial, for someone with good .net font knowledge, to take this work and use the wrapper to wrap the .net Font library and allow it to be used in IronPython.

  • I'd look at a wrapper library too. Unless your wanting to write something massive like a latex editor, you're probably only wanting a small subset. I'd look at texnet free (www.texdotnet.com).

Single or multiple process, what criteria decides it?

In embedded systems using linux for an application; under which condition will you divide an application into two/three processes. My main doubt is; is it required to divide a single application component into multiple processes and then run multiple processes to achieve the required application functionality.

From stackoverflow
  • By experience I tend to isolate possibly problematic pieces of code. For example if you're depending on a sensor which ships with 3rd party libraries that you do not trust, making it a separate process will make your application more robust and fault-tolerant because you'll be (hopefully) able to restarts only parts of it.

    Also for integration purposes it might be easier. Suppose your process A runs fine, then you can plug in the process B easily instead of adding new parts to process A. It might not seem like a big plus right now but it depends a lot on your project.

    It does come with some overhead however, as dealing with synchronization and message passing can be more complicated and add to the design.

    You don't have to do anything like that however.

    Liran Orevi : My thoughts exactly (only better)
  • You don't tell much about the circumstances that led you to your question, so I can only guess what kind of answer you are interested in.

    Linux offers multi-threading functionality since ages, so concurrent programming can be done without multiple processes.

    There is rarely a functional reason to divide integral components of an application into processes.

    My suggestion is to write a single-process application. Should the requirement arise, that is: a problem can only be solved by managing runtime resources in separate processes, you can still take on the heavy work of solving inter-process communication and resource sharing, without having to change much in your business logic.

What to do when I want to use database constraints but only mark as deleted instead of deleting?

I am working in a project where database items are not deleted, but only marked as deleted. Something like this:

id   name     deleted
---  -------  --------
1    Thingy1  0
2    Thingy2  0
3    Thingy3  0

I would like to be able to define something like a UNIQUE constraint on the name column. Seems easy, right?

Let's imagine a scenario in which "Thingy3" is deleted, and a new one is created (perhaps years later). We get:

id   name     deleted
---  -------  --------
1    Thingy1  0
2    Thingy2  0
3    Thingy3  1
...
100  Thingy3  0

From the user's point of view, he deleted an item and created a new one. Much like deleting a file, and creating a new file. So it's obvious to him that the new item is unrelated and unattached to any data connected to the old item.

That's already handled, since the DB only cares about the id, and since the new item has an id of 100 instead of 3, they are utterly different.

My difficulty arises when I want to prevent the user from creating another "Thingy3" item. If I had a UNIQUE constraint that only looked at items that aren't marked deleted, then I would have solved one problem.

(Of course, then I'd have to deal with what happens when someone does an undo of the delete...)

So, how can I define that sort of a constraint?

From stackoverflow
  • Not sure about SQLServer2005, but you can define compound constrainst/indexes

    CREATE UNIQUE INDEX [MyINDEX] ON [TABLENAME] ([NAME] , [DELETED])
    

    As pointed out by SteveWeet, this will only allow you to delete/create twice.

    Steve Weet : This will only allow one delete of a 'Thingy3' you can't create it, delete it, create it again and then delete it again.
    Robert Gould : Good point, this won't allow N updates, fixing it
  • For example, you can add an illegal character (*) to the deleted name. But you still have problems undeleting a deleted item. So probably the better idea is to prohibit double names even if they are deleted.

    You can clean the deleted records after an amount of time (or move them to a separate table).

    belugabob : Modifying the user entered data is always going to be problematic, as you can't necessarily predict whether the data will end with an illegal character already. Admittedly, the character will only be added to 'deleted' records, so that introduces a certain element of predictability. Either way, I prefer Steve Weet's solution, as it support undeletes.
  • Create a unique constraint on (name, deleted). This will mean you can only have one deleted per name, however.

    The obvious work-around for that works under ANSI-92 but not on MS SQLServer: https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=299229

  • For a simple table called [Test] with columns ID(int), Filter(nvarchar), Deleted(bit)

    ALTER TABLE [dbo].[Test] ADD 
        CONSTRAINT [DF_Test_Deleted] DEFAULT (0) FOR [Deleted],
        CONSTRAINT [IX_Test] UNIQUE  NONCLUSTERED 
        (
            [filter],
            [Deleted]
        )  ON [PRIMARY]
    
    belugabob : This approach become problematic when a record is 'deleted' a record with the same 'Filter' value is added and the an attempt to 'delete' this record is made - as the constraint is then violated.
  • Add a random hash after the unique name. Something that is easily reversible. Possibly separate with an underscore or some other character.

    Edit after comment: You could simply add underscore and the current timestamp.

    scraimer : Brilliant! Heck, I could even change the name to be something like "Thingy3 (deleted on 1/1/2000 #1)" for extra info to the user!
  • You could add the id value to the end of the name when a record is deleted, so when someone deletes id 3 the name becomes Thingy3_3 and then when they delete id 100 the name becomes Thingy3_100. This would allow you to create a unique composite index on the name and deleted fields but you then have to filter the name column whenever you display it and remove the id from the end of the name.

    Perhaps a better solution would be to replace your deleted column with a deleted_at column of type DATETIME. You could then maintain a unique index on name and deleted at, with a non-deleted record having a null value in the deleted_at field. This would prevent the creation of multiple names in an active state but would allow you to delete the same name multiple times.

    You obviously need to do a test when undeleting a record to ensure that there is no row with the same name and a null deleted_at field before allowing the un-delete.

    You could actually implement all of this logic within the database by using an INSTEAD-OF trigger for the delete. This trigger would not delete records but would instead update the deleted_at column when you deleted a record.

    The following example code demonstrates this

    CREATE TABLE swtest (  
        id   INT IDENTITY,  
        name  NVARCHAR(20),  
        deleted_at DATETIME  
    )  
    GO  
    CREATE TRIGGER tr_swtest_delete ON swtest  
    INSTEAD OF DELETE  
    AS  
    BEGIN  
        UPDATE swtest SET deleted_at = getDate()  
        WHERE id IN (SELECT deleted.id FROM deleted)
        AND deleted_at IS NULL      -- Required to prevent duplicates when deleting already deleted records  
    END  
    GO  
    
    CREATE UNIQUE INDEX ix_swtest1 ON swtest(name, deleted_at)  
    
    INSERT INTO swtest (name) VALUES ('Thingy1')  
    INSERT INTO swtest (name) VALUES ('Thingy2')  
    DELETE FROM swtest WHERE id = SCOPE_IDENTITY()  
    INSERT INTO swtest (name) VALUES ('Thingy2')  
    DELETE FROM swtest WHERE id = SCOPE_IDENTITY()  
    INSERT INTO swtest (name) VALUES ('Thingy2')  
    
    SELECT * FROM swtest  
    DROP TABLE swtest
    

    The select from this query returns the following

    id      name       deleted_at
    1       Thingy1    NULL
    2       Thingy2    2009-04-21 08:55:38.180
    3       Thingy2    2009-04-21 08:55:38.307
    4       Thingy2    NULL
    

    So within your code you can delete records using a normal delete and let the trigger take care of the details. The only possible issue (That I could see) was that deleting already deleted records could result in duplicate rows, hence the condition in the trigger to not update the deleted_at field on an already deleted row.

    belugabob : Voted this up, because it was exactly what I was considering for my own application. Trying to think of any downsides, but it seems solid enough so far.
    scraimer : I love the "deleted_at" idea!
  • The problem with a compound unique constraint is that it's not possible to have multiple records with the same name that are deleted. This means that the system will break once you delete a third record. I wouldn't recommend appending stuff to the names because, theoretically, a duplicate situation could arise. Also, by doing so, you are basically corrupting the data in the database as well as adding cryptic business logic to the data itself.

    The only possible solution, database wide, is to add a trigger that checks that the inserted/updated data is valid. It's also possible to put the checks outside of the database, into code.

  • It might be worth considering using a "recycle bin" table. Instead of keeping the old records in the same table with a flag, move them to its own table with its own constraints. For instance, in the active table you do have a UNIQUE constraint on name, but in the recycle bin table you don't.

  • Instead of deleted column use end_date column. When user deletes a record add the current date in end_date column. Any records where end_date column is NULL are your current records. Define a unique constraint on two columns name and end_date. Due to this constraint you never have a scenario where valid record name is duplicated. Any time user wants to undelete a record, you need to set the end_date column to null and if this violates the unique constraint then you show a message user to user that the same name already exists.

    scraimer : That's what Steve Weet already said at http://stackoverflow.com/questions/771197/what-to-do-when-i-want-to-use-database-constraints-but-only-mark-as-deleted-inste/771337#771337
  • The type of constraint you require is a table-level CHECK constraint i.e. a CHECK constraint consisting of a subquery which tests NOT EXISTS (or equivalent) for the table e.g.

    CREATE TABLE Test 
    (
       ID INTEGER NOT NULL UNIQUE, 
       name VARCHAR(30) NOT NULL, 
       deleted INTEGER NOT NULL, 
       CHECK (deleted IN (0, 1))
    );
    
    ALTER TABLE Test ADD
       CONSTRAINT test1__unique_non_deleted
          CHECK 
          (
             NOT EXISTS 
             (
                SELECT T1.name
                  FROM Test AS T1
                 WHERE T1.deleted = 0
                 GROUP
                    BY T1.Name
                HAVING COUNT(*) > 1
             )
          );
    
    INSERT INTO Test (ID, name, deleted) VALUES (1, 'Thingy1', 0)
    ;
    INSERT INTO Test (ID, name, deleted) VALUES (2, 'Thingy2', 0)
    ;
    INSERT INTO Test (ID, name, deleted) VALUES (3, 'Thingy3', 1)
    ;
    INSERT INTO Test (ID, name, deleted) VALUES (4, 'Thingy3', 1)
    ;
    INSERT INTO Test (ID, name, deleted) VALUES (5, 'Thingy3', 0)
    ;
    INSERT INTO Test (ID, name, deleted) VALUES (6, 'Thingy3', 0)
    ;
    

    The last INSERT (ID = 6) will cause the constraint to bite and the INSERT will fail. Q.E.D.

    ...ooh, nearly forgot to mention: SQL Server doesn't yet support CHECK constraints with that contain a subquery (I tested the above on ACE/JET, a.k.a. ). While you could use a FUNCTION I've read this is unsafe due to SQL Server testing constraints on a row-by-row basis (see David Portas' Blog). Until this full SQL-92 feature is supported in SQL Server, my preferred workaround is to use the same logic in a trigger.