Sync up your life: Sync Files, Notes and remote access on Multiple PCs for Free

Do you work on different computers at different places? If you do, then you must always miss things that you have left on the other computer. I did! I used to miss relevant information from my home notebook when I am working on the office PC. Sometimes I jot down a phone number or some other information on my office PC and then look for it when I am home. These scenarios are quite frustrating. For last few months I have gotten rid of all these issues. How ?

There are several principles that we need to look at before we come to a solution

First Principle: You are connected to the Internet and all you data can be synched via Internet.

Second Principle: Even though you are connected to Internet all your devices are not always online. For example when you come to office you home PC might be or might not be online. A solution to this scenario need to be provided.

Third Principle: Sometimes just file/folder sync is not enough, you need remote access to the computer and you always do not have a public IP and sometime you are behind a private IP and a firewall and you still need proper access.

Fourth Principle: Sometimes you may need to access your files from the web when you are using them from someone else’s computer.

File and Folder Synchronization with Live Mesh

Microsoft Live Mesh (http://www.mesh.com) is so far the best free file and folder synchronizer that I have seen. It offers free 5 Gigabyte storage space. It lets you synchronize folders between multiple computers, not just two computers. It will let you sync between a MAC and a PC very soon . Microsoft is also going to release a version for windows mobile soon that will let you add a windows device to live mesh.

LiveMeshSite

In Live Mesh every PC is called a device. You need to add you PC as a device to Live Mesh. When you try to do this, Live Mesh will allow you to download a client software that you will need to install on you computer. You can then select a folder to sync using Mesh. One of cool features of Mesh is that you can select which devices to synch with the folder, and you even omit devices that you do not want that folder synched. You can choose the PCs where the folder will be synched. Also you can choose if the folder will be synched to web under your account. Now all you have to do is put files in the folder and live mesh will sync with web to upload your files, and also it will update changes as well.

One good feature here is that you do not need to explicitly sync information, Mesh will do it. Lets think of a scenario where I have put a document in a Mesh synched folder at home. When I open my office PC then Mesh client software will automatically download that document and put it in the proper folder. The experience is seamless. I even used it to put my C# project solutions in synced folders so that I can work on them seamlessly from home and work. Live mesh also allows you to remotely connect to you PC, but I failed to get that working properly at it is still in tech preview.

Benefits

1. Live Mesh allows you to sync you folders seamlessly

2. The folder data can be downloaded by logging into Live Mesh from any browser so that you data is available online ( of course you decide if its is public or private)

3. You can also sync other softwares that cannot be synched normally and have no web access. For example I use TodoList (open source versatile hierarchical list) for Getting Things Done and managing my work and I use KeePass ( open source password manager) to store various passwords to different websites, email, and software licenses that I bought. Both of these softwares do not have web access where it can sync. But I keep the todolist files and the encrypted password files in the synced folder of Mesh. That way these software data are synched between different computers.

3a. If I am traveling to different country and do not have access to my PC I can just download the files to different computer and download the software and access from there.

By the way, Live Mesh supports sharing files with other people as well.

Notes synchronization with Evernote

Evernote2 was a amazing piece of software for organizing information but it was a software that you had to buy. Evernote3 is till in beta and has an awesome UI. I personally prefer it over Microsoft OneNote. Evernote (http://www.evernote.com)  has the capability to read text from images, even handwritten text. You can use it to take a picture of the whiteboard and later search items that were written on the white board.

evernote

The coolest thing about Evernote is that you can synchronize the data. So this is what I do ...

Whenever I need write down some piece of information at office I use Evernote to write it down. Later I press the big “Synchronize” button and the notes are synced to the web.

Later when I come back home, I press the “Synchronize” button and I can see the notes that I have taken in office. 

Unlike Evernote version 2, the current beta version 3 is free to use as long as you upload 40MB data max. 40 Megabyte gives you 19,000 typed notes, 250 web clips, 380 camera phone photos, 37 audio files or 10 high resolution photos. Since I do not need more that 40MB space each month ( just like free flickr – 30 MB limit) for notes I can use it for free.

Second ultra cool thing about this software is that I can just login online to the my Evernote account and then use that account to search my notes online. When you are traveling without your notebook, this is a cool feature.

Evernote even has mobile version for windows mobile and iPhone. Things can’t get any better than this.

Ultimate Remote Access, File transfer and VPN with TeamViewer

TeamViewer (http://www.teamviewer.com) is a software that just blew my mind away when a colleague introduced me to it. Stop buying any remote desktop software Now! Why ?

Because you can have a better software for personal use. TeamViewer lets you to connect to 5 PCs for free (personal use only). When you download the software you would be amazed to see that it is a download less that 2MB. When you run it, it will let you run in two different modes, one is run another is install. The run mode can be used to run the software and provide support. See the software screen in run mode (below). If you provide someone the computer ID and the password, then he will able remotely connect to you PC using his copy of TeamViewer. (See image below)

TeamViewer1

Now if you want to do remote access to your PC then you should install TeamViewer and then set a permanent password. Install it or just go to the options screen and make it start with windows and set a permanent password like this ...

TeamViewer2

Then from a remote computer type in the computer ID and password when prompted and then, Walla! You can see your screen and access it. If you need some files from you laptop at home just ask a someone at home to turn on the laptop and then you can remotely connect to it or you can just leave it running when you leave home.

Coolest Feature : Access behind private IP

I have tried many different software and none of those let me access my PC from a private IP. I had to forward the port from the public IP to the private IP etc. But you don’t have do any of that hassle from with TeamViewer.

File Transfer

You can also connect to transfer the files and transfer files between two computers when both of you are behind private IPs.

Presentation and VPN

You can also allow remote access to someone and demo from your computer. It also lets you run a VPN connection between the two computers.

Screen Recording

When you are accessing remotely, you can also record the screen of the remote access PC and view it later.

Conclusion

These are the 3 software that I use to sync my life at home and at work and at other remote places. The combination of these 3 software have made my life a lot easier and simpler. I hope this makes your life easier and simpler as well.


Get started JQuery by example in 15 mins : Reduce Your Javascript Size and Development Time

I am one of those few developers who will not give one ounce of respect to Javascript development and does not even consider it a serious programming language even. Unfortunately with the advent of Web 2.0 the Javascript has taken a more serious role, still I did not get to grow any respect for it. My attitude has always been like, use it when needed, learn if needed ... then throw it out of your brain as it is wasting precious neural pathways.

However, the Web 2.0 and startup surge is waning and it has got a few good developers to work on this dynamic language who have come up a few good development frameworks which I have finally learned to respect. The most amazing framework here is JQuery, which have changed my outlook on Javascript. I have taken an hour of my time to learn what JQuery does and I must say I am impressed. To give a short example I would say at my first try with JQuery I was able to write code in one single line that would normally take me 8 to 10 lines. I was also able to write it in 2 or 3 minutes, which would have taken me 15 mins.

The objective of this post is to provide you with a very basic and very fast start to JQuery . I know there are a million really good posts and tutorials out there on the internet. So, if you already know JQuery you can skip this.

Getting started and the ‘$’ function

The first step is to download the JQuery js file from the site and adding a script reference to your html page. If you want to see how it works internally then download the uncompressed version 100KB, otherwise use the compacted 15KB runtime js. The basic function in JQuery is the ‘$’ and  is used everywhere. Any JQuery notation starts with $. If you are already using the ‘$’ character for some functions then you can still use JQuery by calling the ‘noConflict()’ function. It will revert back the use of $. The ‘$’ is a selector function.

Here are some sample JQuery notations

// Makes an element visible which has the id 'mydiv'
$("#mydiv").show();
// Makes each odd tr element to have a blue backcolor $("tr:odd").css("background-color", "blue");

Simple Selectors by Example

The $ function serves as a selector that selects a single html element or multiple html element. Here is how to select the span elements that are children of a div element and make it have 1 pixel solid border. Here all span that are inside a div element (may not be immediate child of the div) will be selected.

$("div span").css("border", "1px solid");

Here is how we select the links that are descendent of span which are direct children of a div

$("div > span a")

Here is how we can select a div with id mydiv

$("div#mydiv")

Here is how we select all links under div elements that have css class set to mycss

$("div.mycss a")

We can also use attributes to search for elements. The format is [attribute name=attribute value]. For example if we want to find a link that points to http://www.google.com then we would write

$("a[href=http://www.google.com]")

We can also use partial match. For example if we want to find any image that have been used outside of our domain we can try looking for the images that have started with the ‘http://’. The operator for starts with matching looks like this [attribute name ^= starts with value]. See example below

$("img[src^=http]")

Similarly if we can also match string that ends with a specific word. The format is [attribute name *= end with value]. This is how we can find only the png images ..

$("img[src$=.png]")

JQuery can also match any part of the string with the *= operator. If we want to find any link that refers to the word ‘washington’ anywhere in its path then we would write

$("a[href*=washington]")

How do we find an element that has an attribute which is optional. For example we want to find images that have alternative text assigned. This is how …

$("img[alt]")

Position Selection By Example

JQuery also has very strong support for selection based on position of an element.  So in order to demonstrate lets use a table. Click the the button below see a table.

$("#results").fadeIn("slow");  // Show table with fade in effect
$("#results").fadeOut("slow"); // Show hide with fade out effect
Show Table Hide Table Reset Table

Before you read any further, please make sure that you have clicked show table and can see a table

If we want to make all the odd rows of the table to have a bluish gray color we would write

Show Me

$("#results tr:odd").css("background","#ccccff");

Now lets make the even rows  have lighter bluish gray Show Me

$("#results tr:even").css("background", "#ddddff");

What if we want to make the header row have a different look ? Show Me

$("#results tr:first").css("background", "black");
$("#results tr:first").css("color", "white");
$("#results tr:first").css("font-weight", "bold");

We also could have assigned a class name to the header tr element like this

$("#results tr:first").addClass("header");

JQuery has other advanced ordering operators, but we don’t have the scope to cover that here.

Modifications By Example

Modification to the html DOM in JQuery is fairly simple and easy. See the examples below

Let assume that  we want add an image banner at the top of the document. Here is how ...

$("body").prepend("<img src='banner.jpg' />");

Change the inner html of an existing div or any html element

$("div#mydialog").html("<p>Hi There!</p>");

What if we want to wrap a div around an existing table? Use the wrap function ...

$("#mytable").wrap("<div></div>");

How to replace all hr elements (horizontal line) with a br element

$("<br/>").replaceAll("hr");

Call the empty function to remove all child nodes. The code example below will clean all div elements with class set to ‘header’. The div will be empty.

$("div.header").empty();
The ‘clone’ function clones any html element. You can also clone with the event handler in place. 
$("#mybutton").clone();     // clone the button
$("#mybutton").clone(true); // clone the button with event handlers

Learn it, there is so much more ...

In last 15 minutes I have only covered a fraction of what JQuery can do with very little code. JQuery can do so much more. It can do animation, ajax, superb event handling, extreme css manipulation and much more. I have only covered the surface of what it can do in selection and modification. The areas I have covered is less than 10% of the core JQuery library, imagine what the thousand other plugins can do. Stop using plain JS, learn JQuery, Its efficient, excellent and is worth the time. With my very little experience, I would say JQuery can reduce your JavaScript code to a minimum of 60% or its original size and on average 20%-30% of original code size. Don’t waste a second ... grab JQuery from the net and learn it, IMMEDIATELY!

kick it on DotNetKicks.com

Magnitude 5.0 earthquake hits Bangladesh

Around 1 hour and 20 mins ago at 12:51 AM (Dhaka, GMT +6) an earthquake of magnitude 5.0 hit Bangladesh. I felt it as if someone was rocking my bed. The quake was quite strong for my little or no earthquake experience. It lasted from 10 to 30 seconds, cannot say accurately. So far the only news on media is from BDNews24 site which says someone broke his leg when he jumped from a floor.

The earthquake was felt in Maymansingh, 115 KM away from Dhaka and the depth was around 12 km or 7.5 miles.

However more recent and accurate data (also scientific data) with maps can be found at USGS site.

Earthquake data can be found at the link below:

http://earthquake.usgs.gov/eqcenter/recenteqsww/Quakes/us2008uybc.php#details

Earthquake Maps available here:

http://earthquake.usgs.gov/eqcenter/recenteqsww/Quakes/us2008uybc.php#maps


Getting Things Done with TodoList

When I first learned about the methodology of Getting Things Done (commonly known as GTD) by David Allen, I did not give it much thought as it seemed too simple a technique to revolutionize my life. I discarded the the process initially. A few days later I realized that it was the only process that was simple enough to work. Following the process is hard since it requires that you follow a set of simple rules without exception. There are over millions of blog entries and articles referring to GTD, so I am not going describe it. Search web for “Getting things done” and you will find enough information.

 

GTD Softwares? 

There are over 100 web based GTD tool, also more than 100 desktop based GTD tools as well. I tried several and some were wonderful in different aspects. But none were fulfilling or perfect. Let me describe a few of them. First of all I refuse to accept any web solutions ( there are hundreds of them out there) as it requires you to be online 100% time which does not work for me. Lets review the software’s that I tried

Thinking Rock 2

ThinkingRock2 Thinking Rock is a Java based GTD software that in my mind is the reference implementation of David Allen’s concept of GTD. It also follows the full process. The UI is acceptable (as sleek as possible for a Java application, which is not so good). It has supports for different types of context like place based context, time available context, energy available context. Also another great thing about Thinking Rock is that it makes you write the stuff down first and process later on. Unfortunately I could not bear to live with the Java UI and font. Also keyboard shortcuts were adequate but not so friendly. It also lets you defer tasks or delegate a task to someone as well. I tried to use this reference implementation for several days but a few days later I found the UI to be inadequate and hard to find stuff. The screen where the user filters the actions after a few days proved hard to read and find relevant information because of poor Java widgets. So I stopped using this software. But I would suggest you try it as it is still on my top 3 list of GTD software. 

My Life Organized

My Life organized is another great software, unfortunately it is not freeware. There is a version for pocket PC as well, which is great news. But I believe the price is too high. After trying a few days I found it to be missing something. I could not exactly point to what it is missing, but was missing something for sure. The thing I liked most was the time of the day allocation to a context. You can just create a context called office and visually draw time from 9 AM to 5 PM and then remove the lunch time for different weekdays. Also the tree structure was excellent. If you have the capability to buy online, it is a good software.

What’s next

What’s next is an excellent software written in ruby on rails, I used to think ruby to be full of hype ( I still do ….a little somehow) . I actually hate functional programming languages, they don’t work in software projects that is supposed to be more than 3 months long and generally screws up the architectural beauty. Probably its more of those Ajax, Linq, Javascript stuff which will phase off in a few years. Anyway … I am drifting further away from the real topic. What’s next is a Great software I must say, it runs on Ruby on Rails server which you will have to run on your PC and connect to it via a browser. The UI is awesome, the keyboard shortcuts are marvelous. I must say, it almost won my choice of the GTD software. But it is still in beta and has only a few features of the GTD process.

Open source TodoList by dan g from Abstract Spoon

Now with all other software described, I must say TodoList is not a software specially made for GTD but it does it better than the specialist softwares. TodoList right now running version 5.5.7. The software is developed by Dan G (www.abstractspoon.com). He wrote this and posted in my once favorite website http://www.codeproject.com in 2003. This is one of the best resource ever (free tool) on code project with 2 million page view and still a rating of 4.77 out of 5. This software is written in VC++ and is open source with The Creative Commons Attribution-ShareAlike 2.5 License. It can serve as a simple todo list, hierarchical todo list or even as a replacement for Microsoft Project ( watch out project team). The developer even wrote the help file as a todo list. See screenshot  down below to see the application. The software is so flexible it can work as a todo list, a project management software, a mind mapping software, a gtd software, a hierarchical document etc.  You can download todolist, both source and binaries from this CodeProject atricle. By the way, once great site CodeProject has lost its article quality and does not attract me (probably others as well) there anymore.

MainScreen2

  Screenshot of TodoList 

Getting Ready convert TodoList into A GTD tool

 

Define contexts  

First I needed to define the contexts that I work with. I have defined my context based on my lifestyle( different people will have different contexts based on their lifestyle). Let me discuss a few of them  Home is for the things that I must do at home, Work is for any official work, Office is for things to do in office, Meeting is for my meeting time from 6PM to 9PM. So if there is a work that can do only in office, I tag it with category office, if it is some work that I might do in office or do at home I tag it both office and work. Because of that I can find it in my list when I filter it with work and I am working from home.

  First Step is to save a TodoList and mark different task as different categories. Watch the bottom properties portion of TodoList and you will find the category drop down. Just add the categories that want to associate with a task. Look at the image below. 

ContextCategory

 

You can assign multiple categories to a single task by checking the list. So the task can be valid for different contexts. Also it is very simple to add news to different elements as well. As you can see the pop up combo also has a textarea to write onto. You can just add new categories there by typing in … if you want to. You can also edit the list of categories manually if you want to my editing the todo list file. As you type in a category for the first time the software learns the category and offers it in future. In case you have mistakenly added a category and want to remove it. Just open the file and find the xml tag marked CATEGORY and edit it using notepad ( assuming you know what xml files are and do not screw up the file). See an example here :

  <CATEGORY CATEGORY1="Home" CATEGORY2="Meetings" CATEGORY3="Office"

CATEGORY4="Outside" CATEGORY5="Personal" CATEGORY6="Relaxed" 
CATEGORY7="Work" CATEGORY0="Communicating"/>

If I wanted to removed the category ‘Relaxed’, then I would just remove the attribute CATEGORY6="Relaxed" and make CATEGORY7="Work" to CATEGORY6="Work" and save the todo file.

Defining Task Status

TaskStatus

As you can see from the image that you can mark a task status form the status dropdown and unlike category a task may have only one status. I have selected ‘Active’ as the task the need to be done ASAP, ‘Deferred’ as the task that need to looked at later (remember to always select a due date for deferred task), ‘Delegated’ as  the task that I have delegated somehow ( remember to type in the person’s name in the Allocated To field), ‘Draft’ for task that has been entered but not categorized or reviewed, ‘Inactive’ for all items that is not a must do now, but I can review later.

Now whenever I enter a new task I want it to start in ‘Draft’ status. Go to Tools>Preferences screen and find “Default Task Attributes” and set the default value there. See image below.

DefaultTaskStatus

Columns to view

By default there are many columns visible, but I thought of them to be a distraction and have the columns that only I wanted to see. Right click on the column header of the task list the image below :

ChangeColumns

Click ‘Select columns’ and you will see the column selection screen. See the fields that I have selected to see on image below …

ColumnSelectionscreen

Filtering by Tasks

Since I believe that you can enter tasks by yourselves, it is time to introduce filtering. On top if the filter bar for the application. You can select and filer the items you want to see.

Filtering

Now if I wanted to see the draft tasks and process them, I would filter by ‘Draft’. If I was at home and in a relaxed mode, I would filter by ‘Active’ status and ‘Home’ and ‘Relaxed’ category with ‘All categories must match’ option selected. So this way I can only see the things that I want to see.

timeFilter  I can even filter by the tasks that are incomplete, or tasks that are due today, or tasks that are due tomorrow, or tasks due by the end of this weeks etc. See the image on left side.

Hierarchical View & Other Features

Unlike David Allens simple list based on context, I love to have hierarchy among my tasks, so I love this tool. It lets me do more and see more than a one hierarchy list. The software lets me store notes against each task and they can be either simple text or rich text. I track progress with % done field. Map it to some external software with external id, add dependency etc.

Awesome Keyboard Shortcuts

This is one of the biggest reason I have selected this software. It has awesome natural keyboard shortcuts. F2 edits a task, Ctrl+N creates new task, Ctrl+Right makes the task a child of task above, Ctrl+Left moves it a one level up. I never have to leave my keyboard and touch the mouse or touchpad. I am a keyboard person, the less I have to touch the mouse the better the usability is, to me.

Other Capabilities

The other features that I loved about this software are as follows

1. I can encrypt the list with a password  

2. It can import tasks from Freemind, GanttProject, My Life Organized, outlined text file or another todo list

3. It can also export to html, Freemind, GanttProject, plain text file, Spreadsheet or and iCalendar file. You can select columns or the tasks that you want to export.  

4. It has plugin support

calendar You can also download this calendar plugin from codeproject and have a nice calendar like the picture below. I had to black ink over some entries for privacy reasons. But this gives you an overall look of the timeline. Also you may even write a plugin to sync with outlook since the file is only xml.

Have fun!

By the way ... if you want to download the settings that I used and the template you can find it here:

Download gtdtemplate.zip. Just download and import the settings file, then use the todolist file.


My quest to select a good Antivirus for the year 2008

The anti-virus provider community seems to change their standing every year on who is the best and the anti-virus that was good for the last year seems ineffective the next year. I used to rely on the famous computer magazines to select the anti-virus to use since each year they seem to write a review on the security products and were generally informative. But the trouble begins when two different magazine provide different results and anti-virus products on one's top 3 list does not even appear on other review list. Who to believe?

I love my firewall but not the anti-virus

I use a security suite from Agnitum called Outpost security suite which other that their excellent firewall product includes a moderate performing anti-virus and ad and spyware protection as well. I am really a fan of this Outpost firewall, in my opinion the only other firewall that comes close to it is the freely available Comodo personal firewall, everything else I tried is poor and probably not in the same league and believe I tried many. In a nutshell even though I love the firewall I was just not satisfied with the anti-virus protection that I was getting. So I decided to look for a decent anti-virus protection and as usual I looked for the reviews of the famous computer magazines and got lost in a jungle of irrelevant or no information. Not only there was very little information available the trend of misinformation seems to have gotten worse.

Firewall Related post : Controlling Windows Firewall using C# (actually COM)

Looking for information

As always I jumped to Google's sea of links and went looking for information. The first good place to look was the VB100 site. These guys have been testing anti-virus for many years and they award a VB100 certificate to the vendors who pass their barrage of virus and other malware thrown to the anti-virus products. You can find their recent results at http://www.virusbtn.com/vb100/archive/results?display=summary but you might need to register to see it. It is a table showing different products and who passed or failed. The anti-virus that came with the security suite that I have, failed last two test iterations. When I drill down to see why it failed, I can see that it failed to detect 4 wildlist samples. Imagine my confidence level after finding that!!

Now it was a time to be surprised, big names like McAfree failed that last test, the only one that passed the recent test are Symantec Anti-virus , Eset NOD32 ANti-virus, Grisoft's AVG, CA eTrust. Now something is definitely wrong there! I have used Norton Anti-Virus for a long time before and in my experience, although it is reliable it really is a sluggish thing that slows my PC down significantly and I am not going to install it. So now I need more information on speed as well ...

Treasure cove of test information

Then I stumbled on this blog from sunbelt software and Walla! It has links to very detailed information on many different products with numbers! What?Numbers?! Can this really be happening! Some real human being among the six billion (now reaching seven) horrible humanoids on the face of this blue planet has been kind enough to share the test information with rest of us!  It seems that there is a site called http://www.av-test.org/ and they receive virus samples from all over the world and they have over 5 million virus samples and in this year they acquired more that 1 million samples. So these guys (who wrote the blog) ran tests with samples on different product and published their findings. They did not stop there, they also graded the systems with A,B,C,D,F on various criterions like performance, rootkit detection etc. I was in heaven ... so I decided to look into it!

Here is grade sheet http://www.sunbelt-software.com/ihs/alex/Results_2D2008m3b_US.htm with lettered grades

Here is the malware detection rate http://www.sunbelt-software.com/ihs/alex/Results_2D2008m3b_US.xls_detection2.htm with numbers

Here is the super detailed excel sheet with all information http://www.sunbelt-software.com/ihs/alex/Results_2D2008m3.xls

Too much information

Now this is too much information for me, I needed find a solution that has high detection rate at high speed with good rootkit detection and preferably good malware and and adware detectio. Looking at the gradesheet I had the following contenders left

  Malware Adware - Spyware False positives Performance Unknowns Response time Active root kit Cleaning
AntiVir (Avira) A A (*1) B A B A B B
AVK (G Data) A A C F B A F D
BitDefender B A C D A B B C
F-Secure B C B C A B A B
Ikarus A A C B B B C C
Kaspersky B C C D B A B B
McAfee B A A C B C B A
Nod32 (Eset) B B A A A B B B
Norton (Symantec) B A A A B C A A
Sophos A A B B A B B B
Trend Micro A B B B B B A B
TrustPort A A D F A A F F
WebWasher-GW A A C A A A n/a (*2) n/a (*2)

The decision

I gave up McAfee, Symantec, Nod32, Kapersky, Bitdefenderfor getting a B in detection, then had to eliminate AVK, F-Secure, Ikarus, Trustport, Sophos, TrendMicro for getting a B or less in performance. I ended up with Avira, WebWasher. When I went to web washer's site it was hard to find a download link. Then I chose Avira, because they had a free personal edition, which these testers have tested. Only flaw was that the free version did not have ad-ware or spyware protection. I already had that protection in the security suite that I own. So I selected Avira ... and I am quite happy, specially because I did not have to spend a single dime.

So, if you are a developer who is looking for a good anti-virus then I hope I have been able to narrow down your search. If you are someone who wants to test the anti-virus themselves then you can go and download the samples from www.av-test.org and test it yourself, although I cannot guarantee that your PC wont be infected you can try that as well. Good luck on finding a good solution. :)


Memory control : Use GCHandle to pin down the objects

In the .NET framework memory control is mostly autonomous and is controlled by the CLR. Although in managed languages we do not care much about controlling memory but when we have to interact with other languages we have to be aware of the memory implications. When we create an object in memory there is no guarantee that the object will remain in the same location it was created in. This is because the GC moves memory around by itself when needed to.

Variable movement in memory

I am sure that everyone reading this have already read about how GC collects memory and generations. As you know that GC allocates memory spaces in bulk. When needed GC collects unused memory and moves it. For example if the object you are using is collected, in order make better allocation GC can move it a different block of memory and free the block you were in. Let think we have a variable called "x" and it allocated in the memory like in the position like shown below.

 GC Generation

Figure 1: Before GC collection

in the figure above 1 is the space that are allocated and 0 are the ones that need to garbage collected because there is no reference to it. When GC collects it might decide to move the occupied items to the top block keep the second block empty by compacting. If so our memory could look like this diagram below

GC Generation1 
Figure 2: After compacting the variable moved to different virtual address

As you see that GC has moved all items to the first block of memory and the second block is empty which will result in faster memory allocation for new variables and it makes sense to do to so. Our variable x has moved to a different location in memory space which means the address of the memory where the variable is kept has changed. (Please keep in mind that the address space used does not have anything is physical ram as the OS may decide to change the physical address anytime and the address we are referring to is virtual address. Usually GC collect after 256KB of memory has become occupied, depending on the version of GC and OS and the mode it runs. As GC is independent of the thread you are running, it can collect any time.

GC Thread

If you are doing unmanaged memory operation and you are using the memory address and GC can come in move the memory away as you use the address to do unmanaged operations.

Pin down: API Calls to PInvoke

So can can this be a problem when we are calling windows APIs? For example, what happens if the window handle (hwnd) that I specified in the pinvoke is moved to a different memory address. The variable is pinned down to memory before the PInvoke call and pinned status is released just after the call. This is done automatically by the CLR. So what would have happened if GC had come in while the unmanaged PInvoke was running? See the figure below

GC Generation 3

As you can see in the figure above that the variable x  did not move to another virtual address in memory. This is useful when I need some unmanaged code to access a memory address that is constant. For example lets think of a scenario where I have an integer array which I pass to some unmanaged function and then I change the values of the variable at times and unmanaged function read changed values in the integer array and does some work. In such a scenario I will need the array to remain in one constant space. So I will need GCHandle class to pin it down in memory

GCHandle class

We find the class in System.Runtime.InteropServices namespace. In order use this class we will need SecurityPermission with Unmanaged code flag most of the time. Each application domain has a for GC handles, with this GCHandle class we can control what items are in that table. The Garbage Collector actually reads this table  and abides by it. Each entry in the table points to an object in the managed heap and how GC should treat it. There are four behaviors types as described in the GCHandleType enumeration. They are as follows,
    1. Weak
    2. WeakTrackResurrection
    3. Normal
    4. Pinned

Weak and WeakTrackResurrection for tracking weak referenced objects (see earlier post WeakReference: GC knows the Best for more on weak references). The Normal type is used to keep an object alive even if there are no reference to it. We are interested in the last type called Pinned. This tells the Garbage Collector to keep this object in memory even if there are no reference to it and never to move this object around in memory. See an example below on how to use the GCHandle class

string name = "My Name";
byte[] nameinbyte = ASCIIEncoding.ASCII.GetBytes(name);
// Pin down the byte array
GCHandle handle = GCHandle.Alloc(nameinbyte, GCHandleType.Pinned); 
IntPtr address = handle.AddrOfPinnedObject ();
// Do stuff ... with the pinned object address 
// ....
handle.Free();

Things to Remember

Please note that too many pinned object will make the GC slowdown. Also only blittable types and arrays of blittable types can be used. If you have written a custom object you can make it blittable by implenting a custom marshaler with the ICustomMarshaler interface.

kick it on DotNetKicks.com

Selected posts on CLR, threading, Internationalization and WPF

I have been professionally working in the software industry for over 9 years but I am relatively new to the blogging community. I have only started to blog around 5 months ago. I have selected some of my previous posts which I liked. Please find the links below

CLR Fun Stuff: How is my C# code converted into machine instructions?
This post decribes the process of MSIL being converted to binary instruction bt the JIT compiler.

WeakReference: GC knows the Best
A basic look at the Weak Reference class which helps to re-aquire data left for garbage collection.

Multi-core CPU Caching: What is volatile?
What is the impact of the volatile keyword in the world of multi-cored CPUs

Dll heaven: Executing multiple versions of the same assembly
How can you execute code from different versions of an assembly in a single process.

Spider's Web: Spawning threads in .NET, The Basics
A basic look at threading. It was going to be 1st part of a 5 part series, but it was discontinued as there was a good free e-book available on .NET threading.

Basic WPF: Stylize standard tabs into Aqua Gel
How can you change the look of the standard controls with styles in WPF

Fun with Generics: Using constraints to limit Generics applicability using the 'where' keyword
A less used but powerful architecture tool, type limiting in generics

Internationalization: Creating a custom culture
How can you add support for your language/culture if .NET does not have built in support for the language like my language ' Bangla'

kick it on DotNetKicks.com

Basic WPF: Stylize standard tabs into Aqua Gel

I was making this WPF based application on weekends and wanted it to have a gel like look. I did not want to create a new control instead I wanted to make sure that I used WPF styles to change the look of the tab. I decided to share this experience so that anyone who wants to do this does not have to do any research. The things that I will do to make this happen required very simple and basic WPF knowledge and is thus considered as kid stuff to many WPF pros. But none the less, I am interested to share this. Here goes ...

Download GelTab.zip

Styling and Templates

Basic WPF ControlWPF has the capability of applying styles like css does to html. Any WPF control that we use has something called a control template. The control template defines how the control will look. The control template may contain triggers also. Let try to understand from the diagram below how WPF renders a control UI.

The basic WPF control has a template which it uses to render the UI from the control definition. This can be changed by applying a custom style. In order to do that we must first define a custom style where we can modify the template for the control. By doing so we will able to completely change the look and behavior of the control. We can even make a tab look like a listbox a tree. The possibilities are endless. However today we will only try to make the tab look like blue gel based (Aqua) tab. Which should look like this (by the way. I have not yet decided on the blue shade ... it still looks a little ugly) ...

Tab Look

In order change a tab to look like this I will need to write a style and modify that style.

Basic WPF Control with Styling The control code will stay the same but the style template will change. In order to this we will create a resource dictionary. So we have created a resource dictionary called GelTabStyle.xaml. In order for this to be used by the application the this will need to be added into the application dictionary ( we can also put it in the file with the tab instance, but that is not a good practice). When we add such a resource dictionary from the Visual studio or Microsoft Expression Blend the IDE automatically modifies the App.xaml to include the resource dictionary. Here is how our App.xaml should look like ...

<Application.Resources>        
  <
ResourceDictionary>
    <
ResourceDictionary.MergedDictionaries>
      <
ResourceDictionary Source="GelTabStyle.xaml"/>
    </
ResourceDictionary.MergedDictionaries>
  </
ResourceDictionary>       
</
Application.Resources>

WPF Control Composition & Templates

As I have already stated that a WPF control has templates to define its UI, what are these templates made of? They are made of WPF shapes, other WPF controls, triggers and GDI resource definitions. To have a very simple idea see the diagram below...

WPF Control Anatomy 

A control has a template which is made of WPF basic elements and controls, and each of those controls have templates which have WPF elements and controls in them. We can define a style in a resource dictionary (in our case the GelTabStyle.xaml) and inside a style we can define our custom control template. Before we go any further lets try to look up a tab controls template.

Anatomy of a Tab

If you pry open the template that renders the tab control with Expresssion Blend then you would find that there is a grid with 2 rows. The first row contains the tab item headers and second part contains the tab body. See the diagram below ...

TabControlStructure

Since we want the tab headers to be gradient gel like we will define a style for those and will call them "GelTabItem" and also will need to change the bottom container and will call that "GelTab" style. For our case we only the the tab headers to placed at top ... so we wont bother with placing them at left, right or bottom.

Inside the resource dictionary we have defined some colors and some gradient brushes to do our painting, which looks like this ...

 <Color x:Key="TabItemGradStart" R="#AA" G="#AA" B="#BB"/>
<
Color x:Key="TabItemGradEnd" R="#EE" G="#EE" B="#FF" A="#FF"/>
...
...

<
LinearGradientBrush x:Key="TabBackgorundBrush" StartPoint="0,0" EndPoint="0,1" >
     <
GradientStop Offset="0" Color="{StaticResource TabItemGradStart}"/>
     <
GradientStop Offset="1" Color="{StaticResource TabItemGradEnd}"/>
</
LinearGradientBrush>
<
LinearGradientBrush x:Key="TabBackgorundBrushSel" StartPoint="0,0" EndPoint="0,1" >
     ...
     ...

So we have defined the basic drawing resources, lets look at the style header

<Style x:Key="GelTabItem" TargetType="{x:Type TabItem}">

If you look carefully that you would find that this style can only apply to a TabItem object and also it will only apply to those tab items which have their style set to "GelITabtem". By the way if we wanted to make sure all the tab items in the application would use this style (except the ones that has explicit style defined) then we would remove the x:Key keyword from the style. That would ensure that all tab items by default will have the style applied. However that is not our goal.

TabItems

Lets see how the xaml code makes the header part with tab items to be styled. The diagram below will make it clear.

TabHeader

As you can see that we have used a border with rounded corners to make a border for the gel tab item, we have also used a rectangle to fill the gradient area of the button. We used the gradient brush that we defined at the start of the resource file.

Triggers

In order make sure that the selected tab has one color and the unselected tabs have different color we used triggers to change the back color. See the code snippet below

<ControlTemplate.Triggers>
  <
Trigger Property="IsSelected" Value="True">
    <
Setter TargetName="TabItemBackgorund" Property="Fill"
      Value="{
StaticResource TabBackgorundBrushSel}" />
  </
Trigger>
  <
Trigger Property="IsSelected" Value="False">
    <
Setter TargetName="TabItemBackgorund" Property="Fill"
      Value="{
StaticResource TabBackgorundBrush}" />
  </
Trigger>
  <
Trigger Property="IsEnabled" Value="False">
    <
Setter TargetName="TabItemBackgorund" Property="Fill"
      Value="{
StaticResource TabBackgorundBrushDisabled}" />
  </
Trigger>
</
ControlTemplate.Triggers>

When the tab is selected use a brush called "TabBackgorundBrushsel" as the fill value of the rectangle and when it is not selected we use the brush called "TabBackgorundBrush" to have an effect of unselected item. Similarly we use "TabBackgorundBrushDisabled" to fill the rectangle for the disabled tab item. See figure ...

SelectionBrush

Tab Body

If you observe the tab body style then you would see a control with the "controlpresenter" tag which actually contains the controls that we place inside the tab.

<ControlTemplate TargetType="TabControl">
  <
Grid>
  <
Grid.RowDefinitions>
    <
RowDefinition Height="Auto"/>
    <
RowDefinition Height="*"/>
  </
Grid.RowDefinitions>
  <
Border BorderBrush="Transparent" BorderThickness="0" Grid.Row="1"
    
CornerRadius="5,5,5,5" Background="Transparent" Padding
="5,5,5,5" >
     <
Border BorderBrush="Gray" BorderThickness="1" CornerRadius="5,5,5,5"
       
Background="{
StaticResource TabBackgorundBrushSel}"  >
        <
ContentPresenter ContentSource="SelectedContent" />               
     </
Border>
   </
Border>
   <
TabPanel Grid.Row="0" IsItemsHost="true"/>
   </
Grid>
</
ControlTemplate>

If we observe the xaml above we would see that the body resides in second row and the header panel (<TabPanel> in xaml) resides at top row this is how the bottom and top placement of the two different parts are defined. We have made the body rounded and also padded it and used the selected brush to paint it.

Using the styles with the tabs

Styling Strategy  There are two ways to apply the style. Depending on how we want the tabs to look it may change. One strategy is to use css class like style that we made and apply them the control items. Another is to make the apply the style whole application wide. In order to make it application wide we would have to remove the x:key that names the style.

Now if we want to make it specific for a control we use the style tag to specify the style like the code below ( the part marked in bold letters)

<TabControl Style="{DynamicResource GelTabControl}" >            
   <
TabItem Header="Rapid Note" Style="{DynamicResource GelTabItem}">


kick it on DotNetKicks.com

Using Expression Blend with VS2008: Invalid project File Error

Recently I had to reinstall my laptop, so I also installed VS 2008 and Expression Blend. Expression Blend is a better WPF designer and VS2008 still has to lot of bumps to fix like frequent crashes on WPF, showing errors that are not there etc. So I tried to use Expression blend but it seemed that when ever I tried to open a VS2008 project I get an error message. The message tells me that the project file is invalid because there in an Import directive there. When I looked closely I found this

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

When Blend finds this tag it cannot load the project. So I tried removing this line and the project loaded with errors. Then I downloaded the Service Pack 1 for Microsoft Expression Blend from this location and installed and Walla! All my problems were gone. Please note that according to MS installing Blend 2 September Preview will also fix this issue.


Dynamic Language Runtime: What is it?

On many blog entries around the world, specially from the bloggers from Microsoft, one would find a numerous mention about the Dynamic Language Runtime (also known as the DLR). Specially since many MS bloggers are writing a lot about IronPython, DLR is reflected in their topics. So I was questioning myself a few days ago about the DLR and how is it different from the CLR? Here are my findings.

Dynamic Programming Languages

The first and most common example of dynamic programming languages is Javascript, where one can define types and its methods at runtime. By definition, a dynamic language is a high level programming language whose behavior at runtime is similar to its behavior at compile type. So the compile time behaviors in normal programming languages can also execute at runtime for the dynamic languages. For example a class (type) can be defined at runtime or its methods can be defined at runtime in JavaScript. So a types behavioral properties can be extended at runtime. The type or the object system may be defined or changed at runtime, even the inheritance tree might be modifiable.    

Dlr1    

These behaviors can be emulated by standard runtime like the .NET CLR but, it takes a lot of work to do that. Thus the DLR is born.

Dynamic Language Runtime

First of all let me state that the CLR already has support for dynamic languages, however adding the DLR on top of CLR makes it much more easier to implement a dynamic language and makes communication between multiple dynamic languages a breeze just the way CLR did it for multiple .NET languages. This added layer on top of the existing CLR provides the following services.

Shared Dynamic Type System (I am calling this DTS)
Unlike the CTS where type safety is a crucial requirement the DTS allows us to morph the types at runtime. So we can add methods to the a type or modify it. Also two dynamic languages can talk to each other with same vocabulary.

Dlr23_2

Dynamic Method Dispatching
Ever heard of C++ virtual function tables? Dynamic dispatching is dynamically being able to change which code executes for a method at runtime. There is also another form of dynamic dispatching which is per instance dynamic method dispatching. For example at runtime we can define what code will execute for the method of a class, which is simple method dispatching. But if we are able to define for an instance of a class which code will execute for the instance of that class type that would be instance based dynamic dispatching.

Dynamic Code Generation
Code generation capabilities at compile time is called dynamic code generation. The generated code may have the capability to modify itself. For example, JavaScript eval() function is very powerful and it is able to compile and modify itself.

Hosting Capabilities
Just like the CLR, the DLR also has a hosting API.

Summary

So the DLR makes it a whole lot easier for two dynamic languages to have shared code. The keyword here is sharing. Also the DLR is built on the existing CLR. Microsoft has its DLR source code available at codeplex with IronPython project. IronPython is the first sample DLR language and MS plans to implement DLR in VB.NET 10 and next Jscript.

kick it on DotNetKicks.com