Sunday, April 17, 2011

ASP.NET Storing global variables - accessible from every page

I am building a large application and I ususally use a simple session to store private global information however as the application could be rather large I belive this could be a problem due to the amount of memory sessions it could have.

Is there a better way to store such variables?

For example, when the user logs in I want to store data about that user and display it where needed without having to query the database each time.

From stackoverflow
  • use cookies - they would work irrespective of your load balance environments

    other options include:

    1) writing your sessionvalues to a sql database - you can configure your app to configure session state to use sql server - but this has its own problems as sessions never time out (so u need to handle this via code explicitly)

    2) if not using sql server - basically you would face a problem when you have too many users and you implement load balancing on your web server - so a user can go to a different web server in the same session (and it would not work)

    there is a work around for this too - its called STICKY SESSIONS - where your web server guarantees your user would always hit the same web server within the session

    3) with .net 2.0 provider model, you can even write your own session storage provider by implementing their delegates - so you can create your own xml files on your web server / shared server to read / write session data there :-)

    so there are many ways you can solve this. however the simplest and cost effective solution is to use cookies

  • You might use Cache. That has built-in mechanism to free up when memory is running out...

    annakata : and doesn't depend on client cookie settings
  • If you think your data is too large for the Session, I would consider a database of some sort using cache so that you don't unnecessary calls.

  • If it is per-user-session data you're storing, using the ASP.NET Session is definitely your best bet. If you're most worried about memory usage then you can use MSSQL mode. The data has to live somewhere and the choice of which session mode to use is dependent on your environment and the usage patterns of your users.

  • Don't assume there will be a problem with the size of session state until you see such a problem and have tried to solve it. For instance, it's possible that, although the application as a whole may use a large amount of session state, that any given user may not use that much in the course of a session.

    I's also possible that changing from the default session state provider to the SQL provider or state server provider would ease a memory issue.

    You can use Cache, but Cache is application-wide. You would need to qualify Cache entries with the user id or session id: Cache[userID + ".MyCacheEntry"].

    Do not, under any circumstances, use static variables to store this data. As suggested by your subject line, they are application-wide, not per-user.

  • Sessions are the way to go here, they are intended to persist information about the current session across requests. There is no other object in the ASP.NET framework that has this intention.

    You could use the Cache, or store in the Application collection, but then the responsibility of uniquely identifying the individual session data is up to you.

    What's also up to you is handling when the session terminates, and freeing up the instances that are stored in those collections (Cache or Application).

    It's really a bad idea to start to ask these questions based on what you might "think" will happen. This is a form of premature optimization, and you should avoid it. Rather, use Sessions, as they were intended for this purpose, then measure where your bottlenecks are and address them, should performance be an issue when testing.

  • Definitely use cookies for this. The best approach is to make yourself a cookies wrapper class that will do all the heavy lifting for you - checking if cookie is null, accessing the httpcontext, etc. No need to mess up your code with all that; just abstract it all out into cookies.cs or .vb.

    SetCookieValue(someValue, cookieName); //there will be some expiration concerns here as well
    myValue = GetCookieValue(cookieName);

    Christian Weiss has a good strategy.

JMS Topic Creation in JBoss 5 AS

In Jboss 4, when I deployed an ear with an MDB for a topic that had not been specified in the deployment descriptors, the server would automatically create the topic (after posting a warning saying that topic didn't exist).

In Jboss 5, it doesn't seem to automatically create the topics anymore (errors out instead). Is there a configuration option somewhere that would allow automatic topic creation?

From stackoverflow
  • From the JBoss community forums -- This JIRA was added in 5AS.

    Unfortunately it looks like there is no way to implement createDestination globally in the standardjboss.xml descriptor -- You have to add a custom jboss.xml descriptor to the ear deploying the mdb.

    <jboss xsi:schemaLocation="" version="3.0">

Distributed Transaction from .NET to DB2

I have a problem where in I have to call into the AS400 db2 to call a series of insert/update stored procedures from my .net and then update a few SQL2005 tables if everything in the AS400 db goes ahead fine. The driver I am using does not have distributed transactions so I was wondering if you can use any of IBMs iSeries Drivers for DB2 to create a COM+/.NET Component which would participate in a distributed transaction. Pls let me know if any one out there has done anything like this before or any pointers would be greatly appreciated.

From stackoverflow
  • Which driver are you using?

    IBM's DB2 Connect supports distributed transactions managed by Windows DTC.

    The DB2 driver from Microsoft, which is packaged in Microsoft Host Integration Server, also does transactions.

    I am hearing two different things from you. You want to do a transaction that spans SQL and DB2. and also you want to build a component that participates in a distributed transaction. These can be done together but the former does not require the latter.

    Using the System.Transactions classes in .NET 2.0, you can do this:

      TransactionOptions options = new TransactionOptions();
      options.IsolationLevel = IsolationLevel.Serializable;
      options.Timeout = TransactionManager.DefaultTimeout;
      using(var scope = new TransactionScope(TransactionScopeOption.Required, 
            EnterpriseServicesInteropOption.Full) )

    The result will be a distributed transaction that spans DB2 and SQL, but it is not a component that participates in a distributed transaction, if you see what I mean.

    The other alternative is to use the EnterpriseServices/COM+ model of defining a component that does something, and marking that component as transactional. This works too, but is not required to do distributed transactions in .NET.

What is Shadow Memory?

What is Shadow Memory? Can SO briefly shed light on how memory profiling tools use it?

From stackoverflow

How do I get rid of the unknown property name errors in Visual Studio?

When using jQuery UI and ThemeRoller the CSS files created contain several CSS properties that are not known by Visual Studio, such as zoom and opacity. How can I keep these from showing up as errors in the error list when the CSS file is open in the editor pane?

In the spirit of SO, I'll add the solution I found as a response.

From stackoverflow
  • Go to Tools --> Options --> Text Editor --> CSS --> CSS Specific (or Validation) and uncheck the Detect unknown properties checkbox.

Java Micro Edition (JME) SDK for Mac OS X or Linux

The question is clear from the title.

Is there an SDK for the Java Micro Edition available for Mac OS X or Linux? Or does one need Windows XP to develop JME applications?

From stackoverflow
  • Netbeans has a JME SDK

    hhafez : Thats true but look here Java ME is only included for windows xp...
    Jack : XP and Linux, I think....
  • No, with a 'but'

    There is no WTK (Wireless Toolkit) from the main vendors available for Mac (NetBeans Wiki reference) so basically you can't debug nor test the code. But, you can use an emulator from a third co: MPowerPlayer

    If you are using netbeans in any other OS but windows, you still can download and add the J2ME packages using the tools/plugins menu. Then you can add the MPowerPlayer to the IDE as a J2ME platform. Netbeans (and i guess any other IDE with J2ME WTK support) will recognize it as a valid WTK,

    I've posted an specific entry about this in my blog, but it's in spanish, although maybe you can follow the images. Give it a try, and don't hesitate to ask anything: J2ME in Mac Os with NetBeans

  • Offically Sun's WTK is available only on Linux and Windows, however both SDKs can be used on Mac to compile J2ME applications. Unfortunately the emulator and the preverifier will not work (since they are not Java based) so you will not be able to test your application.

    To solve this problem you can use MicroEmulator or MPowerPlayer for both emulation and preverification (you can also use PhoneME for preverification).

    This is a good guide to setup you development environment using Eclipse and this one is good for Netbeans.

    But, if I can give an advice (I'm working since two years on J2ME development and I'm a Mac user), it is better if you develop on Windows or Linux through a virtual machine, because the two emulators do not have a very good compliance to the JSR's standard and do not include all of them. Moreover on OSX it will be very difficult for you to test features like Bluetooth or LocationAPIs.

  • May be this is helpful, I've found a Java ME Developer Studio for Mac OS X, developed by Motorola, I haven't tested yet, it's only and EA Release, I'll try this one, and I'll let u know in a subsequent post,


  • Oddly enough ... I just set this up 5 minutes ago on Linux.

    You will need: <-- WTK

    The WTK installer will ask where your JDK is. Do

    find . -name "jar" -type f

    and then where you have


    Knock of the 'jar' and give that path to the installer. This will install ktoolbar which includes a phone emulator.

    The download netbeans and install the mobile addons

    This is not pure J2ME, but includes most of the API

    I am using it to develop an application for my SE-C902

Really simple question: grabbing the onSubmit event for a form

Hi there,

I have a really simple question. I want to know how to grab the onSubmit event from a form to do some form validation, because I don't have access to it directly. (I'm writing a Wordpress plugin for comments, so don't have direct access to the form tag or the submit button.)

I've got so frustrated trying to do this for my plugin that I've written a Hello World version - below. I want it to show the 'Hello World' alert when I load the page, and the "form submitted" alert when I click on the submit button. Instead, it shows both pop-ups when the page loads. What am I doing wrong???

Here is my code:

  <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <title>Hello World</title>
    <form action="#" method="post" id="commentform">

    <p><input type="text" name="author" id="author" size="22" tabindex="1" />
    <label for="author"><small>Name (required)</small></label></p>

    <p><input name="submit" type="submit" id="submit" tabindex="5" value="Submit Comment" />


    <script type="text/JavaScript">
    alert("Hello world");

    var formCheck = document.getElementById("commentform");

    formCheck.onSubmit = doMapping(); 

    function doMapping() {
        alert("form submitted");
        return false;


From stackoverflow
  • Change this:

    formCheck.onSubmit = doMapping()

    to this:

    formCheck.onSubmit = doMapping

    When you add parenthesis to the end of a function you execute that function. When you assign a function (or pass it as a parameter to another function) you need to omit the parenthesis as that is the way to retrieve a function pointer in JavaScript.

    Edit: You will also need to move the declaration of the doMapping function above the assignment of that function to the onsubmit event like this (good catch tvanfosson!):

    function doMapping() {
            alert("form submitted");
            return false;
    formCheck.onSubmit = doMapping();

    However if the doMapping function is not used elsewhere you can declare the doMapping function as an anonymous function like this:

    formCheck.onSubmit = function() {
            alert("form submitted");
            return false;

    which seems a bit cleaner to me.

    tvanfosson : I think you'll also have to change the order since doMapping may need to be defined before you assign it as the onSubmit handler.
    Andrew Hare : Thanks - I edited my answer to address your point.
  • Using jQuery.

    $(document).ready( function() {
        $('#commentform').submit( function() {
            alert('form submitted');
            return false;
  • Thank you! Actually I solved it another way, using both Andrew's suggestion and the window.onload event - I think the problem was partly because the element hadn't actually loaded.

    window.onload = function(){
        if (document.getElementById("commentform")){
            document.getElementById("commentform").onsubmit = doMapping;
    function doMapping(){
                alert("form submitted");
                return false;
    Rashack : Note thought that the onload event is fired after the whole page has been loaded. So should there be an image that takes long to load - usually something like google analytics your event handler will not be assinged before the user hits submit.
    Rashack : The jQuery answer handles that...

Failing to add controls to a page dynamically

I'm adding a User Control for each record pulled up in a data reader, here's the basic loop:

while (dr.Read())
     ImageSelect imgSel = new ImageSelect(dr["Name"].ToString());

The problem is that there are no controls added to the page, I check the html output and there is my panel, with nothing in it.

I even stepped through the code in the debugger, and verified that myPanel.Controls gets a control added on each loop, with the count being 6, no errors, but then they dont show up on the page.

I've run the above code in the Page_Init and Page_Load events, both with the same result.

EDIT: Ok so I've switched to using LoadControl("....ascx") to get my control instance, which is now working. But originally I was also passing in data via the controls constructor.. Is this still possible or do I just need to set them via get/sets?

EDIT 2: Thanks to Freddy for pointing out that the LoadControl has an overload where you CAN pass in constructor params, see accepted answer.

EDIT 3: After trying this method both with and without the constructor. I have found its better to just use setters for any properties I want the control to have versus trying to use the passed in object array for my constructor.

From stackoverflow
  • Update: As Steve pointed out, the overload of LoadControl that uses the type won't take into account the controls in the ascx. This is also mentioned in this answer:

    As I mentioned before, the get/set are more in line with the model, so I recommend using that with the LoadControl variation that receives the user control path. That said, the Steve's version is an interesting alternative:

    My take is the LoadControl with type is meant to be used with web custom controls instead.

    If it is an user control you should use LoadControl(usercontrolpath) to get the instance of the user control.

    You can use a constructor by doing:

    var name = dr["Name"].ToString();
    var imgSel = LoadControl(typeof(ImageSelect), new object[]{ name });

    Notice that depending on the project model you are using, you need to add a Reference to the aspx to use it with the typeof variation:

    <%@ Reference Control="~/somepath/myusercontrol.ascx" %>

    Ps. I usually use the set/get for controls as I find them more in line with the model

    Neil N : can you expand on that? .Load of what? The page?
    eglasius : @Neil y, updated it, memory failed, it is LoadControl and you specify the path to the user control, as in: "~/somepath/mycontrol.ascx"
    Neil N : ok, got it, now can I use constructor parameters LoadControl, like I did in my original example?
    eglasius : y, posted an update for that too :)
    Neil N : ok, great, missed that overload of LoadControl in intellisense. Thanks for the explanations.
    Steven Robbins : Bear in mind that that overload doesn't work the same way as the other one, so you may get null reference exceptions if you have designer items in there. There's an extention method on my blog to work around it if needed.
    eglasius : @Steve thx, updated it. That's a nice trick btw.
    Steven Robbins : No worries, as you said, the other overload is more for custom WebControls, so it's slightly confusing having them both with the same name.
  • To add UserControls you must call the LoadControl method passing in the path to the .ascx file. You can not create them by just instantiating the object the .ascx file inherits from.

    A UserControl consists of both the markup and the class in the code behind. The markup contains a link to the class behind, but the class behind does not know where the markup lives and therefore can not be created on it's own.

    Neil N : ++; thanks for the explanation, that makes sense now.

How to send data to port in binary format..


I am newbie in Low level programming. In my project(C#.NET) we are using EDBS protocol(7 bit format) for communication and i have the data in bit format to send like 00101010 so we would please guide me how to send these to port.I know that the serial port class accepts data in binary format but dont know how convert the bit format into byte .

Thanks in advance


From stackoverflow

Potential downtime during MSI upgrade

I'm considering deploying websites to an Win2k3/IIS6 machine using a MSI built with WiX.

The website in question has a collection of .html, .jpg, .js, .swf & .asp files (no ASP.NET)

I'm doing a "Major Upgrade" when installing the MSI (i.e, it first uninstalls the old MSI, then installs the new MSI). This is the only way I can figure to get the MSI to remove redundant files.

My question is; will there be any downtime for visitors to the site during the uninstall / reinstall process?

Or does IIS cache the files being used by currently open connections?

From stackoverflow
  • No, you'll definitely be in an outage. It does not cache that info.

  • If you're that concerned about downtime, you should be thinking about load balancing and redundant webservers.

Multi-Dimension any()

I'm testing an arbitrarily-large, arbitrarily-dimensioned array of logicals, and I'd like to find out if any one or more of them are true. any() only works on a single dimension at a time, as does sum(). I know that I could test the number of dimensions and repeat any() until I get a single answer, but I'd like a quicker, and frankly, more-elegant, approach.


I'm running 2009a (R17, in the old parlance, I think).


From stackoverflow
  • If your data is in a matrix A, try this:

    anyAreTrue = any(A(:));

    EDIT: To explain a bit more for anyone not familiar with the syntax, A(:) uses the colon operator to take the entire contents of the array A, no matter what the dimensions, and reshape them into a single column vector (of size numel(A)-by-1). Only one call to ANY is needed to operate on the resulting column vector.

    Marc : Of course. Thanks.
  • As pointed out, the correct solution is to reshape the result into a vector. Then any will give the desired result. Thus,


    gives the global result, true if any of numel(A) elements were true. You could also have used


    which uses the reshape operator explicitly. If you don't wish to do the extra step of converting your matrices into vectors to apply any, then another approach is to write a function of your own. For example, here is a function that would do it for you:


    function result = myany(A)

    % determines if any element at all in A was non-zero

    result = any(A(:));


    Save this as an m-file on your search path. The beauty of MATLAB (true for any programming language) is it is fully extensible. If there is some capability that you wish it had, just write a little idiom that does it. If you do this often enough, you will have customized the environment to fit your needs.

[Django Templates] 'for' loop through form fields and excluding one of the fields with 'if'.

Hi, The problem I'm struggling with is as follows:

I have:

{% for field in form %}
    {{ field }}
{% end for %}

What I want is to put an 'if' statement to exclude a field which .label or whatever is provided. Like:

{% for field in form%}
    {% if field == title %}
    {% else %}
        {{ field }}
    {% endif %}
{% endfor %}

Is it possible? I have to many fields to write them one by one and only one or two to exclude.

Thank you for any tips.

BR, Czlowiekwidmo.

From stackoverflow
  • Yes, this should be possible:

    {% for field in form %}
        {% ifnotequal field.label title %}
            {{ field }}
        {% endifnotequal %}
    {% endfor %}

    Django's template tags offer ifequal and ifnotequal variants, and you can test the field.label against either a context variable, or a string.

  • You might be a lot happier creating a subclass of the form, excluding the offending field. See

    class SmallerForm( MyForm ):
        class Meta(MyForm.Meta):
            exclude = [ title ]
    muhuk : +1. This is a better solution than {% if %}. Also I'd try using as_* rendering methods on form.

How to add/update an attribute to an HTML element using javascript?

I'm trying to find a way that will add / update attribute using javascript. I know I can do it with SetAttribute function but that doesn't work in IE.

From stackoverflow
  • What do you want to do with the attribute? Is it an html attribute or something of your own?

    Most of the time you can simply address it as a property: want to set a title on an element? element.title = "foo" will do it.

    For your own custom JS attributes the DOM is naturally extensible (aka expando=true), the simple upshot of which is that you can do element.myCustomFlag = foo and subsequently read it without issue.

    dev.e.loper : this is something of my own. basically i need a way to set a flag on an element....something like div.thisDivIsSet = true;
    annakata : edited into answer
  • Obligatory jQuery solution. Finds and sets the title attribute to foo. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.

    $('#element').attr( 'title', 'foo' );
  • You can read here about the behaviour of attributes in many different browsers, including IE.

    element.setAttribute() should do the trick, even in IE. Did you try it? If it doesn't work, than maybe element.attributeName = 'value' might work.

    dev.e.loper : this works. it creates attribute if it doesn't exists and updates it if it does exist. is this documented somewhere as far as how this works?
    dev.e.loper : by 'this works' i mean element.attributeName = 'value'

.WSC won't recognize code changes

I've run into this problem before and the solution has usually been to restart IIS. Basically I've made a number of changes to a .wsc file on our server. But when it runs it doesn't run the new code changes I made. I've verified this with event logging at the beginning of the file and it doesn't show up.

My problem is that obviously restarting IIS on our production server is something I'm loathe to do, but we need this running today. I've tried re-registering the file but to no avail.

The server is a 32-bit Server 2008 OS. And the code is running, it still generates the file it is supposed to, but like I said, it's not using the latest changes.

Any other info I can provide, please leave a comment and I'll edit.

Thank you, Jeff

Edit: Oisin, thanks for the reply and yes I know I hate VBScript, and anything related to it including these Window Script Components. I've expressed such feelings to my manager, but it's a dirty job and someone has to do it!

Yes it's using a Server.CreateObject to call the component.

ANSWER: I've since realized my mistake. I was only 'registering' it over and over, when I should have first 'unregester'ed it the 'register'ed it. Man I feel stupid, but haste makes waste as they say.

Thanks for the response and link!

From stackoverflow
  • Eek, you mean WSC as in a Windows Script Component? I haven't written one of them since 2000.

    Are you loading it using CreateObject (e.g. it's registered as a COM object via regsvr32), or are you using a file-based moniker to load it? (not registered).

    If it's registered, it probably is cached until app restart. If you switched to a file based moniker, e.g. like: Set o = GetObject("script:c:\path\obj.wsc"), you might get away with runtime changes to the .wsc file.

    (man, how did I even remember this)

    more info here - quick before it's archived! :D


    Jeff Keslinke : I'll give you the answer since you're the only one who wrote back :)
    x0n : heh, probably cos i'm the only one old enough to know this stuff. :)
    Cheeso : WSC is still viable and still works well. With all the code being written in JavaScript, Python, and other scripting languages, WSC is even more useful now. Today I hosted Google's Diff/Match/Patch library, written in Javascript, in a WSC. No porting, no code change. It's now usable from any COM client. Easy.

Is there a Perl module to monitor an email queue?

I'm working on an issue tracking system and would like the application to handle email replies. That is, I would like a script that can monitor an email queue and perform some action based on the email contents. It should then be able to delete the email, etc.

I currently use MIME::Lite to send email, and I can handle writing the script etc. (read: I'm not new to Perl). However, I have no idea what modules are good for doing this particular task. I'd like to get started on this as quickly as possible so I hope to narrow my search space for possible modules.

In case you need to know, the application will be running on a standard linux, Perl, MySQL stack with Exchange as the mail server.

Can anyone suggest a Perl module to help me out? Any tutorials or best practices related to this would also be helpful.


From stackoverflow
  • Do you have access to the Exchange server via IMAP or WebDAV?

    For IMAP:

    For WebDAV:

    POP3 would also be an option if it's enabled on the server. IMAP is probably the way to go if you've got it.

    James van Dyke : That's kind of interesting... it uses the web access site. Have you used this in an application?
    James van Dyke : I have access to pop, imap, and webdav. I would think IMAP or WebDAV are the better protocols. Any preference?
    Leon Timmermans : IMAP is much faster than WebDAV, so I'd advise you to go with that.
    James van Dyke : Excellent. Thank you, Leon.
    Mark Johnson : IMAP is probably the way to go if it's available. I've not personally used Email::Folder::Exchange (or done anything with Exchange over WebDAV). I thought it worth a mention in case IMAP was not enabled on your Exchange server.
    James van Dyke : Thanks for the suggestions!
  • I've done something similar using Mail::POP3Client

  • The Perl Email Project @ has recommendations and other information on the mail oriented modules for perl.

    James van Dyke : I did try out the Email::* modules updated by this group and found the one I needed (Email::Folder::IMAP) to have a bug that caused it to die when connecting. I also found the API to be very inconsistent between connection types. Net::IMAP::Client has a similar, simple API but is more mature.

How should I document my C# code?

I am building the documentation for our C# API containing:

  1. A general overview and description of the current state as a doc/pdf file.
  2. A class library API in a .chm file using Sandcastle.


  1. Should I merge these two into the same .chm file? What is a good way to merge them?
  2. I need to exclude certain classes/packages. How can I specify that in SandCastle?
  3. It generates documentation for the VB code and the Visual C++ code. How can I change this? Or should I leave it, knowing that I am only using safe code?
  4. Where can I find HTML Help 2.x Viewer Path on my system?


The comments I make above methods, fields and classes are not generated in the documentation.

What should I do?

From stackoverflow
  • I recommend that you use Sandcastle Help File Builder from Codeplex. You can easily include and exclude namespaces, but I am unsure how to go about excluding a single class. You can set the option to only generate documentation for public/protected classes, but I do not know if that will fit your scenario.

    You can also target a specific language in SHFB, as to your second question.

    Additionally, you can use MAML within SHFB for conceptual documentation, such as you mention as being in the doc/pdf file. You should be able to use Doc2Maml for to migrate your existing documentation. Doc2Maml is a part of DocProject, but it appears that you might be able to run it standalone.

    Edit in response to comment:

    Directions are for SHFB I do not remember the exact way to do it in 1.7, but I believe it is similar:

    1. Under "Comments" group in the Project Properties tab, click the ellipsis to the right of "NamespaceSummaries".
    2. In the checkbox list in the top left, uncheck any namespace you want to exclude.

    This is also the screen where you put namespace summaries in.

    joseph.ferris : Added directions to message body. Not sure what version you are using, but I am using the version from February.
  • Sandcastle Help File Builder (SHFB) itself has a .chm file where you can find the answers to questions like "how can I exclude certain namespaces or classes from the generated doc?"

    You may think I know the answer and I am being snarky by not telling you. Not true. But I was skimming the doc last night and saw an entry on this very topic.

    I don't know why you wouldn't just leave in the VB and C++ stuff; there may in the future be someone who uses a language that is (shockingly) not C# with your library. The language is normally settable by the help viewer, so C# devs can ignore the VB syntax.

    As for merging, SHFB has a mechanism to add in arbitrary HTML in an arbitrary hierarchy. In the GUI it is here:

    Using this, you could convert the PDF/DOC to HTML and then just embed it in the .chm.

  • In addition to Sand Castle as mentioned above, I would also recommend looking at FxCop and StyleCop to help make sure your code and documentation is up to CLS Compliance standards.

  • SandCastle don't have a Getting Started help.

    Try to use NDoc.

    Here is the NDoc Help

There is a way to access the "previous row" value in a SELECT statement?

I need to calculate the difference of a column between two lines of a table, there is any way I can do this directly in SQL? I'm using Microsoft SQL Server 2008.

I'm looking for something like this:

SELECT value - (previous.value) FROM table

Imagining that the "previous" variable reference the latest selected row. Of course that with a select like this I will end up with n-1 rows selected in a table with n rows, that's not a probably, actually is exactly what I need.

Is that possible in some way?

From stackoverflow
  • SQL has no built in notion of order, so you need to order by some column for this to be meaningful. Something like this:

    select t1.value - t2.value from table t1, table t2 
    where t1.primaryKey = t2.primaryKey - 1

    If you know how to order things but not how to get the previous value given the current one (EG, you want to order alphabetically) then I don't know of a way to do that in standard SQL, but most SQL implementations will have extensions to do it.

    Here is a way for SQL server that works if you can order rows such that each one is distinct:

    select  rank() OVER (ORDER BY id) as 'Rank', value into temp1 from t
    select t1.value - t2.value from temp1 t1, temp1 t2 
    where t1.Rank = t2.Rank - 1
    drop table temp1

    If you need to break ties, you can add as many columns as necessary to the ORDER BY.

    Augusto Radtke : That's fine, order is not a issue, I just removed it from the example to make it simpler, I gonna try that.
    MartinStettner : which assumes, that primary keys are generated sequentially and rows are never deleted and the select doesn't have any other order clause and and and ...
    Tom H. : Martin is correct. Although this might work in some cases you really need to define exactly what you mean by "previous" in a business sense, preferably without relying on a generated ID.
    RossFabricant : You're right, I added an improvement using a SQL Server extension.
    Augusto Radtke : That won't run often in the database, and the rows are never deleted. I believe it gonna work fine.
    HLGEM : Remember you might have gaps due to rollbacks.
    JohnFx : In response to "That's fine, order is not an issue"... Then why don't you just subtract an arbitraty value in your query since that is what you are doing if you don't consider order?
  • LEFT JOIN the table to itself, with the join condition worked out so the row matched in the joined version of the table is one row previous, for your particular definition of "previous".

    Update: At first I was thinking you would want to keep all rows, with NULLs for the condition where there was no previous row. Reading it again you just want that rows culled, so you should an inner join rather than a left join.

  • Oracle has analytic functions called LAG and LEAD that do this thing.

    In SQL Server, you'll need to do the following:

    SELECT  value - (
            SELECT  TOP 1 value
            FROM    mytable m2
            WHERE   m2.col1 < m1.col1 OR (m2.col1 = m1.col1 AND <
            ORDER BY 
                    col1, pk
    FROM mytable m1
          col1, pk

    , where COL1 is the column you are ordering by.

    Having an index on (COL1, PK) will greatly improve this query.

  • The selected answer will only work if there are no gaps in the sequence. However if you are using an autogenerated id, there are likely to be gaps in the sequence due to inserts that were rolled back.

    This method should work if you have gaps

    declare @temp (value int, primaryKey int, tempid int identity)
    insert value, primarykey from mytable order by  primarykey
    select t1.value - t2.value from @temp  t1
    join @temp  t2 
    on t1.tempid = t2.tempid - 1

Python 3.0 Windows/COM

How to access a COM object from a python file using python 3.0.

And, yes, I know that not a lot of people are using Python 3.0. Switching back to 2.6 is a huge hassle for me, so I don't want to unless I absolutely have to.

I appreciate your time, and any assistance!

From stackoverflow
  • Install pywin32 and then create the object using it's progid:

    import win32com.client
    object = win32com.client.Dispatch("Outlook.Application")

    See also the Python and COM tutorial.

    EDIT: Hmm... looks like they may not have a python 3.0 version yet.

    Sean Ochoa : Dude, that was awesome. Lightning quick, too. :) I must have gone to either the wrong SF download page, or an old version of the same proj, or something. :) Thanks!

Building an OCX with VS.NET?

What happened to OCX's? Are they no longer possible to create with the latest tools?

I need to create an ActiveX control that I can place in Word, PowerPoint and Excel documents. If I use VS.NET, I can only create a UserControl DLL with COM Interop, but I don't think I can add that using the "More Controls" toolbox of PowerPoint's Developer Tab.

What would you do?

From stackoverflow
  • Yes, you can still create them. But you can't create an OCX with a .NET language. Need to be unmanaged C++ (or VB). The DLLs with COM interop you can create in C# or VB.NET are just .NET objects that are invoked via CCW.

    Jason : Are they on their way out (OCXs)?
    DannySmurf : I'd say that's very likely. With the move to .NET, COM is really a legacy technology now in any form. There's little reason these days to use an OCX. A CCW-invoked .NET assembly is almost always a better solution now.
    recursive : What is CCW? I assume you're referring to something other than concealed carry.
    DannySmurf : COM-Callable Wrapper
  • Use a C++ or VB compiler which can target native code + ActiveX.

    kenny : yup. they were so easy to create in VB6.
  • You can still use .NET to create ActiveX components. However, this is experimental and not recommended. If you still want to try it you can find information in the blog of Andrew Whitechapel:

    Using Managed Controls as ActiveX Controls

    But as Andrew says:

    This seems to work OK for Excel (with the very limited testing I've done), partly works with PowerPoint, but fails miserably with Word.

    So if you don't want to spend a lot of time debugging strange errors I would recommend you to use the old VB 6.0 and Visual Studio 6.0 to build you ActiveX components.

  • Depending on what you need to do, an Add-in may be more appropriate than an OCX, and you can certainly create those with .NET. You should also look at the Visual Studio Tools for Office, not as a direct replacement for an OCX, but only to understand the new capabilities. It may show you new approaches to the problems you're now solving with an OCX.

How can I select distinct rows when a text field is part of the returned fields in MS SQL Server 2000?

I have a database-driven FAQ that is organised into sections and I am trying to get the section data for only those sections who have a question/answer associated with them.

Here is the schema:

|---------------------|      |----------------------|
|       Section       |      |       Quest-Ans      |
|---------------------|      |----------------------|
| PK | id(int)        |<--|  | PK     | id(int)     |
|    | title(varchar) |   |--| FK     | Sec_id(int) |
|    | desc(text)     |      |        | body(text)  |
|---------------------|      |----------------------|

When I try this query:

SELECT DISTINCT, s.title, s.desc
FROM Section as s INNER JOIN Quest-Ans as q ON = q.Sec_id

I get an error saying that DISCRETE cannot be applied to a text field. How can I get the data I want?

If it matters, this is an SQL2000 database.


Ok, so it seems like there are two ways to go about this. Either with EXISTS and a subquery in the where clause, or with the subquery in the inner join. Which is faster?

From stackoverflow
  • This should do it:

    SELECT, s.title, s.desc
    FROM Section as s 
    WHERE EXISTS (SELECT * FROM Quest-Ans as q where q.Sec_id =
  • Try it:

    SELECT s.Title, s.Desc
    FROM Section as s
      FROM Section as s 
      INNER JOIN Quest-Ans as q ON = q.Sec_id
    ) q ON s.Id = q.Id
    Lieven : @Ekeko - That should be SELECT DISTINCT
    cdeszaq : Returns a row for every question.
    eKek0 : @Lieven: Select returns a set of rows, and a set has not repetead elements and inner join is done based on the key (I guess). So, distinct is not necessary.
    cdeszaq : @Ekeko, without DISTINCT, it gives 1 row per question. With, it works correctly. It is necessary.
    eKek0 : @cdeszaq: That is what you want
    cdeszaq : @Ekeko: I am looking for section data for the **sections**, that have a question in them, not for section data for the questions themselves.
    Lieven : +1 This is the second time today I give an upvote because I completely disagree with whoever downvoated this reply. Besides a missing distinct, it was a correct answer
  • select, s.title, s.desc
    from Section s 
    inner join (select distinct sec_id from Quest-Ans) dqa on = dqa.sec_id

Most useful animation in web or desktop application

Many animation effects are simply gratuitous eye candy -- however, there are situations where animations effectively communicate to the user what's going on. What are some of your favorite uses for animations, and what specific animation type would you use?

E.g.: Animate items downwards when a new item is inserted into a list

From stackoverflow
  • From

    Press your mouse button

    and move to look around.

  • One example I can think of is the animation used by operating systems when you minimize a window.

    Both Microsoft Windows and Apple OS X animate the window going down to the taskbar (or the Dock in OS X) to show the user where the window went. Otherwise novice users that hit minimize by accident might have trouble getting the window back.

    I don't use linux, but I'm pretty sure it does the same. I'm not being discriminative =)

  • I really like Google Chrome's use when a file is being downloaded. It's hard to describe, but, it's a circle that fills like a pie chart as the download progresses, and the circle is overlaid with the icon for the file you're downloading. Very slick.

  • Progress bars are nice for things that take more than a moment or two, but only when they are accurate. An inaccurate progress bar is worse than none, in my opinion.

  • I believe that all visual changes should not be swift. Be it status notification, window maximized/minimized, or data deleted/added. I cannot find a reference, but usually it is recommended that all animations should not be around 1-2 seconds, matching human's response time.

    My favorite uses of animation is not in a commercial software (though Apple is good at this) but a research paper called Phosphor which I consider one of the great UI ideas that have not yet implemented into major operating systems.

  • AJAX loading gifs - you've got to have an indicator that you definitely registered an event and you're doing something about it

  • There is a very nice paper by Ben Bederson and Angela Boltman in which they evaluate the impact of animation on user’s ability to build a mental map of the information in the space: Does Animation Help Users Build Mental Maps of Spatial Information?

Branch from the past in mercurial

I'm a single developer using Mercurial to create a program. I have so far committed at every step of developing, and I have messed things up and want to work on something else.

How shall I go to a previous state (ie. rollback) and then create a branch, maintaining the newer states?

Does rollback ever delete anything? Should that be all I do? Just rollback untill I'm at the place where I want, edit, then commit? Will I be able to merge the changesets later, or at least look at them? Of course I can just save this repository, rollback, and then create new changesets, then merge the two repositories?

I'm new to SCM and of course DSCM, so be gentle :)

From stackoverflow
  • You don't want to use hg rollback, that only erases exactly one change (the most recent). See You Can Only Roll Back Once in the hg book.

    To make a branch from an earlier revision, you need to find the revision number you want to branch from and run:

    hg clone -r <revnum> <source repository> <destination repository>

    You can then do your changes in the newly-cloned repository (which will not contain any of the history that came after the revision number you specified) and then merge those changes back into the original later, if you wish.