Tuesday, February 8, 2011

How to illustrate usage of volatile keyword in C#

I would like to code a little program which visually illustrates the behavior of the 'volatile' keyword. Ideally, it should be a program which performs concurrent access to a non volatile static field and which get incorrect behavior because of that.

Adding the volatile keyword in the same program should fix the problem.

That something I didn't manage to achieve. Even trying several times, enabling optimization, etc., I always get a correct behavior without the 'volatile' keyword.

Do you have any idea about this topic ? Do you know how to simulate such a problem in a simple demo app ? Does it depend on hardware ?

  • Yes, it's hardware dependent (you are unlikely to see the problem without multiple processors), but it's also implementation dependent. The memory model specifications in the CLR spec permit things which the Microsoft implementation of the CLR do not necessarily do. The best documentation I've seen on the volatile keyword is this blog post by Joe Duffy. Note that he says the MSDN documentation is "highly misleading."

    Xaqron : http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/
  • It's not really a matter of a fault happening when the 'volatile' keyword isn't specified, more that an error could happen when it hasn't been specified. Generally you are going to know when this is the case better than the compiler!

    The easiest way of thinking about it would be that the compiler could, if it wanted to, inline certain values. By marking the value as volatile, you are telling yourself and the compiler that the value may actually change (even if the compiler doesn't think so). This means the compiler should not in-line values, keep cache or read the value early (in an attempt to optimize).

    This behaviour isn't really the same keyword as in C++.

    MSDN has a short description here. Here is a perhaps a more in depth post on the subjects of Volatility, Atomicity and Interlocking

    From Ray Hayes
  • It's hard to demonstrate in C#, as the code is abstracted by a virtual machine, thus on one implementation of this machine it work right without volatile, while it might fail on another one.

    The Wikipedia has a good example how to demonstrate it in C, though.

    The same thing could happen in C# if the JIT compiler decides that the value of the variable cannot change anyway and thus creates machine code that doesn't even check it any longer. If now another thread was changing the value, your first thread might still be caught in the loop.

    Another example is Busy Waiting.

    Again, this could happen with C# as well, but it strongly depends on the virtual machine and on the JIT compiler (or interpreter, if it has no JIT... in theory, I think MS always uses a JIT compiler and also Mono uses one; but you might be able to disable it manually).

    From Mecki
  • I achieve really working example!

    The main idea received from wiki, but with some changes for C#. The wiki article demonstrates this for static field of C++, it is looks like C# allways carefully compile requests to static fields... and i make example with non static one:

    If you run this example in RELEASE mode and WITHOUT DEBUGGER (Ctrl+F5) than a line 'while (test.foo != 255)' will be optimized to 'while(true)' and this program never returns. But after adding 'volatile' keyword, you always get 'OK'.

    class Test
    {
        int foo;
    
        static void Main()
        {
            var test = new Test();
    
            new Thread(delegate() { Thread.Sleep(500); test.foo = 255; }).Start();
    
            while (test.foo != 255) ;
            Console.WriteLine("OK");
        }
    }
    

What's the best to method call a Webservice from ASP?

Note: not ASP.NET.

I've read about various methods including using SOAPClient (is this part of the standard Windows 2003 install?), ServerXMLHTTP, and building up the XML from scratch and parsing the result manually.

Has anyone ever done this? What did you use and would you recommend it?

  • We use the MS Soap Toolkit version 3 here. Seems to work ok (I only wrote the services).

    AnthonyWJones : I'd avoid this. Its deprecated, not recommend for server 2003, uses MSXML4 and I'm not even sure it uses WinHTTP but may use WinINET instead.
    From leppie
  • Well, since the web service talks XML over standard HTTP you could roll your own using the latest XML parser from Microsoft. You should make sure you have the latest versions of MSXML and XML Core Services (see Microsoft Downloads).

    <% 
        SoapUrl = "http://www.yourdomain.com/yourwebservice.asmx" 
        set xmlhttp = CreateObject("MSXML2.ServerXMLHTTP") 
        xmlhttp.open "GET", SoapUrl, false 
        xmlhttp.send()
        Response.write xmlhttp.responseText 
        set xmlhttp = nothing 
    %>
    

    Here is a good tutorial on ASPFree.com

    From pdavis
  • I am trying to call one of three methods that a web service offers. Does anyone know how to do that using MSXML2.ServerXMLHTTP?

    Thanks

How do I sort a list of integers using only one additional integer variable?

How to sort list of values using only one variable?

EDIT: according to @Igor's comment, I retitled the question.

  • Do nothing?

    From Galwegian
  • You dont, it is already sorted. (as the question is vague, I shall assume variable is a synonym for an object)

    From leppie
  • care to elaborate?

  • Do you mean list with only one element, or you mean sort it using only one additional variable?

  • You could generate/write a lot of sorting-networks for each possible list size. Inside the sorting network you use a single variable for the swap operation.

    I wouldn't recommend that you do this in software, but it is possible nevertheless.

    Here's a sorting-routine for all n up to 4 in C

    // define a compare and swap macro 
    #define order(a,b) if ((a)<(b)) { temp=(a); (a) = (b); (b) = temp; }
    
    static void sort2 (int *data)
    // sort-network for two numbers
    {
      int temp;
      order (data[0], data[1]);
    }
    
    static void sort3 (int *data)
    // sort-network for three numbers
    {
      int temp;
      order (data[0], data[1]);
      order (data[0], data[2]);
      order (data[1], data[2]);
    }
    
    static void sort4 (int *data)
    // sort-network for four numbers
    {
      int temp;
      order (data[0], data[2]);
      order (data[1], data[3]);
      order (data[0], data[1]);
      order (data[2], data[3]);
      order (data[1], data[2]);
    }
    
    void sort (int *data, int n)
    {
      switch (n)
        {
        case 0:
        case 1:
          break;
        case 2:
          sort2 (data);
          break;
        case 3:
          sort3 (data);
          break;
        case 4:
          sort4 (data);
          break;
        default:
          // Sorts for n>4 are left as an exercise for the reader
          abort();
        }
    }
    

    Obviously you need a sorting-network code for each possible N.

    More info here:

    http://en.wikipedia.org/wiki/Sorting_network

    Blair Conrad : Interesting, but it seems kind of impractical.
    Nils Pipenbrinck : It is impractical. The sort-networks are useful if you do hardware design because you can do multiple compare and swaps in parallel / at the same time, but in software a loop is almost always faster. Even vor small N
    florin : It's also outside the scope of the original challenge: you are using the stack.
  • I suspect I'm doing your homework for you, but hey it's an interesting challenge. Here's a solution in Icon:

    procedure mysort(thelist)
        local n # the one integer variable
        every n := (1 to *thelist & 1 to *thelist-1) do
     if thelist[n] > thelist[n+1] then thelist[n] :=: thelist[n+1]
        return thelist
    end
    
    procedure main(args)
        every write(!mysort([4,7,2,4,1,10,3]))
    end
    

    The output:

    1
    2
    3
    4
    4
    7
    10
    
    From Hugh Allen
  • A solution in C:

    #include <stdio.h>
    
    int main()
    {
     int list[]={4,7,2,4,1,10,3};
     int n;  // the one int variable
    
     startsort:
     for (n=0; n< sizeof(list)/sizeof(int)-1; ++n)
      if (list[n] > list[n+1]) {
       list[n] ^= list[n+1];
       list[n+1] ^= list[n];
       list[n] ^= list[n+1];
       goto startsort;
      }
    
     for (n=0; n< sizeof(list)/sizeof(int); ++n)
      printf("%d\n",list[n]);
     return 0;
    }
    

    Output is of course the same as for the Icon program.

    From Hugh Allen
  • In java:

    import java.util.Arrays;
    
    /**
     * Does a bubble sort without allocating extra memory
     *
     */
    public class Sort {
     // Implements bubble sort very inefficiently for CPU but with minimal variable declarations
     public static void sort(int[] array) {
      int index=0;
      while(true) {
       next:
       {
        // Scan for correct sorting. Wasteful, but avoids using a boolean parameter
        for (index=0;index<array.length-1;index++) {
         if (array[index]>array[index+1]) break next;
        }
        // Array is now correctly sorted
        return;
       }
       // Now swap. We don't need to rescan from the start
       for (;index<array.length-1;index++) {
        if (array[index]>array[index+1]) {
         // use xor trick to avoid using an extra integer
         array[index]^=array[index+1];
         array[index+1]^=array[index];
         array[index]^=array[index+1];
        }
       }
      }
     }
    
     public static void main(final String argv[]) {
      int[] array=new int[] {4,7,2,4,1,10,3};
      sort(array);
      System.out.println(Arrays.toString(array));
     }
    }
    

    Actually, by using the trick proposed by Nils, you can eliminate even the one remaining int allocation - though of course that would add to the stack instead...

  • If you have a list (1 5 3 7 4 2) and a variable v, you can exchange two values of the list, for example the 3 and the 7, by first assigning 3 to v, then assigning 7 to the place of 3, finally assigning the value of v to the original place of 7. After that, you can reuse v for the next exchange. In order to sort, you just need an algorithm that tells which values to exchange. You can look for a suitable algorithm for example at http://en.wikipedia.org/wiki/Sorting_algorithm .

    From Svante
  • In ruby: [1, 5, 3, 7, 4, 2].sort

Threading when sending emails

Hi,

I have a simple function that sends out emails, how would I go about using threads to speed email delivery?

Sample code would be ideal.

  • Use SendAsync isntead.

    From leppie
  • Create your class with a static void method that will make your class start doing what you want to do on the separate thread with something like:

    using System;
    using System.Threading;
    
    class Test
    {
        static void Main() 
        {
            Thread newThread =  new Thread(new ThreadStart(Work.DoWork));
            newThread.Start();
        }
    }
    
    class Work 
    {
        Work() {}
        public static void DoWork() {}
    }
    

    Another alternative is to use the ThreadPool class if you dont want to manage your threads yourself.

    More info on Threads - http://msdn.microsoft.com/en-us/library/xx3ezzs2.aspx

    More info on ThreadPool - http://msdn.microsoft.com/en-us/library/3dasc8as(VS.80).aspx

    From Wolfwyrd
  • Having a seperate thread will not speed the delivery of email however. All it will do is return control back to the calling method faster. So unless you need to do that, i wouldnt even bother with it.

    From mattlant
  • You know what would be nicer and easier is to create an application back end and send emails every 30 minutes. Throw the information into a database that you need to send to and from there, create an application pool that launches every 30 minutes. When it launches, you can send an email. No need to wait for your event handler to send the email...

    It works for us. Just thought it would help for you.

    From Scott
  • Check out the following link for a demonstration of the sendAsync method. [MSDN]

    http://msdn.microsoft.com/en-ca/library/x5x13z6h(VS.80).aspx

    From chris
  • You can run the function in another thread. Being SendMail your mail sender function you can:

    ThreadPool.QueueUserWorkItem(delegate { SendMail(message); });
    
  • When you send e-mails using multiple threads, be careful about getting identified as spam by your isp. It will be better to opt for a smaller batches with some delay between each batch.

    From Vijesh VP

Are there any emulator for the JTAPI API?

We want test the JTAPI feature of our application. Are there any emulator for JTAPI available? The testing with real hardware is a little diffcult.

Why should I ever use inline code?

I'm a C/C++ developer, and here are a couple of questions that always baffled me.

  • Is there a big difference between "regular" code and inline code?
  • Which is the main difference?
  • Is inline code simply a "form" of macros?
  • What kind of tradeoff must be done when choosing to inline your code?

Thanks

  • Inline code works like macros in essence but it is actual real code, which can be optimized. Very small functions are often good for inlining because the work needed to set up the function call (load the parameters into the proper registers) is costly compared to the small amount of actual work the method does. With inlining, there is no need to set up the function call, because the code is directly "pasted into" any method that uses it.

    Inlining increases code size, which is its primary drawback. If the code is so big that it cannot fit into the CPU cache, you can get major slowdowns. You only need to worry about this in rare cases, since it is not likely you are using a method in so many places the increased code would cause issues.

    In summary, inlining is ideal for speeding up small methods that are called many times but not in too many places (100 places is still fine, though - you need to go into quite extreme examples to get any significant code bloat).

    Edit: as others have pointed out, inlining is only a suggestion to the compiler. It can freely ignore you if it thinks you are making stupid requests like inlining a huge 25-line method.

    Ferruccio : Keep in mind that inline functions are guaranteed to have the same semantics as the equivalent non-inlined functions. Macros can have unexpected side-effects.
    From Sander
  • If you are marking your code as inline in f.e. C++ you are also telling your compiler that the code should be executed inline, ie. that code block will "more or less" be inserted where it is called (thus removing the pushing, popping and jumping on the stack). So, yes... it is recommended if the functions are suitable for that kind of behavior.

    From kitofr
  • "inline" is like the 2000's equivalent of "register". Don't bother, the compiler can do a better job of deciding what to optimize than you can.

    Charles Duffy : Inaccurate -- if you don't mark a function inline, the compiler isn't allowed to inline it without your approval. Thus, by using "inline", you're giving the compiler more options in making its better-than-the-programmer's decisions.
    Richard Corden : The as-if rule allows the compiler to inline a fucntion if it wishes. However, it can only do so if the function definition is visible. Due to the ODR this basically means the compiler cannot implicitly inline a function from a different TU.
    Nils Pipenbrinck : @Charles, not true. The compiler is allowed to do anything that does not change the semantic of the program. All modern compilers will inline trivial functions even if you don't declare them as inline.
    Suma : To be exact: @Nils: this depends on compiler settings. With Visual Studio three degreess are possible (no inlineing, only inline, any suitable). @Richard Corden - Whole Program Optimization can inline even across TUs.
    Richard Corden : @Suma: Theoretically that is true. How many platform/compilers support WPO? The platforms I am required to support still use a very basic linker to do the job. Others have highlighted how some linkers still don't remove duplicate template instantiations. 'inline' will be here for a while yet.
  • It depends on the compiler...
    Say you have a dumb compiler. By indicating a function must be inlined, it will put a copy of the content of the function on each occurrence were it is called.

    Advantage: no function call overhead (putting parameters, pushing the current PC, jumping to the function, etc.). Can be important in the central part of a big loop, for example.

    Inconvenience: inflates the generated binary.

    Is it a macro? Not really, because the compiler still checks the type of parameters, etc.

    What about smart compilers? They can ignore the inline directive, if they "feel" the function is too complex/too big. And perhaps they can automatically inline some trivial functions, like simple getters/setters.

    From PhiLho
  • Marking a function inline means that the compiler has the option to include in "in-line" where it is called, if the compiler chooses to do so; by contrast, a macro will always be expanded in-place. An inlined function will have appropriate debug symbols set up to allow a symbolic debugger to track the source where it came from, while debugging macros is confusing. Inline functions need to be valid functions, while macros... well, don't.

    Deciding to declare a function inline is largely a space tradeoff -- your program will be larger if the compiler decides to inline it (particularly if it isn't also static, in which case at least one non-inlined copy is required for use by any external objects); indeed, if the function is large, this could result in a drop in performance as less of your code fits in cache. The general performance boost, however, is just that you're getting rid of the overhead of the function call itself; for a small function called as part of an inner loop, that's a tradeoff that makes sense.

    If you trust your compiler, mark small functions used in inner loops inline liberally; the compiler will be responsible for Doing The Right Thing in deciding whether or not to inline.

    • Is there a big difference between "regular" code and inline code?

    Yes - inline code does not involve a function call, and saving register variables to the stack. It uses program space each time it is 'called'. So overall it takes less time to execute because there's no branching in the processor and saving of state, clearing of caches, etc.

    • Is inline code simply a "form" of macros?

    Macros and inline code share similarities. the big difference is that the inline code is specifically formatted as a function so the compiler, and future maintainers, have more options. Specifically it can easily be turned into a function if you tell the compiler to optimize for code space, or a future maintainer ends up expanding it and using it in many places in their code.

    • What kind of tradeoff must be done when choosing to inline your code?

      • Macro: high code space usage, fast execution, hard to maintain if the 'function' is long
      • Function: low code space usage, slower to execute, easy to maintain
      • Inline fuction: high code space usage, fast execution, easy to maintain

    It should be noted that the register saving and jumping to the function does take up code space, so for very small functions an inline can take up less space than a function.

    From Adam Davis
  • Inline differs from macros in that it's a hint to the compiler (compiler may decide not to inline the code!) and macros are source code text generation before the compilation and as such are "forced" to be inlined.

    From Kasprzol
  • By inlining, the compiler inserts the implementation of the function, at the calling point. What you are doing with this is removing the function call overhead. However, there is no guarantee that your all candidates for inlining will actually be inlined by the compiler. However, for smaller functions, compilers always inline. So if you have a function that is called many times but only has a limited amount of code - a couple of lines - you could benefit from inlining, because the function call overhead might take longer than the execution of the function itself.

    A classic example of a good candidate for inlining are getters for simple concrete classes.

    CPoint
    {
      public:
    
        inline int x() const { return m_x ; }
        inline int y() const { return m_y ; }
    
      private:
        int m_x ;
        int m_y ;
    
    };
    

    Some compilers ( e.g. VC2005 ) have an option for aggressive inlining, and you wouldn't need to specify the 'inline' keyword when using that option.

    From QBziZ
  • I won't reiterate the above, but it's worth noting that virtual functions will not be inlined as the function called is resolved at runtime.

    KeithB : Virtual functions can be inlined, if the compiler knows the dynamic type of the object at the point of the call. For example, if you have a pointer or reference to a base class, it won't be inlined, if you have a derived object (not ptr/ref), it may be inlined.
    QBziZ : Typical example for KeithB's comment : virtual destructors of base classes can be inlined by the compiler in the dtor of the derived class if definition is visible
    From RC
  • Inlining usually is enabled at level 3 of optimization (-O3 in case of GCC). It can be a significant speed improvement in some cases (when it is possible).

    Explicit inlining in your programs can add some speed improvement with the cost of an incresed code size.

    You should see which is suitable: code size or speed and decide wether you should include it in your programs.

    You can just turn on level 3 of optimization and forget about it, letting the compiler do his job.

    • Is there a big difference between "regular" code and inline code?

    Yes and no. No, because an inline function or method has exactly the same characteristics as a regular one, most important one being that they are both type safe. And yes, because the assembly code generated by the compiler will be different; with a regular function, each call will be translated into several steps: pushing parameters on the stack, making the jump to the function, popping the parameters, etc, whereas a call to an inline function will be replaced by its actual code, like a macro.

    • Is inline code simply a "form" of macros?

    No! A macro is simple text replacement, which can lead to severe errors. Consider the following code:

    #define unsafe(i) ( (i) >= 0 ? (i) : -(i) )
    
    [...]
    unsafe(x++); // x is incremented twice!
    unsafe(f()); // f() is called twice!
    [...]
    

    Using an inline function, you're sure that parameters will be evaluated before the function is actually performed. They will also be type checked, and eventually converted to match the formal parameters types.

    • What kind of tradeoff must be done when choosing to inline your code?

    Normally, program execution should be faster when using inline functions, but with a bigger binary code. For more information, you should read GoTW#33.

    Martin York : Worth a commment is that the programmer can only hint to the compiler to use inline code is upto the compiler to actually make the choice (even when methods are defined in the class). The compiler will only inline if analyasis indicates an advantage to do so
  • The answer of should you inline comes down to speed. If you're in a tight loop calling a function, and it's not a super huge function, but one where a lot of the time is wasted in CALLING the function, then make that function inline and you'll get a lot of bang for your buck.

    From stu
  • First of all inline is a request to compiler to inline the function .so it is upto compiler to make it inline or not.

    1. When to use?When ever a function is of very few lines(for all accessors and mutator) but not for recursive functions
    2. Advantage?Time taken for invoking the function call is not involved
    3. Is compiler inline any function of its own?yes when ever a function is defined in header file inside a class
    From yesraaj
  • inlining is a technique to increase speed. But use a profiler to test this in your situation. I have found (MSVC) that inlining does not always deliver and certainly not in any spectacular way. Runtimes sometimes decreased by a few percent but in slightly different circumstances increased by a few percent.

    If the code is running slowly, get out your profiler to find troublespots and work on those.

    I have stopped adding inline functions to header files, it increases coupling but gives little in return.

  • Take a look at this question in regard to inlining code and the tradeoffs concerned.

    From Alan
  • Inline code is faster. There is no need to perform a function call (every function call costs some time). Disadvantage is you cannot pass a pointer to an inline function around, as the function does not really exist as function and thus has no pointer. Also the function cannot be exported to public (e.g. an inline function in a library is not available within binaries linking against the library). Another one is that the code section in your binary will grow, if you call the function from various places (as each time a copy of the function is generated instead of having just one copy and always jumping there)

    Usually you don't have to manually decide if a function shall be inlined or not. E.g. GCC will decide that automatically depending on optimizing level (-Ox) and depending on other parameters. It will take things into consideration like "How big is the function?" (number of instructions), how often is it called within the code, how much the binary will get bigger by inlining it, and some other metrics. E.g. if a function is static (thus not exported anyway) and only called once within your code and you never use a pointer to the function, chances are good that GCC will decide to inline it automatically, as it will have no negative impact (the binary won't get bigger by inlining it only once).

    Richard Corden : Some corrections. You can pass a pointer to an inline function. The function can be "extern", but it's definition needs to be visible to each TU that uses it. The code *may* grow. AFAIK, GCC cannot yet do Whole Program Optimisation which is needed for full implicit inline.
    Zan Lynx : The GCC workaround for that is to glom all the code for a group of TU's together. There are several scripts for it. KDE does it. Downside is 800+ MB RAM usage during KDE compile.
    From Mecki
  • Performance

    As has been suggested in previous answers, inline can make code faster, often at the expense of increased executables. However, modern compilers are very good at inlining automatically without any prompt from the user when set to high optimization. Actually, compilers are usually better at determining what to inline for speed gain than humans are.

    Declaring functions inline explicitly for the sake of performance gain is (almost) always unnecessary!

    Additionally, compilers can and will ignore the inline request if it suits them. Compilers will do this if the function is hard to inline (i.e. using nontrivial recursion or function pointers) but also if the function is simply too large to be meaningfully inlined.

    One Definition Rule

    However, declaring a function inline may actually be necessary for completely different reasons, namely to satistfy the One Definition Rule (ODR). This rule in the C++ standard states that a given symbol may be declared multiple times but may only be defined once. If the link editor (= linker) encounters several identical symbol definitions, it will generate an error.

    One solution to this problem is to make sure that a compilation unit doesn't export a given symbol by marking it static (static – the keyword with the most completely unrelated meanings in C).

    However, it's often better to mark a function inline instead. Thus, you allow the compiler to not create the function definition at all. This is often very useful when working with templates which usually have to be declared in header files.

    As an example, consider the following program:

    // header.hpp
    #include <iosfwd> // for std::ostream&
    
    #ifndef HEADER_HPP
    #define HEADER_HPP
    
    template <typename IteratorT>
    /*inline*/ void print_all(IteratorT begin, IteratorT end, std::ostream& out, char sep = ' ') {
        while (begin != end)
            out << *begin++ << sep;
    }
    
    #endif // !defined(HEADER_HPP)
    


    // test.cpp
    #include <iostream>
    #include <vector>
    #include "header.hpp"
    
    void test_function() {
        using namespace std;
        vector<int> vec;
        int x;
        while (cin >> x) vec.push_back(x);
        cout << "Results: ";
        print_all(vec.begin(), vec.end());
        cout << endl;
    }
    


    // main.cpp
    #include <iostream>
    #include <vector>
    #include "header.hpp"
    
    void test_function(); // Forward declaration.
    
    int main() {
        using namespace std;
        vector<int> xyz(23, 42);
        print_all(xyz);
        cout << endl << "Test call:" << endl;
        test_function();
    }
    

    Notice that both .cpp files include the header file and thus the function definition of print_all. Although the file is saved with include guards against double inclusion, this will result in two definitions of the same function, albeit in different compilation units.

    Now, if you try to link those two compilation unit, say, using the following command:

    $ g++ -Wall -pedantic main.cpp test.cpp
    

    you'll get an error saying “duplicate definition of print_all” or something similar. If, however, you unquote the inline modifier in front of the function definition, the code compiles and links correctly.

    rubenvb : Dang, I've been searching for a fix like this forever... I had a header with function definition+implementation, but didn't inline. Although there were header guards, there were still multiple definitions... Finally found the fix :)

ASP.NET/IIS: 404 for all file types

I set up 404 handler page in web.config, but it works ONLY when extension of URL is .aspx (or other which is handled by ASP.NET). I know I can setup static HTML page in website options, but I want to have a page. Is there any options to assign ASPX handler page for all request extensions in IIS?

  • The web.config can only set up errors pages for pages controlled by it's web site. If you have any other pages outside the purview of the ASP.Net application, then you set up handling for them in IIS. There's an option in there for configuring the 404 page where you can point it to your custom page.

  • Only other thing i can think of is passing ALL extensions to asp.net.

    This way all types of files get processed by asp.net and your custom error page will work.

    Joel Coehoorn : It would work, but there are performance considerations for high-traffic sites.
    mattlant : indeed, there would be.
    From mattlant
  • In the IIS application configuration, you can set a wildcard mapping (".*") to C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll

  • The direct question was whether or not there are options to assign the ASPX handler to all request extensions: Yes, there is. I'll discuss how to do that shortly.

    First, I think the "hidden" question -- the answer you really want -- is whether or not there's a way to redirect all 404 errors for pages other than ASPX, ASMX, etc. Yes, there is, and this is the better choice if it'll solve the issue you're having.

    To redirect all 404s in IIS 6, right click your web application root (whether it be its own site or a virtual directory in the main site), and choose "Properties." From there, choose the "Custom Errors" tab. Find 404 in the list and change it to the redirect you want.

    Now, if that won't suffice -- and I really hope it does -- yes, you can run every page through the ASPX handler. However, doing so comes at a fairly high cost in terms of efficiency -- raw HTML/image serving is considerably faster than anything dynamic.

    To do this, right click your web application root and choose "Properties." Choose the "Home Directory" tab. Click "Configuration;" a new window will pop up. Copy the path from one of the ASP.NET page serves, and then use it for a wildcard application map.

    Bear in mind, again, this is the wrong answer most of the time. It will negatively impact your performance, and is the equivalent of using a chainsaw to carve a turkey. I highly recommend the first option over this one, if it will work out for you.

    Sergey Osypchuk : Thanks for complete answer. We will test performance and will decide which to choose.
    From John Rudy
  • For information:

    This is one of the several nice things that IIS7 brings - all pages are routed through the handler such that you can do custom 404s and - usefully - directory and file level security for any file (based on the same web.config stuff as for asp.net files prior to IIS7).

    So notionally "use II7" is an answer (will be "the" answer in time) - but of course its not a terribly practical one if you're not hosting/being hosted on W2k8 (or higher).

    From Murph
    1. You can setup wild card mapping in IIS (Application configuration/Mappings/Wildcard mappings/ - just set aspnet_isapi.dll as executable and uncheck the Verify that file exists box) that will route all incoming requests to your app - so you can control the behavior directly from it.

    2. You don't have to setup static page in your IIS application settings. Imho, you should be able to setup valid url (e.g. /error_handler.aspx) from your app that will be used as landing page in case of specific server error.

    From ljubomir

Foxpro App and removable drives problem

I have a foxpro app, that contains hard coded path for icons and bitmaps. That's how foxpro does it and there is no way around it. And this works fine, except that when a removable drive has been used but is not connected, and when is connected windows assigns the same letter as hard coded path, when opening any form that contains such path, the following error message apears (FROM WINDOWS, not fox):

Windows-No disk Exception Processing Message c0000012 Parameters .....

Any help please Nelson Marmol

  • Nelson:

    "That's how foxpro does it and there is no way around it"?

    I'm using FOX since FoxPro 2.5 to Visual FoxPro 9, and you are NEVER forced in any way to hard-code a path, you can use SET PATH TO (sYourPath), you can embed the icons and bitmaps in your EXE / APP file and therefore there's no need of including this resources externally.

    You say that you have a "Foxpro App": which version? Old MS-DOS FoxPro o Visual FoxPro? If you're using VFP 8+, you can use SYS(2450, 1):

    Specifies how an application searches for data and resources such as functions, procedures, executable files, and so on. 
    
    You can use SYS(2450) to specify that Visual FoxPro searches within an application for a specific procedure or user-defined function (UDF) before it searches along the SET DEFAULT and SET PATH locations. Setting SYS(2450) can help improve performance for applications that run on a local or wide area network.
    
    
    SYS(2450 [, 0 | 1 ])
    
    
    
    Parameters
    0 
    Search along path and default locations before searching in the application. (Default)
    
    1 
    Search within the application for the specified procedure or UDF before searching the path and default locations.
    

    One quick workaround could be assign another letter to your USB via the Disk Manager.

    From PabloG
  • I agree with @PabloG - it's been over a decade since I worked with FoxPro (Dos & Windows) but even back in FPW2.6 you could determine where your app was running 'from', set absolute or relative search paths and even bundle your resources straight into the "compiled" (heh) exe. All of our resources lived in a specific subfolder within the app folder, the database files in another subfolder also below the app folder. We used relative paths for everything as I recall.

    Can you give us a bit more information about the problem?

    If you think it would be helpful I could try and dig out some of our FPW2.6 code where we're doing this kind of thing. :-)

    From robsoft
  • It's VFP8 and sorry if I did not explained myself corectly. Also I think "there's no way around it" may sounded bad. What I meant is the property "ICON" in the forms. Since we have each component type separated in folders (forms,reports, menus, icons, etc), if you try to make the path relative, next time you edit the file, foxpro will include the fullpath. This problem started recently and we found that our clients started using external usb drives as means for backups.

    PabloG : Nelson: did you try _COMMAND = SYS(2450, 1) in CONFIG.FPW ?
  • It sounds to me like you are distributing the forms/reports/labels etc to the clients. If you build an EXE, then you shouldn't get the "path" problem as VFP will embed the resource (in this case icon) into the exe and will know how to extract it at runtime.

    Peterson

  • No, we are no distributing forms or anything with the app... it's an exe. I forgot to mention that the EXE is compressed and obfuscated with KONXIZE 1.0.

    From nmarmol
  • Assuming your application can determine the path to the icon file at runtime, then in the load event of the form, you can set the icon with:

    THIS.Icon=<path to file>
    
  • If anybody else runs across this, you can generally type something like this for the Icon property in the Properties window to force it to be evaluated, which will probably prevent the path auto-filling:

    ="icon.ico"

    instead of just icon.ico.

    From nstenz

Eval scripts in server side control property

how do i implement an eval script in a sever side control?

eg. <a runat="server" href="?id=<%= Eval("Id") %>">hello world</a>

  • <%# Eval("Id") %>

    as far as I know, its <%# instead of <%=

    From Robinb
  • The Data-Binding expression is your friend, see MSDN for examples.

    From snomag
  • If the server-side control is within a databound control (ListView, GridView, FormView, DetailsView), then the syntax is: <%# Eval("Id") %>.

    If the server-side control is not within a databound control, you will have to access it via the code-behind and set your attribute there.

What is the best way to obtain an index into a vector when using Iterators to loop over it.

When iterating over elements of a vector it is preferred to use iterators instead of an index (see Why use iterators instead of array indices?).

std::vector<T> vec;
std::vector<T>::iterator it;
for ( it = vec.begin(); it != vec.end(); ++it )
{
   // do work
}

However, it can be necessary to use the index in the body of the loop. Which of the following would be preferable in that case, considering performance and flexibility/extensibility?

  1. Revert to the indexed loop
    std::vector vec;
    size_t i;
    for ( i = 0; i < vec.size(); ++i )
    {
       // use i
    }
    
  2. Calculate offset
    std::vector vec;
    std::vector::iterator it;
    for ( it = vec.begin(); it != vec.end(); ++it )
    {
       size_t i = it - vec.begin(); 
       // use i
    }
    
  3. Use std::distance
    std::vector vec;
    std::vector::iterator it;
    for ( it = vec.begin(); it != vec.end(); ++it )
    {
       size_t i = std::distance( vec.begin(), it );
       // use i
    }
    
  • Using std::distance is a bit more generic since it works for all iterators, not just random access iterators. And it should be just as fast as It - vec.begin() in case of random access iterators.

    It - vec.begin() is basically pointer arithmetic.

    From QBziZ
  • Revert to the indexed loop.

    Basically in 90% of the cases, iterators are superior, this is one of those 10%. By using a iterator you are making the code more complex and therefore harder to understand, when the entire reason for using the iterator in the first place was to simplify your code.

    Guvante : Forgot to mention performance, generally it is safe to assume that the indexed loop would have better performance, but the performance would be very similar in both cases.
    QBziZ : I cannot say I agree. The body of the loop might contain other code that does dereference the iterator. Iterators are not meant to make your code simpler, they make your code more generic. By using the iterators you can swap the vector for list and it would still work.
    Doug T. : Also, std::map or std::set iterators are far from stupid. If I looped over all possible keys, it would probably take forever. Also, I'd have to do a O(log(n)) lookup on every key. So my loop would take O(m*log(n)). Using an iterator I could loop over the collection in O(n) time.
    From Guvante
  • If you're planning on using exclusively a vector, you may want to switch back to the indexed loop, since it conveys your intent more clearly than iterator-loop. However, if evolution of your program in the future may lead to a change of container, you should stick to the iterators and use std::distance, which is guaranteed to work with all standard iterators.

  • You're missing one solution: keep an index in case you need it, but don't use it as a loop condition. Works on lists too, and the costs (per loop) are O(n) and an extra register.

    From MSalters
  • I would always tend towards keeping with iterators for future development reasons.

    In the above example, if you perhaps decided to swap out std::vector for std::set (maybe you needed a unique collection of elements), using iterators and distance() would continue to work.

    I pretty sure that any performance issues would be optimized to the point of it being negligible.

    From Alan
  • std::distance(vec.begin(), it) will give you the index it is pointing at, assuming it points into vec.

    Carl

  • For vectors, I always use the integer method. Each index into the vector is the same speed as an array lookup. If I'm going to be using the value a lot, I create a reference to it, for convenience.

    vector iterators can be slightly faster than an index in theory, since they're using pointer arithmetic to iterate through the list. However, usually I find that the readability is worth the minimal runtime difference.

    I use iterators for other container types, and sometimes when you don't need the loop variable. But if you need the loop variable, you're not doing anything except making your loop harder to type. (I cannot wait for c++0x's auto..)

    From tfinniga

Opensource Implementation of the Alias Method

I am doing a project at the moment, and in the interest of code reuse, I went looking for a library that can perform some probabilistic accept/reject of an item:

i.e., there are three people (a, b c), and each of them have a probability P{i} of getting an item, where p{a} denotes the probability of a. These probabilities are calculated at run time, and cannot be hardcoded.

What I wanted to do is to generate one random number (for an item), and calculate who gets that item based on their probability of getting it. The alias method (http://books.google.com/books?pg=PA133&dq=alias+method+walker&ei=D4ORR8ncFYuWtgOslpVE&sig=TjEThBUa4odbGJmjyF4daF1AKF4&id=ERSSDBDcYOIC&output=html) outlined here explained how, but I wanted to see if there is a ready made implementation so I wouldn't have to write it up.

  • Would something like this do? Put all p{i}'s in the array, function will return an index to the person who gets the item. Executes in O(n).

    public int selectPerson(float[] probabilies, Random r) {
     float t = r.nextFloat();
     float p = 0.0f;
    
     for (int i = 0; i < probabilies.length; i++) {
      p += probabilies[i];
      if (t < p) {
       return i;
      }
     }
    
     // We should not end up here if probabilities are normalized properly (sum up to one)
     return probabilies.length - 1;  
    }
    

    EDIT: I haven't really tested this. My point was that the function you described is not very complicated (if I understood what you meant correctly, that is), and you shouldn't need to download a library to solve this.

    From finalman
  • i just tested out the method above - its not perfect, but i guess for my purposes, it ought to be enough. (code in groovy, pasted into a unit test...)

        void test() {
            for (int i = 0; i < 10; i++) {
                once()
            }
        }
        private def once() {
            def double[] probs = [1 / 11, 2 / 11, 3 / 11, 1 / 11, 2 / 11, 2 / 11]
            def int[] whoCounts = new int[probs.length]
            def Random r = new Random()
            def int who
            int TIMES = 1000000
            for (int i = 0; i < TIMES; i++) {
                who = selectPerson(probs, r.nextDouble())
                whoCounts[who]++
            }
            for (int j = 0; j < probs.length; j++) {
                System.out.printf(" %10f ", (probs[j] - (whoCounts[j] / TIMES)))
            }
            println ""
        }
        public int selectPerson(double[] probabilies, double r) {
            double t = r
            double p = 0.0f;
            for (int i = 0; i < probabilies.length; i++) {
                p += probabilies[i];
                if (t < p) {
                    return i;
                }
            }
            return probabilies.length - 1;
        }
    
    outputs: the difference betweenn the probability, and the actual count/total 
    obtained over ten 1,000,000 runs:
      -0.000009    0.000027    0.000149   -0.000125    0.000371   -0.000414 
      -0.000212   -0.000346   -0.000396    0.000013    0.000808    0.000132 
       0.000326    0.000231   -0.000113    0.000040   -0.000071   -0.000414 
       0.000236    0.000390   -0.000733   -0.000368    0.000086    0.000388 
      -0.000202   -0.000473   -0.000250    0.000101   -0.000140    0.000963 
       0.000076    0.000487   -0.000106   -0.000044    0.000095   -0.000509 
       0.000295    0.000117   -0.000545   -0.000112   -0.000062    0.000306 
      -0.000584    0.000651    0.000191    0.000280   -0.000358   -0.000181 
      -0.000334   -0.000043    0.000484   -0.000156    0.000420   -0.000372
    
    From Chii

Classic ASP and ASP.NET Integration

In a previous job we had a classic ASP application that no one wanted to migrate to ASP.NET. The things that it did, it did very well.

However there was some new functionality that needed to be added that just seemed best suited to ASP.NET. The decision was made to allow the system to become a weird hybrid of ASP and ASP.NET.

Our biggest sticking point was session management and we hacked together a solution to pass session values through form variables. I've talked to others that handled this same problem through cookies.

Both methods seem a horrible kluge (in addition to being terribly insecure).

Is there a better or cleaner way or is this just such a bad idea to begin with that discussion on the topic is pointless?

  • I have had to deal with the same problem. In my case, I encrypted a key into a cookie and used the database for any other information. I wrote the encryption in .NET and inter-op'd to decrypt the id on the ASP side. There is some weirdness dealing with base-64 string in that ASP will not get the same string as .NET, so you may have to do as I did and rewrite the base-64 string to hex equivalent or some similar lowest-common-denominator tactic. It is relatively secure (save a XSS attack).

    AnthonyWJones : The Base64 algrothim is very stable and ASP has no way to handle Base 64 natively. Hence whatever algorithm you were using before was just simply bugged.
    Greg Ogle : The Request.Cookies in ASP does some encoding that is not done in ASP.NET
    From Greg Ogle
  • Well, ultimately the best idea would probably to have converted the ASP app to .NET. I think that probably goes without saying though. If security is a big concern there are steps you can take as far as encryption and maintaining the integrity of the session information, to make it more secure, such as some symmetrical encryption and hashing and what not.

    From Wes P
  • I dont know of any cleaner way to do this in the general case. But perhaps you can describe more specifically what state you have to share between the systems? There may be a cleaner solution in your specific case. Session object state are not always the best way of keeping state.

    From JacquesB
  • Can you not persist session data to a serverside data store? ie XML file, database etc. You could then pass just a hash (calculated based on some criteria that securely identifies the session) to a .NET page which can the pick the data up from the data store using this identifier and populate your session data. It still means having to pass requests from ASP to ASP.NET through a proxy each time to ensure the latest session data is available in each app but I don't know of an alternative way to achieve this I'm afraid.

  • I would have to agree with Wes P ... what are the long-term goals? If the long-term goal is migrate the classic ASP application to ASP.NET then I think I short-term fix, whatever it may be, will work. If the long-term is to keep the classic ASP application then you would be better off going with a more robust solution for session management, similar to what Oglester recommended.

    From mattruma