Thursday, February 17, 2011

Web splitter control: where to get one

I have an ASP.NET web project that has a requirement to have a "splitter" like functionality in order to hide the left/right margins of a page. I would like to avoid frames and am not able to use the Infragistics controls.

I have installed the trial version of Obout.com's Splitter control(http://www.obout.com/splitter/) and it works GREAT! However, there's virtually no budget for this.

Does anyone know of a good splitter control available for web apps?

Your insight is appreciated!

From stackoverflow

How to stop BaseHTTPServer.serve_forever() in a BaseHTTPRequestHandler subclass?

The python documentation states that BaseHTTPServer.HTTPServer is a subclass of SocketServer.TCPServer, which dows support a shutdown method - but it is missing in HTTPServer.

I am running my HTTPServer in a separate thread (using the threading module which has no way to stop threads...) and want to stop serving requests when the main thread also shuts down.

The whole BaseHTTPServer module has very little documentation :(

From stackoverflow
  • I should start by saying that "I probably wouldn't do this myself, but I have in the past". The serve_forever (from SocketServer.py) method looks like this:

    def serve_forever(self):
        """Handle one request at a time until doomsday."""
        while 1:
            self.handle_request()
    

    You could replace (in subclass) while 1 with while self.should_be_running, and modify that value from a different thread. Something like:

    def stop_serving_forever(self):
        """Stop handling requests"""
        self.should_be_running = 0
        # Make a fake request to the server, to really force it to stop.
        # Otherwise it will just stop on the next request.
        # (Exercise for the reader.)
        self.make_a_fake_request_to_myself()
    

    Edit: I dug up the actual code I used at the time:

    class StoppableRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer):
    
        stopped = False
        allow_reuse_address = True
    
        def __init__(self, *args, **kw):
            SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, *args, **kw)
            self.register_function(lambda: 'OK', 'ping')
    
        def serve_forever(self):
            while not self.stopped:
                self.handle_request()
    
        def force_stop(self):
            self.server_close()
            self.stopped = True
            self.create_dummy_request()
    
        def create_dummy_request(self):
            server = xmlrpclib.Server('http://%s:%s' % self.server_address)
            server.ping()
    
    Jeff Hammerbacher : I think you can call "self.serve_forever()" after "self.stopped = True" and avoid implementing "create_dummy_request(self)". It's worked for me so far, but there may be a subtlety that I'm missing.
  • In my python 2.6 installation, I can call it on the underlying TCPServer - it still there inside your HTTPServer:

    TCPServer.shutdown
    
    
    >>> import BaseHTTPServer
    >>> h=BaseHTTPServer.HTTPServer(('',5555), BaseHTTPServer.BaseHTTPRequestHandler)
    >>> h.shutdown
    <bound method HTTPServer.shutdown of <BaseHTTPServer.HTTPServer instance at 0x0100D800>>
    >>>
    
    Daren Thomas : ah. yes, and I *am* reading the 2.6 docs - alas, I'm running 2.5. Bummer. Me idiot.
  • I think you can use [serverName].socket.close()

Where does DLLImport look for unmanaged DLLs?

A quick question: When declaring the DLLImport Attribute in .Net, where does the runtime look to resolve that DLL dependency? Would I have to dump the DLL and all of its dependencies in the bin folder?

From stackoverflow

Call a specific button onClick event when the enter key is pressed C#

Hey,

I'm trying to get a specific asp:button onclick event to fire when I press the enter key in a specific asp:textbox control.

The other factor to be taken into account is that the button is within a asp:Login control template.

I've no idea how to do this, suggestions on a postcard please.

From stackoverflow
  • You need to do it with javascript. It's really easy with jQuery.

    You can do something like (off the top of my head, not tested):

    $('#myTextBox').keypress(function(e){
        if(e.which == 13)
            $('#myBtn').click();
    });
    

    Edit: Be aware that although jQuery works exceptionally cross browser, there are some quirks with keypress described here.

    Whoops i didnt see you said the "enter key" i thought you said "any key", yeah in that case use DefaultButton on asp:panel

    David Kemp : You don't need to do this with javascript.
  • You could look at the DefaultButton property of the panel control.

  • Its HtmlForm.DefaultButton

  • You could set the DefaultButton property on the form. Either as an attribute of the form tag in your markup DefaultButton = "btnSubmit" or using something like this in your code-behind:

    Page.Form.DefaultButton = "btnSubmit"
    

How to debug a disappearing app

On a Windows 2003 server I have a pure .NET 3.5 C# app (no unmanaged code). It connects to various other remote systems via sockets and acts like a data hub. It runs for 10-15 hours fine with no problem but from time to time it just disappears. If I watch the app using task manager the memory usage remains constant.

In the Main() function I wrap the invocation of the rest of the app in a try..catch block which it just blows completely past - the catch block which logs the exception to a file is ignored. If I manually raise an exception for testing, the catch block is invoked.

Prior to entering the try..catch I do ....

Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

The system has Dr. Watson on it, but nothing gets written in the directory DRWTSN32.EXE is pointing to.

How can I catch whatever exception is causing this?

From stackoverflow
  • If it's a Windows Forms application, you could try Application.ThreadException.

  • Try using the debugging tools from microsoft. You can download them from here.

    Use adplus to capture the crash and then windbg to analyze it.

    adplus -crash -pn your.exe -quiet

    Lots of great info about debugging on windows on this blog.

    Pure.Krome : Tess' blog is a goldmine of debugging information. The net would be a lot darker if she didn't tell us the secrets to .NET debugging.
  • If this is a Windows Forms app, then it's likely that the unhandled exception is being caught by the window message pump, which is why you never see it. To deal with this, see my answer here.

    If it's a Windows service, then the exception might be appearing on a background thread and not being marshalled back to your main thread. To deal with this, you need to marshal any background thread back to your main thread, and the exception will be re-thrown there so that you can catch it.

    If it's a console app, then I'm a bit mystified.

    EDIT: Your comment says this is a Windows Forms app. In that case, you're probably not seeing the exception because it's being handled by the built-in Windows Forms exception handler that does the following by default:

    • Catches an unhandled managed exception when:
      • no debugger attached, and
      • exception occurs during window message processing, and
      • jitDebugging = false in App.Config.
    • Shows dialog to user and prevents app termination.

    You can disable this behaviour by setting jitDebugging = true in App.Config. Then you should be able to see the unhandled exception by registering for the event Application.ThreadException, e.g. in C#:

    Application.ThreadException += new Threading.ThreadExceptionHandler(CatchExceptions);
    
    rc1 : It's a winforms app with one form
  • You could also attach WinDBG at startup and enable breakpoints on .NET exceptions. You can then do a !printexception to see what is going on.

  • There might be trace of the application in the EventLog.

    I have had a .Net app disappear without the possibility to catch an Exception. There was an entry in the EventLog every time this happened.

    To view the eventlog just type EventVwr on the command prompt, or run box.

    Deestan : The submitter might not be aware of the existence of the EventLog. Mayhaps add a hint on how to access it.
    GvS : Thx for the remarks. Changed.

Getting array subsets efficiently

Is there an efficient way to take a subset of a C# array and pass it to another peice of code (without modifying the original array)? I use CUDA.net which has a function which copies an array to the GPU. I would like to e.g. pass the function a 10th of the array and thus copy each 10th of the array to the GPU seperately (for pipelining purposes).

Copying the array in this way should be as efficient as copying it in one go. It can be done with unsafe code and just referencing the proper memory location but other than that I'm not sure. The CopyTo function copies the entire array to another array so this does not appear useful.

From stackoverflow
  • I'm not sure how efficient this is but...

    int[] myInts = new int[100];
    
    //Code to populate original arrray
    
    for (int i = 0; i < myInts.Length; i += 10)
    {
        int[] newarray = myInts.Skip(i).Take(10).ToArray();
        //Do stuff with new array
    }
    
  • You could use extension methods and yield return:

    public static IEnumerable Part<T>(this T[] array, int startIndex, int endIndex )
    {
        for ( var currentIndex = startIndex; currentIndex < endIndex; ++currentIndex )
            yield return array[currentIndex];
    }
    
  • Okay, I'd misunderstood the question before.

    What you want is System.Buffer.BlockCopy or System.Array.Copy.

    The LINQ ways will be hideously inefficient. If you're able to reuse the buffer you're copying into, that will also help the efficiency, avoiding creating a new array each time - just copy over the top. Unless you can divide your "big" array up equally though, you'll need a new one for the last case.

  • You could try Marshal.Copy if you need to go from an array of bytes to an unmanaged pointer. That avoids creating unsafe code yourself.

    Edit: This would clearly only work if you reimplement their API. Sorry - misunderstood. You want an efficient subarray method.

    It strikes me that what you really want is an api in the original class of the form

    void CopyToGpu(byte[] source, int start, int length);
    

Are CAs allowed to modify CSRs before signing?

Can anyone please tell me if Certifying Authorities (CAs) are allowed to make modifications to the Certificate Signing Request (CSR) before actually signing the certificate with their own private key?

Specifically, I'd like to know if it's valid for the CA to insert additional fields (such as EKUs) into the cert before adding their signature.

From stackoverflow
  • I can't speak about CAs in general, but I once ran a Windows Server 2003 network with its own CA, and it's definitely possible to make certreq (through the -attrib option) add additional fields to the CSR before it gets to the CA. Thus, it looks to me like it's possible for the CA itself to do much the same thing.

    Your mileage may vary.

  • Yes

    The Certificate Authority is responsible for enforcing the organisations PKI security policy via its policy files and templates. This may include EKU (extended key usage) attributes.

    In reality you are requesting a certificate of a certain type from the CA on behalf of your subject. It is up to the CA to enforce the type of certificates (and the associated uses) that it will issue.

    The CA is not actually modifying the request so much as issuing a cert of a permitted type.

Exception vs Validation

I've just come across a property setter that catches exceptions (all Exceptions; I know that's bad, but it's not relevant here), and only logs them. First of all, I think it should through them again as well; why wait for a crash and a log study when you can know something is wrong right away?

However, my main question is, do I validate against invalid date values, add a RuleViolation object to a ValidationRules object on my document, or throw an InvalidDate exception, or just let the CLR throw the exception for me (invalid dates are nothing but invalid dates, not checked for range etc.)

From stackoverflow
  • Catching and rethrowing is the worst thing to do. Its expensive to TRY, if youre just going to rethrow what the point? You can catch unhandled exceptions with the global.asax for example if you need to log them.

    In terms of validation, from a web perspective i always use regex validators for dates, these fire client and server side so i know when im inside an

    if(Page.IsValid)
    

    block that my txtDate.Text is a valid date, so i dont bother checking because its just wasteful.

  • It depends on the specific task at hand. If you are writing a library class that will be used as a component in other programs and the contract of the method of the class says that it should only accept valid dates then throwing the Exception is fine.

    If you are accepting user input and then waiting for an exception is a bad practice. In this case you should validate the date yourself.

    Exceptions are for exceptional cases, and should not be part of your logic. It usually means that a contract was broken by the programmer.

  • It really depends on the logic of your application. Exceptions should only really be thrown for circumstances that are exceptional. For something like validation it depends on the tolerance for invalid data.

    When you are building an interractive application and the user may enter anything, it is probably ok that the document gets into an invalid state and you should expose validation information via properties on the document class.

    If you are processing pre-prepared documents from a database or log file then it probably isn't ok for the document to be invalid and continuing to operate after that might corrupt data in the system. When that happens you should throw.

  • I think it depends where the date values come from. If it comes from user input or some other source where it is perfectly well possible to enter 'invalid' dates, then validation would be the way to go. On the other hand, if there is no foreseeable reason why the data values might be invalid, then throwing an exception is appropriate.

  • Exceptions should be thrown whenever the method or class member is unable to complete whatever task it is designed to accomplish.

    So for a property setter, if the setter is unable to set the property, then it should throw an exception.

    As to whether you should catch it and rethrow it, the answer is yes, but only if you need to process the exception immediately in the setter, before passing it up the stack... but logging it is not a reason to do that. In general, you should implement cross-cutting logging of exceptions at a higher level, where the exception is NOT going to be re-thrown... if you are taking care of those cross-cutting concerns higher up the stack somewhere, then no, definitely do not catch and re-throw the same exception.

    However, if you are writing a tool, or a framework library, where you want your component's clients to have a clearly defined set of expected exceptions, and you have defined your own custom exceptions that your component will throw to client code, and which client components will expect to see, then you may want to catch CLR generated exceptions and rethrow your own custom exceptions instead.. Always include the Actual underlying exception in your custom exceptions "InnerException" property before passing it up the stack, so that the data in it is available to whatever system end up consuming it.

Hooking sycalls from userspace on Linux

Is there any way to catch all syscalls on Linux? The only solution I know of is using LD_PRELOAD à la fakeroot, but that only works for dynamically linked applications. Furthermore, this approach requires enumerating all syscalls which is something I'd like to avoid.

From stackoverflow
  • You can trace a program. Think about how strace works. Hint: it doesn't use LD_PRELOAD tricks.

  • I think you are looking for ptrace(2).

How do I add attributes to a method at runtime?

We're using Microsoft.Practices.CompositeUI.EventBroker to handle event subscription and publication in our application. The way that works is that you add an attribute to your event, specifying a topic name, like this:

[EventPublication("example", PublicationScope.Global)]
public event EventHandler Example;

then you add another attribute to your handler, with the same topic name, like this:

[EventSubscription("example", ThreadOption.Publisher)]
public void OnExample(object sender, EventArgs e)
{
    ...
}

Then you pass your objects to an EventInspector which matches everything up.

We need to debug this, so we're trying to create a debug class that subscribes to all the events. I can get a list of all the topic names... but only at runtime. So I need to be able to add attributes to a method at runtime, before we pass our debug object to the EventInspector.

How do I add attributes to a method at runtime?

From stackoverflow
  • Attributes are a compile-time feature (unless you are dealing with ComponentModel - but I suspect it is using reflection). As such, you cannot add attributes at runtime. It would a similar question to "how do I add an extra method to a type at runtime?". In regular C# / .NET (pre-DLR), you can't.

    Bogdan Maxim : Actually, it can be done by mixing Dynamic Assemblies and normal assemblies. .NET 2.0 Has support for them, and you don't need to use DLR just for this.
    Marc Gravell : @Bogdan - but that still doesn't allow you to add attributes to an existing type/member.
  • You need to delve into the world of the DynamicMethod. However, as you need then to know MSIL, I really suggest you think hard about your architecture.

    Bogdan Maxim : Maybe his architecture is dynamic, aiming to provide services to multiple types, at runtime. It's not uncommon, and it is actually recommended if you want to have a modular system.
  • What you are trying to achieve is quite complicated, so I will try to provide something just to get you started. This is what I think you would need to combine in order to achieve something:

    1. Define an abstract class AbstractEventDebugger, with a method Search that searches all of the event members, and registers them with the EventInspector. Also, define a method IdentifyEvent that will allow you to identify the event that has called it (this depends on you - what parameters will have, etc.).
    2. Define a dynamic type using TypeBuilder (as described here), that inherits from your class. This class would be the class of your debugger object.
    3. Attach the Handlers to your class using Reflection.Emit.MethodBuilder (see here), which will be calling the IdentifyEvent method from the parent class and,
    4. Reflection.Emit the attributes on the handlers using CustomAttributeBuilder class (see here).
    5. Create an instance of your dynamic class and send it to the EventInspector.
    6. Fire it up :)

    Here is a sample on how to create a method that calls something (Actually it's the classic "Hello world").

    You will need to do a lot of tweaking in order to get it done well, but you will learn a lot about reflection.

    Good luck!

  • The EventInspector uses EventTopics (which are stored in the WorkItem) to do all the heavy lifting. Each EventTopic object has access to a TraceSource called

    Microsoft.Practices.CompositeUI.EventBroker.EventTopic

    Which you can enable in your app.config file like this:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
        <system.diagnostics>
         <switches>
          <add name="Microsoft.Practices.CompositeUI.EventBroker.EventTopic" value="All" />
         </switches>
        </system.diagnostics>
    </configuration>
    

    This should make plenty of useful messages get routed to your debug window in Visual Studio. If you want to go beyond the VS debug window you have plenty of options. I'd recommend checking out the following article:

    Code Instrumentation with TraceSource My Persoanl Vade Mecum

How to open a new tab and change the current page

<form id="frm_1" name="frm_1" target="_self" method="GET" action="local_page.php" >
</form>
<form id="tgt_1" name="tgt_1" target="_blank" method="POST" action="http://stackoverflow.com/" >
</form>
<a onclick="test(event, '1'); " href="#" >Click Here</a>
<script>
    function test(event, id){
        document.getElementById("frm_"+id).submit;
        document.getElementById("tgt_"+id).submit;
    }
</script>

Is it possible to open a new tab/window and change the current page ?

From stackoverflow
  • As far as I know, it's not possible to submit two forms at once. Since you're using PHP however, why not take a look at the cURL library? It lets you send POST and GET requests and parse the results in PHP.

    To answer the question in the title, if you simply want to open two pages with one click, you could do it like this (excuse the inline javascript):

    <a
        href="http://www.google.com"
        target="_blank"
        onclick="document.location.href='http://www.yahoo.com'"
    >Click here to open Google in a new window and yahoo in this window</a>
    
  • You should use the window.open to open the new page and then submit the tabchange e.g.

    <form id="frm_1" name="frm_1" target="_self" method="GET" action="local_page.php" >
    </form>
    <a onclick="test(event, '1'); " href="#" >Click Here</a>
    <script>
        function test(event, id){
            window.open("http://stackoverflow.com/", "_blank");
            document.getElementById("tgt_"+id).submit();
        }
    </script>
    
  • Use the ‘target’ attribute on the form elements to make them submit to eg. a new window or an iframe, without reloading the current page (breaking any other form submissions).

    Your a.onclick should also return false to stop the href link being followed. Really this should be a button not a link.

    Avoid this sort of stuff unless you've got a specific good reason. Depending on what you're actually trying to do there is usually a better way.

  • Still trying this end.

    Usage of <a> was to have the browser status bar show the href url.

    My original code works when the href param is href="local_page.php" and only document.getElementById("tgt_"+id).submit; exists.

    BUT this means that I am unable to POST to the local page any info about the chosen option.

    In this case using GET and appending parameters is not an option.

  • <form id="frm_1" name="frm_1" target="_self" method="POST" action="local_page.php" >
    <input type="hidden" name="vital_param" value="<?= $something ?>">
    </form>
    
    <form id="tgt_1" name="tgt_1" target="_blank" method="POST" action="http://stackoverflow.com/" >
    </form>
    
    <button type="submit" onclick="test(event, '1'); " >Click Here</button>
    
    <script>
        function test(event, id){
        window.open( document.getElementById("tgt_"+id).action, "_blank");
        setTimeout('document.getElementById("frm_'+id+'").submit();', 1000);
    
        return true;
        }
    </script>
    

    tgt kept as source of target url, could be array or attribute. Without setyTimeout() browser stays on current page (FF/IE).

Bidirectional 1 to 1 Dictionary in C#

I am looking for a generic, bidirectional 1 to 1 Dictionary class in C# (2), ie. a BiDictionaryOneToOne<T, S> which is guaranteed to only contain one of each value and key (up to RefEquals anyway), and which can be searched using either key or value. Anyone know of one, or should I just implement it myself? I can't believe that I'm the first person to need this...

There is a BiDictionary in the answers to this question, but it is not for unique elements (and also does not implement RemoveByFirst(T t) or RemoveBySecond(S s)).

Thanks!

From stackoverflow
  • A simple container class with 2 Dictionary's should work just fine IMO.

    Update: Do you require uniqueness on every 'column' or across all of them (like a composite primary key)?

  • The question you refer to also shows a one-to-one implementation in this answer. Adding RemoveByFirst and RemoveBySecond would be trivial - as would implementing extra interfaces etc.

    Joel in Gö : OK, fair enough, I have done so. I will add it to the answers when I've finished the unit tests...
  • I have created such a class, using C5 collection classes.

    public class Mapper<K,T> : IEnumerable<T>
    
    {
        C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();
        C5.HashDictionary<T,K> TToKMap = new HashDictionary<T,K>();
    
    
        /// <summary>
        /// Initializes a new instance of the Mapper class.
        /// </summary>
        public Mapper()
        {
            KToTMap = new TreeDictionary<K,T>();
            TToKMap = new HashDictionary<T,K>();
        }
    
    
        public void Add(K key, T value)
        {
            KToTMap.Add(key, value);
            TToKMap.Add(value, key);
        }
    
        public bool ContainsKey(K key)
        {
            return KToTMap.Contains(key);
        }
    
        public int Count
        {
            get { return KToTMap.Count; }
        }
    
    
        public K this[T obj]
        {
            get
            {
                return TToKMap[obj];
            }
        }
    
        public T this[K obj]
        {
            get
            {
                return KToTMap[obj];
            }
        }
    
        public IEnumerator<T> GetEnumerator()
        {
            return KToTMap.Values.GetEnumerator();
        }
    
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return KToTMap.Values.GetEnumerator();
        }
    }
    
  • OK, here is my attempt (building on Jon's - thanks), archived here and open for improvement :

    /// <summary>
    /// This is a dictionary guaranteed to have only one of each value and key. 
    /// It may be searched either by TFirst or by TSecond, giving a unique answer because it is 1 to 1.
    /// </summary>
    /// <typeparam name="TFirst">The type of the "key"</typeparam>
    /// <typeparam name="TSecond">The type of the "value"</typeparam>
    public class BiDictionaryOneToOne<TFirst, TSecond>
    {
        IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
        IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
    
        #region Exception throwing methods
    
        /// <summary>
        /// Tries to add the pair to the dictionary.
        /// Throws an exception if either element is already in the dictionary
        /// </summary>
        /// <param name="first"></param>
        /// <param name="second"></param>
        public void Add(TFirst first, TSecond second)
        {
            if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))
                throw new ArgumentException("Duplicate first or second");
    
            firstToSecond.Add(first, second);
            secondToFirst.Add(second, first);
        }
    
        /// <summary>
        /// Find the TSecond corresponding to the TFirst first
        /// Throws an exception if first is not in the dictionary.
        /// </summary>
        /// <param name="first">the key to search for</param>
        /// <returns>the value corresponding to first</returns>
        public TSecond GetByFirst(TFirst first)
        {
            TSecond second;
            if (!firstToSecond.TryGetValue(first, out second))
                throw new ArgumentException("first");
    
            return second; 
        }
    
        /// <summary>
        /// Find the TFirst corresponing to the Second second.
        /// Throws an exception if second is not in the dictionary.
        /// </summary>
        /// <param name="second">the key to search for</param>
        /// <returns>the value corresponding to second</returns>
        public TFirst GetBySecond(TSecond second)
        {
            TFirst first;
            if (!secondToFirst.TryGetValue(second, out first))
                throw new ArgumentException("second");
    
            return first; 
        }
    
    
        /// <summary>
        /// Remove the record containing first.
        /// If first is not in the dictionary, throws an Exception.
        /// </summary>
        /// <param name="first">the key of the record to delete</param>
        public void RemoveByFirst(TFirst first)
        {
            TSecond second;
            if (!firstToSecond.TryGetValue(first, out second))
                throw new ArgumentException("first");
    
            firstToSecond.Remove(first);
            secondToFirst.Remove(second);
        }
    
        /// <summary>
        /// Remove the record containing second.
        /// If second is not in the dictionary, throws an Exception.
        /// </summary>
        /// <param name="second">the key of the record to delete</param>
        public void RemoveBySecond(TSecond second)
        {
            TFirst first;
            if (!secondToFirst.TryGetValue(second, out first))
                throw new ArgumentException("second");
    
            secondToFirst.Remove(second);
            firstToSecond.Remove(first);
        }
    
        #endregion
    
        #region Try methods
    
        /// <summary>
        /// Tries to add the pair to the dictionary.
        /// Returns false if either element is already in the dictionary        
        /// </summary>
        /// <param name="first"></param>
        /// <param name="second"></param>
        /// <returns>true if successfully added, false if either element are already in the dictionary</returns>
        public Boolean TryAdd(TFirst first, TSecond second)
        {
            if (firstToSecond.ContainsKey(first) || secondToFirst.ContainsKey(second))
                return false;
    
            firstToSecond.Add(first, second);
            secondToFirst.Add(second, first);
            return true;
        }
    
    
        /// <summary>
        /// Find the TSecond corresponding to the TFirst first.
        /// Returns false if first is not in the dictionary.
        /// </summary>
        /// <param name="first">the key to search for</param>
        /// <param name="second">the corresponding value</param>
        /// <returns>true if first is in the dictionary, false otherwise</returns>
        public Boolean TryGetByFirst(TFirst first, out TSecond second)
        {
            return firstToSecond.TryGetValue(first, out second);
        }
    
        /// <summary>
        /// Find the TFirst corresponding to the TSecond second.
        /// Returns false if second is not in the dictionary.
        /// </summary>
        /// <param name="second">the key to search for</param>
        /// <param name="first">the corresponding value</param>
        /// <returns>true if second is in the dictionary, false otherwise</returns>
        public Boolean TryGetBySecond(TSecond second, out TFirst first)
        {
            return secondToFirst.TryGetValue(second, out first);
        }
    
        /// <summary>
        /// Remove the record containing first, if there is one.
        /// </summary>
        /// <param name="first"></param>
        /// <returns> If first is not in the dictionary, returns false, otherwise true</returns>
        public Boolean TryRemoveByFirst(TFirst first)
        {
            TSecond second;
            if (!firstToSecond.TryGetValue(first, out second))
                return false;
    
            firstToSecond.Remove(first);
            secondToFirst.Remove(second);
            return true;
        }
    
        /// <summary>
        /// Remove the record containing second, if there is one.
        /// </summary>
        /// <param name="second"></param>
        /// <returns> If second is not in the dictionary, returns false, otherwise true</returns>
        public Boolean TryRemoveBySecond(TSecond second)
        {
            TFirst first;
            if (!secondToFirst.TryGetValue(second, out first))
                return false;
    
            secondToFirst.Remove(second);
            firstToSecond.Remove(first);
            return true;
        }
    
        #endregion        
    
        /// <summary>
        /// The number of pairs stored in the dictionary
        /// </summary>
        public Int32 Count
        {
            get { return firstToSecond.Count; }
        }
    
        /// <summary>
        /// Removes all items from the dictionary.
        /// </summary>
        public void Clear()
        {
            firstToSecond.Clear();
            secondToFirst.Clear();
        }
    }
    
    Jon Skeet : Why "i32NoOfPairs" instead of just Count?
    Joel in Gö : oops, true; edited.
    Peter M : As a suggestion I think for greater robustness you need to treat all the operations as the equivalent of an SQL transaction. For example, what happens to the overall dictionary state in Add(), if the firstToSecond.Add() throws an exception?
    Peter M : Oops - that should been about what happens if secondToFirst,Add() fails/throws an exception.
    Joel in Gö : When would Dictionary throw an exception? If the alternative is to keep a copy of the pre-Add dictionaries in case of Exception, in order to replace them in a finally block for example, then perhaps it is ok to just let it fail without check. Or check in a finally block and throw Exception on fail?

Is it OK to return a KeyValuePair from a .NET function?

I was just working on a function that I needed to return two values, one being a column name and one being the value of that column for that current row. I am returning KeyValuePair(of String,Object). I was wondering if this is a good idea or does it make it hard to read/use?

From stackoverflow
  • If it genuinely is a key-value pair, then that seems a pretty reasonable thing to do. .NET 4.0 will include a proper Tuple class for cases where there isn't a key-value relationship.

    The alternative is to use out/ref parameters, letting the caller decide whether or not to keep the values together - but I prefer the KeyValuePair approach when there's an obvious relationship and the caller is likely to want to keep them combined.

    Wolfbyte : If there is no KVP relationship then just create your own simple class encapsulating what you are returning. In the sample provided KeyValuePair seems OK.

Where do you draw the line between design and architecture ?

The Agile architecture question makes me wonder this.

Does it depends of what is being build ? Do applications (I mean single computing program here) have an architecture ?

UPDATE: to try to clarify the question, I'll give my opinion on the question: I defined the architecture as the cutting of the system in components, and the relationships between the components ;while the design is about the interns of the component. Is this opinion shared ?

From stackoverflow
  • It is purely subjective. Whatever the dev lead or architect says is the truth.

  • Interesting answers in this Joel's thread forum

    One of the funniest:

    In my experience, about $30k.
    

    One of the shortest:

    I would say that "design" is what is done to achieve an architecture
    

    Architecture can cover issues beyond the scope of design, such as an entire line of products, or a range of versions of a single product. Architecture also deals with the famous "ilities", such as testability, upgradability, reliability, availability etc etc.

    You will find in SEI further definitions of Software Architecture where design is mentionned.

    Chii : LOL @ the $30k comment!
    peterchen : .. and the "shortest" pretty much sums it up.
  • It's really fairly simple: architecture is about the design decision you make to meet the "non-functional" requirements: requirements like cost, maintainability, performance, reliability, availability, and security. This about a web application: you can build it in a zillion ways, from a big C program that runs as a CGI (really, we used to do that), a Python webapp, to a J2EE application, to a LAMP application. Any of them would have the same functional behavior, they all would post the same pages; the differences come in when you try to change the C program's database or load-balance your big LAMP application.

How to change a text value tag to a cdata section

I generate a XMLDocument based on a dataset by binding the dataset to the XMLDocument object and then display it to user in vb.net. I have a requirement in which certain tags to contain cdata sections rather than text value. After generating the XMLDocument how to change only certain tag to cdata section and keeping all else as it is? Or is there a way to modify while binding itself?

From stackoverflow
  • There is no difference between a text section and a CDATA, except how characters are quoted inside them. The parser that consumes the data won't see a difference. Are you sure you need to create a CDATA section?

  • Actually the reason we are going with CDATA section is that the output text contain certain HTML format strings in it. When it is took as a plain text it will be taken by parser as a XMl element. For eg.

    I need to display as

    "<tag><![CDATA[Sample HTML tag <head> ]]> </tag>"
    
  • You could use the "XmlDocument.CreateCDataSection(string)" method. First search each text string for "<" or ">" characters -- or for a full tag "" if known -- then use the appropriate method to output the data.

InstallShield2009 Unicode Support

Our installation program is written using InstallShield2009, and as part of certification requirements we have to support Unicode throughout.

The application itself is .NET, so supports Unicode natively, however on testing our installation with a Chinese character set we can see problems thrown up by InstallShield dialogs.

Having done a quick google, I found one related post whereby someone has deemed there is no unicode support in IS2008.

I have also emailed Acresso directly, but being the caring developer I am, thought I'd post the question here for future reference, in case anyone else has the same problem.

If anyone has encountered this problem in the past, any help would be appreciated. Thanks.

From stackoverflow
  • Turns out that IS2009 does NOT fully support Unicode, as it cannot handle paths containing (amongst others) Japanese characters.

Free diagramming tool for web site specification

Are there any free diagramming tools for web site specification? Which is your favourite?

From stackoverflow
  • I usually use a Mind Mapping tool, here's a freebie that's very good. It's not v1 yet, but worth checking out:

    Cayra

    Download Link

    alt text

    bob : I tried several days to download this, still broken. Any idea where I can find a mirror?
  • Dia is a multipurpose diagraming tool, ala visio. http://live.gnome.org/Dia

  • I'm not sure kind of diagrams you want to use but you could check out these:

    • FreeMind - an open source java-based mind mapper
    • StarUML - an open source UML tool (only for Windows unfortunately)
  • Inkscape is my favourite drawing tool. Has fantastic SVG support.

  • I found this one for Windows:

    It is basic but just what I needed to design the web structure

    @Touko, your link to StarUML is not working. This is the URL

    Touko : Thanks for noticing =)
  • Just in case you're talking about sketching out the UI specifications, Balsamiq is really nice.

    JoeBloggs : The OP specifically says a) Free, which Balsamiq is not and b) web-site spec, not UI spec. I love Balsamiq, but it's clearly offtopic here.

Using Samba for random access without mounting the file system?

I am using a machine on which I do not have root access and would like to access files on a Samba server in random access mode. I know I can transfer the files in their entirety using smbclient but the files are very large (>1GB) and I would rather just treat them as remote files on which I can do random access.

The problem as noted is that I don't have root access to this machine (a Linux box) so I can't mount the remote Samba file system.

Is there a user-level solution that will let me randomly access the contents of a file on a Samba server? Seems it should be possible to do everything that the kernel file system client is doing but from a user-level application.

I only need read-only access btw and the remote file is guaranteed not to change.

From stackoverflow
  • Try to use smbmount to mount the filesystem without root permissions:

    mkdir ~/temp
    smbmount //{server}/{share} ~/temp -o username=username={username},password={password}
    

    Edit: Updated to use smbmount instead of mount.

    Dave Griffiths : Tried that. It says: mount: only root can do that
    xsl : I updated the post to use smbmount instead of mount.
    Dave Griffiths : Hmmm, well I downloaded and installed samba and tried mount.cifs which appears to be the replacement for smbmount. That also fails and the reason appears to be that the command needs the suid root bit set. Catch 22!
  • To answer my own question after digging around in the Samba source: there is a client library libsmbclient which includes all the usual file handling stuff: smbc_open, smbc_fstat, smbc_lseek, smbc_read etc. For instance, here is a snippet I just wrote which reads a file backwards (just to check it was doing a true seek):

    fd = smbc_open(path, O_RDONLY, 0);
    smbc_fstat(fd, &st);
    
    for (offset = st.st_size - BUFLEN; offset > 0; offset -= BUFLEN) {
        smbc_lseek(fd, offset, SEEK_SET);
        smbc_read(fd, buffer, BUFLEN);
    }
    

    (error checking removed for clarity)

    Dave Griffiths : Since writing the above I found a much better solution (for me at least because it's in Java) here: http://jcifs.samba.org/

ASP.Net Validation

I want to validate the value a user enters in a text box, so that it only enters float numbers. I'm not interested in range. How can I do this, considering also culture localization information (e.g. "." or "," as separators)?

From stackoverflow
  • My usual method is to use a RegexValidator with a validation expression of ^(\d+(\.\d*)?)|(\d*(\.\d+))$. You could ammend this to enable "." or ",": ^(\d+([\.,]\d*)?)|(\d*([\.,]\d+))$.

    If you wanted to be strictly correct, you'd enable the correct validation expression for each culture.

    Also note that you still need a RequiredFieldValidator if the value is compulsary.

    Joel Coehoorn : I'm not normally a fan of using a regex to test whether something is a number, but I'll concede that it has the nice advantage in this case of doing the same validation both client and server-side while only writing the logic once.

Group by alias (Oracle)

How to 'group by' a query using an alias, for example:

select count(*), (select * from....) as alias_column 
from table 
group by alias_column

I get 'alias_column' : INVALID_IDENTIFIER error message. Why? How to group this query?

From stackoverflow
  • select
      count(count_col),
      alias_column
    from
      (
      select 
        count_col, 
        (select value from....) as alias_column 
      from 
        table
      ) as inline
    group by 
      alias_column
    

    Grouping normally works if you repeat the respective expression in the GROUP BY clause. Just mentioning an alias is not possible, because the SELECT step is the last step to happen the execution of a query, grouping happens earlier, when alias names are not yet defined.

    To GROUP BY the result of a sub-query, you will have to take a little detour and use an nested query, as indicated above.

  • It does not work, I get

    'subquery expression not allowed here'
    

    error message

    Tomalak : Please use the comment function to comment on an answer.
  • Nest the query with the alias column:

    select count(*), alias_column
    from
    ( select empno, (select deptno from emp where emp.empno = e.empno) as alias_column
      from emp e
    )
    group by alias_column;
    
  • select count(*), (select * from....) as alias_column 
    from table 
    group by (select * from....)
    

    In Oracle you cannot use an alias in a group by clause.

ASP Tabpanel postback only on one tab

Hi I have a tabpanel with a calendar control on the 4th tab but when I select a date, the postback causes the tabpanel to return to the first tab instead of the 4th that it came from. Is there a way to get it to return to the tab that the calendar control is on and not revert back to the first tab ?

I know setting autoPostback to true on the TabContainer will do this but that means it reloads on every tab change not just the one I want.

Any ideas ?

From stackoverflow
  • Wrapping the contents of the fourth tab in an UpdatePanel control should do the trick.

    <ajaxToolkit:TabPanel runat="server" ID="tabCS" HeaderText="Country Settings">
      <ContentTemplate>
        <asp:UpdatePanel runat="server" ID="upCountry" UpdateMode="Conditional">
          <ContentTemplate>
    
              ... content and calendar
    
           </ContentTemplate>
        </asp:UpdatePanel>
      </ContentTemplate>
    </ajaxToolkit:TabPanel>
    
  • Here is a best practice that I've found.

    Unless other tabs in the tab panel need to be updated only put the contents of each panel in an update panel. If you need to update other panels you can call the method programmatically to update them.

    There are two good reasons for this: 1.) By putting update panels in the tabs you will have fewer bits to get back from the server. 2.) Calling the update methods programmatically makes you more aware of what it is you are providing the end user and you won't forget to update the data.

    Remember that if you use multiple panels to change the update mode from always to conditional so that only the relevant information is updated on the client.

    Also if you want to put the entire tab panel control into the update panel you may need to add any formatting that is done to a CSS file since my experience is that it fails to retain the default formatting with it updates.

    If you need more info or a code sample just message me.

    Andrew

Execute a JavaScript function in a C# application.

Without using a WebBrowser control, how could I execute a JavaScript function, that is decoupled from any browser DOM dependencies, in a C# application? I am investigating implementing validation rules only once, for both server and client validation. See this question for reference if you like. Are there any JS interpretor libraries I could use?

Addendum: My goal here is to automatically deploy and invoke exactly the same validation logic on client and server, without communication between the two during the actual validation. So, ideally I would code my validation logic in JavaScript, and render that to the page. Alternatively, I could code my logic in C#, convert that to JavaScript using Script#, and render that to the page.

I don't want separate validation functions being maintained client and server side, and I don't want AJAX calls to server validation functions, and I don't want client only or server only validation.

From stackoverflow
  • You could use JScript.Net

    Either that, or investigate Script#

    ProfK : Thanks, JScript.Net is not quite what UI want, but see my mod to the question regarding Script#.
  • Windows Script Host (WSH) is a Windows administration tool. You can use PInvoke to activate it from C#. Recognizes an MS specific (and old) version of JavaScript.

    WSH creates an environment for hosting scripts. That is, when a script arrives at your computer, WSH plays the part of the host — it makes objects and services available for the script and provides a set of guidelines within which the script is executed. Among other things, Windows Script Host manages security and invokes the appropriate script engine.

  • This may help A script host for C#/VB.NET/JScript.NET it uses built in classes within the Framework to execute script in VB, C# or JavaScript.

    It uses the CodeDomProvider to execute the scripts, also check out this article for a more complex example.

  • Try pinvoke spider monkey - http://www.mozilla.org/js/spidermonkey/