Asp.Net: DataPager problem with Listview

When using the Datapager with a ListView I had the following problem. When clicking a paging button for the first time nothing happens.But when I click a button the second time, then the page from the first click loads.

I search the internet for a solution and found that you need to add some code to the OnPagePropertiesChanging event of the list view to reload the DataPager.

The following code is the solution to my problem. Including a fix that the data doesn’t get loaded two times.


private List productList;

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        fillGrid();
}

private void fillGrid()
{
    if(productList == null)
        productList = getproducts();
    ListView1.DataSource = productList;
    ListView1.DataBind();
    DataPager1.DataBind();
}

public List getproducts()
{
    using (AdventureWrksDataContext db = new AdventureWrksDataContext())
    {
        return db.Products.ToList();
    }
}

protected void lvproducts_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
    DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
    fillGrid();
}


You can download the solution (PagingExample.zip (83.05 kb))

Cheers,

Pieter

TypeMock: Mock Unittest examples

In this example I will show how to create a Unit Test with TypeMock.

First I have created some basic dummy classes for the example


public sealed class ServiceFactory
{
    public static ExpireDateService CreateExpireDateService()
    {
        ExpireDateService expireDateService = new ExpireDateService();
        expireDateService.administration = new SqlAdministration("connectionstring");
        return expireDateService;
    }
}

/// <summary>
/// SqlAdministrion creates connection and managed queries with SQL
/// </summary>

public class SqlAdministration
{
    private static DateTime LoadParameterPrivate()
    {
        return DateTime.Parse("01-01-1980");

    }

    public SqlAdministration(string connectionString)
    {
        //Create connection to sql�
    }

    public static DateTime LoadParameter(string expireDateType)
    {
        //GET expireDate from Database:
         SqlAdministratie.LoadParameter("expireDateType");
        // Load Date from Private method for other mocking examples

        return LoadParameterPrivate();
    }
}

public class ExpireDateService
{
    public SqlAdministration administration;

    public DateTime GetDate(string expireDateType)
    {
        DateTime expireDate = SqlAdministration.LoadParameter(expireDateType);

        return expireDate;
    }
}

public class CheckDate
{
    public static bool CheckExpireDateBooking()
    {
        ExpireDateService expireDateService = ServiceFactory.CreateExpireDateService();
        DateTime expireDate = expireDateService.GetDate("expireDateDateFirst");
        return DateTime.Parse("01-01-2000") &lt; expireDate;
    }
}


With the following Unit test I will test the code written above. I don't want to change my code or add code for testing purpose. That's where Mocking comes in. With TypeMock I will mock the outcome of specified methods.

The first example is a standard unit test. No Mocking there.

[code language='c#']
///

/// Checks the expiredate from ‘database’ 01-01-1980
/// with a hardcoded date 01-01-2000
///

[TestMethod()]
public void TestMethodWithoutTypeMock()
{
    Assert.IsFalse(CheckDate.CheckExpireDateBooking());

[/code]

 Now I want to mock the method GetDate to return a date specified by me (01-01-2010).


/// <summary>
/// Checks the expiredate from database (01-01-1980)
/// with a hardcoded date provided by TypeMock (01-01-2010)
/// </summary>

[Isolated]
[TestMethod()]
public void TestMethodWithTypeMockIsolate()
{
    //Create a dummy version of the ExpireDateService object to use for Mocking

    ExpireDateService expireDateService = new ExpireDateService();
    expireDateService.administration = new SqlAdministration("dummyConnectionString");

    //Return the declared expireDateService when method CreateExpireDateService is called

    Isolate.WhenCalled(() =&gt; ServiceFactory.CreateExpireDateService())
        .WillReturn(expireDateService);

    //Isolate the call to method expireDateService.GetDate with parameter 'expireDateDateFirst' and return 01-01-2010

    Isolate.WhenCalled(() =&gt; expireDateService.GetDate("expireDateDateFirst"))
        .WillReturn(DateTime.Parse("01-01-2010"));

    Assert.IsTrue(CheckDate.CheckExpireDateBooking());
}


For the latest example I wanted to Mock a Private method.


/// <summary>
/// Checks the expiredate from database (01-01-1980)
/// with a hardcoded date provided by TypeMock on privatemethod(01-01-2010)
/// </summary>

[Isolated]
[TestMethod()]
public void TestMethodWithTypeMockIsolatePrivate()
{
    Isolate.NonPublic.WhenCalled(typeof(SqlAdministration), "LoadParameterPrivate")
        .WillReturn(DateTime.Parse("01-01-2010"));

    Assert.IsTrue(CheckDate.CheckExpireDateBooking());
} 


You can download the source here:
MockingWithTypeMockExampleSource.zip (44.47 kb)

Hope it helps.

Cheers,

Pieter

Asp.Net: invoke WCF method with WCF Test Client

When deploying a Silverlight application we ran into problems a WCF web-service, to find out what the problem was I wanted to invoke the method.

Microsoft shipped an application for invoking methods from your Windows PC (WCFtestclient.exe). The following steps explain how to use WCFtestclient.exe.

First startup Visual Studio 2008 Command Prompt. In the command prompt type wcftestclient, the application will startup.

Now we need to add the Service. Click File and Add Service.

 

Add the URL to your service in the pop-up and pres ok. The service will now add all methods from your service. You can add multiple service URLs.

Double click the method you want to invoke from the tree on the left pane. Enter the values that are required for the Invoke and press Invoke. The method will be invoked.

The right bottom pane will show the response. In my case this shows the Stack-trace because of the error. Normally this will show the web-service response (XML).

With the stack-trace I could located the error and fix it.

Hope this helps,

Pieter

LINQ: Creating a if statement in Linq query

A lot of times I need to check a statement within my LINQ-query and I wish there was a possibility of a IF statement within LINQ.

The following code is the solution to my IF problem. I use a temporary variable (let isOlderThen30) to check if a statement is true. Then in my WHERE statement I use the temporary variable in a INFLINE IF.

For this example I use my Blogger class with some data



public class Blogger
{
 public string FirstName { get; set; }
 public string LastName { get; set; }
 public int Age { get; set; }
 public string Blog { get; set; }
}

List personList = new List{
 new Blogger { FirstName = "Pieter", LastName = "Brinkman", Age = 27, Blog = "http://blog.newguid.net" },
 new Blogger { FirstName = "Mark", LastName = "van Aalst", Age = 26, Blog = "http://www.markvanaalst.com" },
 new Blogger { FirstName = "Bas", LastName = "Hammendorp", Age = 32, Blog = "http://www.hammendorp.net" }
};


It’s kind of hard to think of a easy good example, but here it is. In this example I want to set the Age property to “Older then 30” when the Blogger is older then 30 (how useful!).


//If a blogger is older then set Age text to "Older then 30"

var rawList = from item in personList
  let <strong>isOlderThen30</strong> = item.Age &gt; 30
  select new
  {
   Name = item.FirstName,
   Age = (isOlderThen30 ? "Older then 30" : item.Age.ToString()),
  };

//GENERATE OUTPUT

foreach (var item in rawList)
{
 Response.Write(item.Name + " (" + item.Age + ")<br />");
}

//OUTPUT
//Pieter (27)
//Mark (26)
//Bas (Older then 30)


Hope that the example is clear. If you have any questions let me know.

// UPDATE (3 aug 2009) //

I thought about the codeexample and offcourse you can do it shorter (but less readable with complex queries).


var rawList = from item in personList
  select new
  {
   Name = item.FirstName,
   Age = (item.Age &gt; 30 ? "Older then 30" : item.Age.ToString()),
  };


Linq to Xml: Generate Google Sitemap with sitemap-protocol

In this example I will generate a XML site-map that complies with the sitemap-protocol XML schema.


//create datasource

List blogPosts = new List{
 "http://blog.newguid.net/mypost1.aspx",
 "http://blog.newguid.net/mypost_about_Net.aspx",
 "http://blog.newguid.net/morePosts.aspx",
 "http://blog.newguid.net/andEvenMorePosts.aspx"
};

//Create namespace for sitemap-protocol

XNamespace xmlNS = "http://www.sitemaps.org/schemas/sitemap/0.9";
XDocument xmlDoc =
 new XDocument(
  new XDeclaration("1.0", "UTF-8", null),
  new XElement(xmlNS + "urlset",
   from blogPostUrl in blogPosts
   select
    new XElement(xmlNS + "url",
    new XElement(xmlNS + "loc", blogPostUrl))
    ));

//Show output

Response.Write(xmlDoc);


This example will give the following output:


&lt;urlset xmlns=&quot;<a href="http://www.sitemaps.org/schemas/sitemap/0.9">http://www.sitemaps.org/schemas/sitemap/0.9</a>"&gt;
  
    http://blog.newguid.net/mypost1.aspx
  
  
    http://blog.newguid.net/mypost_about_Net.aspx
  
  
    http://blog.newguid.net/morePosts.aspx
  
  
    http://blog.newguid.net/andEvenMorePosts.aspx
  



To keep the example as simple as possible I only use the LOC element of the URL node. In the real world you can implement the lastmod, changefreq and priority node.

More information about the sitemap-protocol.

Add meta data (keywords, description) dynamicly

Add meta-data dynamically to your page by adding a HtmlMeta control to your Header. In this example I dynamically add a keyword string to the page.


string keyWords = "metatags, html, dynamic, generate";

HtmlMeta keywords = new HtmlMeta();
keywords.Name = "keywords";
keywords.Content = keyWords;
Page.Header.Controls.Add(keywords); 


You can do the same for other meta-data like description.