Skip to content

MikeBevers.be

Putting it out there…

The Problem

At a customer, I had to gather data from two databases. So I started writing a SQL query that combined data from two databases and wanted to join them on an ID field. Then this popped up: “Cannot resolve the collation conflict between “SQL_Latin1_General_CP1_CI_AS” and “Latin1_General_BIN” in the equal to operation“. Apparently along the way they decided, or by accident, switched collations.

The Solution

It’s actually very simple, you have to explicitly specify the collation in your query. I posted the code because it’s too lengthy and error-prone to write it manually several times a day…

SELECT p.KeyField
FROM DB1.PrimaryTable p
INNER JOIN DB2.SecondaryTable s ON LTRIM(RTRIM(p.KeyField))COLLATE SQL_Latin1_General_CP1_CI_AS = s.KeyField

That should do the trick!

The problem

Recently we’ve changed the extension of the external url of our TFS server. Strange enough Visual Studio doesn’t provide an edit feature in the TFS servers window. Maybe that’s why it’s called “Add/Remove Team Foundation Server”.

The solution

I went looking where Visual Studio stored the TFS info. After a bit of searching in the Registry I ended up in: “CURRENT_USER\Software\Microsoft\VisualStudio\10.0\TeamFoundation\Instances”.

In the Instances folder you’ll see all your added TFS servers. You can start by changing the name of the folder, this text is used as the name label. What is important, is to change all the Uri entries you’ll find in the subfolders. There is one per TFS server and one for each collection!

Happy coding!

The problem

I was trying to “DropCreate” a database using Entity Framework 4.3. Suddenly I get an exception that EF was unable to drop the database. I fired up my SQL Server Mngt Studio and tried to take the database offline. Again, an error message that it couldn’t get an exclusive lock because of open connections.

The solution

After a bit of searching on the SQL Server processes I ended up with this:

USE master
go

DECLARE @dbname sysname
SET @dbname = 'MyDbName'

DECLARE @spid int
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)
WHILE @spid IS NOT NULL
BEGIN
EXECUTE ('KILL ' + @spid)
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid
END

And instantly, it was my! database yet again.

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…