Home

rss

Telerik ASP.NET MVC controls and jQuery

For those who are using the Telerik controls for MVC you will most likely have the following somewhere on your page or Master page

This will create issues if you then try to add any jQuery to the page including jQuery plugins.

To get around this, you can append a method to the Telerik ScriptRegistrar to disable the jQuery reference. You need to change it to

And your page should be happy again.

Getting random records from a table using LINQ to SQL

I needed to get a number of random records from a table and a quick google search led me to http://mosesyap.com/BlogWeb/post/2008/07/C-Getting-a-Random-Record-from-a-Table-inside-the-SQL-Server-Database.aspx This is a very quick and easy mechanism to use and will work on any table. To load a specific number of random records change the .First() function
DataContext db = new QuoteDataContext();
var quote = db.Quote.OrderBy(q => db.GetNewId()).First();
to be .Take(x)
DataContext db = new QuoteDataContext();
var quote = db.Quote.OrderBy(q => db.GetNewId()).Take(x);
replacing x with however many records you need.

Getting IPv4 Bytes Sent and Received from NICs on a PC or Server

I recently had a need to track the data usage on a number of Hyper-V virtual machines for billing hosting customers. There was nothing cheap and easy in the marketplace so as a developer always does, I wrote one myself. The whole app consists of an ASP.NET Web Service, a .NET Windows Service and an ASP.NET web app for the reporting/charting but I thought I’d share a small part of the code.

I found it hard to find good examples on the web of how to do it so it took a fair amount of time to find the right objects to do the job. In the end the code proved quite easy. This is a very cut down version of the function that deals with getting the bytes sent and received.

Dim NICList() As NetworkInterface = NetworkInterface.GetAllNetworkInterfaces()
Dim NICStats As IPv4InterfaceStatistics

Dim NetworkName As String
Dim BytesSent As Double = 0
Dim BytesReceived As Double = 0

For Each NIC As NetworkInterface In NICList
    If NIC.OperationalStatus = OperationalStatus.Up And NIC.NetworkInterfaceType = NetworkInterfaceType.Ethernet Then
        NetworkName = NIC.Name
        NICStats = NIC.GetIPv4Statistics
        BytesReceived = NICStats.BytesReceived
        BytesSent = NICStats.BytesSent

        'Do Something with the data here
    End If
Next

You then have to figure a way to track the data usage over a period of time as this just gives you a since last reboot figure. Each implementation of these requirements will differ so I won’t go any further into my solution.

The biggest issue I found with this method is that there is no way to track a specific connection. You can’t use the network name because that can change at any time and although using the MAC address would work on physical servers, it won’t work on VM’s because the MAC can change. At the moment I’m just recording it by name but I’m looking for a better answer.

Creating a Tag Cloud with c# and IEnumberable<>

I recently had to create a tag cloud for an application I’m writing. The tags are attached to bookmarks.

The function returns a paragraph tag with a link for each tag. Each link has a specific class attribute set depending on the weighting given to that tag.

The C# code:

public class TagCloudGenerator
    {
        public string MakeTagCloud(IQueryable<BookmarkTag> Tags)
        {
            Decimal totaltags = Tags.Count();
            Decimal tagpercent = 0;
            int tagweight = 0;

            StringBuilder TagCloud = new StringBuilder();

            var groupedtags = Tags.GroupBy(t => t.Tag);

            TagCloud.Append("

"); foreach (var tag in groupedtags) { tagpercent = (tag.Count() / totaltags) * 100; if (tagpercent >= 90) { tagweight = 1; } else if (tagpercent >= 70) { tagweight = 2; } else if (tagpercent >= 40) { tagweight = 3; } else if (tagpercent >= 20) { tagweight = 4; } else if (tagpercent >= 3) { tagweight = 5; } else { tagweight = 0; } TagCloud.Append(String.Format("{2} ", tag.Key.Replace(" ", "-"), tagweight, tag.Key)); } TagCloud.Append("

"
); return TagCloud.ToString(); } }

The CSS:

/* Tag Cloud */

.tagcloud
{
    text-align: left;
}

.tagcloud a
{
    padding: 0px 10px 0px 0px;
    text-decoration:none;
    padding:3px 4px;
    white-space:nowrap  
}

.tagcloud a:hover
{
    background-color:#fff;
    color:#012840;
}

.tagcloud .tag1
{
    font-size: 2em;
}

.tagcloud .tag2
{
    font-size: 1.7em;
}

.tagcloud .tag3
{
    font-size: 1.5em;
}

.tagcloud .tag4
{
    font-size: 1.2em;
}

.tagcloud .tag5
{
    font-size: 1em;
}

.tagcloud .tag0
{
    font-size: .8em;
}

Using Data annotations with partial classes and LINQ to SQL

If you’re using LINQ to SQL as your data provider then you will need to add a few extra steps to utilise Data annotations with ASP.NET MVC.

If you have created your own objects then you can append annotations such as [DisplayName(“This is the display name I want in the view”)] directly to the object properties as you can see below. These will then be used by UI Helper and for Model validation by MVC.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace MyApp.Models
{
    public class MyObject
    {
        [DisplayName("First Name")]
        public string Property1 { get; set; }

        [DisplayName("Surname")]
        [Required]
        public string Property2 { get; set; }        

    }
}

You can see in the code above that we’ve set some metadata for the DisplayName for the UI Helpers and a Required attribute for model validation.

You can create a partial class to add additional functions and overrides to your LINQ to SQL objects but you cannot add data annotation attributes directly to the LINQ object properties. To achieve this you need to use a separate class and link it to the LINQ to SQL object using the Metadatatype attribute.

Lets assume that the MyObject class is now a LINQ object. We can create a partial class to add additional functions but we cannot use the data annotations shown above (DisplayName and Required)

namespace MyApp.Models
{
    public partial class MyObject
    {
        public string MyAddedFunction()
        {
            return "Some additional data";
        }

    }
}

To add the data annotation attributes we will create another class called MyObject_Validation as shown below

namespace MyApp.Models
{
    public class MyObject_Validation
    {
        [DisplayName("First Name")]
        public string Property1 { get; set; }

        [DisplayName("Surname")]
        [Required]
        public string Property2 { get; set; }        

    }
}

Which overrides the DisplayName on our two fairly poorly named properties Property1 and Property2 to more meaningful names and we assert that Property2 is a required field.

We can now use the Metadatatype  attribute to link the data annotations in MyObject_Validation to MyObject

namespace MyApp.Models
{
    [MetadataType(typeof(MyObject_Validation))]
    public partial class MyObject
    {
        public string MyAddedFunction()
        {
            return "Some additional data";
        }

    }
}