Back from NSBCon 2015

December 10, 2015 Leave a comment

I just returned from Dallas having attended NSBCon 2015.  Overall, a very positive experience with several informative sessions.  It was a good opportunity for me to relax and rejuvenated since I haven’t been feeling very motivated lately.

One of the announcements was ServiceMatrix is being discontinued. I’ve never been a fan of using drag-drop tools for anything outside of user interface development, so the discontinuation will probably save me some stress in the future.

The next release of NServiceBus will utilize asynchronous message handlers, which is unfortunately a breaking change. The session continued with explanations on how to migrate existing codebases and pitfalls to watch out for.

The session on Akka.NET and the actor model peaked my interest. I’ve heard of Akka.NET, but I haven’t investigated any further. Having one of the developers talk about Akka.NET was a good chance to hear what it brings to table. Definitely something I’ll need to look into more.

I especially enjoyed listening to the panel discussions and hearing everyone’s opinion on topics that the audience brought up. It’s always a pleasure to listen to several well known developers in the industry talking about past, present, and future architectures/patterns being used in the wild. The topic around technological fads resonated with me. In my opinion, there are simply too many people that immediately become overzealous about new and shiny patterns or technologies without looking at past mistakes. History repeats itself and too many people ignore that.

There was another great session about things not to do with NServiceBus. While the examples were targeted to NServiceBus, the principle applies to a lot of other things. Too many times, certain software is shoved down everyone’s throat as the end-all solution for everything.

Everything considered, I enjoyed the four days I spent in Dallas. Most of the sessions were very informative and insightful, so I have plenty to think about.

Logging database and web service calls with PostSharp

November 4, 2015 Leave a comment

We’ve been having some sporadic performance problems with our website. We needed to find out which page or operation was taking too long to complete and exhausting all the worker threads. Unfortunately, due to the size of the codebase and the lack of performance auditing, it was difficult to pinpoint where the problem was occurring.

Only a small portion of the codebase was utilizing dependency injection, so we couldn’t decorate or intercept all dependencies with an auditing class. Fortunately, an IL weaving framework such as PostSharp can help with this situation. This was my first time using PostSharp, but I found it tremendously helpful.

A good would start would be logging database and web service calls.

using (SqlConnection conn = new SqlConnection("Server=.\\SQL2008; Database=Test; Trusted_Connection=True"))
using (SqlCommand cmd = new SqlCommand("cp_GetUserInfo", conn))
{
	cmd.CommandType = CommandType.StoredProcedure;
	cmd.Parameters.AddWithValue("@UserName", "JD");
	conn.Open();

	using (SqlDataReader reader = cmd.ExecuteReader())
	{
		while (reader.Read())
		{
			Console.WriteLine("User {0} {1}'s member ID is {2}.", reader["FirstName"], reader["LastName"], reader["MemberID"]);
		}
	}
}

Without modifying the existing code, I want to log the connection string, any parameters, and the amount of time it took to execute this stored procedure. We’ll inherit from OnMethodBoundaryAspect to record information before and after our database call.

[AttributeUsage(AttributeTargets.Assembly)]
[MulticastAttributeUsage(MulticastTargets.Method)]
[Serializable]
public class DatabaseAspect : OnMethodBoundaryAspect
{
	public override void OnEntry(MethodExecutionArgs args)
	{
		args.MethodExecutionTag = Stopwatch.StartNew();
		
		SqlCommand cmd = (SqlCommand) args.Instance;

		Console.WriteLine("Executing command: {0}", cmd.CommandText);
		Console.WriteLine("\t- Connection String: {0}", cmd.Connection.ConnectionString);
		
		List<string> parameters = new List<string>();

		for (int i = 0; i < cmd.Parameters.Count; i++)
			parameters.Add("\t- Parameter " + cmd.Parameters[i].ParameterName + ": " + cmd.Parameters[i].Value);

		if (parameters.Count > 0)
			Console.WriteLine(String.Join("\n", parameters));
	}

	public override void OnExit(MethodExecutionArgs args)
	{
		Stopwatch sw = (Stopwatch) args.MethodExecutionTag;
		sw.Stop();

		SqlCommand cmd = (SqlCommand) args.Instance;

		Console.WriteLine("Command \"{0}\" took {1} ms.", cmd.CommandText, sw.ElapsedMilliseconds);
	}
}

Running the code will produce the following:

Executing command: cp_GetUserInfo
        - Connection String: Server=.\SQL2008; Database=Test; Trusted_Connection=True
        - Parameter @UserName: JD
Command "cp_GetUserInfo" took 1124 ms.
User John Doe's member ID is 1234.

Great, now I can see the length of each database call and the parameters without digging through IIS logs hoping to find something to reconstruct the request. In additional to database calls, I want to log any web service requests. As with the database aspect, we can inherit from OnMethodBoundaryAspect to log information before and after the request.

[AttributeUsage(AttributeTargets.Assembly)]
[MulticastAttributeUsage(MulticastTargets.Method)]
[Serializable]
public class WebServiceAspect : OnMethodBoundaryAspect
{
	public override void OnEntry(MethodExecutionArgs args)
	{
		args.MethodExecutionTag = Stopwatch.StartNew();
		dynamic client = args.Instance;
		Console.WriteLine("Found service call to: {0}", client.Client.Endpoint.Address);
	}

	public override void OnExit(MethodExecutionArgs args)
	{
		Stopwatch sw = (Stopwatch) args.MethodExecutionTag;
		sw.Stop();

		dynamic client = args.Instance;
		Console.WriteLine("Service call to \"{0}\" took {1} ms.", client.Client.Endpoint.Address, sw.ElapsedMilliseconds);
	}
}

We’ll apply these aspects to the entire assembly using assembly attributes.

[assembly: WebServiceAspect(AttributeTargetMembers = "regex:Return|Use", AttributeTargetAssemblies = "Example", AttributeTargetTypes = "Example.WcfClient*")]
[assembly: DatabaseAspect(AttributeTargetMembers = "Execute*", AttributeTargetAssemblies = "System.Data", AttributeTargetTypes = "System.Data.SqlClient.SqlCommand")]

Muting sounds in a Chrome tab

May 1, 2015 Leave a comment

Although I still prefer the Firefox’s developer tools for debugging, I have switched to Chrome almost exclusively for my day-to-day browsing.

A while ago, Chrome added an audio icon to indicate which tabs were playing sounds.

Audio icon in Chrome

While I love this feature, I always wanted a way to manually mute a single tab. Well, there is a way and I can’t believe I never knew about it until now. Just copy and paste the following into Chrome’s address bar and enable the audio mute option:

chrome://flags/#enable-tab-audio-muting

Now I can click on the audio icon and mute a single tab without having to mute my entire computer.

Audio muted in Chrome

Encrypting files

October 16, 2014 Leave a comment

I have several files I need to backup to the cloud. I looked at automated backup solutions like Mozy, CrashPlan, etc…, but they were expensive compared to storage solutions like Amazon S3, Azure Storage, and others. So I figure that I can just encrypt the files myself and upload it to one of those services. I wrote the code below to encrypt my files:

void Main()
{
	string pass = "$ecret p@ssword";
	 
	string source = @"C:\file.dat";
	string encryptedDestination = @"C:\file.encrypted";
	string decryptedDestination = @"C:\file.decrypted.dat";
	
	byte[] salt = EncryptFile(pass, source, encryptedDestination);
	DecryptFile(pass, salt, encryptedDestination, decryptedDestination);
			 
	Console.WriteLine ("Done");
}

byte[] EncryptFile(string password, string source, string destination)
{	
	if (!File.Exists(source))
		throw new ArgumentException("Source does not exist.", "source");
	
	if (File.Exists(destination))
		throw new ArgumentException("Destination already exist.", "destination");
		
	byte[] IV;
	
	using (var provider = new RijndaelManaged())
	using (var passwordGen = new Rfc2898DeriveBytes(password, provider.IV))
	{
		provider.Key = passwordGen.GetBytes(provider.KeySize / 8);
		IV = provider.IV;
			
		using (var encrypt = provider.CreateEncryptor())
		using (var destinationStream = File.Create(destination))
		using (var cryptoStream = new CryptoStream(destinationStream, encrypt, CryptoStreamMode.Write))
		using (var sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read))
		{
			sourceStream.CopyTo(cryptoStream);
		}
	}
	
	return IV;
}

void DecryptFile(string password, byte[] salt, string source, string destination)
{
	if (!File.Exists(source))
		throw new ArgumentException("Source does not exist.", "source");
	
	if (File.Exists(destination))
		throw new ArgumentException("Destination already exist.", "destination");
		
	using (var provider = new RijndaelManaged())
	using (var passwordGen = new Rfc2898DeriveBytes(password, salt))
	{
		provider.Key = passwordGen.GetBytes(provider.KeySize / 8);
		provider.IV = salt;
				
		using (var decrypt = provider.CreateDecryptor())
		using (var destinationStream = File.Create(destination))
		using (var cryptoStream = new CryptoStream(destinationStream, decrypt, CryptoStreamMode.Write))
		using (var sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read))
		{
			sourceStream.CopyTo(cryptoStream);
		}
	}
}

Although the encryption code works, I still need to store the generated initialization vectors (IV) somewhere along with the encrypted files. That’s kind of a hassle. Instead, I can prepend the IV to the encrypted files. When I’m decrypting files, I can read the first 16 bytes and assume that’s the IV.

void EncryptFile(string password, string source, string destination)
{   
    if (!File.Exists(source))
        throw new ArgumentException("Source does not exist.", "source");
     
    if (File.Exists(destination))
        throw new ArgumentException("Destination already exist.", "destination");
     
    using (var provider = new RijndaelManaged())
    using (var passwordGen = new Rfc2898DeriveBytes(password, provider.IV))
    {
        provider.Key = passwordGen.GetBytes(provider.KeySize / 8);
                     
        using (var encrypt = provider.CreateEncryptor())
        using (var destinationStream = File.Create(destination))
		using (var cryptoStream = new CryptoStream(destinationStream, encrypt, CryptoStreamMode.Write))
		using (var sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read))
		{
			destinationStream.Write(provider.IV, 0, provider.IV.Length);
			sourceStream.CopyTo(cryptoStream);
		}
    }
}
 
void DecryptFile(string password, string source, string destination)
{
    if (!File.Exists(source))
        throw new ArgumentException("Source does not exist.", "source");
     
    if (File.Exists(destination))
        throw new ArgumentException("Destination already exist.", "destination");
	
	byte[] salt = new byte[16];
	
	using (var sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read))
	{
		sourceStream.Read(salt, 0, salt.Length);
	}
	
    using (var provider = new RijndaelManaged())
    using (var passwordGen = new Rfc2898DeriveBytes(password, salt))
    {
        provider.Key = passwordGen.GetBytes(provider.KeySize / 8);
        provider.IV = salt;
                 
        using (var decrypt = provider.CreateDecryptor())
        using (var destinationStream = File.Create(destination))
        using (var cryptoStream = new CryptoStream(destinationStream, decrypt, CryptoStreamMode.Write))
        using (var sourceStream = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
			sourceStream.Seek(salt.Length, SeekOrigin.Begin);
            sourceStream.CopyTo(cryptoStream);
        }
    }
}

Extracting text messages on iPhone

August 20, 2014 1 comment

I bought an iPhone a few years ago and I’m about to switch phones. I didn’t want to lose the history of my text messages, so I wanted a copy of all my text messages.

After manually backing up the phone using iTunes, we can navigate to where the backup is stored locally. In my case, the backup is stored at:

C:\Users\<MyUserName>\AppData\Roaming\Apple Computer\MobileSync\Backup\

All text messages are stored in a SQLite file named 3d0d7e5fb2ce288813306e4d4636395e047a3d28. There are two tables I’m going to focus on: message and handle. The message table contains your entire history of text messages and various flags to determine whether a message was sent or received, whether the message was read, etc…. The handle table contains a list of phone numbers you’ve messaged and some additional information such as whether they were sent as a text message (SMS) or an iMessage.

Since I just wanted to backup my entire history, I can join these two tables using the following query:

select 
	DATETIME(date + 978307200, "unixepoch", "localtime") as "Date", 
	h.id as "Phone Number", 
	m.text as "Text"
from message m inner join handle h on m.handle_id = h.rowid
order by m.rowid desc

I did have some trouble with the date column in the message table. The date column stores a number like 340475640, which I wrongly assumed was the Epoch time that began on January 1, 1970. Turns out that dates in iOS starts on January 1, 2001. The magic number 978307200 in the query above represents how many seconds there are between these two dates.

Because LINQPad has support for SQLite using the IQ driver, it was easy to use LINQpad to query this database using both SQL and LINQ.

(from m in message
join h in handle
on m.handle_id equals h.ROWID
orderby m.date descending
select new 
{
	Date = new DateTime(2001, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc)
		.AddSeconds(m.date.Value)
		.ToLocalTime(),
	PhoneNumber = h.id,
	Text = m.text
})
.Dump();

An organization’s leader

July 21, 2014 6 comments

I chose the word “organization” very carefully. I did not say pod or company because this goes beyond the scope of the workplace. An organization is a group of people that share a purpose.

In 2013, I met a man that completely changed the way I think about leaders. This man was friendly, but intimidating at the same time. His directions were stern, but everyone followed them without question.

This man led a group of people who were very good at what they did. They participated in an activity that required a lot of teamwork. Each person in this group were already considered extremely strong individuals, but teamwork was the deciding factor for the success of the group.

The way this group operated was much different than anything I’ve experienced and it’s hard to describe how well it worked. The first time I participated, I was completely overwhelmed by how well everything worked while under pressure, just by the singular action of following the leader’s direction. Everyone had immense respect for the leader because he was on the front line along with everyone else. This group moved through obstacles like a rolling ball, everyone stayed close and moved as a single cohesive unit. This was the opposite of divide and conquer. Individual skill contributed to keeping the group as tight as possible, but following the leader’s direction was key.

Does that sound like your cookie cutter leadership article? It probably does. So why was this leader so different than everyone else? His charisma, willingness to stand on the front lines, and long history of success made me trust him completely. I wasn’t close friends with this man. In fact, I rarely spoke to him. In addition to that, the exclusivity of this group allowed me to surround myself with people who were extremely talented.

There’s not really a purpose or message in this blog post. This is just something I needed to get off my chest. I miss being part of a team that was led by that man. Will I ever find a group that operated as well as they did in the professional world? I have my doubts. Granted what we were doing was much different than programming. With all of today’s politics and bureaucratic bullshit, it really shows how inefficient things can get.

Versa Gripps

July 10, 2014 Leave a comment

My posts are usually technical, but every once in a while I’ll post something here that isn’t related to programming. I don’t usually do product reviews, unless it’s something that I really like.

I’ve always been fairly active, so I’m usually at the gym 4 – 5 times a week. My grip will start to give about 20 minutes into a heavy workout, so I purchased some cheap lifting straps to prevent my grip from being the limiting factor. Unfortunately, these cheap/generic lifting straps don’t have very good wrist support, so my wrists will start to hurt after a while.

About three years ago, I saw a professional use a set of unique looking straps. After some research, I found out he was using a pair of Versa Gripps. They’re much more expensive than your generic lifting straps, but it has been one of the best purchases I’ve made in the last few years.

They do take some getting used to and it may seem a little awkward at first. The neoprene padding provides good support without digging into my wrists. The straps are long enough to assist in gripping power, but short enough to allow me to drop the weights if I fail. Because the straps are short, they easily allow for one handed wrapping. The only real con I have is that the non-slip material isn’t effective when your hands are sweaty.

I’ve worn these straps 4 – 5 times a week, every week, for the past three years. As you can see, they are starting to deteriorate.

The stitching on the non-slip material was the first to go. As the stitching continued to unravel, the non-slip material started to rip, exposing the cloth material between the layers.

Eventually it has gotten to the point where half of the strap is gone.

Durability issues aside, it’s still the best lifting straps I’ve used. I can probably get another six months out of these straps, but I’ve already purchased another pair in anticipation for when these fail.

Do I recommend these straps for everyone? Probably not. I would only recommend these straps if you’ve been lifting regularly and your grip fails before you can finish your workout. For those people that do fall into this category, then these straps are great to have.

Follow

Get every new post delivered to your Inbox.