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

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

LINQtoSQL – Grouping and selecting

Wednesday, 21 April 2010 15:00 by mha

I have a Order->OrderLine table setup where I need to check if any “duplicate” orders exists. In order to check this I need to be able to select select various columns *not* contained in the group (key) – playing around in LinqPad I quickly came up with this query:

from line in AxSaleLines
where line.QuantityRemaining > 0
group line by new {line.AxSale.AccountNumber, line.ItemNumber, 
ProdName = line.Product.Name, ProdFormat = line.Product.ProductFormat.Name}
into myGroup
where myGroup.Count() > 1
from s in AxSaleLines
where s.ItemNumber == myGroup.Key.ItemNumber && 
      s.AxSale.AccountNumber == myGroup.Key.AccountNumber
select new { s.AxSale.SalesId, s.AxSale.AccountNumber, 
             CustomerName = s.AxSale.Customer.Name, s.ItemNumber, 
             ProductName = s.Product.Name, s.Product.ProductFormatName, 
             s.Quantity, s.AxSale.SalesOrigin}
 


When bound to a grid, I can then show this to the user:

groupedgrid

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

Register Custom Controls In Web.config

Thursday, 15 April 2010 15:43 by mha

If you’re using a lot of UserControls or a control package, you’re probably finding yourself adding tons of <%@ Register… %> tags to your .aspx pages.

Phil Haack has an excellent post about how to avoid all this mess and put your assembly references into the Web.Config file. Go check it out!

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

Slide Screen for Android

Wednesday, 7 April 2010 13:44 by mha
slidescreenui If you’re an Android fan (as I am) and thinks the stock homescreen is really not that great/usable, you should take a look at SlideScreen

SlideScreen is a homescreen replacement, which totally changes how you use your phone.

The cool thing about SlideScreen is that it integrates information from various sources—Google Reader, Twitter, Facebook, email, text messages, calendar appointments and stocks—right onto the homescreen

If you’re a proud Android user, be sure to check it out!
Tags:  
Categories:   Mobile | Tools
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed

ASPX Edit Helper Add-In For Visual Studio

Thursday, 11 February 2010 08:07 by mha

Jacob mentioned a nice little free Add-In for VS2005/2008 yesterday while we we’re chatting on Messenger :-)

Short description: “The ASPX Edit Helper is an add-in for Visual Studio 2005 for those who like to type ASPX markup themselves instead of using the visual designer"

Usage:

Type <asp:Label and press Enter. The add-in will replace it with:

<asp:Label runat=”server” id=”asp_Label2943″ />

The add-in will also highlight the ID attribute value so you can immediately type a new ID for the control.

Very handy, thanks to Jacob for mentioning this – free download at: http://www.ardentdev.com/aspxedithelper

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

ASP.NET MVC Best Practices

Wednesday, 10 February 2010 07:49 by mha

Kazi Manzur Rashid has put together a blog post (in 2 parts) about ASP.NET MVC Best Practices which is worth reading if you’re working with ASP.NET MVC.

ASP.NET MVC Best Practices (Part 1)
ASP.NET MVC Best Practices (Part 2)

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

ASP.NET MVC and ASCX

Tuesday, 9 February 2010 14:51 by mha

Jeffrey Palermo has an inspiring article about templating and (why not) to use .ascx aka UserControls in ASP.NET MVC – I’ll definitely be using this approach:

http://jeffreypalermo.com/blog/asp-net-mvc-and-the-templated-partial-view-death-to-ascx/

jQuery IntelliSense on ASP.NET MVC

Tuesday, 9 February 2010 12:51 by mha

If you’re using ASP.NET MVC, you’re probably also using jQuery and hence would like to have IntelliSense support in your ViewPages. According to Scott Gu all you need to do is to make sure you’re having the “-vsdoc.js” file in your script folder (e.g. “jquery-1.3.2-vsdoc.js”) and VS2008 (with the patch installed!) will find this file and jQuery IntelliSense works – however as it turns out if you’re using a path which starts with “/” (as you should!) VS2008 is unable locate the “-vsdoc.js” file and you will not have any jQuery IntelliSense support.

So there’s a little more to know about how exactly jQuery IntelliSense actually works in order to make this work correctly (not to mention IntelliSense support in .ascx files). Luckily Jouni Heikniemi have written a great article about this – check it out:

http://www.heikniemi.net/hardcoded/2009/08/jquery-intellisense-on-asp-net-mvc/

TamperData – security test your web applications

Friday, 5 February 2010 17:26 by mha

Working more and more with ASP.NET MVC I’ve found the Tamper Data Firefox Add-on to be quite useful. With this add-on you can view HTTP/HTTPS headers and browser-requests and (which is really awesome) edit POST parameters.

Use this add-on to security test your web applications by modifying POST parameters and simulate a scenario where a user changes/tampers with information sent to your site, like e-commerce sites where a user tries to buy cheap stuff, hack passwords, etc..

LINQ and PagedList

Tuesday, 26 January 2010 18:04 by mha

If you’re using LINQ you probably know about the .Skip and .Take methods. However often you need to do paging, hence you probably use something similar to this to get around that:

public PaginatedList(IQueryable<T> source, int pageIndex, int pageSize)
    {
        PageIndex = pageIndex;
        PageSize = pageSize;
        TotalCount = source.Count();
        TotalPages = (int)Math.Ceiling(TotalCount / (double)PageSize);

        this.AddRange(source.Skip(PageIndex * PageSize).Take(PageSize));
    }


However you don’t need the above code – instead take a look at the CodePlex project called PagedList located at http://pagedlist.codeplex.com/

PagedList allows you to take any List<T> and by specifying the page size and desired page index, select only a subset of that list, there’s also a StaticPagedList if you should need that.

Simply download the source, run “Release.bat” to build a release version and reference the .dll file in your solution, then you can have code like this:

var somePage = list.ToPagedList(4, 50); // fifth page, page size = 50