2009-07-01

TIP: Defragment your VMs and VPCs

I have several VMs (VMWare) and VPCs (MS VPC), and one of them in particular has been performing worse and worse, so I thought it could be good to defragment it.

Now there’s internal fragmentation and there’s external fragmentation (just like indexes in SQL Server :P). The internal fragmentation is handled using the windows defragmentation tool inside the VM or VPC. External fragmentation occurs if you have set your disks to grow incrementally as needed. You could also say that all the space for your virtual disks should be reserved, and if your physical disks were defragmented in the first place, there would be no external fragmentation of your virtual disks. But if you let them grow incrementally, or your physical disk was fragmented when you created the virtual disk, there might be some fragmentation.

So I found this excellent tool from Sysinternals: http://technet.microsoft.com/nb-no/sysinternals/bb897428(en-us).aspx

Now I don’t need to defragment the whole physical disk. I can just defragment one file at a time. Should save me some time :)

How to check if an assembly has been built in DEBUG or RELEASE mode

I found this cool code that checks if an assembly has been built in debug or release mode: http://blogs.msdn.com/jb/archive/2006/06/14/631469.aspx 
It compiles and runs using .NET 1.1, and thats what I used for building it.

I used it on some assemblies in a solution I have, and were somewhat surprised to find that the following assemblies were reported as being debuggable:

  • EPiServer.dll (version 4.62)
  • log4net.dll
  • Microsoft.Web.Services2.dll

This is probably done on purpose (to enable debugging), but it makes me wonder if my applications would run faster if the assemblies were built using Release mode.

2009-06-16

MVVM Toolkit for WPF and Silverlight

Laurent Bugnion has created a toolkit for creating MVVM applications. He says:

“To make development of WPF and Silverlight applications according to the Model-View-ViewModel pattern easier, I have put together a small toolkit which should speed up the creation of such applications by automating certain tasks.”

Here’s the URL: http://geekswithblogs.net/lbugnion/archive/2009/06/14/mvvm-lsquolightrsquo-toolkit-for-wpf-and-silverlight.aspx

2009-06-03

The Web Platform Installer

ScottGu’s last blog post is about the Web Platform Installer: http://weblogs.asp.net/scottgu/archive/2009/06/02/microsoft-web-platform-installer.aspx

Looks like a very useful application for configuring your web server or web development server. It can be downloaded for free from this direct link to the installer.

I also like very much that it integrates with the new Windows Web Application Gallery: www.microsoft.com/web/gallery. I am very likely going to use it very soon.

2009-05-28

Are you mocking me?

I am learning to mock :D. I understand the principle, that you can write your unit tests without any finished methods or data sources (sometimes referred to as TDD). So just looking for nice places to start with Moq. Found a couple of nice links so far:

http://stephenwalther.com/blog/archive/2008/06/12/tdd-introduction-to-moq.aspx

http://blog.objectmentor.com/articles/2009/05/19/a-first-look-at-moq

2009-05-14

Getting started with S#arp Architecture

I am trying to get started with S#arp Architecture, and I found some nice (short) videos at Dime Casts.NET:

Introdction to S#arp Architecture

Another look at Sharp Architecture- Validation, Design Decisions and Automapping

Taking a look at how to modify the T4 templates used by Sharp Architecture

I’ll be looking at them and creating my own test project. Should be good :)

There should also be a good Northwind example available with the downloads from Google Code.

2009-05-12

Microsoft laying off 12 people in Norway

A sad day when even MS has to start downsizing: http://www.digi.no/812605/microsoft-norge-maa-nedbemanne (Norwegian). Good luck to the twelve people laid off in Norway, and to their families.

2009-05-08

TSQL: Checking if an ID is in a Comma Separated String

Ok, so the scenario is that we have a list of IDs, maybe from a checkboxlist, and we want to get the records that match those IDs from a table. So for the sake of this example, I just assume that the list of IDs is passed to my stored procedure as a varchar(8000) string. Using Northwind as an example database, heres an example of how an SP that gets products could look like:

CREATE PROCEDURE GetProducts
@ListOfProductsAsCSVString varchar(8000)

AS

SET @ListOfProductsAsCSVString = ',' + @ListOfProductsAsCSVString + ',';

SELECT ProductID, ProductName FROM Products
WHERE CHARINDEX(',' + CAST(ProductID as varchar(10)) + ',', @ListOfProductsAsCSVString ) > 0;

So what I do is to first append a comma before and after the CSV-list. This is because I need to search for somthing that starts with a comma and ends with a comma, and usually a CSV-list doesn’t have a comma before the first element or after the last one. Then, in my select, I search using the CHARINDEX function for the ProductID prefixed and postfixed by a comma.

Now, please be aware that this could lead to a possible SQL Injection attack, if you use this procedure uncritically without validating the input before passing it to this stored procedure, so use with caution.

2009-05-02

FileUpload for ASP.NET MVC 1.0

I worked my way through the free Nerd Dinner chapter from ASP.NET MVC 1.0, creating my own web from the example. My web is a Food Recipe application where one can search among 7000 recipes on words in the title or ingredients.

The web should also be able to have pictures of the food, so I needed to do some file uploading, and so I found Scott Hanselman’s article http://www.hanselman.com/blog/ABackToBasicsCaseStudyImplementingHTTPFileUploadWithASPNETMVCIncludingTestsAndMocks.aspx. I copied some of his code, and put the parts I needed into this function (the definition of the ViewDataUploadFilesResult class is in Scott’s article):

private List<ViewDataUploadFilesResult> uploadFiles()
{
    var r = new List<ViewDataUploadFilesResult>();

    foreach (string file in Request.Files)
    {
        HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase;
        if (hpf.ContentLength == 0)
            continue;
        string savedFileName = Path.Combine(
           string.Concat(AppDomain.CurrentDomain.BaseDirectory,"images\\upload"),
           Path.GetFileName(hpf.FileName));
        hpf.SaveAs(savedFileName);

        r.Add(new ViewDataUploadFilesResult()
        {
            Name = savedFileName,
            Length = hpf.ContentLength
        });
    }
    return r;
}

Now, from before I had an Edit-action for the posting of my Edit View in my Controller, and from this I called the function above, as hown in the following code:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection collection)
{
    try
    {
        var recipe = recipeRepository.GetRecipe(id);
        recipe.RecipeDescription = Request.Form["RecipeDescription"];

// code removed for brevity

        List<ViewDataUploadFilesResult> fileUploaded = uploadFiles();

        if (fileUploaded.Count > 0)
            recipe.RecipePictureUrl = Path.GetFileName(fileUploaded[0].Name);

        recipeRepository.Save();
        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

I also had to make some changes to my View:

First, I had to add an “enctype” to the form element. This is done like this with the Html-helper class:

<% using (Html.BeginForm("Edit", "<EntityController>", null, FormMethod.Post, new { @enctype = "multipart/form-data" })) {%>

Second, to be able to use a FileOpen dialog, I had to add an attribute to the text box for entering the file name. In plain old ASP/Html, you would use:

<input type=”file”>

And that is also what we need to do here, except we need to use the Html-helper class like this:

<%= Html.TextBox("RecipePictureUrl", Model.RecipePictureUrl, new { @type = "file" }) %>

2009-04-29

The old UDL-trick: Testing Database Connection Strings

If you have problems creating a connection string, here’s an old trick:

1. Create a text file and call it for instance test.udl. It’s the file type (extension) that’s important.

2. Click (double-click) on the file to open it. A “Data Link Properties” dialog box will open.

3. Select the provider you want from the first tab. Click “Next”.

4. Select or type the name of the server.

5. Provide username and password.

6. Select database. This will only be possible if the parameters provided above are correct.

7. Check “Allow saving passwords”.

8. Click the “Test Connection”. If you get a message box saying the test was successful, proceed to the next step.

9. Close the Data Link Properties.

10. Hold shift down while right clicking on the UDL-file, then select “Open with”, then select “Notepad”.

Voila! You now have your connection string to be copied and used in your application.

2009-04-27

Using TryParse

I just figured out a way to use int.TryParse in an if-sentence.

string myInputString = myTextBox.Text;
int i = –1;
if(int.TryParse(myInputString, out i) && i > 0)
{

//do cool stuff

}

This only works with the “&&” operator. If the parse fails, the second part that uses the “out” parameter from the parse, will not be run.

2009-04-24

Searching inside strings with LINQ2Objects

I made a search form containing a button and a text box for entering multiple search words, and for excluding words by putting a dash in front of them. So at first I mixed LINQ2Entities with LINQ2Objects, and it didn’t work at all, but after converting from entities to objects (using the .ToList() method), things are working.

Here’s my sample code, as always using Northwind as the database:

protected void SearchButton_Click(object sender, EventArgs e)
{
    using (NORTHWNDEntities context = new NORTHWNDEntities())
    {
        string[] crit = SearchBox.Text.Split(' ');
        List<string> included = new List<string>();
        List<string> excluded = new List<string>();

        for (int i = 0; i < crit.Length; i++)
        {
            if (crit[i].StartsWith("-"))
            {
                //adds the string without the dash to the excluded collection
                excluded.Add(crit[i].Substring(1));
            }
            else
            {
                //adds the string to the included collection
                included.Add(crit[i]);
            }
        }

        List<Products> products = context.Products.ToList(); //converting to objects

        var searchResult =
            from p in products
            where included.Any(i => p.ProductName.Contains(i))
                && !excluded.Any(x => p.ProductName.Contains(x))
            select p;

        ProductsDataList.DataSource = searchResult;
        ProductsDataList.DataBind();
    }
}

2009-04-23

ASP.NET MVC + Silverlight? Try MVVM + Silverlight in stead!

I have been thinking about how it would be cool to use the new ASP.NET MVC project type with Silverlight as the “View”, and a quick google gives some interesting results.

Some attempts have been made to use Silverlight as the view in MVC:

In this one http://timheuer.com/blog/archive/2009/02/09/silverlight-as-a-view-in-aspnet-mvc.aspx the approach is to start with a Silverlight application, and then select ASP.NET MVC as the container-web for the Silverlight views. But it seems that this approach has some problems (just read the comments).

In this approach http://blogs.msdn.com/jowardel/archive/2009/03/09/asp-net-mvc-silverlight.aspx, one starts out with an MVC web project, and then put Silverligh controls into the views. This solution is not usable, because it relies on using a property (some parameters) that is no longer accessible in the release version of MVC.

The solution is: Don’t use MVC, Use MVVM!
From the comments from the first one, it seems MVVM (http://msdn.microsoft.com/nb-no/magazine/dd458800(en-us).aspx) is the way to go (Model-View-ViewModel).

Jonas Follesøe also have some good stuff:
http://jonas.follesoe.no/YouCardRevisitedImplementingDependencyInjectionInSilverlight.aspx

And this discussion provides some good links:
http://stackoverflow.com/questions/375301/should-i-use-the-model-view-viewmodel-mvvm-pattern-in-silverlight-projects

2009-04-22

The fate of Linq2SQL

The fate of Linq2SQL: http://tinyurl.com/5kcvzd is it dead or not? Only the future can tell, I guess...

2009-04-20

SendHttpRequest

I made a little console application using .NET 1.1, that sends a request to an address given as parameter. It is to be used to simulate traffic on a web site. Probably could use some refinement of the code (just consider it my alpha, and that there will be no beta, RTM, etc.).

using System;
using System.Web;
using System.IO;
using System.Net;

namespace SendHttpRequest
{
    /// <summary>
    /// Summary description for Class1.
    /// </summary>
    class EntryPoint
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            if(args.Length > 0)
            {
                string url = args[0];

                Uri uri = null;
                try
                {
                    uri = new Uri(url);
                }
                catch
                {
                    Console.WriteLine("Invalid URL. No request sent.");
                    return;
                }

                WebRequest request = WebRequest.Create(uri);
                request.Method = "GET";

                WebResponse response = null;
                try
                {
                    response = request.GetResponse();
                    StreamReader rdr = new StreamReader(response.GetResponseStream());
                    string content = rdr.ReadToEnd();
                    Console.WriteLine(content);
                }
                catch (Exception ex)
                {   
                    Console.WriteLine(ex.Message);
                    return;
                }
            }
            else
            {
                Console.WriteLine("Usage: SendHttpRequest {url}");
            }
        }
    }
}

2009-04-14

ScottGu's Silverlight 2.0 Tutorial

I am trying to work my way through Scott Gu's http://weblogs.asp.net/scottgu/pages/silverlight-tutorial-part-3-using-networking-to-retrieve-data-and-populate-a-datagrid.aspx tutorial.

The tutorial contacts a service using a WebClient.

Someone called David has posted a question regarding him getting the error "The remote server returned an error: (403) Forbidden.".

The answer to the question is to add this line: Service.Headers.Add("user-agent", "Silverlight Sample App");

However, the Headers have no "Add" method any more: http://msdn.microsoft.com/en-us/library/system.net.webheadercollection_members(VS.95).aspx.

In stead I think you need to use the bold italic line in the source below:

        private void SearchBtn_Click(object sender, RoutedEventArgs e)
{
string topic = txtSearchTopic.Text;
string diggUrl = string.Format("http://services.digg.com/stories/topic/{0}", topic);

WebClient diggService = new WebClient();
diggService.DownloadStringCompleted += new DownloadStringCompletedEventHandler(diggService_DownloadStringCompleted);
diggService.Headers[HttpRequestHeader.UserAgent] = "Silverlight Sample App";
diggService.DownloadStringAsync(new Uri(diggUrl));
}


But this doesn't work either, because UserAgent is a restricted header that cannot be set. Attempting to set it will throw an exception:

http://msdn.microsoft.com/en-us/library/system.net.webheadercollection(VS.95).aspx



So is there any way of making the tutorial work? Am I barking up the wrong tree? If I find out I'll post the answer :)

ASP.NET MVC 1.0

Rob Conery, Scott Hanselman, Phil Haack and Scott Guthrie have come up with a book on the Model-View-Controller framework, and the first chapter describes building a simple web site using the framework.

The chapter is free and can be downloaded from this link: http://aspnetmvcbook.s3.amazonaws.com/aspnetmvc-nerdinner_v1.pdf

The example web site is on the net: http://www.nerddinner.com

David Hayden has blogged about the book here: http://davidhayden.com/blog/dave/archive/2009/03/11/AnotherASPNETMVCSampleApplicationEBookTutorialNerddinner.aspx

2009-03-25

Creating your first Silverlight 2.0 application

Good article with some videos that show you how to get started with Silverlight 2.0 in Visual Studio 2008: http://visualstudiomagazine.com/columns/article.aspx?editorialsid=2644

Microsoft Patterns and Practices: Application Architecture Guide 2.0a

I came across this excellent book while surfing yesterday: Application Architecture Guide 2.0a. It seems to be very good, taking into consideration most of the aspects of an application Architecture. It has a "Fast Track" chapter that summarises different patterns and practices, and when to use what. This chapter has references to the other chapters if one needs to go deeper in.

Best of all: the book is free! The book can be downloaded as PDF from CodePlex: http://www.codeplex.com/AppArchGuide/Release/ProjectReleases.aspx?ReleaseId=20586

I just discovered that there is a presentation available that summarises much of the book: http://apparch.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=17700

The book may be a little outdated with regards to the latest developments in O/RM (Entity Framework / NHibernate etc.) and maybe some other places as well, but it gives an excellent overview, and tries to be technology-agnostic.