blog.mha.dk
The on-line blog of Michael Holm Andersen

Clean copy of LinqToSQL Entity object

Monday, 28 November 2011 09:53 by mha

Often you need to make a copy of a LinqToSQL (Entity) Object with all the values intact. For some reason the .NET framework does not have a method for this.

However the below code will make a “clean copy” of a LinqToSQL object.

// Instanciate new object and copy all properties from old Bill ("clean" copy)
Bill billNew = (Bill)Entity.Copy(billOld, new Bill());

And the method actually doing the work, looks like this:

public static class Entity
{
    /// <summary>
    /// Copies an LinqToSQL entity object ("clean" copy)
    /// </summary>
    /// <param name="source">Source Entity object</param>
    /// <param name="destination">Destination Entity object</param>
    /// <returns>Destination Entity object with all properties copied from Source object</returns>
    public static object Copy(object source, object destination)
    {
 
        System.Reflection.PropertyInfo[] sourceProps = source.GetType().GetProperties();
        System.Reflection.PropertyInfo[] destinationProps = destination.GetType().GetProperties();
 
        foreach (System.Reflection.PropertyInfo sourceProp in sourceProps)
        {
            ColumnAttribute column = Attribute.GetCustomAttribute(sourceProp, typeof(ColumnAttribute)) as ColumnAttribute;
 
            if (column != null && !column.IsPrimaryKey)
            {
                foreach (System.Reflection.PropertyInfo destinationProp in destinationProps)
                {
                    if (sourceProp.Name == destinationProp.Name && destinationProp.CanWrite)
                    {
                        destinationProp.SetValue(destination, sourceProp.GetValue(source, null), null);
                        break;
                    }
                }
            }
        }
 
        return destination;
    }
}
Categories:   C# | LINQ
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

AutoComplete, PageMethod and LINQtoSQL

Wednesday, 12 May 2010 15:49 by mha

I’m using AutoComplete to enhance the functionality of a TextBox and make it act like the below image, where the user enters the customer accountnumber, which is then displayed together with their name (the blurry stuff in the picture :-)

autocompletesearch

As I have to use this functionality on many pages, I needed it to be a UserControl.

I wanted to use a PageMethod (instead of a Web Service) to populate the AutoCompleteExtender, but since the page method must reside on the page (in the .aspx.cs file, it does not work if it’s placed in the .ascx.cs file – dammit MS), I wanted to limit the code needed on the .aspx.cs page to a bare minimum.

The number of entries displayed in the AutoComplete DropDown list had to be limited, but the user need to know how many matches the prefix entered.


The Page Method (ServiceMethod) of the AutoCompleteExtender requires a string[] to work and I wanted the Page Method to contain as little code as possible. I ended up with this:

[System.Web.Services.WebMethodAttribute(), 
System.Web.Script.Services.ScriptMethodAttribute()] public static string[] GetDataCustomerAccountNo(string prefixText,
int count, string contextKey) { CustomerRepository customerRepository = new CustomerRepository(); return customerRepository.GetCustomerAccountNumbersByPrefix(prefixText); }


The GetCustomerAccountNumbersByPrefix looks like this:

/// <summary>
/// Retrieves all AccountNumbers which match prefix (AutoComplete)
/// </summary>
/// <param name="prefix">Prefix to match</param>
public string[] GetCustomerAccountNumbersByPrefix(string prefix)
{
    var customers = from e in db.Customers
            where e.AccountNumber.StartsWith(prefix)
            orderby e.AccountNumber
            select e;

    int count = customers.Count();
    string[] result = customers.Take(21).Select(x => x.AccountNumber + " – " 
                                         + x.NameAlias).ToArray<string>();

    if (result.Count() > 20)
    {
       result[20] = ">> antal: " + count.ToString();
    }

    return result;
}


If the ResultSet contains more than 20 rows I want to provide information about this to the user, displaying the total number of rows, which is why I do a Count() before Take()

I use .Select() to transform the properties AccountNumber and NameAlias into a single string, which is then returned as a string[] using ToArray(), in the process I limit the number of rows to a maximum of 21 using Take()

And all there’s left to do is to optionally change the 21th entry to show the total number of rows information. As the string[] is fixed it’s much easier simply to take out an extra row - Take(21) – and use this last row to show the information.

Hope the above example is useful to others who might want to use the AutoCompleteExtender in a UserControls only to find out that the PageMethod actually DO have to reside in the .aspx.cs file.

Categories:   C# | ASP.NET | LINQ
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

ViewData and the null-coalescing operator

Wednesday, 30 December 2009 08:12 by mha

If you’re using ASP.NET MVC and are using the ViewData collection you might want to familiar yourself with the ?? operator.

The ?? operator is called the null-coalescing operator and is used to define a default value for a nullable value types as well as reference types. It returns the left-hand operand if it is not null; otherwise it returns the right operand.

Knowing this we can use the below syntax to e.g. display the title of a page in the browser with a value from ViewData and if this is null instead display a default value.

<%= ViewData["title"] ?? "Home Page" %>

MSDN has more info about the ?? operator.

Categories:   C# | ASP.NET MVC
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

CultureInfo – National Language Support (NLS) API Reference

Thursday, 8 October 2009 13:10 by mha

I’m working on a web-portal kind of system, which will support multiple languages and needed to find a table with all the CultureName etc.

After finding different tables which was lacking the information I needed, I came across this one which have everything you need to start Localizing :)

http://msdn.microsoft.com/en-us/goglobal/bb896001.aspx

Update: I’ve made a SQL table to store all the above information. No need for anyone else to do this, so here’s the SQL scripts to create table and insert data:

Categories:   C#
Actions:   E-mail | del.icio.us | Permalink | Comments (1) | Comment RSSRSS comment feed

Maintain debug information while in release mode

Thursday, 1 October 2009 08:11 by mha

REL (René) showed me a very interesting link the other day that I think I’ll share (as some of you probably already have guessed, I sometime uses this blogs as a means of remembering great articles/links :-)

Anyway here’s the link, which shows how to maintain debug information (and get information about the exact line of code that caused the exception) while running in release mode (this is really awesome):

http://www.rohland.co.za/index.php/2009/02/11/maintain-debug-information-while-in-release-mode/

http://msdn.microsoft.com/en-us/library/8cw0bt21(VS.80).aspx

Categories:   ASP.NET | C#
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

PDC2008 session videos online!

Tuesday, 4 November 2008 07:02 by mha

All the session videos from Professional Developers Conference 2008 are now available online, so grap your favorite cup, brew a nice hot cappuccino and start watching...

Cool ViewStateDecoder

Thursday, 11 September 2008 14:42 by mha

ViewState is a great feature of ASP.NET, however too much ViewState might degrade performance. But what's actually "hidden" inside that weird looking form field you might be wondering? Well, use Fritz Onion's viewstate decoder to find out, I say ... you can download it right here: ViewStateDecoder2.0.zip (8.25 kb)

 

Categories:   ASP.NET | C#
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

Calculate you age

Friday, 5 September 2008 09:53 by mha

I needed to calculate a persons age the other day, and came up with this simple code:

DateTime myBirthDay = new DateTime(1970, 9, 5);
TimeSpan diffAge = DateTime.Now.Date - myBirthDay.Date;
int myAge = new DateTime(diffAge.Ticks).Year - 1;

Categories:   ASP.NET | C#
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

GEAR and MSDN Magazine

Wednesday, 3 September 2008 20:36 by mha

MSDN Magazines Issues from 2008 and GEAR 2008-2007 Issues (a danish 'gadgets' magazine) can be downloaded completely free of charge!

Happy reading!

Umbraco v4 in beta

Wednesday, 9 July 2008 08:47 by mha

Umbraco v4.0 beta1 is available for download - looks like it's going to be a great release :)

Check it out / download the bits from: http://www.umbraco.org/v4

.. and by the way - aspnethotel.dk is of course capable of hosting both v3 and v4 umbraco sites! ('hidden' ad, beware! :-)

Categories:   .NET hosting | ASP.NET | C# | Tools
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed