Using KnockoutJS with SignalR in ASP.NET MVC

KnockoutJS is a MVVM implementation for JavaScript written by Steve Sanderson, in my opinion the author of the best ASP.NET MVC textbooks available. Simply put it lets you bind a JavaScript object model to your HTML UI using a Read more

A MongoDB Tutorial using C# and ASP.NET MVC

In this post I'm going to create a simple ASP.NET MVC website for a simple blog that uses MongoDB and the offical 10gen C# driver. MongoDB is no NOSQL database that stores information as Binary JSON (BSON) in documents. I Read more

Linq To SQL Tutorial

Check out some of my other Linq to SQL posts: EntityBase Inheritance Modifiers with SQLMetal Linq to SQL with WCF Services Linq to SQL Framework (Repository/Business wrapper) ObjectDataSource binding with server side paging and sorting Load Options Generic Framework using reflection This is a basic tutorial for Read more

Linq to SQL Tutorial – Using Load Options to preload data immediately without lazy loading

Posted on by Joe in ASP.NET, C#, Linq | 1 Comment

Download source

With Linq to SQL lazy loading is used by default. That means that if one object contains another object, the child object will only be loaded when first accessing it. Using Load Options it is possible to tell Linq to SQL to also load the child object at the same time as loading it’s parent.

Read more

ASP.NET FormView SetFocus

Posted on by Joe in ASP.NET, C# | 1 Comment

I have FormView and on changing to Edit mode I wanted to set focus to the first textbox. I thought I’d do this hooking into the ModeChanged event but this doesn’t work as the textbox hasn’t been rendered.

I then tried overriding the Render method and setting the focus after rendering; at this point the control was created but I get an exception to say focus can only be set in PreRender, but in PreRender the control won’t be available.

One way I found to get this to work was to set the focus in a handler for the DataBound event of the FormView.

Read more

Read only Automatic Properties in C#

Posted on by Joe in C# | 1 Comment

Automatic Properties were a nice addition to C# 3 and I use them all the time. A lot of people may already know this but somehow I only found out this week; you can create a read only automatic property simply by adding the ‘private’ keyword before ‘set’:


public class UserEventArgs : EventArgs
{
    public UserEventArgs(int userID)
    {
        UserID = userID;
    }

    public int UserID { get; private set; }
}

Convert file size bytes to megabyte/gigabyte string using C#

Posted on by Joe in C# | 11 Comments

I feel like I haven’t posted in ages. Have been busy changing job and moving house but I have a list of things I want to blog about soon.

Recently I needed to convert a number of bytes to a readable string that represents the number of kilobytes, megabytes or gigabytes.

I created an extension method for Int32 which does this for me Int64 as per Alex’s comment about the FileInfo.Length property being a long. I also changed my method for Int32 to call the other method so that it can be used for both int and long.

Read more

Linq Tutorial – Using the Enumerable.Any extension method

Posted on by Joe in ASP.NET, C#, Linq | Leave a comment

Consider the following:

Entities

Using Linq I want to select all the roles for a particular user. I could create a query like this:

 

public List<Role> GetByUserID(int userID)
{
    List<Role> roles = (from r in Context.Roles
                       join ur in Context.UserRoles on r.ID equals ur.RoleID
                       where ur.UserID.Equals(userID)
                       select r).ToList();

    return roles;

}

This simply creates the following SQL:

SELECT [t0].[RoleID] AS [ID], [t0].[Name]
FROM [dbo].[Role] AS [t0]
INNER JOIN [dbo].[UserRole] AS [t1] ON [t0].[RoleID] = [t1].[RoleID]
WHERE [t1].[UserID] = @p0

Alternatively I could use the Any extension method.

public List<Role> GetByUserID(int userID)
{
    return Context.Roles.Where(r => r.UserRoles.Any<UserRole>(ur => ur.UserID.Equals(userID))).ToList();
}

The Any method returns a bool which indicates if any of the UserRoles meet the lambda expression; in this case checking the UserID property. The Where method evaluates the Roles against the Roles the User belongs to so we only get those Roles.

The resulting SQL looks like this:

SELECT [t0].[RoleID] AS [ID], [t0].[Name]
FROM [dbo].[Role] AS [t0]
WHERE EXISTS(
    SELECT NULL AS [EMPTY]
    FROM [dbo].[UserRole] AS [t1]
    WHERE ([t1].[UserID] = @p0) AND ([t1].[RoleID] = [t0].[RoleID])
    )

Linq to SQL – Using EntitySet.Remove to delete records

Posted on by Joe in ASP.NET, C#, Linq | 4 Comments

Download source

Quite often you have two tables with a linker table which causes Linq to SQL to generate an EntitySet of the related records in each table.

Take the following example:

Entities

Here, the User entity will have an EntitySet called UserRoles containing the Role entities that the user is part of.

When I want to remove a role from a user what I’d like to do is the following:

user.UserRoles.Remove(userRole);

Unfortunately after doing this, when I try to submit the changes to the database I get the following error:

“An attempt was made to remove a relationship between a User and a UserRole. However, one of the relationship’s foreign keys (UserRole.UserID) cannot be set to null.”

Read more

Using FindControl for a control in the ItemTemplate of a ListView

Posted on by Joe in ASP.NET, C# | 14 Comments

Update: I’m not sure what was going on in my head the day I wrote this article, but as Lukas points out in a comment below you can simply use e.Item.FindControl(“cblRoles”) as apposed to the convoluted way I’m doing it :-)

I’ve been playing around with the ListView control recently and am quite impressed with it.  I like how it gives full control over the markup used as apposed to the other data driven controls.

I came across an issue where in my ItemTemplate I have a CheckBoxList which I needed to reference when I hit a button also in the ItemTemplate.

As the ItemTemplate repeats there will be many CheckBoxLists so how do I find the correct one?

Read more

Control.TryFindControl Extension Method

Posted on by Joe in ASP.NET, C# | Leave a comment

Following on from my last post creating an extension method to use FindControl recursively I thought it would be cool to also have a TryFindControl method which works in a similar way to Int32.TryParse which I use regularly.

Below is a generic extension method that uses my previously created recursive FindControl method to cast the object to the correct type if found and send it back as an out parameter, then return a boolean indicating if the control was found.

public static bool TryFindControl<T>(this Control ctrl, string id, out T control, bool recursive) where T : class
{
    Control ctrlFound = ctrl.FindControl(id, recursive);
    control = ctrlFound as T;
    return ctrlFound is T;
}

The method could then be used like so.

TextBox txt = null;
if (this.TryFindControl<TextBox>("txtName", out txt, true))
{
    txt.Text = "Joe Stevens";
}

Recursive FindControl Extension Method

Posted on by Joe in ASP.NET, C# | Leave a comment

When working with templated controls it’s quite common to need a recursive FindControl method to navigate down through the control hierarchy to find the control you want.

Here is a simple extension method I wrote for Control to do this:


public static Control FindControl(this Control ctrl, string id, bool recursive)
{
    if (recursive)
    {
        foreach (Control child in ctrl.Controls)
        {
            if (child.ID != null && child.ID.Equals(id))
            {
                return child;
            }

            if (child.Controls.Count > 0)
            {
                Control found = FindControl(child, id, true);
                if (found != null)
                {
                    return found;
                }
            }
        }
    }
    else
    {
        return ctrl.FindControl(id);
    }

    return null;
}

CheckBoxList ListBox SelectedItems Extension Method

Posted on by Joe in ASP.NET, C# | Leave a comment

I’ve been working with the CheckBoxList control and it’s annoying there is no property to get the selected items.

I wrote a simple extension method for ListControl, the abstract class that CheckBoxList and ListBox derive from, to get the selected items:


public static ListItemCollection GetSelectedItems(this ListControl source)
{
    ListItemCollection selectedItems = new ListItemCollection();

    foreach (ListItem item in source.Items)
    {
        if (item.Selected)
        {
            selectedItems.Add(item);
        }
    }

    return selectedItems;
}

I could loop through the selected items like so:

foreach (ListItem item in myCheckBoxList.GetSelectedItems())
{
    //Do something with the item
}

It would be even better if Microsoft implemented extension properties so that I can loose the parenthesis.