Skip to content

MikeBevers.be

Putting it out there…

The Problem

I recently acquired a new Windows hosting space. Everything ran fine and smooth until I tried to sent an E-Mail from my website. I received the following error: Mailbox unavailable. The server response was: No such user here. Which was weird to me, because I re-used my mailer class which worked fine on other websites. Usually I would setup my Web.Config like this:

<configuration>
  <system.net>
    <mailSettings>
      <smtp>
        <network host="my.host.com" port="25" defaultCredentials="true" />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

… and I would set the Sender information in code to whatever I want.

The solution

Apparently some servers don’t allow anonymous SMTP. You need to configure an E-Mail account registered on your domain.

Then your Web.config will look:

<configuration>
  <system.net>
    <mailSettings>
      <smtp from="noreply@host.com" deliveryMethod="Network">
        <network host="my.host.com" port="25" defaultCredentials="true" />
      </smtp>
    </mailSettings>
  </system.net>
</configuration>

Problem

I recently started using ASP.NET MVC 3 with the new Razor view engine. Everything looks great and cool at first sight. I tried to implement a simple Ajax postback form, without any success. Every time I tried to submit the form, it returned a new blank page with my data on it. A common mistake is to forget referencing the MicrosoftAjax.js and MicrosoftMvcAjax.js libraries in your master layout. After spending half an hour trying to figure out what I might have done wrong, I turned to google and MSDN.

Solution

UnobtrusiveJavaScriptEnabled was the buzzkill. By default, you’ll find this in your root web.config file:

<add key="UnobtrusiveJavaScriptEnabled" value="true"/>

If you change the value from “true” to “false”, your Ajax will start working. I don’t know why it’s enabled by default. I’ll guess you’ll have to google it yourselves.

If you want to know more on Unobtrusive JavaScript, visit Wikipedia.

A simple Ajax form example

Some people asked me for a very basic example using Ajax and ASP.NET MVC 3. So here goes:

For starters, change the UnobtrusiveJavaScriptEnabled entry in your root web.config to “false”

<add key="UnobtrusiveJavaScriptEnabled" value="false"/>

Next, add the javascript references in your Master layout

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>

    <script src="@Url.Content("~/Scripts/MicrosoftAjax.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/Scripts/MicrosoftMvcAjax.js")" type="text/javascript"></script>
</head>

<body>
    @RenderBody()
</body>
</html>

Your HomeController has the default View and handles the PostBack

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public PartialViewResult Index(FormCollection data)
    {
        List<string> result = new List<string>();
        string[] input = data["MyInput"].Split(new string[] { "\n" }, StringSplitOptions.None);

        result.Add("<b><i><u>I said</u></i></b>:<br />");

        foreach (var line in input)
            result.Add(line + "<br />");

        return PartialView("_IndexPartial", result);
    }
}

You’ll have the Index view that looks like:

@{
    ViewBag.Title = "Index";
}

<h2>Hello!</h2>
<p>Please tell me something...</p>

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "targetDiv" }))
{
    @Html.TextArea("MyInput", new { @style = "width:100%;height:200px;" });
    <br /><br />
    <input type="submit" value="What did you say?" />
}

<div id="targetDiv" style="width:100%;margin-top:20px;padding:10px;">
    ...
</div>

The _IndexPartial.cshtml will look like this:

@if (Model != null)
{
    foreach (string line in (Model as List<string>))
    {
       @Html.Raw(line)
    }
}

Eventually, it will look like this:

Ajax form

Ajax form - result

The source code is also available: Ajax Support Mvc3 Source Code

The MD5 function

When you’re working with hashed passwords, it might be useful to have the MD5 encryption feature in your database.

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- ==================================================
-- Author:		Mike Bevers
-- Create date: 07/04/2011
-- Description:	Hashes a value with the MD5 algorithm
-- ==================================================
CREATE FUNCTION MD5
(
	@value varchar(255)
)
RETURNS varchar(32)
AS
BEGIN
	RETURN SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', @value)),3,32);
END
GO

Usage:

select dbo.MD5('test')
-- Will return '098f6bcd4621d373cade4e832627b4f6'

Where are my regions?

When I implemented my first interface with Visual Studio 2010, I noticed that the implemented methods were not enclosed with the Region directive.

Interface without regions

Interface implementation without regions

If you want your regions back, you explicitly need to tell Visual Studio by enabling them in the options dialog.

Options - Texteditor - Advanced

Options - Texteditor - Advanced

After you’ve enabled them, all is back to normal…

Interface with regions

Interface implementation with regions

Problem

If you don’t place a ‘not null’ condition before raising an event, you might get a NullReferenceException. That’s why we usually type something like:

event EventHandler MyEvent;

void RaiseMyEvent()
{
    if (MyEvent!= null) MyEvent(this, EventArgs.Empty);
}

Solution

Why not use the following pattern:

event EventHandler MyEvent = delegate { };

void RaiseMyEvent()
{
    MyEvent(this, EventArgs.Empty);
}

This way we can avoid the following:

Raising Events

Raising Events

Source

I found a nice tutorial on Josip Medved’s blog. I’ve copied the article below for back-up purposes.

How to connect VS2008 with TFS 2010

Team Foundation Server 2010 works great when combined with Visual Studio 2010. However, if you wish to combine it with Visual Studio 2008, some additional setup is required.

First thing that you need to install is Team Explorer 2008. If you already used source control, you may have it. Easiest way to check is to go into Tools > Options and select Source Control. If there is “Visual Studio Team Foundation Server” in plug-in list, you can skip this download.

Another thing I installed was Visual Studio Team System 2008 Service Pack 1 Forward Compatibility Update for Team Foundation Server 2010. I do not think that this long-named update is really “must” but I decided to install it anyhow – just in case.

Once you install everything, you can try adding Team Foundation Server 2010 as destination, but you will be greeted with error “TF31002: Unable to connect to this Team Foundation Server …”. Reason behind this is that old Team Explorer 2008 does not know anything about collections.

Solution would be to add it as full path (e.g “http://server:8080/tfs/collection”). I could not do it because every time I entered full path, I also got error “TF30335: The server name cannot contain characters ‘/’ or ‘:’ …”. Since official way would not work it was time to come up with alternative.

In order to add TFS 2010 server, you will need to exit Visual Studio 2008 and go into Registry editor. Find key “HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\TeamFoundation\Servers” and at this location just add string value. Name of this value will be what Team Explorer 2008 will use for display. It’s value is full address of your server. It should be something like “http://server:8080/tfs/collection”.

Now you can go into Visual Studio 2008 and Team Explorer will have new entry. As you work with it, you will notice that not everything is “bump-free” (e.g. tasks). However, source control it self will work perfectly and that was enough for me.

What type of motherboard is in this PC?

The other day, I was at a friend’s house. His PC was running slow and wanted to know how he could improve performance.

After I perfomed some general clean-up actions (Windows disk clean-up, defragmenting, uninstalling crappy software/spyware), my friend wanted to know if he could add some RAM memory. I didn’t want to open up his machine, but I did need info about the motherboard. I had a utility I found a long time, called: CPU-Z. This utility is … awesome and free!

CPU-Z

CPU-Z Motherboard Information

With this information I could do a look-up on the manufacturer’s website. I found out that he had 4 RAM slots, so he could add extra memory…

Developing RegEx patterns

Recently I was creating some regular expressions. Because I’m not very experienced with RegEx, I was kind of “debugging” in my TDD approach. A colleague of mine recommended a website which helped a lot: http://www.gskinner.com/RegExr/.

It’s completely free and you can use it online!

Context

Before WCF, there was ASMX aka ASP.NET Web Services. Debugging ASMX or WCF are quite different. Let’s take a look how we can enable debugging in ASMX and WCF.

Basics of running a web application

When you hit the F5 button and your startup project is an ASP.NET, ASP.NET Web Services or WCF application, Visual Studio will start an ASP.NET Development Server. This is what we call Client-side hosting using Cassini. If want to know more check Dino Esposito’s article on MSDN. Wikipedia also has a description about UltiDev Cassini Web Server.

After Cassini is loaded, by default an Internet Explorer (IE) window will open and browse to the Cassini URL on your localhost.

Debugging ASMX

When you hit the F5 button, IE will open a webpage which looks like the image below:

Browse ASP.NET Web Service

Browse ASP.NET Web Service

You’ll notice that all Web Methods are listed as hyperlinks. So when I click “HelloWorld” in my example, it will browse forward:

Invoke ASP.NET Web Service

Invoke ASP.NET Web Service

Before we invoke the Web Method using IE, first we need to attach the Visual Studio instance with our sources to Cassini! In Visual Studio, navigate to “Debug” > “Attach to Process …”. In the list of Available Processes there should be a process called “WebDev.WebServer.exe” and the Title should be “ASP.NET Development Server – Port XXXX”. The Port XXXX is the port on which Cassini is active. Click the “Attach” button and you are ready to go!

Now, click the button “Invoke” in Internet Explorer and your Visual Studio will stop at the first breakpoint it encounters. When the method has returned its result, a new IE window will open and display the result as XML, like below:

ASP.NET Web Service Result

ASP.NET Web Service Result

 

Debugging WCF

Like ASMX, Visual Studio will open a browser by default:

Browse WCF Service

Browse WCF Service

At first it shows the directory listing. When you open your Service1.svc, you’ll notice that no hyperlinks or Invoke buttons are available on our Operation Contracts. To debug the WCF service, Microsoft provided a small tool in your Visual Studio installation directory, called “wcfTestClient.exe”. The tool is usually located in “C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\wcfTestClient.exe”. If not, you can download and install the Windows SDK from the Microsoft website.

In order to automatically start the “wcfTestClient.exe” and load our Services, we need to edit the WCF application project:

Start wcfTestClient.exe

Start wcfTestClient.exe

You can add multiple svc’s by leaving a space between the addresses.

When your WCF Service is loaded, you can double click an Operation Contract and invoke it. You don’t need to attach your Visual Studio to another process, it’s already attached for you.

wcfTestClient Method Invokation

wcfTestClient Method Invokation

Context

When you’re working with a UI or plain text data integration, conversions are often an issue. In this case I would like to talk about DateTime objects.

Recently, there was an issue in one of the other teams. They had a WinForms UI where they wanted to display a DateTime property in two different textboxes, one for the date and another for the time. They had their reasons for not using a DateTimePicker control or any other method. That wasn’t really the problem. One of the business users discovered an error when trying to save changes. The development team figured out what went wrong, apparently it was a “Culture” thing.

The business user’s computer was using Windows XP and its regional settings were set to English – United States. When the application tried to parse the textboxes and store the value back in the property, the month and day were swapped. In Europe we usually use “dd/MM/yyyy”, in the US they use “MM/dd/yyyy”.

Normally this should not pose a problem, the date was successfully loaded, so why wouldn’t it convert back as expected. Well, one of the main reasons is VB.NET. VB.NET has a feature called CDate, which can convert a string to a Date object. In C#, you only have a DateTime object. What happened? The CDate takes the regional settings and when you enter 16/10/2010, it will crash, because there is no 16th month.

Enter Mike

I overheard an intense discussion going on and decided to see if I could be of use. Call it interfering if you want; I see it as helping colleagues ;) . They explained the situation of the custom controls (the two textboxes) and the error. One of them was telling they needed to use DateTimePicker controls, another wanted to change regional settings in the database and application (I missed the point of that one), and so.

After a bit of evaluating, I noticed they were only complicating the solution/problem. I told them they only needed to parse the string into a DateTime object with specific format, and then assign the DateTime to the Date object. So instead of doing a lot of changes, add a single line of code…

I created a helper/utility class on the fly, so they could end their discussion and get back to work (and stop bothering the rest of us :) ).

DateTimeParser

using System;
using System.Globalization;

namespace MyNamespace
{
    public static class DateTimeParser
    {
        public static DateTime ParseDateTime(string value, string inputFormat)
        {
            return ParseDateTime(value, inputFormat, CultureInfo.InvariantCulture);
        }

        public static DateTime ParseDateTime(string value, string inputFormat, CultureInfo provider)
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentNullException("value");

            try
            {
                return DateTime.ParseExact(value, inputFormat, provider);
            }
            catch (Exception ex)
            {
                throw new Exception("Could not parse date: " + value, ex);
            }
        }
    }

	public class DateTimeParserDemo
	{
		public DateTime Test()
		{
			string myDate = "31/12/2010 23:59:59";
			return DateTimeParser.ParseDateTime(myDate, "dd/MM/yyyy HH:mm:ss");
		}
	}
}

 

VB.NET code

If you prefer the code in VB.NET head to the website of DeveloperFusion.com, they have an excellent C# to VB.NET converter.