Silverlight: Grid Control – Hide Row or Column


It seems like there is quite a bit of confusion about how to go about hiding a row or a column in the Grid control. Take the Grid control as defined below with two rows:

<Grid Name="grid" Height="100" HorizontalAlignment="Left" Margin="0,0,0,0" VerticalAlignment="Top" Width="200">
    <Grid.RowDefinitions>
         <RowDefinition></RowDefinition>
         <RowDefinition></RowDefinition>
     </Grid.RowDefinitions>
</Grid>

If you want to hide the first row, simply do the following:

// Hide the first row
this.grid.RowDefinitions[0].Height = new GridLength(0);

The same thing can be done to hide columns except instead of accessing the RowDefinitions collection, access the ColumnDefinitions collection.

C#: FTP Upload Error – The remote server returned an error: (550) File unavailable (e.g., file not found, no access).


I developed an application a while back that automatically backs up a group of SQL servers every night and then uploads the backups to an offsite location using FTP. The application has worked flawlessly for months now so I was quite surprised to get a call this morning saying that the automatic backups failed last night. I checked the error logs and saw a 550 error – “The remote server returned an error: (550) File unavailable (e.g., file not found, no access).” I then ran the program through a debugger again saw that this exception was thrown while attempting to close the FileStream.

I tested for the usuals, spaces in the ftp uri, ensuring correct permissions for ftp user, changed the code around to see if it was a coding issue, and a bunch of other things and nothing seemed to fix the problem. I could login to the server with the same credentials using Windows Explorer and FileZilla and I could upload a test text file. I had no idea what was going on. So, after a long time, too long, I whipped out good ol’ WireShark to see if I could discern anything from the actual packet transfer (something I should have done first!) and lo and behold, there I found the error in plain text.

“There is not enough space on the disk.” Such a problem did not cross my mind as the hosting plan we pay for comes with unlimited disk space! Further, the test file I uploaded was a couple of KB rather than the 4 or 5 MB backups that were trying to be uploaded so I wasn’t seeing the error. Turns out despite what it says in the contract, there are still physical limits on the server. Ridiculous! :) After a short call to the hosting company the problem was resolved.

Despite the fact that the server was giving the real reason for the error, the .NET Framework did not relay the message. Kind of strange if you ask me but such is life. Nonetheless, a valuable lesson was learned: when debugging FTP issues, always pull out WireShark!

Posted in .NET Framework. Tags: , , . 4 Comments »

Windows Gadget: Running Flash and Silverlight Gadgets


If you have a 64-bit operating system and you have ever tried to install a Windows Gadget implemented with Silverlight of Flash, you will quickly realize that the gadget will not run. It turns out that the issue lies in the fact that there is not a 64-bit version of either Silverlight or Flash but the default Windows Sidebar application that loads on start up is a 64-bit application. Thus, the gadget and the Sidebar won’t play nicely together. To fix this issue, all you need to do is have the 32-bit version of Windows Sidebar startup with Windows loads. To do this follow the instructions below:

Windows Vista

  1. Click the Start orb.
  2. Click All Programs.
  3. Right click on the Startup folder and click Open or Explore.
  4. In the window that appears, right click and select New -> Shortcut.
  5. In the Create Shortcut window, copy and paste the following text, including the quotes, into the Location text box: “C:\Program Files (x86)\Windows Sidebar\sidebar.exe”
  6. Click Next.
  7. Click Finish.

Windows 7

  1. Click the Start orb.
  2. Type regedit and press enter.
  3. Navigate to the following registry entry: HKEY_CLASSES_ROOT\DesktopBackground\Shell
  4. Right click on the Gadgets registry folder and click Permissions…
  5. In the permissions window, click on the Advanced button.
  6. Click on the Owner tab.
  7. Find your login in the Change owner to list view and select it.
  8. Click Ok.
  9. In the Permissions for Gadget window, click the Add… button.
  10. Enter your login name for the computer and click OK.
  11. Back in the Permissions for Gadget window, make sure your login name is selected in the Group or user names list and check the Allow check box for the Full Control permission.
  12. Click Ok.
  13. Repeat steps 4 through 12 for the HKEY_CLASSES_ROOT\DesktopBackground\Shell\Gadget\command registry folder.
  14. Double click the following registry keys in the HKEY_CLASSES_ROOT\DesktopBackground\Shell\Gadget registry folder and change the Value data field to the specified value:
    Icon: C:\Program Files (x86)\Windows Sidebar\sidebar.exe,-100
    MUIVerb: @%ProgramFiles86%\Windows Sidebar\sidebar.exe,-11100
  15. Double click the following registry keys in the HKEY_CLASSES_ROOT\DesktopBackground\Shell\Gadget\command registry folder and change the Value data field to the specified value:
    (Default): C:\Program Files (x86)\Windows Sidebar\sidebar.exe /showGadgets
  16. Close the registry and restart your computer.

This should make the 32-bit version of Windows Sidebar start when you right click your desktop and select Gadgets and thus allow Silverlight and Flash gadgets to work correctly.

SQL: SQL Server Management Studio – Clear Recent Server List


SQL Server Management Studio will store the names of the servers you have connected to so that you can easily connect at a later date without having to re-enter the IP Address or name of the server. This is a great feature but sometimes my list gets populated with a bunch of servers that I don’t use frequently. Unfortunately, there is no tool that can be used to clear out the list. Luckily there is still a way to accomplish this. Just navigate to the corresponding directory below, depending on your operating system, and delete the SqlStudio.bin file.

Windows XP
C:\Documents and Settings\[User Name]\Application Data\Microsoft\Microsoft SQL Server\100\Tools\Shell

Windows 7
C:\Users\[User Name]\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell

After deleting the SqlStudio.bin file, the list will be cleared.

SQL Server Management Studio 2005 Users: If you are using SQL Server Management Studio 2005 then the file you will delete is named mru.dat. Further, to find the file replace 100 with 90 in the above file paths.

Posted in SQL. Tags: , . Leave a Comment »

Visual Studio: The breakpoint will not currently be hit. The source code is different from the original version.


Some strange things happened today while I was testing some new code. The first problem was that the new code that I wrote wasn’t compiling when I attempted to debug. There were no compiler errors and the build was successful but upon debugging, the changes to the code that I made were not being executed. So, I tried to put a breakpoint at the location of the new code only to be confronted with the below error:

I have seen this error when you have compiler errors but decide to continue debugging using the last successfully compiled version, but this wasn’t the issue as everything was compiling correctly.

I figured something got corrupted in my project configuration so I built the project by right clicking on the project name in the Solution Explorer and clicking Rebuild. This will delete all temporary and intermediate files that are created while compiling and then compile the application from the ground up.

This solved my problem for a while but I was soon confronted with the same situation. I was baffled as I had never seen this problem occur and I didn’t want to have to rebuild the project every time I debugged as that took quite a bit longer. It was then that I realized that what I was doing during my testing was effecting the compilation process.

I was working on a clock in/out system that hooked into the SystemEvents.TimeChanged event so that I could detect changes in the system clock. During my debugging I would change the date and time on my computer to future and past dates, stop debugging, make some more changes, and then run my application again. From what I could gather, Visual Studio was getting confused as the modified date on the source code files were all out of wack. I would save my changes with the correct date and time, then change the system clock during testing, make more changes and save again but this time it saved as a date in the past. Thus, when compiling, Visual Studio would think the previous build was actually more current and not take into account the changes I made. This explains why the Rebuild command worked as it got rid of any files that had been created in previous builds and Visual Studio had no date reference to use when deciding which files to compile.

If you are messing with the date and time during debugging, be aware of this issue.

SQL: Making a Stored Procedure Available to All Databases


I needed to create a stored procedure today that could be used on any database within a given SQL Server instance. After some digging I found that there are three requirements for such a stored procedure:

  1. The stored procedure must be created in the master database.
  2. The name of the stored procedure must start with “sp_“.
  3. The stored procedure must be marked as a system object.

The first two are quite easily accomplished but the third requirement requires the use of an undocumented stored procedure named sys.sp_MS_marksystemobject which will mark the created stored procedure as a system object.


-- 1. Create the procedure in the master database
USE master
GO

-- 2. Create the procedure with the prefix sp_
CREATE PROCEDURE sp_[Stored_Procedure_Name]
AS
BEGIN
     -- Insert the logic of your stored procedure here
END
GO

-- 3. Mark the stored procedure as a system object
EXEC sys.sp_MS_marksystemobject sp_[Stored_Procedure_Name]

After you complete the above three steps, you can run the stored procedure on any of the databases found in that instance of SQL Server.

Note: If you need to “unmark” the procedure as a system object just simply drop the procedure and recreate it.

Posted in SQL. Tags: . 1 Comment »

C#: Get the Most Common (Mode) Element from a Collection


I was surprised today when I couldn’t find a built in Mode extension method that retrieved the most common or most frequently occurring element in a collection so I set out to write my own. My first approach was to use LINQ to Objects and just group the collection by the individual items, order each group descending by their count, and then return the first element as follows.

public static T Mode<T>(this IEnumerable<T> list)
{
    // Null testing
    if (list == null || list.Count() == 0)
        return default(T);

    return (from item in list
            group item by item into g
            orderby g.Count() descending
            select g.Key).First();
}

The above method works great but it left a bad taste in my mouth as ordering the grouped items using LINQ took O(n log n) time and I knew there had to be a way to solve this problem in O(n) time. So, I dropped the LINQ approach and went back to the good ol’ loop. The following method simply traverses the collection and adds an entry for each unique element in the collection into a Dictionary. The value of each Dictionary entry is incremented every time an element is encountered. Then we traverse the Dictionary to find the element with highest value.

/// <summary>
/// Gets the element that occurs most frequently in the collection.
/// </summary>
/// <param name="list"></param>
/// <returns>Returns the element that occurs most frequently in the collection.
/// If all elements occur an equal number of times, a random element in
/// the collection will be returned.</returns>
public static T Mode<T>(this IEnumerable<T> list)
{
    // Initialize the return value
    T mode = default(T);

    // Test for a null reference and an empty list
    if (list != null && list.Count() > 0)
    {
        // Store the number of occurences for each element
        Dictionary<T, int> counts = new Dictionary<T, int>();

        // Add one to the count for the occurence of a character
        foreach (T element in list)
        {
            if (counts.ContainsKey(element))
                counts[element]++;
            else
                counts.Add(element, 1);
        }

        // Loop through the counts of each element and find the 
        // element that occurred most often
        int max = 0;

        foreach (KeyValuePair<T, int> count in counts)
        {
            if (count.Value > max)
            {
                // Update the mode
                mode = count.Key;
                max = count.Value;
            }
        }
    }

    return mode;
}

Usage

List<int> ints = new List<int>() { 1, 2, 6, 3, 6, 7, 3, 6, 8, 4, 2, 1, 7, 6 };
int mode = ints.Mode();

Console.WriteLine(mode);

// Output
// ------
// 6

After some performance testing on large collections, the second method proved to take about half the time compared to that of the LINQ method. Also note that both methods are created using generic types so this extension method can be used on any collection of any type.

Follow

Get every new post delivered to your Inbox.

Join 70 other followers