Sunday, May 1, 2011

How To: Use a datareader without a count of records

It seems folks have lost the ability to generate old style COBOL/RPG reports using modern day languages.

I often see code using DataReaders that relies on a count of records. So an additional aggregrate query is present when it need not be.

In most circumstance this code needs to know if there is another record available or not. In other words, tell me if I'm at the last record so I can display a record separator.

A simple algorithm would be as follows:


Dim available As Boolean = rdr.Read()
While available
  DisplaySearchRecord(rdr)
  available = rdr.Read()
  If available Then DisplaySeparator()
End While

Please, do not use COUNT(*) or a datatable/dataset when a simple change in algorithm will suffice.

From stackoverflow
  • Why not showing the separator after the while?

       While rdr.Read()
           DisplaySearchRecord(rdr)
       End While
       DisplaySeparator()
    
  • You can try something like this

    Dim IsFirst As Boolean = True
    
    While rdr.Read()
      If Not IsFirst
        DisplaySeparator()
      Else
        IsFirst = False
      End If
    
      DisplaySearchRecord(rdr)
    End While
    
  • you have to keep calling reader.Read() and it will return false when there are no more records.

    So what I would do is dump the data out of the db into a List<YourRecord> and after I have the list populated ... iterate through it with a for( i++ ) loop and check i against the list.Count

WebOrb to record from my webcam

Can WebOrb record a video (flv) streaming using the webcam as a source? How?

From stackoverflow
  • Here they talk about this.

    On the weborb site i found this entry, so it can be done, but apperently they haven't updated their site yet with an example...

Getting a list of logical drives.

How can I get the list of logial drives (C#) on a system as well as their capacity and free space?

From stackoverflow
  • System.IO.DriveInfo.GetDrives()

    Eoin Campbell : Is this something new that was added in the latest version of .NET. I wrote a small app to display this years ago but had to go the WMI route at the time. Very handy to know anyway... cheers
    PaulB : Perfect ... thank you
    Richard : Quick look on MSDN: was added in .NET 2.0.
  • You can retrieve this information with Windows Management Instrumentation (WMI)

     using System.Management;
    
        ManagementObjectSearcher mosDisks = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");
        // Loop through each object (disk) retrieved by WMI
        foreach (ManagementObject moDisk in mosDisks.Get())
        {
            // Add the HDD to the list (use the Model field as the item's caption)
            Console.WriteLine(moDisk["Model"].ToString());
        }
    

    Theres more info here about the attribute you can poll

    http://www.geekpedia.com/tutorial233_Getting-Disk-Drive-Information-using-WMI-and-Csharp.html

  • Directory.GetLogicalDrives

    Their example has more robust, but here's the crux of it

                string[] drives = System.IO.Directory.GetLogicalDrives();
    
                foreach (string str in drives) 
                {
                    System.Console.WriteLine(str);
                }
    

    You could also P/Invoke and call the win32 function (or use it if you're in unmanaged code).

    That only gets a list of the drives however, for information about each one, you would want to use GetDrives as Chris Ballance demonstrates.

  • DriveInfo[] drives = DriveInfo.GetDrives();
    
    foreach (DriveInfo drive in drives)
    {
    double fspc = 0.0;
    double tspc = 0.0;
    double percent = 0.0;
    
    fspc = drive.TotalFreeSpace;
    tspc = drive.TotalSize;
    percent = (fspc / tspc)*100;
    float num = (float)percent;
    
    Console.WriteLine("Drive:{0} With {1} % free", drive.Name,num);
    Console.WriteLine("Space Reamining:{0}", drive.AvailableFreeSpace);
    Console.WriteLine("Percent Free Space:{0}",percent);
    Console.WriteLine("Space used:{0}", drive.TotalSize);
    Console.WriteLine("Type: {0}", drive.DriveType);
    }
    

Does the size of database fields matter?

Hi

I have a database table, let's call it Countries. Countries all have names, short names and continents. Let's assume that the longest name of any country in the world is 54 characters long. Should I set the maximum size to 54 or should I set it to e.g. 64 or something else? Will my choice affect queries or storage in any way?

I know this might seem like pre-optimizing, but I find myself often choosing 32, 64, 128, etc. and I'd like to know if that matters.

Thanks

From stackoverflow
  • Answers will be RDBMS specific:

    If you are using SQL Server (2000 onwards), a varchar only uses space for the actual characters stored in it (plus a small overhead), up to the maximum size as declared.

    As a general rule of thumb, don't optimise until you have a problem.

  • A solid DBMS should know what's best for it. If you need "54 chars" but the database can do better search-optimizations with 64 chars, it will expand the data-field internally automatically. If it doesn't, you will have saved 12 chars per row.

    I don't think that's something you should worry about, just write down what you need.

  • If you're using SQL Server, I would strongly recommend NOT using VARCHAR(8000) or VARCHAR(MAX) for all fields..... you need to let common sense prevail here - make the field as big as you think you'll probably need it, add a little extra for unexpected length, and you're done :-)

    Also, I think it's a good idea to keep it to a few lengths that you use over and over again. E.g. I use VARCHAR(255) for most fields like street address or e-mail etc. that could be a bit longer, VARCHAR(50) for things like phone numbers etc., and VARCHAR(20) for short strings like zip code and such.

    Be pragmatic about it - find a style that works for you. Don't over-optimize, but don't go nuts the other way, either.

    Marc

    Deniz Dogan : So what's the rationale behind using 255 instead of 256?
    marc_s : Don't know - possibly my Pascal heritage - strings were limited to 255 chars then :-) No particular reason - just a personal (bad?) habit
    karim79 : I use 255 for many varchars. I thought that came from the email address RFC, but I could be wrong.
  • Depends on the data type. For instance in ORACLE - a varchar2 data type would be a good choice for variable-length strings. You need only to define the maximum length of the string - varchar2(maxsize). This would mean that any string with a length of up to 10 would fit. The length of the column would depend on the actual string stored in it.

    See. link text

    In your case, if your absolutely sure that there is no country name longer than 54 characters, I would use variable-size data type of size 54.

Using Cocoa to detect when a running application plays audio

I'm looking into writing an app that runs as a background process and detects when an app (say, Safari) is playing audio. I can use NSWorkspace to get the process ID's of the currently running applications but I'm at a loss when it comes to detecting what those processes are doing. I assume that there is a way to listen in on a process and detect what public messages the objects are sending. I apologize for my ignorance on the subject.

Has anyone attempted anything like this or are aware of any resources that can help?

From stackoverflow
  • SoundFlower is an open-source project that allows Mac OS X applications to pass audio to each other. It almost certainly does something similar to what you describe.

    Ilya Birman : Cool, I’m using SoundFlower but I completely forgot its being open-source. Thanks for this info.
  • I've been informed on another thread that while this is possible, it is an extremely advanced technique and not recommended. It would involve using Application Enhancer (APE) and is considered a not 'nice' thing to do. Looks like that app idea is destined for the big recycling bin in the sky :)

  • I don't think that your "answer" is an answer at all...

    and there IS an answer (which is not "42")

    your best bet for doing this would be to write a pass-through audio output device. Much like soundflower, actually. so your audio output device would then load the actual (physical) audio output device and pass the audio data along to it directly (after first having a look at the audio stream, of course!). then you only need to convince your users to configure your audio device as the default audio output device so that the majority of applications which play sound will use it automatically. and voila...

    your audio processing function will probably just do a quick RMS on the buffer before passing it along to the actual output device. and when the audio power crosses a certain threshold (probably something like -54dB with apple audio hardware), then you know that some app is making sound.

    |K<

Friday, April 29, 2011

applying function on a value returned from MarkupExtension in xaml

Is there a way to apply a function on a value returned from a MarkupExtenstion such as {Binding ... } or {StaticResource ...} in XAML? Usage example: making the font size of button1 to be twice bigger than the font size of button2?

From stackoverflow

Determine state of keyboard in non-keyboard-event method call.

Hi

In a textbox.TextChanged event I want to prevent some specific (processor intensive) functionality from executing if a key is still held down. E.g. while the user is deleting large regions of text by holding down the delete key I want to prevent the code from firing if the delete key is still held down.

I looked into Control.ModifierKeys which is the closest thing a google search kicks up, but in my specific case I want to trap if the delete or backspace key are pressed - which ModifierKeys doesn't provide.

Does anyone know how to do this? Ideally something which doesn't involve me having to track the state of keyup/keydown for each and every textbox (although if there is no other way I'll do it like that)

From stackoverflow
  • Why not handle the KeyUp event instead of handling KeyPress. That way you can always be sure that the key has already been depressed and is in the process of being... errr.. released (for lack of a better word!)

    Ash : Its an idea, but initially I'm hooking into the TextChanged event on the textbox as it copes with things like Cut & Paste and text changed programatically.
  • If your wanting to known the current keyboard state (via KeyPreview), can't you attach the event on the main form.

    Then check against the stored state from the textbox event handler.

  • Overriding Control.ProcessKeyPreview should do it.

    Ash : I've just looked into this and in this case I'd rather not have to subclass the control just for this functionality.
    leppie : And why is that an issue? If 10 lines of extra code is more bothersome than fixing your problem, then there are bigger problems...
  • In the end I've resorted to the external function GetKeyboardState

    So for future reference i'm doing something along the lines:

    [DllImport("user32.dll")] public static extern int GetKeyboardState(byte[] lpKeyState);
    
    private void myFunc()
    {
        byte[] keyboardState = new byte[255];
        int keystate = GetKeyboardState(keyboardState);
    
        if (keyboardState[(int)Keys.Back] == 128)
        {
           // backspace still pressed
           return;
        }
        else if (keyboardState[(int)Keys.Delete] == 128)
        {
           // Delete key still pressed
           return;
        }
    
        // More processor intensive code ...
    }
    

    I am not sure of the function call overhead, but I'm pretty sure it will be less than the processing the function would perform were it not there.