Sunday, February 13, 2011

Best way to find all factors of a given number in C#

All numbers that divide evenly into x.

I put in 4 it returns: 4, 2, 1

edit: I know it sounds homeworky. I'm writing a little app to populate some product tables with semi random test data. Two of the properties are ItemMaximum and Item Multiplier. I need to make sure that the multiplier does not create an illogical situation where buying 1 more item would put the order over the maximum allowed. Thus the factors will give a list of valid values for my test data.

edit++: This is what I went with after all the help from everyone. Thanks again!

edit#: I wrote 3 different versions to see which I liked better and tested them against factoring small numbers and very large numbers. I'll paste the results.

static IEnumerable<int> GetFactors2(int n)
        {
            return from a in Enumerable.Range(1, n)
                          where n % a == 0
                          select a;                      
        }

        private IEnumerable<int> GetFactors3(int x)
        {            
            for (int factor = 1; factor * factor <= x; factor++)
            {
                if (x % factor == 0)
                {
                    yield return factor;
                    if (factor * factor != x)
                        yield return x / factor;
                }
            }
        }

        private IEnumerable<int> GetFactors1(int x)
        {
            int max = (int)Math.Ceiling(Math.Sqrt(x));
            for (int factor = 1; factor < max; factor++)
            {
                if(x % factor == 0)
                {
                    yield return factor;
                    if(factor != max)
                        yield return x / factor;
                }
            }
        }

In ticks. When factoring the number 20, 5 times each:

  • GetFactors1-5445881
  • GetFactors2-4308234
  • GetFactors3-2913659

When factoring the number 20000, 5 times each:

  • GetFactors1-5644457
  • GetFactors2-12117938
  • GetFactors3-3108182
  • pseudocode:

    • Loop from 1 to the square root of the number, call the index "i".
    • if number mod i is 0, add i and number / i to the list of factors.

    realocode:

    public List<int> Factor(int number) {
        List<int> factors = new List<int>();
        int max = (int)Math.Sqrt(number);  //round down
        for(int factor = 1; factor <= max; ++factor) { //test from 1 to the square root, or the int below it, inclusive.
            if(number % factor == 0) {
                factors.add(factor);
                if(factor != max) { // Don't add the square root twice!  Thanks Jon
                    factors.add(number/factor);
                }
            }
        }
        return factors;
    }
    

    As Jon Skeet mentioned, you could implement this as an IEnumerable<int> as well - use yield instead of adding to a list. The advantage with List<int> is that it could be sorted before return if required. Then again, you could get a sorted enumerator with a hybrid approach, yielding the first factor and storing the second one in each iteration of the loop, then yielding each value that was stored in reverse order.

    You will also want to do something to handle the case where a negative number passed into the function.

    Jon Skeet : One extra check to add - the above will add 2 twice :)
    Echostorm : Math.Sqrt returns a double. Also, that needs to be rounded up. Try using 20 as an example.
    Mark Ransom : Rather than taking the square root, you can restructure the loop: for(int factor = 1; factor*factor <= number; ++factor)
    Chris Marasti-Georg : True - and I would imagine there is a point past which performance would degrade for that, since you are calculating it on each loop? It is probably not as significant as other parts of the loop. Benchmarking would have to be performed, I suppose.
    Echostorm : cool idea Mark. you have to test against factor * factor != x when you're yielding tho.
  • Is this homework? If so, I'd rather walk you through you solving it than just give you an answer.

    Are you aware of the % (remainder) operator? If x % y == 0 then x is divisible by y. (Assuming 0 < y <= x)

    I'd personally implement this as a method returning an IEnumerable<int> using an iterator block, but that's relatively advanced if you're fairly new to C#.

    From Jon Skeet
  • Linq solution:

    IEnumerable<int> GetFactors(int n)
    {
      Debug.Assert(n >= 1);
      return from i in Enumerable.Range(1, n)
             where n % i == 0
             select i;
    }
    
    Chris Marasti-Georg : This is wrong - it only returns half of them.
    Jay Bazuzi : This only gets you the first 1/2 of factors. e.g., for 10, it would return 1 and 2, but not 5 and 10.
    Jon Skeet : Suggested change: Math.Sqrt will return a double, which won't work with Enumerable.Range. Also that won't return 4 - just 1 and 2.
  • As extension methods:

        public static bool Divides(this int potentialFactor, int i)
        {
            return i % potentialFactor == 0;
        }
    
        public static IEnumerable<int> Factors(this int i)
        {
            return from potentialFactor in Enumerable.Range(1, i)
                   where potentialFactor.Divides(i)
                   select potentialFactor;
        }
    

    Here's an example of usage:

            foreach (int i in 4.Factors())
            {
                Console.WriteLine(i);
            }
    

    Note that I have optimized for clarity, not for performance. For large values of i this algorithm can take a long time.

    From Jay Bazuzi
  • How big is x going to be?

    For small numbers, you can get away with a naive solution, but for larger x it would be useful to implement a better algorithm (Wikipedia describes some).

  • Here it is again, only counting to the square root, as others mentioned. I suppose that people are attracted to that idea if you're hoping to improve performance. I'd rather write elegant code first, and optimize for performance later, after testing my software.

    Still, for reference, here it is:

        public static bool Divides(this int potentialFactor, int i)
        {
            return i % potentialFactor == 0;
        }
    
        public static IEnumerable<int> Factors(this int i)
        {
            foreach (int result in from potentialFactor in Enumerable.Range(1, (int)Math.Sqrt(i))
                                   where potentialFactor.Divides(i)
                                   select potentialFactor)
            {
                yield return result;
                if (i / result != result)
                {
                    yield return i / result;
                }
            }
        }
    

    Not only is the result considerably less readable, but the factors come out of order this way, too.

    Chris Marasti-Georg : Why not just edit the old answer?
    Jay Bazuzi : Because they are two different answers, with differing merit.
    From Jay Bazuzi
  • Wouldn't it also make sense to start at 2 and head towards an upper limit value that's continuously being recalculated based on the number you've just checked? See N/i (where N is the Number you're trying to find the factor of and i is the current number to check...) Ideally, instead of mod, you would use a divide function that returns N/i as well as any remainder it might have. That way you're performing one divide operation to recreate your upper bound as well as the remainder you'll check for even division.

    Math.DivRem http://msdn.microsoft.com/en-us/library/wwc1t3y1.aspx

    From mspmsp
  • Another LINQ style and tying to keep the O(sqrt(n)) complexity

            static IEnumerable<int> GetFactors(int n)
            {
                Debug.Assert(n >= 1);
                var pairList = from i in Enumerable.Range(1, (int)(Math.Round(Math.Sqrt(n) + 1)))
                        where n % i == 0
                        select new { A = i, B = n / i };
    
                foreach(var pair in pairList)
                {
                    yield return pair.A;
                    yield return pair.B;
                }
    
    
            }
    
    From pablito
  • A bit late but the accepted answer does not give the correct results. (at least the 3 different answers does not give the results even if they run in similar time)

    I don't know why there is a limit set at the square root ? It's been a while since I did some math but it seems that we can only divide by two (maybe 3 for odd number to decrease a little bit the runtime?)

        public static IEnumerable<uint> getFactors(uint x)
        {
            uint max = x / 2;
            for (uint i = 1; i <= max; i++)
            {
                if (0 == (x % i))
                {
                    yield return i;
                }
            }
        }
    

Which is recommended: "static public" or "public static"

Hi,

If you have a class member that is static and public. Would you write "static public" or "public static"? I know they are the same. But is there some recommendation / best practice for writing this?

  • I personally would go with public static because it's more important that it's public than that it's static.

    And check this: http://checkstyle.sourceforge.net/config_modifier.html

    As well as this: http://java.sun.com/docs/books/jls/second_edition/html/classes.doc.html (These two links are for Java, but the concept is the same)

    Short version: "public static" is recommended and is far more common.

    From Epaga
  • "public static" is far more common, so you might want to go with that just to increase readability for programmers who never stumbled upon "static public".

  • see this question

    If you download the Microsoft StyleCop Visual Studio addin, it can validate your source code against the rules Microsoft use. It likes the access modifier to come first.

    From Mark Heath
  • When nothing else matters, go with consistency. In this case the rest of the world uses public static, so I'd go with that too just to avoid unnecessary surprise in those reading your code.

How to determine if XElement.Elements() contains a node with a specific name?

For example for the following XML

 <Order>
  <Phone>1254</Phone>
  <City>City1</City>
  <State>State</State>
 </Order>

I might want to find out whether the XElement contains "City" Node or not.

  • Just use the other overload for Elements.

    bool hasCity = OrderXml.Elements("City").Any();
    
    Daud : Thnx. This is the one I wanted.
    jcollum : Or use Descendants("MyNode").Any() if you don't care about where it is in the tree.
    From David B
  • It's been a while since I did XLinq, but here goes my WAG:

    from x in XDocument
    where x.Elements("City").Count > 0
    select x
    

    ;

How to enable buttons when scroll bar hits bottom with Win32?

I'm writing a license agreement dialog box with Win32 and I'm stumped. As usual with these things I want the "accept/don't accept" buttons to become enabled when the slider of the scroll bar of the richedit control hits bottom, but I can't find a way to get notified of that event. The earliest I've been able to learn about it is when the user releases the left mouse button.

Is there a way to do this?

Here's what I tried so far:

  • WM_VSCROLL and WM_LBUTTONUP in richedit's wndproc
  • EN_MSGFILTER notification in dlgproc (yes the filter mask is getting set)
  • WM_VSCROLL and WM_LBUTTONUP in dlgproc.
  • EN_VSCROLL notification in dlgproc

I got so desperate I tried polling but that didn't work either because apparently timer messages stop arriving while the mouse button is down on the slider. I tried both:

  • timer callback (to poll) in dlgproc
  • timer callback (to poll) in richedit's wndproc
  • You need to sub-class the edit box and intercept the messages to the edit box itself. Here's an artical on MSDN about subclassing controls.

    Skizz

    EDIT: Some code to demonstrate the scroll bar enabling a button:

    #include <windows.h>
    #include <richedit.h>
    
    LRESULT __stdcall RichEditSubclass
    (
      HWND window,
      UINT message,
      WPARAM w_param,
      LPARAM l_param
    )
    {
      HWND
        parent = reinterpret_cast <HWND> (GetWindowLong (window, GWL_HWNDPARENT));
    
      WNDPROC
        proc = reinterpret_cast <WNDPROC> (GetWindowLong (parent, GWL_USERDATA));
    
      switch (message)
      {
      case WM_VSCROLL:
        {
          SCROLLINFO
            scroll_info = 
            {
              sizeof scroll_info,
              SIF_ALL
            };
    
          GetScrollInfo (window, SB_VERT, &scroll_info);
    
          if (scroll_info.nPos + static_cast <int> (scroll_info.nPage) >= scroll_info.nMax ||
              scroll_info.nTrackPos + static_cast <int> (scroll_info.nPage) >= scroll_info.nMax)
          {
            HWND
              button = reinterpret_cast <HWND> (GetWindowLong (parent, 0));
    
            EnableWindow (button, TRUE);
          }
        }
        break;
      }
    
      return CallWindowProc (proc, window, message, w_param, l_param);
    }
    
    LRESULT __stdcall ApplicationWindowProc
    (
      HWND window,
      UINT message,
      WPARAM w_param,
      LPARAM l_param
    )
    {
      bool
        use_default_proc = false;
    
      LRESULT
        result = 0;
    
      switch (message)
      {
      case WM_CREATE:
        {
          CREATESTRUCT
            *creation_data = reinterpret_cast <CREATESTRUCT *> (l_param);
    
          RECT
            client;
    
          GetClientRect (window, &client);
    
          HWND
            child = CreateWindow (RICHEDIT_CLASS,
                                  TEXT ("The\nQuick\nBrown\nFox\nJumped\nOver\nThe\nLazy\nDog\nThe\nQuick\nBrown\nFox\nJumped\nOver\nThe\nLazy\nDog"),
                                  WS_CHILD | WS_VISIBLE | ES_MULTILINE | ES_AUTOVSCROLL | WS_VSCROLL | ES_DISABLENOSCROLL,
                                  0, 0, client.right, client.bottom - 30,
                                  window,
                                  0,
                                  creation_data->hInstance,
                                  0);
    
          SetWindowLong (window, GWL_USERDATA, GetWindowLong (child, GWL_WNDPROC));
          SetWindowLong (child, GWL_WNDPROC, reinterpret_cast <LONG> (RichEditSubclass));
          SetWindowLong (child, GWL_ID, 0);
    
          child = CreateWindow (TEXT ("BUTTON"), TEXT ("Go Ahead!"), WS_CHILD | WS_VISIBLE | WS_DISABLED, 0, client.bottom - 30, client.right, 30, window, 0, creation_data->hInstance, 0);
    
          SetWindowLong (window, 0, reinterpret_cast <LONG> (child));
          SetWindowLong (child, GWL_ID, 1);
        }
        break;
    
      case WM_COMMAND:
        if (HIWORD (w_param) == BN_CLICKED && LOWORD (w_param) == 1)
        {
          DestroyWindow (window);
        }
        break;
    
      default:
        use_default_proc = true;
        break;
      }
    
      return use_default_proc ? DefWindowProc (window, message, w_param, l_param) : result;
    }
    
    int __stdcall WinMain
    (
      HINSTANCE instance,
      HINSTANCE unused,
      LPSTR command_line,
      int show
    )
    {
      LoadLibrary (TEXT ("riched20.dll"));
    
      WNDCLASS
        window_class = 
        {
          0,
          ApplicationWindowProc,
          0,
          4,
          instance,
          0,
          LoadCursor (0, IDC_ARROW),
          reinterpret_cast <HBRUSH> (COLOR_BACKGROUND + 1),
          0,
          TEXT ("ApplicationWindowClass")
        };
    
      RegisterClass (&window_class);
    
      HWND
        window = CreateWindow (TEXT ("ApplicationWindowClass"),
                               TEXT ("Application"),
                               WS_VISIBLE | WS_OVERLAPPED | WS_SYSMENU,
                               CW_USEDEFAULT,
                               CW_USEDEFAULT,
                               400, 300, 0, 0,
                               instance,
                               0);
    
      MSG
        message;
    
      int
        success;
    
      while (success = GetMessage (&message, window, 0, 0))
      { 
        if (success == -1)
        {
          break;
        }
        else
        {
          TranslateMessage (&message);
          DispatchMessage (&message);
        }
      }
    
      return 0;
    }
    

    The above doesn't handle the user moving the cursor in the edit box.

    From Skizz
  • Even though it is possible, I don't think you should do it that way - the user will have no clue why the buttons are disabled. This can be very confusing, and confusing the user should be avoided at all costs ;-)

    That's why most license dialogs have radio buttons for accept/decline with decline enabled by default, so you actively have to enable accept.

    Ilya : Every license agreement i seen up to know have this feature.
    Treb : I doubt that. Anyway, my answer stays: Don't do it.
    Graeme Perrow : I wouldn't say every license agreement has it, in fact most I've seen don't. But I have seen some that do, so it certainly is possible.
    Treb : Yup, I've seen the answer above. It can be done, will edit my answer accordingly.
    From Treb
  • Skizz, I did subclass the richedit control and I did intercept messages that Windows sends to that control. I gave examples of that in my original post. For example, when I said that I had looked for WM_VSCROLL in the richedit's wndproc, it meant that I had substituted my own wndproc for the richedit's default wndproc and was intercepting its WM_VSCROLL message.

    Treb, I am trying to do this the conventional way. I'll l look at some more license agreement screens but I think most of them only enable "Accept" when you scroll to the bottom. (I may have been wrong about both buttons starting off disabled, but even if it's only the "accept" button that needs to become enabled, the technical issue is the same.)

    Skizz : The code I posted above works as required using VS2k5. The only real gotcha was that scroll bar position != scroll bar max when the thumb is at the bottom of the scroll bar. The correct test is scroll bar position + page size >= scroll bar max.
    : I don't think you understand the problem.
    : The problem is that as long as the user's finger is holding down the mouse button and the mouse cursor is on the slider, Windows doesn't send WM_VSCROLL to the controls's wndproc.
    From
  • Skizz, in reply to your code example, my original post said that I had already tried that. The first example I gave of things I had tried was this:

    "WM_VSCROLL and WM_LBUTTONUP in richedit's wndproc"

    That's what you're doing in your example -- responding to WM_VSCROLL in the control's wndproc. Once again -- I'm repeating myself -- I tried that already and it doesn't work for this purpose, because the operating system does not send WM_VSCROLL to the control's wndproc while the user is holding the mouse button down with the mouse cursor on the thumb. That's the problem.

    What's the point of telling me to try things that I already said I tried and found not to work?

    Skizz : It really does work! The code also tracks the ScrollInfo.nTrackPos which is updated even if the user has not let go of the mouse button!
    From
  • I would recommend starting up Spy++ and seeing which windows messages are getting sent to where.

    http://msdn.microsoft.com/en-us/library/aa264396(VS.60).aspx

    From jussij
  • Why not use the EM_GETTHUMB message. (Assuming Rich Edit 2.0 or later).

    If you are lucky this bottom position will match EM_GETLINECOUNT.

Do you know a free hosting for ClickOnce apps?

I am developing an application that will be open source, and i want this application to be updatable through ClickOnce (or similar), but i want to implement it from a free hosting, as i don't know the volume of downloads i will have. I would need something like sourceforge or codeplex,a hosting that allows me to see the version and in that case, alert the user that there is another newer version and download it.

  • As far as I see, you can use any web server to host ClickOnce packages. Because of that, using SourceForge could be good, because they do provide you with normal webspace.

    Also see this question for a bit more information about hosting ClickOnce applications on a normal web server like Apache (which, I believe, is used by SourceForge).

    From hangy
  • You'll probably have to add the following to your .htaccess file:

    AddType application/x-ms-application application
    AddType application/x-ms-manifest manifest
    AddType application/octet-stream deploy
    AddType application/vnd.ms-xpsdocument xps
    AddType application/xaml+xml xaml
    AddType application/x-ms-xbap xbap
    AddType application/x-silverlight-app xap
    

    Beyond that, there are no server side requirements for hosting ClickOnce or Silverlight 2.0 applications. (The last 4 types are those that add support for Silverlight).

    From TimothyP
  • In SourceForge the only thing you can do is upload the files, you cannot touch the htaccess, but i think this is not my problem at this moment. I think the only thing i need is a ftp, but i would like it to be a ftp related with open source world or software world. In any case, a free hosting with ftp.

    From netadictos

Custom Error Pages in JBoss

Hey all, This is my first question here!

I'm trying to setup custom error pages in my JBoss RESTful web service. I'm starting with the 400 error, so in my web.xml I've added

<error-page>
 <error-code>400</error-code>
 <location>/400.html</location>
</error-page>

and I've placed 400.html at the root of my war file (I've also tried placing it at the root of WEB-INF). Unfortunately, I keep getting 404's when I'm supposed to get 400's, presumably because JBoss can't seem to find 400.html. Any ideas what I'm doing wrong?

Might it be because my servlets are mapped to the root?

<servlet-mapping>
 <servlet-name>api</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>

if so, what are the alternatives?

Thanks!

  • For posterity: I was able to finally get this working by redirecting errors to a page that Spring MVC had a controller for. The controller just returned a null ModelAndView. Because it was a RESTful service, I really didn't need to have any HTML emitted anyway.

Python file interface for strings

Is there a Python class that wraps the file interface (read, write etc.) around a string? I mean something like the stringstream classes in C++.

I was thinking of using it to redirect the output of print into a string, like this

sys.stdout = string_wrapper()
print "foo", "bar", "baz"
s = sys.stdout.to_string() #now s == "foo bar baz"

EDIT: This is a duplicate of How do I wrap a string in a file in Python?

  • Yes, there is StringIO:

    import StringIO
    import sys
    
    
    sys.stdout = StringIO.StringIO()
    print "foo", "bar", "baz"
    s = sys.stdout.getvalue()
    
    CAdaker : That's it. Thanks.
  • For better performance, note that you can also use cStringIO. But also note that this isn't very portable to python 3.

C#: How to include dependent DLLs?

I am using a 3rd party API which is defined in 2 DLLs. I have included those DLLs in my project and set references to them. So far so good.

However, these DLLs have at least one dependent DLL which cannot be found at runtime. I copied the missing DLL into the project and set the 'Copy to output' flag but without success.

What should I be doing here to tell the project where it should find the dependent DLL?

Clarification I tried adding a reference to the missing DLL but as it wasn't recognised as a .Net component. In desperation, I added it directly to the output folder but without success.

Finally, I installed the API on the PC and it all worked. The installation sets the PATH variable and the DLL is found in the installation folder. But how to tell the project to look in one of its internal folders?

  • When you say you "copied the missing DLL into the project" - do you mean you added a reference to it, or just copied the file? It's probably best to add a reference.

    From Jon Skeet
  • How are you deploying? Just flat files? If so, it should work as long as the file ends up in the project output directory. Does it?

    If you are using another deployment, you will need to tell that engine to include it. This is different for each of msi/ClickOnce/etc.

  • You can either slowly add the downstream dependencies as references to your project. This is cumbersome, and somewhat fragile

    Or your could use a tool like "Depends.exe" from microsoft to inspect your top level assemblies and get a reference list to the dependencies.

    From Jay Mooney
  • It sounds like you need to better understand the third-party library and how it uses its own dependencies. If the installation of the API solves the problem, but copying the files manually does not, then you're missing something. There's either a missing file, or some environment variable or registry entry that's required. Two things that will really help you in this is the depends tool (which is part of the C++ installation) and procmon, which will tell you all the registry keys and files that get used at runtime.

    If you're lucky, it's just a file that you're missing. If that's all it is, you can use the "Build Events" section of the project to copy the needed files to the right location on a successful build. If not, you're going to have to solve this some other way - either by requiring the API be installed, or rolling your own installation project.

404 page that displays requested page

I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem.

How can I obtain the requested URL after the browser is redirected to my custom 404 page. I tried using:

request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server.

But that didn't work.

Any Ideas?

The site is on IIS 6.0. We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's.

  • Update, you actually want to pick up:

    Request.QueryString("aspxerrorpath")
    
    From Kev
  • How about:

    Request.ServerVariables("HTTP_REFERER");
    
    Gthompson83 : Sorry that was a typo. I am using ServerVariables
    From LordHits
  • A lot of the links have changed, but they can be easily corrected by searching for patters in the url

    Rather than send your users to a 404, have you considered using url re-writes? This way your users (and search engines, if that's important to you in this case) will get a 301 or 302 rather than having to go through your 404 handler. It's usually quicker and less stressful on your servers to handle the rewrite at the url level than firing up your code and processing it there.

    Microsoft have released a URL Rewrite Module for IIS 7, and there's a decent introduction to it here and here.

    For IIS 6, there's a good intro here to getting URL rewriting working with it, slightly different than IIS7.

    An example rewrite rule would be

    # $1 will contain the contents of (.*) - everything after new-dir/
    RewriteRule /new-dir/(.*) /find_old_page.asp?code=$1
    

    there are a few hundred pages, so no one is keen on spending the time to create the 301's

    The beauty of rewrite rules is that you don't need to list to explicitly list all of your pages, but can write rules which follow the same pattern. We had to do something similar to this recently, and it's surprising how many of the moved urls could be handled by a couple of simple rules.

    From ConroyP
  • Instead of using a 404 page, I think the proper thing to do would be to redirect with a 301 - Moved Permanently code.

    Gthompson83 : I realize this is kind of a hack, but the client already launched the website and we are looking for a quick fix to the situation. They don't want to dedicate someone for the next day or so to create a few hundred redirects.
    Rich Bradshaw : You don't have to make them manually, just do them using an URL rewrite.
    From Neall
  • I do basically the same thing you ask in a custom 404 error handling page. On IIS 6 the original URL is in the query string. The code below shows how to grab the original URL and then forward the user. In my case I switched from old ASP to new ASP.NET, so all the .asp pages had to be forwarded to .aspx pages. Also, some URLs changed so I look for keywords in the old URL and forward.

    //did the error go to a .ASP page?  If so, append x (for .aspx) and 
    //issue a 301 permanently moved
    //when we get an error, the querystring will be "404;<complete original URL>"
    string targetPage = Request.RawUrl.Substring(Request.FilePath.Length);
    
    if((null == targetPage) || (targetPage.Length == 0))
        targetPage = "[home page]";
    else
    {
         //find the original URL
        if(targetPage[0] == '?')
        {
         if(-1 != targetPage.IndexOf("?aspxerrorpath="))
              targetPage = targetPage.Substring(15); // ?aspxerrorpath=
         else
              targetPage = targetPage.Substring(5); // ?404;
         }
         else
         {
              if(-1 != targetPage.IndexOf("errorpath="))
           targetPage = targetPage.Substring(14); // aspxerrorpath=
              else
          targetPage = targetPage.Substring(4); // 404;
         }
        }    
    
        string upperTarget = targetPage.ToUpper();
        if((-1 == upperTarget.IndexOf(".ASPX")) && (-1 != upperTarget.IndexOf(".ASP")))
        {
         //this is a request for an .ASP page - permanently redirect to .aspx
         targetPage = upperTarget.Replace(".ASP", ".ASPX");
         //issue 301 redirect
         Response.Status = "301 Moved Permanently"; 
         Response.AddHeader("Location",targetPage);
         Response.End();
        }
    
        if(-1 != upperTarget.IndexOf("ORDER"))
        {
                    //going to old order page -- forward to new page
                   Response.Redirect(WebRoot + "/order.aspx");
               Response.End();
        }
    
    From DougN
  • Here's what we do on init on our 404 pages:

    Dim AttemptedUrl As String = Request.QueryString("aspxerrorpath")
    If Len(AttemptedUrl) = 0 Then AttemptedUrl = Request.Url.Query
    AttemptedUrl = LCase(AttemptedUrl)
    CheckForRedirects(AttemptedUrl)
    

    CheckforRedirects then has custom logic to match up old URLs with new URLs.

    I'd argue that this is the preferred approach (as opposed to 301s or URL rewriting) if you have enough information internally to match up a large number of URLs from the old system with the new system - e.g. if you have a table that matches up old IDs with new IDs or something similar.

    If there's a consistent pattern that you can use to map old URLs to new URLs with a regex, though, then URL rewriting would be the way to go.

  • To build on the Rewrites suggestion, Umbraco already uses UrlRewriting.NET and new rewrites can be added to

    \config\UrlRewriting.config
    

    Hope this helps

Why do I get 3 values inserted into my C# combo box instead of just 1?

When reading the registry for file names I get 3 entries loading into my combo box for every 1 registry entry. If I have 1 file listed in the registry I would see :

Combo box values:

c:\file1.txt

<-----Blank here

c:\file1.txt

I have found the problem lies in this code, it hits 'if (previousFiles != null)' 3 times. How should I correct this?

for (int i = 0; i <= 5; i++)
     {
      Object previousFiles = OurKey.GetValue("Files" + i);
        if (previousFiles != null)
         {
                    comboBox1.Items.Add(previousFiles.ToString());
          }
     }

Many thanks Monday morning blues!

  • just add a "break;" after the first comboBox1.Items.Add(). it will leave the loop after the insert (if this is what you want).

    Claudio : That's not correct. He wants to know why he gets duplicates and blank items. Your solution would populate the combobox with one single item instead.
  • Is it a null on an empty string?

    From moogs
  • Looks like the issue is in your GetValue() function. Plus you should check for null and for empty string before adding to the combobox.

    From OJ
  • Assuming this is a string value what you may be seeing is a blank string coming back; it's hard to tell from the code.

    So instead of a null check cast the object first;

    Object previousFiles = OurKey.GetValue("Files" + i) as string;

    Then use

    string.IsNullOrEmpty()

    instead of a plain null check.

    From blowdart
  • Well, it should hit the if() statement 6 times, the comboBox1.Items.Add() statement 3 times. The logical explanation is that the real problem is located in the code that writes the registry keys. Run Regedit.exe to find out what is really stored in these registry key values.

  • Hi everyone, sorry it was in the code that wrote it, I was looking at an old reg key....sorry!

    OJ : So I was right then :)

How do you share configuration information or business rules between languages

I'm looking for best practices for using the same data in different places without repeating yourself - this could include configuration or business rules.

Example 1. Data validation rules where you want to validate on the client using javascript, but you want to make sure by validating on the server.

Example 2. Database access where your web server and your cronjobs use the same password, username.

Ease of processing and a human-readable solution would be a plus.

  • Encode your data in JSON. There's a JSON library for pretty much any language you'd care to think of, or if not, it's pretty easy to code one up. If JSON is not enough, perhaps look at YAML.

    Rafał Dowgird : I think this works well only for Example 2 (data), not for Example 1 (logic).
    Jouni K. Seppänen : If you want to be totally language-agnostic, you will have to encode the logic in some sort of data anyway. Of course you could go all the way and use Lisp S-expressions, so your code *is* data. :-)
    Ken : Thanks Jouni - sorry for the late acceptance. I was holding out for something that would handle example 2 as well, but yours is a good fit for now.
  • XML is pretty globally used. Easy to read, easy to write, and human readable. If you're concerned about the space overhead (which you actually aren't if you want human readable) then just compress it before you send it out, XML compresses quite well.

    Brad Gilbert : Text files all generally compress well.
    From tloach
  • See answers to this question. I think they are applicable here, especially the one with a DSL.

  • As much hate as they get, for sharing data validation rules, I'm going to have to say Regular Expressions.

    I know, I know, everyone hates them, but they are (generally) language-agnostic.

    Brad Gilbert : They're language-agnostic, only if you use a small subset of features.
    From R. Bemrose

What is the best way for a process inside a VirtualPc to talk to a process on the host?

I have Virtual PC 2007. I am writing a C# program that will run on the Host and Virtual. It needs to communicate both ways.

What is the best way to do this?

Can it be done in a way that does not require changing Virtual settings?

(the OSs will be XP, Vista, Server 2000 / 2003)

  • Via TCP. Simple client/server setup.

    or

    .NET Remoting

  • WCF. .NET Remoting without the calls to the suicide prevention hotline.

    GavinCattell : Good to know, suicide prevention hotline calls should be prevented if possible :)
    From Will
  • WCF is definitely the way to go. Whether or not is requires changing the virtual settings depends on how your virtual machine is set up.

    The most secure way would be to create a new private network that just the host and guest can access. That way you don't have to worry about changing any firewall settings on your main network interface to allow the server and client to communicate.

    OTOH if security isn't a concern then the standard bridged networking options for the guest will work fine.

    From Rob Walker

Does the computer science/software engineering field have a standardized citation format?

Wikipedia provides a number of citations used in the sciences, however does one stand out in computer science and software engineering related documents? My initial guess is to the IEEE format, as they have a number of conferences and publications related to both fields, but I couldn't find anything definite.

  • Typically in college for Com Sci you will be using the MLA citation standards at least from what I have found here in the US.

    Thomas Owens : Hmm. That's good to know, especially since I never had to write a report that involved research for a CS or SE course.
    Dave DuPlantis : My SE courses are similar: no assignments that required research (yet).
  • You'll usually see APA style or MLA style citations used in university CS departments in the US. MLA has been more widely used in the past because it has been used in journalism for years, but APA is gaining ground in academics (not only in CS, but in many fields).

  • I think I used both APA and MLA styles at different points. Unlike journalism or psychology, there isn't a defined standard, so it will probably depend the most on the school/professors that you have.

    From chills42
  • Whatever LaTeX happens to generate. Since there's no standard, I go with the most convenient one.

  • I've always used APA style when I write things on paper, but my preferred form is the hyperlink. This is CS, after all :)

    From rmeador
  • Follow the standards of the publication you plan on submitting to. All conferences and journals should have formatting information available during the submission process, and will often even provide LaTeX stubs that you can work off of.

    If you're just doing a paper for a class, check with your professor if there's a publication's formatting style they prefer, and if they don't have one, feel free to pick your own out of the stubs you can get a hold of.

    The big takeaway here is that if you're worrying about measuring margins and placing commas, you're either reinventing the wheel, not using LaTeX, or probably both, and if you're serious about participating in the academic side of CS, it's something you should learn as soon as possible.

Removing entry of an application from add/remove programs in c#

Hi,

I have developed an installer class which removes certain folders from the base dir.However,I also want to remove the entry of another application from add/remove programs through the inst class.Could anyone suggest the solution.

Regards, Harsh Suman

C# - Placing a PDF inside another PDF

I have multiple logos of various companies in various formats that needs to be added to other PDFs. The format of these logos is not specified at the moment but it could be locked down to only certain formats if it causes issues.

These other PDFs will be mostly posters and will be printed off by the user.

Question: What is the best way for adding these logo's onto the PDF poster artwork on the fly to then be downloaded and printed by the user? Bareing in mind it needs to retain the original quality of the PDF when being printed.

Thanks in advance

  • See at my answer to a similar question. In short, I've used itextsharp to add watermark(s) to an existing PDF.

    From gimel
  • Thanks gimel, I've just had a quick look through and I've spotted an example of what I would need to do.

    Can you let me know if you can add a watermark anywhere within a pdf document? e.g. specify the location by pixel or something to that effect.

    Also I presume the quality of whatever comes out is dependant on what you upload? There is no degredation is what I am saying?

    Thanks

    gimel : In my case, positioning was by pixels. Regarding quality, I've only generated text, so I can't say about images. See comments in the referenced answer, others maybe able to help.
    jcollum : THis should be in a comment, not an answer.
    From John_
  • PDFSharp is a free library that can do this. These watermarking examples should help you get started.

How to map multiple records using SqlMap in Ibatis

I am just getting into ibatis with SqlMap for the first time and I have run into a problem. I have figured out how to insert, delete, update, and select single records. Now however I am trying to write a select statement that will bring back more than a single record and I am getting mapping errors. How do I specify that the result should be a List of my custom objects?

  • I've figured it out. Using java I simply had to use the queryForList function instead of queryForObject.

Why do I get web exception when creating an XPathDocument?

Creating an XPathDocument with referenced DTD sometimes throws a web exception. Why?

  • See http://todotnet.com/archive/2006/07/27/8248.aspx

    Because in the construction of XPathDocument, there's an http GET command to see if it can access the DTD. It's not doing anything with the DTD. It's for just in case. So while XPathDocument is initially set up to be a faster alternative to XmlDocument, you'll have the additional overhead of an http request that needs to be resolved. Imagine that server being on the other side of the globe!

    From Goran
  • You can write a custom XmlUrlResolver and then ignore the remote DTD. Also, I believe you can set use XmlResolver = null on the XmlTextReader.

    Goran : But the MSDN should clearly state this might happen. Looking at the XPathDocument you can't tell it will look for DTD on the web. Also why is the exception thrown? If DTD is not needed - works offline doesn't it? Thanks for the suggestions anyway - I'll try them next time!
    From duckworth