Certification, SQL Server comments edit

I believe I had a considerable amount of experience with SQL Server throughout my career. Recently I decided to get SQL Server MSCA title which requires taking 3 exams (70-461, 70-462 and 70-463 namely). I think it’s a good way of polishing existing knowledge and learning new stuff. Hands on experience is great but generally you only learn enough to get things done, which is the desired result of course but when studying for certification you have to cover all details. Some of them may be quite trivial and don’t have much practical usage but I think they all may come in handy sometime so it doesn’t hurt to learn more.

On to 70-461

The number of questions vary between 40 – 60 and test duration is between 2 – 3 hours. In my exam, I had 44 questions and the time given was 2 hours.

Total score is 1000 and the passing score is 700. I’ve got a whopping 906. Actually at the end of the day doesn’t really matter if you get a full 1000 but it feels better to pass with a high mark.

Study Notes

I decided to release my notes on a separate blog post as it became very lengthy very quickly.

Study Materials

70-461 Training Kit

I used several different sources preparing for the exam. One of the most important ones is the official Training Kit. Also, I found the CBT Nuggets video series quite useful. You can move at a much faster pace to cover the topics with a video. So I recommend those videos (despite the steep price of CBT Nuggets subscription)

There is another series in TrainSignal but I haven’t tried it.Finally I’ve found a short introductory video (around 1h 15m) to the exam. You can find the find link in the resorces section. It’s a very fast-paced introduction mainly underlining the exam topics that are not commonly used in real life.

Resources

Electronics comments edit

Playing with Gadgeteer fuelled my enthusiasm so I dusted off my solderless breadboard and basic electronics components that came with the basic kit I bought a while ago.

Electronics

I don’t know what most of those things are but I decided to start with a simple circuit that lights an LED. After burning a few LEDs I learned that it would be a good idea to use a resistor in the circuit in order not to fry the LED. Reading resistors turned out to be a pain though! They are colour-coded and you have to know the value of each colour. I found here a nice calculator to free myself from that unnecessary waste of time: http://www.csgnetwork.com/resistcolcalc.html

Yet there was another problem. All the sources I had found were talking about 3 bands. But my resistors had 5 colour bands! After spending some more time I learned that there is also a 5-colour version of resistors. Here is the calculator for the 5-band version: http://www.diyalarmforum.com/5-band-resistor-calc

The problem is they are so tiny that it’s not always easy to distinguish the colours. Anyway, I decided to pick one and hope for the best.

The next challenge is using the breadboard. Even though it’s meant to make life easier for circuit builders there’s a still a few things to learn about it which are not very intuitive. I found a nice video on Youtube to learn the basics: http://www.youtube.com/watch?v=k9jcHB9tWko

After playing around a little bit a finally managed to light a LED which was nice but didn’t feel like much of an accomplishment. It required too much time to achieve something so trivial.

Electronics

I think I’ll need various components to build something significant. The kit I have looks very limited. But before I invest more money into this I think I’ll keep playing with more high-level products like Gadgeteer, Netduino and Arduino. If I can incorporate breadboard and lower-level components into systems using those that would a bonus but without such powerful controllers I don’t think I’ll get satisfying results with circuits built on a solderless breadboard.

.NET Gadgeteer, Development, Gadget comments edit

I like gadgets and electronics. Programming against hardware and interact with the real world makes it much more fun I think. I bought a .NET Gadgeteer kit set some time ago but hadn’t much time to spend on it. Now it’s time to break that cycle and actually do something with it.

Setting up dev environment

As this will be more experimenting than actual development I decided to use my spare laptop for this task. I installed the latest version of .NET Micro Framework which can be found in the official site. My kit is GHI Electronics’ FEZ Spider Starter Kit which can be ordered from here: https://www.ghielectronics.com/catalog/product/297. I also needed to install device drivers and Spider mainboard SDK which all could be found on GHI’s website.

Updating the Firmware

Since I bought the device .NET Micro Framework release v4.2 and I wanted to work with the latest version. Turns out it’s a quite complicated process! I tried a bunch of tools but finally managed to upgrade my framework by using FEZSpiderMainboardUpdater.exe application which can be found under the legacy apps from GHI.

Spider updater

Down to coding

After installing every bit it was time to develop my first program to explore its capabilities. For this I used the excellent “Getting started with the FEZ Spider Kit”. You can find the link below in Resources section. What you do is basically designing your gadget using the designer that’s installed in the Visual Studio and comes with the Gadgeteer project. Then you connect the actual hardware components in the same way. After this you run it just like a regular project. It first compiles and deploys the project to the device then runs it. You can even debug your source code even though it’s running on the mainboard.

Mainboard Diagram

After I completed the gadget described in the guide, I got a rather strange and annoying error called “MMP error”. After Googling it a little bit I found the link for the workaround: http://netmf.codeplex.com/workitem/221. After copying the config file the problem was resolved. The source code for the sample project is just a few lines which can be seen below:

Gadgeteer source code

The application is quite simple: You press the button and the camera takes a picture and displays on the screen. You can see a sample screenshot below:

Gadgeteer sample Output

So far so good. I now have the environment ready and I have to check all the components and find out what they are capable of and hopefully come up with a cool project idea to make all this worthwhile.

Resources

Heavy Metal comments edit

Finally I have seen Download Festival. Here’s my experiences:

Wristband

Arrival

The coach ride from London Victoria to festival area took around 3.5 hours. It was a very quite ride. I was lucky to get the front seat of the bus so my view was pretty good during the journey. It was generally cloudy during the trip but started to rain as soon as we arrived! First thing I noticed was it was a huge area. Even the walk from coach stop to festival area took forever (probably because I was carrying a fairly heavy luggage under the rain). First order of business is obviously setting up the tent. It took 15 minutes of walking to find an empty spot. I could only find one in the farthest camping area. So, if you are planning to go to this festival, make sure you arrive a day before the festival. When I was done with setting up my (unnecessarily complicated) tent it was 4pm already and I already missed a few bands I wanted to see like Papa Roach.

Festival

The main problem with this festival is that it is spread over a huge area and getting to the arena from camping site was taking me 30 minutes of on foot. There was supposed to be shuttle busses but I think they were not operational. Another major problem was the logistics. There weren’t enough toilets. I remember waiting 35 minutes in a toilet queue which was simply wasteful. And they weren’t even close to my camping site, I had to walk a few minutes to get to the nearest one.

Bands

Friday

OK, so after a rather disappointing start let’s get to the fun part. Immediately after I marked my territory I ran down to the arena. The first band I could catch was Philip Anselmo’s (ex-Pantera) Down. The band is certainly not among my favourite ones and they once again reminded me why they weren’t! Some songs are fine but overall I felt bored. I just miss old Pantera!

Next band I saw was Korn. I’ve been listenning them since I was 18 or something like that but this was the first time I saw their live performance. They opened up with Blind which is the first Korn song that I’ve ever listened to so it was quite a good start. I think it was a good set list and enjoyed their performance. The next band on the main stage was Bullet For My Valentine. I had no idea how they got a better spot than Korn and they meant nothing to me. But I was too tired to wander around so I just stood there and watched them. Actually I was just trying to kill time until Slipknot took the stage.

Slipknot

Then came the Slipknot! My first live experience with them and it was well worth it. They are one of the best bands around to watch live. I was lucky that a moshpit was formed where I stood so even though I was far away from the stage I could feel that I was in a real heavy metal show! They simply rocked! At one point Corey Taylor said there were 90.000 people in there which blew mind off!

Saturday

After resting during the night I was prepared for another day of heavy metal but the weather got worse. It rained almost all night and morning turning everywhere a big pile of mud. First band of the day for me was called Young Guns. They sounded like a regular rock band. Not bad but nothing special either.

At this point, I had a bag in my hand because I bought an official festival T-Shirt and I wanted to go back to my tent to leave it. When I arrived to my tent the weather was so bad I decided to take a nap in the comfort of my tent so I missed a few bands but I don’t regret it.

When I got back to festival area, it was Motorhead time! Lemmy was magnificent as always. I still don’t understand a band like Queens of the Stone Age had a better spot on the main stage. They were just pointless and boring! Anyway, time for the the headliner of the evening: Iron Maiden! I had seen them before a few times but they have so much material that they played a show that I have never seen before! This time they only played songs from Iron Maiden (1980) to Fear of the Dark (1992). The last time I watched them was at Wacken 2010 and they played only songs mostly from their post-Brave New World era so it was like seeing the old Maiden for the first time for me.

Iron Maiden

Sunday

Started with a very nice sunny weather. After a nice not-so-healthy breakfast I had my plan laid out. I was going to start the day with Hellyeah. I like this band a lot but unfortunately they had very limited time. 25 minutes wasn’t surely enough for them and it was very early in the afternoon but I still enjoyed their strong performance a lot. A good jumpstart for the day!

Headed back to the main stage to see Coal Chamber. I didn’t even know they had reunited. But it was nice to see them for the first time. They played a short set but full of their popular songs. Next band in my list was Five Finger Death Punch. They turned out to be one of my favourite bands in the whole festival. Their frontman Ivan Moody is quite chatty and friendly. I guess one of the most remarkable moments in the festival was when he called all the kids in the audience to the stage and chatted with them. I’ll definitely keep an eye on this band.

Five Finger Death Punch

Next came Amon Amarth. After a short walk to the The Zippo Encore Stage I started waiting for them. Because of some technical difficulties they were a  few minutes late which shortened their already short set. They only played 4 songs one of which is from their upcoming album. It was nice to see them as always so no complaints. I wish they had a better spot. They surely deserve it.

Amon Amarth

Back to the main stage I started watching Stone Sour but didn’t mean much to me so decided to head to bar which seemed to be a better usage of my time!

One of the bands I wanted to see from the get-go was Newsted!  Jason Newsted’s new band is a traditional heavy/trash metal band. They are about to release their debut album and they played a few songs from it which was nice. Their last song was a huge surprise for me: Whiplash! Half of the tent turned into a mosh-pit and the crowd went insane (including yours truly!). It was a good show and this band form me is another gain from this festival. Before the headliner, they placed a stupid band called Thirty Seconds From Mars. I think the name itself is pretty explanatory about the performance of the band: Meaningless! Skipped them immediately to get the last load of the festival before the closing headliner.

The last headliner of Download 2013 was Rammstein. This was my second time with them. I had so high hopes about their show but it was very much like what I’ve seen in Istanbul in 2010. So I definitely was not impressed with it.

Rammstein

Conclusion

My conclusion is that I will not attend to another Download ever again! The main reason is it’s huge and so crowded. I hate waiting in queues and here you have to wait in queues for everything. For toilets, for beer, for food! Everything! There is no place to sit, not much place even to sit on the ground. Granted there are lots of band options but also it means that some of your favourite bands are bound to overlap. Also huge festival area means you have to walk hours from camping site to arena and from one stage to another. Although it was a good exercise still nothing to enjoy in your vacation.

Heavy Metal comments edit

Last year I missed download festival and settled with Bloodstock only.This year for the first time I’ll see Download.

Download Ticket

Only 1 week is left and the wait is quite exciting. I think this year’s line-up is great as well and I’ll get to see many bands I haven’t seen before.

Tickets

Tickets for download festival are definitely not cheap! £195 Considering a Wacken ticket costs €120 and a Bloodstock £132. If it’s worth the price remains to be seen.

Equipment

This year I decided to buy a larger tent and a thicker sleeping bag as I’m going to use them in 2 festivals. I hope they endure both of them. I’ll post my experiences after the festivals as well. Here are the ones I picked:

This year I’ll buy a sunscreen but not sure about the rain boots. Maybe I should to be on the safe side but just don’t want to carry a lot of stuff around. And this year I’m not taking my camera. That bulky thing is only trouble. I will rely on my Galaxy S3 this year. After all, full concerts can be found on the internet along with a ton of photos. So it’s a not a big deal anyway.

Line-up

The three headliners are Slipknot, Iron Maiden and Rammstein. I have seen Maiden and Rammstein before Slipknot will be my first Slipknot show. Looking forward to it. There are many hard rock / nu metal bands in the line-up. Korn, Limp Bizkit, Papa Roach, 3 Doors Down are some of them.

One band I noticed is Jason Nested’s band Newsted. They are about to release their debut album and it’d be nice to see Jason Newsted on the stage for the first time in my life. There are many bands to discover and some old friends(!) like Amon Amarth and Volbeat who I will definitely see.

I’ll post my impressions after the festival.

\m/

Game comments edit

I’m not much of a gamer but recently discovered this game and likes it quite a lot. Not surprising to me of course given that I like everything about The Simpsons. Actually the game is very simple and lack of challenge so if it wasn’t about The Simpsons there wouldn’t be any compelling reason for me to keep playing.

The story is Springfield explodes because of a failure in the nuclear power plant (not surprisingly caused by Homer). The game starts with Homer and Lisa trying to rebuild new Springfield. You unlock characters as you complete tasks. You build houses and collect taxes to buy more items to decorate the town. Here’s what my Springfield looks like:

Simpsons Tapped Out

Simpsons Tapped Out

I like the fact that you can just assign the tasks to the characters and after 8 or 12 hours you tapped them to collect the money and experience points (required to pass levels) they earned. So you don’t have to play it constantly.

There are lots of premium items available but I found the pricing too expensive so I’m just playing it for free. For example you can buy 300 donuts for £14 and for that amount of donuts you can only buy a few premium characters (Otto and Professor Frink for instance). I think for that money you should be able to buy everything in that game. Still I’m happy with the free Springfield I built.

Resources

Gadget, Security comments edit

One of the online shows I enjoy is Hak5.org’s podcast (http://hak5.org). Hak5 also manufactures tools for penetration testers. WiFi Pineapple (https://wifipineapple.com/) is one of the devices they manufacture. It is a “hotspot honeypot” and its most powerful feature is something called a Karma attack.

What is Karma Attack?

Simply put when our wireless devices keep sending out probe requests searching for the networks they “know” to re-associate. Normally all APs that don not have the SSID that’s probed for simply ignore these packets. But not WiFi Pineapple! It runs a modified firmware and replies to all probe requests claiming that it is the network our device is looking for. The modified firmware is called Jasager (yes-man in German) which explains a lot I think.

Build or Buy One

Base WiFi Pineapple costs $99. You can buy one from here: http://hakshop.myshopify.com/collections/gadgets/products/wifi-pineapple

Wi-Fi Pineapple

If you like getting your hands dirty to dig deeper you can build one on your own. The firmware is a free download. The router inside WiFi Pineapple is an Alfa AP121U which costs around £40 or you can go with the bare board which costs around £20 (here on Amazon) Also you need to flash it via serial port and you need a USB TTL cable (here on Amazon) They have a great step-by-step tutorial (see References down below). After following the instructions you can have your own homemade WiFi Pineapple within 20 minutes.

So what is the risk?

If you have a habit of using unsecured wireless networks than you are under risk. As by default most devices try to connect to previous networks automatically, there is a chance to connect to attacker’s AP as it is faking to be your old friendly network that you used to be connected. Good news is that pineapple doesn’t support Karma attack for protected networks. So if you manage to stay away from open networks then you are off the hook. But still it doesn’t hurt to be careful and watch out closely to where you are connecting.

Resources

Cloud Computing, System Administration comments edit

Evernote has been recently hacked. Dropbox has been hacked many times. Who knows what’s going in the other services we are using. So I decided to phase out my cloud service providers and create my own cloud. There are bunch of ways of running this tool. For instance, you can just download a VM image with everything installed. I decided to start from scratch and perform a manual installation on a new Ubuntu server. It’s very easy. First we need to install dependencies:

apt-get install apache2 php5 php5-gd php-xml-parser php5-intl
apt-get install php5-sqlite php5-mysql smbclient curl libcurl3 php5-curl

Then extract the downladed compressed file:

tar -xjf path/to/downloaded/owncloud-x.x.x.tar.bz2
cp -r owncloud /path/to/your/webserver

Set the directory permissions:

chown -R www-data:www-data /path/to/your/owncloud/

Enable .htaccess by settings AllowOverride to “All” in /var/www directory in Apache config which is in /etc/apache2/sites-enabled/000-default on Ubuntu Finally run mod_rewrite:

a2enmod rewrite
a2enmod headers

I got these instructions from Admin Manual which can be found here: ownCloud Admin Manual It’s quite straighforward. Then all we have to do is navigate to login page, create an admin account and start uploading files:

Own Cloud

My favourite features are:

  • Ability to share password protected links with specific users
  • Ability to set expiry date to shared files
  • Ability to sync mulitple local folders (it doesn’t have to mimic the directory structure of server, you can select and map separate folders)
  • Supports plugins. A simple note taking plugin is quite helpful to take and sync notes. Also I installed YubiAuth plugin which supposedly enables using my Yubikey with it. But couldn’t make it work yet. My only negative observation about it is SMTP settings didn’t work. When I tried to send someone a link of shared file I got a bizarre error. On their forums I saw other people having similar problems. To me it’s not a crucial issue (as a single user, who am I going to mail anyway) but for an organization it may quickly become an annoying issue.

Gadget, Programming comments edit

To me a technology that enables you to collect data about your brain activity sounds fascinating. It always felt like Sci-Fi and unreachable. So when I heard about the affordable MindWave I immediately ordered it.

MindWave Mobile

This gizmo is manufactured by a company called NeuroSky focusing on brainwave technologies. I bought the MindWave mobile version as it has support to mobile devices which increases the possibilities of creating something cool. The best thing about it is that it comes with an SDK and you can develop your own applications on the platform. To get more info about the SDK visit http://developer.neurosky.com They even have an app store that you can sell your applications. But the developer program costs $1500 so I don’t think I will sign up for that quite a while.

How does it work

The gadget communicates via Bluetooth. It supports lots of platforms and comes with an API ported to different languages. I prefered .NET and it worked without any problems. The real power of the device comes from the ThinkGear chipset. The API lets the developer to get results from the ThinkGear chipset. When you install the software bundled with the device, it installs ThinkGear connector and a bunch of games. First thing to do is pair the headset with your PC or iOS/Android device. Frankly, I didn’t quite like the applications that come with it. But it is not that important. After all I bought this thing to write my own programs against it.

NeuroSky

The tutorial application, on the other hand, is very useful for testing the device and connection status.

Developing with MindWave

The starting point is definitely here: http://developer.neurosky.com/

The site steers the user very well so that you can select your goals and start developing right away. Actually the API is quite easy to use. After you connect you start receiving values from the sensor. In .NET wrapper the values are encapsulated in a class called ThinkGearState, which looks like this (I got this from its metadata):

public class ThinkGearState
{
    public float Alpha1;
    public float Alpha2;
    public float Attention;
    public float Battery;
    public float Beta1;
    public float Beta2;
    public float BlinkStrength;
    public float Delta;
    public bool Error;
    public float Gamma1;
    public float Gamma2;
    public float Meditation;
    public int PacketsRead;
    public float PoorSignal;
    public float Raw;
    public float Theta;
    public int Version;

    public ThinkGearState();

    public override string ToString();
}

The key fields for me are Attention and Meditation. BlinkStrength is also interesting. If you blink intentionally and strongly, the value wanders around 150 – 200. For normal blinks that we do quite often, it is around 50 – 60. So it is easy to differentiate if someone blinks. I wondered if this could be used as a communication method for Hector Salamanca in Breaking Bad. Instead of ringing a bell he could just blink. Admittedly it wouldn’t provide any extra functionality but it would look much cooler.

Breaking Bad Hector Salamanca

I don’t know how the Attention and Meditation values are calculated. The device also returns values for the various brain waves such as alpha, beta, theta, gamma and delta. I had no clue what these meant so here’s what I’ve learned from here and here.

  • Alpha: Increases in the state of physical and mental relaxation
  • Beta: Increases when we are consciously alert, or we feel agitated, tense, afraid
  • Theta: Shows the state of reduced consciousness
  • Delta: Increases when there is unconsciousness, deep sleep or catalepsy
  • Gamma: These waves are associated with peak concentration and extremely high levels of cognitive functioning

I don’t know why Alpha, Beta and Gamma waves return 2 values whereas Delta and Theta have only 1. As my knowledge on this subject is almost zero, I’ll just concentrate on the already-calculated Attention and Meditation values. I’ll try to develop a project using this gizmo and post it when it’ is ready. I think it is a very cool thing to have the ability to measure brain waves and write programs using those values. I guess the only problem for me is that I already constantly wear a wireless headset so it’s a bit hard to have them both on my head!

Resources

Programming, Raspberry Pi comments edit

I was going to write myself a desktop notification user control. I was planning it to be a simple window popping up when an event occurred. Before investing time and effort into this, I decided to look around to find a similar project and build on it. Unfortunately I couldn’t find something to my liking but discovered Growl. It has all feature you might expect from desktop notification tool. One additional feature that pleasingly surprised me is that you can send notifications to another machine over the network. This sounds good to me as I’m working on running my applications on Raspberry Pi using Mono lately. So the idea is to run the program on my Pi and receive the notifications on my desktop where I spend most of my time. Another benefit of Growl is that it is open-source which can be found here: https://code.google.com/p/growl-for-windows/

I don’t like my programs to be dependent on some external software that needs to be installed on the client machine but I thought this could be optional because desktop notifications can be one channel for communications and others can be added if necessary. So it is not a dependency but rather it enhancement in functionality. Also a pitfall in software development is the anti-pattern described as Not Invented Here. One simply cannot develop every piece of software needed to build complex systems. It’s not feasible. Of course when I write code on my own, my main goal is to learn something new but still I like to get results and produce working software. So best practices for commercial software still apply. Having convinced myself to use Growl for messaging I started looking for ways integrate it with my application. It comes with .NET SDK which is quite easy to use.

There are two assemblies need to be referred to:

  • Growl.CoreLibrary.dll
  • Growl.Connector.dll

The interesting bits are in Growl.Connector library. First you need to create an instance of GrowlConnectorclass. You can specify the remote hostname and password to send the notifications over the network which is what I wanted to do.

this.growl = new GrowlConnector("password", "192.168.1.64", GrowlConnector.TCP_PORT);

Next, you have to register the application. If it is not registered, Growl will discard notifications coming from this source

this.application = new Growl.Connector.Application("Test notifier from ROHAN");
this.notificationType = new NotificationType(sampleNotificationType, "Sample Notification");
this.growl.Register(this.application, new NotificationType[] { notificationType });

Final step is to enable notifications over the network. By default it only accepts messages from the local machine.

Growl Security Settings

After the setup is completed we can send a test notification by this piece of simple code:

string text = string.Format("DateTime: {0}", DateTime.Now.ToString("dd/MM/yyyy HH:mm"));
Notification notification = new Notification(this.application.Name, this.notificationType.Name, DateTime.Now.Ticks.ToString(), "Mmessage from ROHAN", text);
this.growl.Notify(notification);

And the result is:

Growl Message

So far so good. With only a few lines of code we managed to send a desktop notification over the network. We could specify a callback method to handle responses from the Growl host. We could also specify the encryption algorithm to enhance security. Now the last thing to test for me is to see it running on Raspberry Pi. To do that I created a sample console application that looks like this:

using System;
using Growl.Connector;

namespace MonoWorkout
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			GrowlConnector growl = new GrowlConnector("password", "192.168.1.64", GrowlConnector.TCP_PORT);
			growl.EncryptionAlgorithm = Cryptography.SymmetricAlgorithmType.PlainText;
			Growl.Connector.Application application = new Application("Test notifier from Raspberry Pi");
			NotificationType notificationType = new NotificationType("SAMPLE_NOTIFICATION", "Sample Notification");
			growl.Register(application, new NotificationType[] { notificationType });

			Console.WriteLine("Type message to generate notification");

			string message = string.Empty;
			while ((message = Console.ReadLine()) != null)
			{
				if (message == "q")
				{
					Console.WriteLine("Quitting program");
					break;
				}

				string text = string.Format("DateTime: {0} \t Message: {1}", DateTime.Now.ToString("dd/MM/yyyy HH:mm"), message);
				Notification notification = new Notification(application.Name, notificationType.Name, DateTime.Now.Ticks.ToString(), "Message from Raspberry Pi", text);
				growl.Notify(notification);
				Console.WriteLine("Notification sent");
			}
		}
	}
}

I ran the application but did not receive the results. I immediately ran WireShark and could see the packages coming to my desktop machine so it is not a network or firewall issue. After Googling a little bit I’ve found that there is Mono branch in the source code. I downloaded it and replaced the binaries with their Mono counterparts. Tested it again but to no avail.

Growl_Message_Capture

When I sent the message I can clearly see it in wireshark but I don’t know why Growl is rejecting them. I ran the same application in both a Windows 7 instance and Raspberry Pi and captured the message packets. Outcome is interesting:

Here’s the message sent from Windows:

GNTP/1.0 NOTIFY NONE MD5:C5FB01D47A56832A17B3F941BC6F327F.3ECBA79D164DA5F8
Application-Name: Test notifier from Raspberry Pi
Notification-Name: SAMPLE_NOTIFICATION
Notification-ID: 634982701932496447
Notification-Title: Message from Raspberry Pi
Notification-Text: DateTime: 07/03/2013 16:23 	 Message: TEST_ROHAN
Notification-Sticky: No
Notification-Priority: 0
Notification-Coalescing-ID: 
Origin-Machine-Name: ROHAN
Origin-Software-Name: GrowlConnector
Origin-Software-Version: 2.0.0.0
Origin-Platform-Name: Microsoft Windows NT 6.1.7601 Service Pack 1
Origin-Platform-Version: 6.1.7601.65536
</pre>
And this is the one coming from Raspberry Pi:
<pre name="code" class="c-sharp:nocontrols">
0'_`E{@P@ZTg<
	DGNTP/1.0 NOTIFY NONE MD5:45DF50ED8E166AE3AF39F0FEFFC36F5D.6EC74DE6BCD67A71
Application-Name: Test notifier from Raspberry Pi
Notification-Name: SAMPLE_NOTIFICATION
Notification-ID: 634982703645630380
Notification-Title: Message from Raspberry Pi
Notification-Text: DateTime: 07/03/2013 16:26 	 Message: TEST_RASPBERRYPI
Notification-Sticky: No
Notification-Priority: 0
Notification-Coalescing-ID: 
Origin-Machine-Name: raspberrypi
Origin-Software-Name: GrowlConnector
Origin-Software-Version: 2.0.0.0
Origin-Platform-Name: Unix 3.1.9.0
Origin-Platform-Version: 3.1.9.0

There is a 16 byte block at the beginning and I believe because of that Growl cannot parse the message therefore end up discarding it.

At this point, I’ll shelf this problem and look for alternative solutions. I hate leaving a problem unsolved like this but it is not a crucial feature so I’d rather not invest too much time into it. So for now my official opinion is, despite the Mono branch in the SVN, I don’t think Growl supports Mono.

Programming, Raspberry Pi comments edit

As a developer my initial plan was to develop something running on Raspberry Pi. Unfortunately being a .NET developer and playing around with Microsoft stack all the time, my arsenal for Linux development is very limited. Before I master Python, I wanted to run small applications using Mono. This would be a good chance to see how smoothly .NET programs can run independent from the platform.

So I booted my Raspberry Pi with a Raspbian image (hard-float ABI). And installed Mono runtime and MonoDevelop IDE.

sudo apt-get update
sudo apt-get install mono-runtime
sudo apt-get install monodevelop

Launched MonoDevelop eagerly to write my first Hello World program on Raspberry Pi and boom! I got the following error:

MonoDevelop Exception

The good old “Object reference not set to an instance of an object” exception!

After searching around I found out that Mono doesn’t run on Raspbian image and it requires an image with “soft-float ABI“. Turns out soft-float version runs floating point operations using software instead of FPU (Floating Point Unit). Therefore soft-float version it is slower than Raspbian. I quickly downloaded the soft-float image and tried to boot it up again. This time I couldn’t even see the login screen. It got stuck at a stage saying “Waiting for /dev to be fully populated” After some time it timed out and started giving some errors.

Raspberry_SoftFloat_with_512MB

Having no idea what’s going on, consulted Google again and found out other people had the same problem. The proposed solution was to replace start.elf with the one from the hard-float image. I tried running it with the replaced elf file but got the same result. I’ve been doing all these experiments on my new Raspberry Pi which is 512MB. Having failed where others seemed to succeed, I put the blame on the hardware I’m using and decided to try the same image with the old Pi. The result was promising: I could boot the Pi with the soft-float version finally. I installed the Mono runtime and MonoDevelop again but looks like MonoDevelop is above Pi’s paygrade! It was excruciatingly slow that I decided to create the sample project on my desktop PC and carry it over with a USB flash drive. Mounted the flash drive using the following commands (replace tosh with directory name you want and make sure you’re mounting the correct device.)

sudo mkdir /media/tosh
sudo mount -t vfat -o uid=pi,gid=pi /dev/sda1 /media/tosh/

Here comes the moment of truth. I changed the directory to the copied files and ran the exe file. Here’s the output:

Mono on Raspberry

The screen glares but at the bottom of the screen you can see the glowing (by all means) phrase: Hello World! Of course, this is just the beginning. I’ll see how compatible and reliable Mono framework is after I deploy more complex applications on Raspberry Pi.

Programming comments edit

Today I came across an interesting namespace collision. I’m writing a library to wrap a 3rd party API. So without getting into specifics I’ll try to illustrate the situation on a sample piece of code. Let’s say we have a class called Test in TestNamespace namespace.

namespace TestNamespace
{
    public class Test
    {
        public static void StaticMethod()
        {
        }
    }
}

and the calling class is something like this:

namespace DifferentNamespace.TestNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            TestNamespace.Test.StaticMethod();
        }
     }
}

This code doesn’t compile because compiler thinks “TestNamespace.Test” is actually “DifferentNamespace.TestNamespace.Test”.

Adding a using directive doesn’t help either. As it has the same namespace as the subnamespace of the calling class it always resolves to calling class’s namespace. The solution is using “global” namespace.

namespace DifferentNamespace.TestNamespace
{
    using TestNamespace = global::TestNamespace;

    class Program
    {
        static void Main(string[] args)
        {
            TestNamespace.Test.StaticMethod();
        }
    }
}

By explicitly specifying which TestNamespace we are referring to we resolve the conflict. One thing to keep in mind is that we have to define it inside the namespace. If we used it outside the DifferentNamespace.TestNamespace, then inside the namespace TestNamespace would still mean “DifferentNamespace.TestNamespace”

Before this incident, I never had to use the global keyword. Probably the best way to avoid this is by naming conventions but sometimes you may not be able to change the namespace name. You can break lots of things if there are dependant parties on that code. So every now and then this tip may come in handy, just like it did to me in this instance.

Productivity, Programming comments edit

Some code snippets are extremely helpful like prop for properties and ctor for constructors. But writing a method is always taking relatively long time as there is no snippet for methods. For good reason I guess as there are all different shapes and colours of methods but I think a snippet can save some time for simple methods. So I decided to create my own snippets. Here’s how to do it in 3 simple steps:

STEP 01: Download the snippet designer from here: http://snippetdesigner.codeplex.com Install and restart visual studio. From File –> New menu select Code Snippet file type.

STEP 02: Save the output of the snippet designer under code snippets folder %USERPROFILE%\Documents\Visual Studio 2012\Code Snippets\Visual C#\My Code Snippets which looks like this


<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
      </SnippetTypes>
      <Title>MethodVoid</Title>
      <Author>dummy</Author>
      <Description>
      </Description>
      <HelpUrl>
      </HelpUrl>
      <Shortcut>method_void</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal Editable="false">
          <ID>Method1</ID>
          <ToolTip></ToolTip>
          <Default>
          </Default>
          <Function>
          </Function>
        </Literal>
      </Declarations>
      <Code Language="csharp"><![CDATA[public void MyMetHod()
    {
    }]]></Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

STEP 03: Restart Visual Studio for the changes to take effect. I created a few snippets for simple methods returning primitive types. Depending on your needs you can choose the optimum number of snippets. I especially like using the test method snippet which looks like this:

TestMethodSnippet

Another great feature about this tool is you can export a selected text block as a snippet. All you have to do is right-click and select Export as Snippet, make the final touches in the editor and save.

Hardware, Networking comments edit

There aren’t too many reasons why someone would like to make their own Ethernet cables. Sheer fun, learning the nitty-gritty (and useless in most cases) details of how they are made are to name a few. Also as I have too many gadgets making my own cables at any length I please would be convenient and can save a few bucks in the long run. So let’s get started.

The toolkit

Cable:

CAT6: http://www.amazon.co.uk/gp/product/B002SQPDXS/ref=oh_details_o00_s00_i00

CAT5: http://www.amazon.co.uk/gp/product/B000HWY304/ref=wms_ohs_product

For the obvious reasons! It’s best to get the latest version generally. I will use CAT6 all around my network but I also bought CAT5e as I was anticipating some errors at the beginning so I’d better make them by wasting cheaper cable.

RJ45 Modular Connectors:

http://www.amazon.co.uk/gp/product/B004HTK30M/ref=oh_details_o01_s00_i00

I’ve watched a lot of tutorial videos. When an expert is showing it, it looks quite easy but I quickly found out it’s not. Aligning all 8 cables and placing them in the correct order is not as easy as it seems. So I definitely recommend two-piece crimps that come with a “guide”. It’s a small piece that allows you to insert all the cables relatively easily and then you insert the whole block into the crimp.

RJ45 Crimp Tool: http://www.amazon.co.uk/gp/product/B004J02DRU/ref=oh_details_o00_s00_i00

The set I bought comes with a crimper and a cutter. It looks good enough to do tis job and quite cheap. After the cables are inserted in the connector, the crimper is used to press them all in and connect with the

Tester:

http://www.amazon.co.uk/gp/product/B007CJUEDA/ref=wms_ohs_product

Altough it is easy to test the cable by connecting to a machine, it is generally recommended to use a tester. I guess it makes sense especially when you have to make lots of cables. I bought one for £4 so I guess it’s good deal. The downside is doesn’t support CAT6 which I didn’t notice at the or ordering. If manual testing doesn’t prove to be helpful I would consider buying a better product.

Boots:

http://www.amazon.co.uk/gp/product/B009EPCOP6/ref=wms_ohs_product

These are plastic sleeves over the connector. They are helpful sometimes to avoid the connector clip from getting broken

CableStuff[1]

Technical Details

CAT5 vs. CAT5e vs. CAT6: The difference is that CAT6 supports 1000Base-T/1000Base-TX (Gigabit Ethernet). CAT5 and CAT5e supports 10Base-T/100Base-TX (Maximum 100Mbit/s)  CAT5e is an improvement over CAT5. It introduces new crosstalk specifications. (Crosstalk means a signal creating a detrimental effect on another channel)

T568A vs. T568B: The order of the cables matters and they have to be in the same order in both ends. These specific orders are named as T568A and B. What I understand you can use as long as you use it for both ends but all resources I’ve found favoured using T568B so I’ll use that one as well.

Crossover cable: When you connect one end in T568A and the other T568B it becomes a crossover cable (Regular ones are called patch cables). Crossover cables are used to connect two computers instead connecting a computer to a switch or router. I’ll test creating one of these as well.

Action!

I think we have everything ready to get started. Here’s what I did step-by-step:

  1. Cut the required length of cable.
  2. Remove the outer jacket.
  3. Arrange the wires by referring to the wiring standard (T568B) and insert them into the guide of the connector.
  4. Insert the guide into the connector.
  5. Insert the connector to the crimp tool and press it firmly.
  6. Repeat Steps 1- 5 for the other end. 10 minutes later I had my first homebrew CAT5 cable:

CAT5

Let’s use the tester to verify we did good. Using the tester is quite simple: Just plug in the both ends to the device. If you lights blinking from 1 to 8 simultaneously on both sides that means we are good. I tested it with a broken table too. In that case no lights were on so it’s easy to see if it works or not.

Cable Tester

CAT6 is slightly different: It has plastic part in the middle of the cable which holds the cables apart as shown in the image below.

CAT6

All we have to do cut that piece before separating the pairs and the rest is exactly the same as CAT5.

Resources

  • There is a nice KnowHow episode about Arduino and cable making:

NOSQL, Programming comments edit

In this post we are diving into coding and developing a small application using the beer sample database that ships with Couchbase 2.0.

Environment Setup

To develop a .NET application with a Couchbase backend, we need the Couchbase .NET SDK. The current version as of this writing can be downloaded from here. But the best way to get it using Nuget. Using the SDK is fairly simple. It comes with a main class called *CouchbaseClient. *All operations are performed using this class.

Connecting to server

The first step is connecting to the server and the easiest way to do is using the configuration file.

<configuration>
    <configsections>
        <section name="couchbase" type="Couchbase.Configuration.CouchbaseClientSection, Couchbase" />
    </configsections>
    <couchbase>
        <servers bucket="beer-sample" bucketpassword="">
            <add uri="http://192.168.1.111:8091/pools/" />

            <add uri="http://192.168.1.112:8091/pools/" />

        </servers>
    </couchbase>
</configuration>

As you can see from the configuration section, if you have multiple nodes in the cluster just add their URIs to the servers list. Once IPs and the bucket and the password are specified we are done. We don’t need to explicitly connect to the database, we can just create a new client instance and start calling methods

using (CouchbaseClient client = new CouchbaseClient())
{
    // DB operations go here

}

Basic Operations

OK so far so good. We are connected to the server without a hassle. As there is already data in the server let’s get some sample data from the database. As the database is a key/value store we can add any type of data we want to. We can create our JSON objects in a string and insert/update data with it. But most likely we want to use our domain objects instead of manipulating raw JSON. There are 2 things to consider here. Once we tackle those issues the rest is quite easy:

  1. Mark your objects as Serializable: This is required to persist any object. Once you make the class serializable you can run CRUD operations on it.
  2. The default serializer is binary serializer. That means when you store an object using by calling Store method you will get something like this when you try to view the object:

Beer Binary

This is not too helpful. We cannot read and index. So we’d rather store it in JSON format. Luckily StoreJson method comes to rescue. The following code produces the result below which is exactly what we wanted. To map the key’s in JSON object to the properties in our class we use JsonProperty attribute in the Newtonsoft.Json library which is used the SDK itself.

Beer JSON Code

Beer JSON Output

Store and StoreJson methods accept an argument of type StoreMode. The values of StoreMode are Add, Set and Replace. Add is used to create a new record (INSERT), Replace is used to update an existing record (UPDATE). Set adds the record if it doesn’t exist and updates it if it exists (MERGE – but simpler). To delete an object we call the Remove method with the objects key as argument. So basically we perform CRUD operations with Get/GetJson, Store/StoreJson and Remove methods.

Querying database with views

Views in Couchbase 2.0 are functions written in JavaScript that use a technique called Map/Reduce. Map/Reduce is a complex topic that I have not fully covered yet but basically it’s a method for processing large data sets in a distributed environment. It is developed by Google. It involves 2 functions called map and reduce. The map function filters entries for certain information and can extract information. The result of a map function is an ordered list of key/value pairs called an index. The results of map functions are stored in disk by the Couchbase server. Reduce function is optional and can be used to perform sum, aggregate or similar calculations on the output of map function. Views can be grouped in design documents which can be associated with a bucket. I consider them as namespaces. Couchbase Server offers two kinds of views: Development and Production. As creating a view means creating an index. it may incur some overhead on the performance of the system. So development views are handy to fully test before publishing to production environment. Also production views cannot be edited via admin console which forces the developer to develop and test the view in development environment first. So to demonstrate what they look like let’s examine the view that returns all the breweries.

Beer_View_MapFunc

We have 2 types of objects in the database (beer and brewery). This function only emits the objects that are of type brewery.

Demo

So all this theory means nothing if we don’t put it into good use. You can get source code of the sample application (I call it Beer Explorer) from my Github account. Also if you want to see what it looks like before diving into the code I host a live version here: http://beerexplorer.me. Feel free to play with it.

NOSQL comments edit

In this post, I’ll talk about some technical details and terminology of Couchbase. The official documentation is very comprehensive and I highly recommend taking a look at it: http://www.couchbase.com/docs/

Installation

First of all I recommend you check the supported OS list here. I tried to install it on Windows 8 but turns out it’s not supported yet. Then I installed it on Windows Server 2008 R2 and a Ubuntu Server 12.10. You can find Linux installation instructions here.

Installation is quite easy. There are a few things that need to paid attention though.

  1. File locations: Actually this step is very easy, just accept the default location. But Couchbase recommends storing document and index data on different disks to get the best performance,
  2. Memory Size: First node in the cluster determines the quota and that value is inherited to the following nodes. To update it, on the management console, select Data Buckets and click on the arrow on the left of the bucket name. Then by clicking on Edit you can change this value.
  3. Bucket Type: memcached and Couchbase bucket types are significantly different so you have to choose carefully. memcached buckets don’t support persistence nor replication. They are meant to be an in-memory caching solution.
  4. Bucket Name: During setup you cannot change the name of the default bucket. Couchbase recommends to use it for testing purposes only. So it’s best to create your own bucket  for the actual data once the installation is over.
  5. Flush: This is a very dangerous operation. It allows you delete all the data in a bucket. Default is disabled and I’d recommend to keep it that way.

Basic concepts

  • A couch database is called a bucket.
  • A document is a self-contained piece of data. It is a JSON object. A row in a RDBMS would be stored in a document with all the data it’s related to. (i.e: A customer record may contain a list of orders). This approach is called Single-Document approach and the document is called an aggregate. More about it in Modeling Documents section later in this post. A new feature that came with v2.0 is these records can be indexed and queried.
  • vBucket is short for “Virtual Bucket” and they work functionally equivalent to database shards in traditional relational databases. Good news is that Couchbase will automatically manage vBuckets.
  • XDCR stands for Cross Data Center Replication. It’s a very cool feature that can be used in a multiple of scenarios such as spreading data geographically or creating an active offsite backup.

Modelling Documents: has-many vs. belongs-to

The way we model data should depend on the structure and nature of the data. There are two approaches when modelling the data. has-many means storing all the child records with the parent. For example a standard Customer – Order relation could be expressed like this:

{
    "id" : 123,
    "name": Valued,
    "surname": "Customer"
    "orders": [ "order1", "order2", "order3" ]
}
{
    "id": "order1",
    "orderDate": "2012-12-20",
    "status": "sent"
}

The Customer stores the IDs of the orders. This method can be problematic if the parent (Customer in this example) is updated frequently. As orders can be accessed via customer this will effect the overall query performance. belongs-to approach suggests approaching it from the other direction. If we modeled the above example with belongs-to approach we would come up with something like this:

{
    "id" : 123,
    "name": Valued,
    "surname": "Customer"
}
{
    "id": "order1",
    "orderDate": "2012-12-20",
    "status": "sent",
    "customerId": 123
}
{
    "id": "order2",
    "orderDate": "2012-12-10",
    "status": "pending",
    "customerId": 123
 }

This is preferable to avoid contention. With this method we need to use indexing to be able query all orders by customerId. has-many approach performs better because a multiple-retrieve query is faster than indexing and querying.

Backup and Restore

Before diving into playing with the data it’s always a good practice to backup the original data. Couchbase provides 2 options to accomplish these tasks:

  1. Good ol’ file copy Copy the data files stored under the default path (which is “C:\Program Files\couchbase\server\var\lib\couchbase\data” for Windows). The disadvantage of this method is that it can only be restored to offline nodes in an identical cluster environment. Also database is not compressed.

  2. cbbackup / cbrestore These tools can be found in the bin folder.

Couchbase_Backup

I think a slight disadvantage is that you have to specify password in clear text in the command line. I was expecting just providing –p parameter would end up it asking me the password after I enter the command. Instead I got an error saying the password cannot be empty.

Couchbase_Restore

Advantages are that it allows a backup to be restored onto a different size and configuration. Also it compresses the data so it’s disk-space friendly.

Tip: When specifying the backup path to cbrestore make sure to remove the trailing backslash from the path.   In the next instalment of this series I’ll post a sample application using the Beer sample database that is shipped with Couchbase 2.0

Gadget, Hardware comments edit

It is world famous now. It is a dirt cheap ARM-based computer running Linux. Just bought one for myself. I installed Raspbian Wheezy which can be downloaded from here: http://www.raspberrypi.org/downloads. It is the recommended download for newbies so I went straight to it. I used Win32DiskImager and formatted an SD card. Installed it on the Raspberry Pi and it was good to go.

I definitely recommend buying a case which makes it a lot more fun to play with it. I also bought a 3.5” display. I think small screen goes well with the small device. If I’m going to plug something in to my 23” LED monitor, I’d prefer it to be my desktop. The display I bought can be found on Amazon. It doesn’t come with a power supply so you also have to buy a 12V – 2A DC power supply. I also needed a male – male RCA cable to connect the display to the Pi.

The result is the smallest computer I have ever had:

Raspberry Pi

I hope I can do something useful with it too.

NOSQL comments edit

Couch is one of move most popular databases in NOSQL movement. When I first started playing around with Couch I was a bit confused by the naming. I had thought there was one product but turns out there are two actually.

CouchDB vs. Couchbase

Apache CouchDB was created by Damien Katz who then started a company called CouchOne Inc. After some time they decided to merge their company with Membase Inc. which developed another open-source distributed key-value database called Membase. They merged the two products so that it would use Membase as storage backend and some portions were rewritten. The end result was called Couchbase. So even though it’s based on Apache CouchDB it’s a different product and is being developed by a different company. But it’s still open source and licensed under the Apache 2.0 license.

Which one to use?

They serve different needs. Couchbase has a built-in memcached-based caching technology whereas Apache CouchDB is a disk-based database. Therefore Couchbase is better suited low latency requirements. Couchbase has built-in replication which allows data to be spread across all the nodes in the cluster automatically. Apache CouchDB supports peer-to-peer replication. I find auto-replication feature of Couchbase marvellous and it’s extremely easy to manage. When you create a new node it can be a new cluster on its own or it can be added to an existing cluster. Adding it to a cluster consists of just providing the IP address/hostname and administrator credentials of a machine in that cluster and the rest is automagically taken care of. I’m using Couchbase in my test applications.

What’s new in Couchbase 2.0

Couchbase released a new major version recently. Highlights of the new features are:

  • Cross Data-Center Replication (XDCR) enhancements
  • 2 cool sample buckets (beer-sample and gamesim-sample)
  • A new REST-API
  • New command-line tools
  • Querying views during rebalance

In the next post I’ll go into more technical details.

Networking, Security comments edit

When I saw this gadget, I knew I had to have it. Didn’t exactly know what to use it for but it looked and sounded cool. So I ordered one along with a pro version. Unfortunately only the pro version arrived as the other one was out of stock. It would be more fun to build it myself but just seeing it in action is fun too. Of course it’s not as cool as a throwing star but functionality is exactly the same.

LAN Tap Throwing Star

The idea is instead of directly connecting your computer to a switch, you connect the machine to this gizmo and connect the port across to the switch. So essentially getting between the target machine and its final destination for network traffic. The other 2 ports are for monitoring. One of them is for received packets and the other is for the transmitted. Connect a monitoring device to one of these ports and it’s done. The rest is firing WireShark in the monitoring machine and watching the traffic of the other machine. A few cool things about it:

  • It doesn’t require any power source
  • It’s unobtrusive and undetectable

If you want to learn more, here is a nice video about it from Hak5:

Hak5–Throwing Star LAN Tap

I learned that it is commonly used for Intrusion Detection Systems (IDS) so it would be nice to one handy if I can start using one finally. The limitation is of course it only can be used to monitor one target device only. To listen to whole network I’ll need a switch with port mirroring or SPAN support. But for now let’s make sure this device is working properly first. The problem with the pro version is that it doesn’t have any indicators of which ports are for monitoring. So I randomly selected one, connected it between my desktop and the router, connected the laptop to one of the remaining ports. To test it I’m simply pinging google.com. With this confiugration I got nothing, Let’s change the ports and give in another try.. and voila! I filter the packets by my desktop’s IP and ICMP protocol so it’s easy to observe the sniffed packets.

Captued_Ping_Request

But as you can in the above screenshot there’s a problem: This is only one-way traffic. Let’s use the other monitoring port to see what’s going to change. Another ping to Google and this is what we get:

Captued_Ping_Reply

Now we receive only ping reply packets.As Darren Kitchen mentioned in the Hak5 video we can overcome this problem by using a USB Ethernet adapter with multiple ports. I don’t have one of those so I’ll just take his word for it. Verdict: Only monitoring one machine in one direction makes it a bit useless for me. I was planning to use something to see everything in both directions but overall it was a valuable  experience. After all, before I heard about LAN tapping in a TWIET episode (http://twit.tv/twiet) I didn’t even know such thing existed. Hearing about it in a podcast is nice but nothing beats hands-on experience.

System Administration comments edit

When you have Windows Services you must also implement a monitoring solution to make sure that they are running at all times. Some time ago I needed a quick and dirty solution to notify myself when one of the services stopped. The solution I depict here is by no means an ideal one. The only advantage of it is it’s very fast to implement if you don’t already have a monitoring system. Disclaimer aside let’s get to work!

The tools we need come with Windows so no need to install anything. The idea is simple: Create a task scheduler that is triggered on an event. The triggering even will be the stopping of the monitored service and action that will be taken will be sending the notification email.

STEP 01: Create a new filter a. Launch Task Scheduler. b. Right click Task Scheduler Library and select Create Task c. Select the Triggers tab. d. Click New… e. In the Begin the task list select “On an event” f. In the Settings section select Custom and click New Event Filter g. In the New Event Filter dialog, select XML tab and check “Edit query manually” h. As the query text type in the following:

<QueryList>
 <Query Id="0">
 <Select Path="Application">
 *[System[Provider[@Name='Service1']]]
 *[EventData[Data and (Data='Service stopped successfully.')]]
 </Select>
 </Query>
</QueryList>

TaskScheduler_NewEventFilter

Change the name of the service name and the message it displays when it stops. Note that service name is not what you see in the services list. You have to right –click and view properties. For example, as shown in the picture below, service name for DNS client is “Dnscache” where as display name is “DNS Client”.

Service Name

STEP 02: Create action to send mail a. Select the Actions tab and click on New b. From the Action list select “Send an e-mail” c. Fill in the details for the notification email. At this point we are good to go. An email will be fired when the service stops and logs the text we are looking for. Keep in my mind that it’s quite fragile because it will stop working if the text the service logs changes. Having a built-in send mail capability is great but if you need more features, like adding Cc/Bcc recipients or setting the priority of the mail this option would not be enough for you. In that case, playing around with PowerShell would do the trick.

STEP 03: [Optional] Create a script to send mails PowerShell is built on top of .NET framework so with a few lines of code we can send mails just like we can in C#:

$email = New-Object System.Net.Mail.MailMessage
$email.From = "user1@someDomain.com"
$email.To.Add("user2@anotherDomain.com")
$email.CC.Add("user3@yetAnotherOne.com")
$email.Priority = [System.Net.Mail.MailPriority]::High
$email.Subject = "Your notification subject"
$email.Body = "A bleak and gloomy text to drive the recipient into panic"
$smtpClient = New-Object Net.Mail.SmtpClient("SMTP hostname or IP address", 587)
$smtpClient.EnableSsl = $true
$smtpClient.Credentials = New-Object System.Net.NetworkCredential("username", "password");
$smtpClient.Send($email)

This example uses port 587 and SSL, your configuration may vary. That’s all there is to it to send a mail with PowerShell and you have full control over it.

To run this script in the actions list select “Start a program” from the actions list. In the Program/script textbox enter “powershell” and enter the full path of the script in the arguments textbox. Don’t forget to save it with a ps1 extension.