Archive for the ‘CodeProject’ Category

Creating a smoke using Particle System in Silverlight

Here’s what we’re trying to achieve: demo

One of a fellow programmer came up with a question of “How do you create Smoke effect using Silverlight?” Well there may be plenty of code, third-party tools and plug-ins strewn over the internet for this, but out of a professional curiosity I got into the business of creating one out of my own hands.

The whole concept of creating smoke (without fire ;)) can be done through what they call as Particle System. It’s a technique where in you employ very small graphical objects in large numbers to simulate effects like say Smoke, Fire, Snow, Dust, etc…

We need the smoke to be moving freely, so a canvas would be a best bet for the layout.

<Canvas x:Name="myCanvas" Background="White">

From this point on the rest of the Smoke effect would be programmed in code behind file (C-Sharp in my case)

Let’s think a minute about smoke, shall we? Smoke starts at a point, very concentrated (Generation Point). According to the complex laws of physics, it simply rises up becoming dilute all the way. Finally blending well with the air where it seems to disappear (Vanishing Point).


Understanding the dynamics of smoke

Our approach would be to consider smoke as made up of small particles, which would originate at the Generation Point. These particles as time passes would simply rise up, becoming transparent by smaller percentages as it goes and finally becoming invisible at the Vanishing Point.

These particles are going to be ellipses. Let’s have a method which does just that.

public static Ellipse createEllipse()
Ellipse objEllipse = new Ellipse();
//Smaller sized particles
objEllipse.Width = 1;
objEllipse.Height = 1;

//Giving the particles a Smokey look
RadialGradientBrush rgbObj = new RadialGradientBrush();

GradientStop gsObj1 = new GradientStop();
gsObj1.Color = Colors.Transparent;
gsObj1.Offset = 2;
GradientStop gsObj2 = new GradientStop();
gsObj2.Color = Colors.DarkGray;
gsObj2.Offset = 0.5;
GradientStop gsObj3 = new GradientStop();
gsObj3.Color = Colors.Black;
gsObj3.Offset = 0.001;


objEllipse.Fill = rgbObj;

//Set the position of the ellipses to the Generation Point
Canvas.SetTop(objEllipse, 300);
Canvas.SetLeft(objEllipse, 150);
return objEllipse;

While the Silverlight application initializes, we’d simply call the following line to add a new smoke particle:


Well, this is just one particle. By every tick of the clock, new particles should be generated to give the effect of the smoke billowing. This calls for a DispatcherTimer instance which would give me an event for say every 2 millisecond.

System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
timer.Interval = new TimeSpan(2);
timer.Tick += timer_Tick;

At every tick, we need to be doing a set of tasks based on a few decisions.

Firstly, we cannot afford to overload the memory/screen with infinite number of particles. When a smoke particle simply disappears beyond the vanishing point, we can move them down to the generation point and reuse them. For this purpose, let’s have a limit of 1000 particles that can be freshly generated. If the screen has less than 1000 of them, we can go ahead and generate a new one.

if (myCanvas.Children.Count < 1000){

Secondly, at every instant – *all* the smoke particles should perform the following tasks:

  • Rise up
Canvas.SetTop(item, Canvas.GetTop(item) - 1.25);
  • Grow and become lighter in visibility
item.Opacity = item.Opacity - 0.009;
item.Width = item.Width + 0.075;
item.Height = item.Height + 0.075;
  • And take a wavy path up. Smoke particles take a simply chaotic path up, they just don’t go up in a straight line.
Random randObj = new Random(10);
Canvas.SetLeft(item, Canvas.GetLeft(item) - (Math.Pow(-1, randObj.Next(5)) * randObj.Next(2)));

Thirdly, Move every vanished particle back to its original point.

if (item.Opacity < 0.0001){
item.Opacity = 1;
item.Width = item.Height = 1;
Canvas.SetTop(item, 150);
Canvas.SetLeft(item, 300);

So, considering all above, my timer tick event would look like this:

void timer_Tick(object sender, EventArgs e)
if (myCanvas.Children.Count < 1000)
foreach (Ellipse item in myCanvas.Children)
if (item.Opacity < 0.0001)
item.Opacity = 1;
item.Width = item.Height = 1;
Canvas.SetTop(item, Y);
Canvas.SetLeft(item, X);
item.Opacity = item.Opacity - 0.009;
item.Width = item.Width + 0.075;
item.Height = item.Height + 0.075;
Canvas.SetTop(item, Canvas.GetTop(item) - 1.25);
Canvas.SetLeft(item, Canvas.GetLeft(item) - (Math.Pow(-1, randObj.Next(5)) * randObj.Next(2)));

Thus, was how we can generate a smoke effect in Silverlight using Particle System. With a minor change in the color and nature of the ellipse, you can create Fire or other similiar effects.

Suggestions welcome from expert readers on alternate or even better ways!


Online Identity Explosion – Securing your identities

March 4, 2012 2 comments

Firstly, be it a tech-savvy or be it a normal person, everyone has a life online. Here online, I refer to the internet and the myriads of websites there in. Programming forums, healthcare, lifestyle, romance, banking, travel, blogging, electronic mail, ecommerce; these are just few of the categories that pop in my head when I think of what we do online.

Let’s do the math. Each of these categories has at least n different websites/vendors associated with it. Say, electronic mail – you have Gmail, Hotmail, and MSN and so on. Take for instance ecommerce, you have Amazon, e-bay, or may be even the flip kart. Each of these require you to register and have an identity (username and password) associated with them.

Normally you choose to have the same username with all of them. But the rules vary with many, some allowing symbols, some disallowing numbers – you are forced to vary your usernames with the websites. And same is true for passwords – One of your comfortable passwords might be unacceptable by some accounts. Some websites have to be associated with email identities. If you took to internet after Gmail came in, then chances are you’ve associated all your email accounts with it. If otherwise, you might have had a host of other email accounts like, or

Now each identity needs a password. Let’s see.

1.       You can use the same password for all your accounts.

      Great choice. Allows you to remember a single password for all your identities. But this leaves you at a risk. One of your accounts gets hacked into, and you lose across the board.

2.       You use a new password for each of your accounts.

      This reduces your vulnerability to a hack. Even if one of your accounts gets compromised, you can save all your rest. But that gives you N passwords for n accounts you hold. Mighty hard to remember isn’t it?

Good online behaviour states, you cycle your passwords at least every 45 days to prevent your accounts from getting compromised. Now how do you do that, without having to go through the trouble of remembering the new sets of passwords again?

This discussion did not mention, ghost accounts (which you have probably false identities), intranet accounts (which are not under the internet category – but still requires a username/password and hence a necessary payload on your brain)

IMO, this seems to be a pretty interesting and wide area for research. If necessity is the mother of invention, this is the right time to invent, discover or re-discover a cost-effective solution that is within reach for a normal internet user. A normal user is right now juggling with at least 10 online accounts in his hands, forgetting passwords every 10 days, clicking on that seemingly helpful “Forgot your password” link. Or an unassuming user is in a false-sense of assurance having a same password for all his online accounts, screaming to be hacked and compromised.

The solution being proposed for curbing online identity explosion should provide, a way to access all your online accounts in an easier manner, while ensuring that:

  1. Safety of the identities are secure against any forms of hack
  2. Solution is accessible to nay web user – with minimal or zero-overhead
  3. Various modes of access are addressed – Mobile, single point of access, multiple point of access

Extending Internet Explorer – Scenario based overview

February 6, 2012 Leave a comment

For one of my projects, I was working on a minor enhancement. The project was web-based and as per client’s requirement, run only on Internet Explorer. The enhancement was related some data input page but access to any part of the site was restricted by a Login page.

The login page, as like any, consisted of a very minimal input – the username and password. But any change or recompiling on the site made me go from the login screen. Since it was a pretty old (almost a decade), it never had or no one bothered to put a “Remember me” check box. So logging in through the main screen was pretty customary.

I quickly considered the other alternative of hardcoding the values into the code, or at least till the release was made. But the idea of making temporary fixes to code for my pleasure nauseated me immediately.

What I was looking for, was a very efficient way to give me a quick form fill feature on the browser without having to mutilate the project in any possible way. May be Internet explorer had an option of extending itself! Fortunately it did and I finally figured out a way to do exactly that.

What would be the outcome? The outcome of this simple hack procedure would provide me with a new item on the Right click menu on Internet Explorer. On clicking upon such menu item, the fields on my form (website) would be auto filled with pre-set values.

Where all can I apply this hack? This procedure would specifically suit Internet Explorer browsers of versions anywhere in 6, 7 or 8. Although this has not been tested on very recent releases of Internet Explorer. If you’re using browsers like Chrome you have other ways of extending the browser functionality, this is just for my fellow developers like me who have no other browser to turn to except IE.

Can we get on to the hack already? Yeah sure.

All I need for this hack would be:

  • A registry entry
  • A simple javascript function

Registry entry: The whole purpose of the registry entry is to add the menu item to Internet Explorer’s context sensitive menu. As far as my knowledge goes, there isn’t a straight way of doing this than to go for a registry edit.

Warning: This section involves a registry edit. Altering registry settings without proper care might render the operating system useless. Kindly ensure necessary precautions before proceeding. Hazmat suits advised. Alternatively, you can visit this link to back up your registry settings.

  1. Enter regedit in your run command prompt.
  2. In the registry editor, navigate to the following tree-child.
  3. HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\MenuExt\
  4. Create a new key under this tree element, by any name “XYZ” of your choice.
  5. Under the registry item “XYZ”, add the following String Values as below:
  • String Value: CLSID
    • Value: A guid like {1FBA04EE-3024-11D2-8F1F-0000F87ABD16}
    • PS: You may use any GUID generator to get such a string
  • String Value: Menu Text
    • Value: My Menu Extension
    • PS: This text would appear on your Internet Explorer context sensitive menu.
  • String Value: Exec
    • Value: Path to the HTML file, you’ll be coding in the next section.
    • Example – C:\MyFolder\MyFile.html

JavaScript function:

  1. Place a simple javascript code to do the job of the form filling in a html file.
  2. Copy the location to this html file and place in the above registry item’s, Exec value.
  3. Restart your internet explorer
  4. Navigate to your page, a right click on it – you must see “My Menu Extension” on the right click menu.
  5. Click on it to perform the tasks you’ve coded in the javascript function. Or in this case, it would fill two textboxes txtUserId and txtPassword with corresponding values.
<Script language="JavaScript">
var parentwin = external.menuArguments;
parentwin.document.forms.txtUserId.value ="UserName";
parentwin.document.forms.txtPassword.value ="Password";

Well, that’s how I solved my requirement with a simple concept of extending Internet Explorer. The possible areas of further work I looked into were

  • Filling huge web-forms (repetitive tasks) for let’s say testing purposes with the ease of a right-click menu item
  • Automating using a excel macro to create the registry entries and their corresponding javascript function for different sets of values provided. Basically abstracting the user from the nitty gritties and allowing him just the final piece of cake.

For a very detailed look into various customizations on Internet Explorer, check this link

Regular Expressions – String manipulation simplified

February 1, 2012 Leave a comment

Regular Expressions are an amazing way to go. A regular expression (regex or regexp for short) is a special text string for describing a search pattern. You can think of regular expressions as wildcards on steroids. Almost all languages support them and with a little understanding, you can ace at them. What more, they condense tens and thousands of lines of logic into just a couple of simple lines. I’ve used regular expressions both through .NET framework and in JavaScript and found them to be immensely helpful. This blog post focuses majorly on them and here’s a little outline on how I’ll be approaching the concept on hand.

  • A problem –  We engineers are problem solvers, so a simple problem followed by how regular expressions solved it in an even simpler way
  • Dissecting the solution – An understanding of the above simpler solution
  • Link to raw regular expression resources – Unless you can make up some of those regular expressions, you can never make it easier to use this language feature
  • RegEx class – The power of RegEx in .NET framework, what all you can achieve

Starting with this, followed by that, then this and then a dozen of that – A Problem!

I was given, the below problem statement and a laptop to code and solve. Developer instincts are hard to ignore and eventually I started scribbling off an elegant algorithm, or so I thought.

Domestic passport numbers either begin with the letter TW followed by 12 digits, or begin with 6 digits followed by 4 other characters and ending with the letters OFTW.

Pseudo logic:

  1. Is Starting With TW?
    1. Are the remaining 12 characters – digits?

i.      Return “Domestic”

  1. Is Ending with OFTW?
    1. Does it begin with 6 digits?

i.      Return “Domestic”

  1. If all above fails
    1. Return “Foreigner”

So with all the code logic and intricacies figured out, I exactly translate the pseudo code to C# code:

public bool IsDomestic(string PassportNumber)
if (PassportNumber.StartsWith("TW"))
string Rest=PassportNumber.Substring(2,12);
Int64 Result;
if (Int64.TryParse(Rest,out Result))
return true;
else if(PassportNumber.EndsWith("OFTW"))
string First6 = PassportNumber.Substring(0, 6);
Int64 Result;
if (Int64.TryParse(First6, out Result))
return true;
return false;

That’s when I was told; don’t you follow all the language features? Especially something called Regular Expressions?

Well, not to be an all knowing buff but yet, I knew what Regular Expression was and I perfectly knew how to use it. But surprisingly it never struck me. Given a problem, my initial mode of tackling it was to analytically approach it and solve. Although regular Expression’s way of doing it was straight opposite – it was elegant; and I hit myself why my mind didn’t think of it.

The Solution – Simpler one

So here’s the code, if I had used RegEx

public bool IsDomestic(string PassportNumber)
return Regex.Match(PassportNumber, "(TW)(\\d{12})($)|(\\d{6})([A-Za-z0-9]{4})(OFTW)($)").Success;

Surprisingly less lines of code, isn’t it?

Let’s dissect the solution

Without going into much deep, let me explain what the pattern (yes, I called it a pattern) means:


You see the pipe (|) symbol in the middle? Let me split the pattern at that part.

Left part: (TW)(\\d{12})($)

(TW) – Simply means that the two initial characters are TW

(\\d{12}) – tries to say that there are 12 digits following

($)– The string should end at the point, no more characters

Right part: (\\d{6})([A-Za-z0-9]{4})(OFTW)($)

(\\d{6}) – The first 6 characters are digits

([A-Za-z0-9]{4}) –  4 alphanumeric (A-Z or a-z or 0-9) characters would follow

(OFTW) – The next four characters would be OFTW

($)– The string should end at the point, no more characters – as we saw earlier

Did I miss the pipe (|)? You know what it is, it’s just an OR condition. The string in question, say TW012345678901 can choose to match with either the left part pattern or the right part pattern.

Some links before we proceed

This should have given you a basic idea into formulating a simple RegEx pattern; if you need further help you can visit It gives you a good glimpse on RegEx.

Or if you want a quick stop solution/pattern, visit Mark’s, it’s an amazing site.

The almighty RegEx class of .NET

Let’s step back a bit and focus on the RegEx class in .NET framework, and see how better we can use it!

Check if a string is looking as it should

The above solution simply does that. The Match, IsMatch methods of the RegEx class tries to fits the given string into a pattern and says True, the string matches the pattern or False, the string looks nothing like the pattern! The simplest form of the method asks only for the pattern and the string.

Replace a questionable part in a string

Take for instance, the exclaimer. He gets too excited for nothing and you just need to dial his excitement down. How?

string SampleText = "This is Outrageous!!!!!!!! Regex can't solve all my problems!!!! What if it can!!!!!";

You can never track the count of the exclamations he has used (!) nor does he use a specific number all the time. The Replace method of Regex would help you there.

SampleText = Regex.Replace(SampleText, "(!)+", "!");

PS: The plus (+), here in the pattern says that the (!) can appear once or more in the string. And the last part is the replace with part. All questionable parts matching the pattern would be replaced with the input to the method.

This would give me an elegant output like thus:

This is Outrageous! Regex can’t solve all my problems! What if it can!

Pattern matching, only simpler:

Imagine how hard it was to match patterns or find the count of substrings actually matching a pattern you’re looking for. RegEx offers you an elegant way to the same, using RegEx.Matches. Let’s take the below statement.

“Are you working on any special projects at work? I am not reading any books right now. Aren’t you teaching at the university now?”

I need to fish out all the present-continuous forms verbs in them, i.e. the words ending with “ing”. Normally this would be a heavy code. But with RegEx we can do it faster and simpler using the pattern string “(\\b)(\\w+)(ing)(\\b)”

This says – in sequence,

\\b blank space
\\w+ [one or more] word character
ing The specific set of characters “ing”
\\b blank space
MatchCollection collObj=Regex.Matches(TestString, "(\\b)(\\w+)(ing)(\\b)");
foreach (var item in collObj)

Would print me out, all occurrences of the pattern, which are:





Through this post, I’ve summarized most of the key uses of RegEx with special emphasis on .NET code. Beyond a particular point, it depends on your creativity how you take it further to tailor the RegEx solution based on your problem. You can do away with ugly for loops or unnecessary if-else constructs in code.

%d bloggers like this: