C#: Remove line from textfile

With the following code you can remove a line from a textfile (web.config). If the string is within a line the line will be removed.

[code language=’c#’]
string configFile = @”C:devweb.config”;
List lineList = File.ReadAllLines(configFile).ToList();
lineList = lineList.Where(x => x.IndexOf(“<!–") <= 0).ToList();
File.WriteAllLines(configFile, lineList.ToArray());

[/code]

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.

[code language=’c#’]
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();
}

[/code]

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

Cheers,

Pieter

Comments disabled

I disabled the comments because of the huge amounts of spam I’m receiving. So if you have any questions you can contact me trough linked-in.

Sorry for the inconvenience.

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

[code language=’c#’]
public sealed class ServiceFactory
{
    public static ExpireDateService CreateExpireDateService()
    {
        ExpireDateService expireDateService = new ExpireDateService();
        expireDateService.administration = new SqlAdministration(“connectionstring”);
        return expireDateService;
    }
}

///

/// SqlAdministrion creates connection and managed queries with SQL
///

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”) < expireDate;
    }
}

[/code]

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).

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

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

[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(() => ServiceFactory.CreateExpireDateService())
        .WillReturn(expireDateService);

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

    Isolate.WhenCalled(() => expireDateService.GetDate(“expireDateDateFirst”))
        .WillReturn(DateTime.Parse(“01-01-2010”));

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

[/code]

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

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

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

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

    Assert.IsTrue(CheckDate.CheckExpireDateBooking());

[/code]

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

Hope it helps.

Cheers,

Pieter

Realization corporate website hu.nl

For Evident Interactive I was Lead-developer on the hu.nl project. With a team of 5 professionals we build 23 websites in 5 months. All the websites where implemented within one instance of Sitecore CMS.

The websites containing Flash, Silverlight, GoogleMaps, Flick and Youtube.

The project was successfully realized within the deadline.

TSQL: Nested Select with multiple results to one (comma separated) string

For this example I will use the default asp.net Membership tables.

Let say: I need to return all users with their roles (comma separated) in one query. After a long time Googling I found the following solution.

[code language=’sql’]

select
  UserName,
  (select roles.RoleName + ‘, ‘
    FROM aspnet_Roles roles
    join aspnet_UsersInRoles usersInRole on roles.RoleId = usersInRole.RoleId
    WHERE usersInRole.UserId = aspUser.UserId
    for xml path(”)) as roles
from
    aspnet_Users aspUser

[/code]

Don’t know if this is the best way, but it works.