.net
Enable SSL in web.config for SmtpClient
5If you want to use SSL when connecting to your email server and are using the SmtpClient from .Net 4.0 you can now set EnableSSL via the web.config file, which you couldn’t do before.
I’m only posting this because the docs (http://msdn.microsoft.com/en-us/library/w355a94k.aspx) for .net 4 don’t seem to bother mentioning it, which is a bit frustrating.
Now you can do this:
<configuration> <system.net> <mailSettings> <smtp deliveryMethod=”network”> <network host="localhost" port="25" enableSsl="true" defaultCredentials="true" /> </smtp> </mailSettings> </system.net></configuration>So you’d Like Implicit Casting in Moq?
0I love using Moq, it’s great and it saves me a huge amount of time and effort when I’m writing unit tests. There’s only thing that bothers me about it. The Object property on a mock, why is this even needed? Surely the judicious use of the implicit keyword and you could have a cleaner API, for example (coded in a text editor, I haven’t even tried to compile it):
var mockFileSystem = new Mock<T>();
var objectUnderTest = new FileBackedThingy(mockFileSystem.Object);
objectUnderTest.Save();
mockFileSystem.Verify(x => x.SaveFile(It.IsAny()), Times.Once);
Could be replaced with:
var mockFileSystem = new Mock<T>();
var objectUnderTest = new FileBackedThingy(mockFileSystem);
objectUnderTest.Save();
mockFileSystem.Verify(x => x.SaveFile(It.IsAny()), Times.Once);
Now, I know it doesn’t really make much difference, but it does make things a little nicer to my eyes. So it’s Sunday afternoon, my wife’s got rehearsals and gigs all day. What’s a geek to do?
Never having seen the Moq codebase before I thought it might take a little while to find what I needed to do, I was wrong, in about 90 seconds I found the Moq.Mock class and thought I’d just need to add something along the lines of:
public static implicit operator T(Mock mock)
{
return mock.Object;
}
A really simple change, weirdly the code is already there, but commented out. Since commented out code is one of my programmer pet hates and it was code I was hoping for, this was a bit like a red rag to a bull. Fortunately there was a reasonably sensible comment justifying this heinous action:
// NOTE: known issue. See https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=318122
The complaint is a simple one, C# won’t let you have user defined casts between interface types. Also, they won’t let us have it, ever. So the lesson learned? No idea, but I think Bravo is show the monster trucks, so I might watch that and snooze before I go out.
Saving CSV files in UTF8 Creates  Characters in Excel
1A few weeks ago in work I was minding my own business creating one of the ubiquitous “Export to CSV” features. You know the one, the one that screams “My application even get close to what my client needs, we’ve run out of time, CSV FTW!”, yep, that one. Anyway, I ran my testing and checked the code in, happy that it did what it was supposed to.
Wrong.
I got a bug report from the client that the exported file had spurious  characters in it. Well, I ran the tool popped open the file in notepad++, nope, nothing in there. I ran the export with a larger dataset and tried again, ok now for a monster export, give me everything. Still no joy, so I did what the average developer is prone to doing and assumed that the client was being daft. I pushed back and asked for the client to give me an example. They did, I opened the file and nope, there wasn’t a single  in the file. Ok, so either the client is having a laugh at my expense, they’re lying or I’m missing something. Knowing this client, I’m missing something. I open the file again, but for a moment pretend I’m not a developer and open the file in Excel. Â’s abound, arse, how did I do that?!
It turns out that for all Excel’s sophistication it doesn’t like UTF-8 encoded files. It’s much more at home with files encoded as Windows-1252, well at least for Latin languages; I’m not sure what happens in non-Latin languages.
So if you have code that looks like this:
using (var writer = new StreamWriter("myfile.csv", false))
{
writer.WriteLine("Look,Ma,I,Can,Do,CSV");
}
Change it to this:
using (var writer = new StreamWriter("myfile.csv", false, Encoding.GetEncoding("Windows-1252")))
{
writer.WriteLine("Look,Ma,I,Can,Do,CSV");
}
And now Excel will play nice. You can now rest easy in the knowledge that your client can use Excel to draw pretty graphs, pivot things and you know, do whatever it is normal people do with Excel.
Slow file Deletion in Visual Studio 2010
0I’ve recently been trying to delete some cruft from a few projects I’m working on. In one solution with about 16 projects I was trying to remove about 40 or so image files. It was taking a small eternity. I suspected that it was our flaky in house install of TFS, or maybe Resharper or maybe even a T4 template going crazy. I tried eliminating all of these and it was still very, very slow.
After a bit of digging around I found this posting http://tech.groups.yahoo.com/group/altdotnet/message/11685 which basically suggests that if your recycle bin is getting near its limit and is set to be quite large it’s going to take ages to remove files.
After emptying the recycle bin I went from 90 seconds to delete a file (yes 1 file, 90 seconds) I can now delete files almost instantly.
Problem solved, back to work.
GUI Autorunner for NUnit
0
For a sometime MBUnit has had an auto runner, sadly NUnit has managed to avoid getting one for itself. I like using NUnit, in fact all my unit tests are now written in NUnit. I really like the idea of having an auto runner, so I built one.
The binaries are here: Auto Runner (Binaries) and the source is here: Autorunner NUnit-2.5.7.10213 (src) It’s not had much testing, I simply got it to work for the tests that I was trying to run and not a lot more in fact I think I may use it to get my “Works on My Machine” certification.
Using it is fairly simple, open up the GUI, load your project as normal and in the test menu there is a new option called “Auto Run” clicking that kicks off the first run and then waits for changes to the Assemblies, when they are changed a new test run is kicked off. To stop the auto run simply click the same menu item.
If people like this then I’ll take a look at pushing it into the main NUnit project. What do you think?
Migrator .Net Code Templates
2A little while ago I posted some code samples that made the process of creating migrations in migrator .net a bit more simple. Well it came with the “it works on my machine” seal of approval and indeed it worked on my machine, but not on others. It turns out there is a difference between the way VS 2010 Express and VS 2010 Ultimate process code templates.
Anyway, I’ve found the bug and fixed it. You can download the latest version of the code from here: http://github.com/ilivewithian/Migrator-.Net-Project-Templates. If you don’t want to compile the source your source yourself, don’t worry there is a release folder in the root of the project with a compiled version of the project available.
To install the templates simple take the “Migrator .Net Templates.dll” and register it in the GAC and take the “MigrationTemplate.zip” file and drop it into your “<Documents>\Visual Studio 2010\Templates\ItemTemplates\Visual C#” folder. Now all that’s left to do is restart Visual Studio and you are up and running.
To check it’s up and running go to file new item and select migration template. Give it a name that’s sensible and you should get something like this:
using System.Data;
using Migrator.Framework;
namespace MigrationLibrary
{
[Migration(201009302115255)]
public class Migration1 : Migration
{
public override void Up()
{
throw new System.NotImplementedException();
}
public override void Down()
{
throw new System.NotImplementedException();
}
}
}
Let me know what you think.
Simplifying Session Wrapping Properties using Expression<Func>
4I’m not a big fan of using session, but sometimes there isn’t a sensible alternative. In that case I always wrap the session object in a property. In the past I’ve failed to come up with a satisfactory session variable naming convention. With that I’ve always hated using strings for session names. Each solution basically boils down to typing some strings some where in your code, either directly into the call to Session[] or the same process, but via a series of predefined const strings. Using a const string gets you slightly cleaner code, but there is nothing to prevent a developer picking the wrong const and ending up in a delightful mess.
Once you’ve got past the string mess, you then end up having to write code to check the session value, set a default value and return. Sure, it’s not hard, but you will end up writing a lot of repetitive code. That’s boring, laborious and error prone.
To try and fix both the string problem and to try and keep my code nice and D.R.Y I’ve come up with is this:
public class SessionManager: ISessionManager
{
private HttpSessionState Session
{
get { return HttpContext.Current.Session; }
}
public T GetSessionValue(Expression> expression, T defaultValue)
{
var sessionKey = GetSessionKey(expression);
object sessionValue = Session[sessionKey];
if (sessionValue == null || ! typeof(T).IsAssignableFrom(sessionValue.GetType()))
{
Session[sessionKey] = defaultValue;
sessionValue = defaultValue;
}
return (T)sessionValue;
}
public void SetSessionValue(Expression> expression, T value)
{
var sessionKey = GetSessionKey(expression);
Session[sessionKey] = value;
}
private string GetSessionKey(Expression> expression)
{
MemberExpression me;
var body = expression.Body;
if (body is MemberExpression)
{
me = body as MemberExpression;
}
else if (body is UnaryExpression)
{
var ue = body as UnaryExpression;
me = ue.Operand as MemberExpression;
}
else
{
throw new NotImplementedException();
}
return "SessionManager_" + me.Member.ReflectedType + "." + me.Member.Name;
}
}
To use this I would simple create a property similar to this:
public IList AnImportantProperty
{
get
{
return SessionManager.GetSessionValue(() => AnImportantProperty, new List());
}
set
{
SessionManager.SetSessionValue(() => AnImportantProperty, value);
}
}
Now my session is tidily hidden away. It will survive refactoring of the property name and guarantee a unique session name. To my eyes it looks clean, simple and D.R.Y.
Working with partially constructed objects in .Net
1Just a quick one, but what do you think will be the output of this program? It’s not what I expected:
class Program
{
static void Main()
{
CanILeak leakyRef = null;
try
{
new CanILeak(cil => leakyRef = cil);
}
catch (Exception)
{
Console.WriteLine("Exception");
}
if (leakyRef != null)
leakyRef.AreYouStillThere();
Console.ReadLine();
}
}
class CanILeak
{
public CanILeak(Action fail)
{
fail(this);
throw new Exception();
}
public void AreYouStillThere()
{
Console.WriteLine("I'm still here");
}
}
