Saturday, May 29, 2010

AJAX or AJAJ: XML vs JSON

Why JSON? One word: Simplicity.

More than one word: JSON is simple, simpler than Xml. I am big fan of Xml, and that makes me a love XPath as well. But this does not mean that I am against JSON or otherwise. While on my way back home the other evening, this guy who works in the IT department of one of my customer, where I was for the project implementation. While he was talking to "his" friend(colleague, probably) about JSON and Xml, and if Xml is there then why would you ever use JSON? I was sort of magnet'ically attracted to the discussion and eventually became the part of it. So, here I thought I should add my two cents of understanding of how and where I would use either and what would be the use case.

Custom Thread Pool: Multithreading in a loop

Should you come across a scenario where you want spawn threads from within a loop, you can have a quick two options:

Option 1: Use ThreadPool.QueueUserWorkItem

Depending on the size of the job to be processed, I always admire the ThreadPool.QueueUserWorkItem; this creates a handy pool of threads, and execute the process upon request whenever a thread is idle'ly availble in the pool.


using System;
using System.Threading;
public class Example {
    public static void Main() {
        // Queue the task.
        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));

        Console.WriteLine("Main thread does some work, then sleeps.");
        // If you comment out the Sleep, the main thread exits before
        // the thread pool task runs.  The thread pool uses background
        // threads, which do not keep the application running.  (This
        // is a simple example of a race condition.)
        Thread.Sleep(1000);

        Console.WriteLine("Main thread exits.");
    }

    // This thread procedure performs the task.
    static void ThreadProc(Object stateInfo) {
        // No state object was passed to QueueUserWorkItem, so 
        // stateInfo is null.
        Console.WriteLine("Hello from the thread pool.");
    }
}


Option 2: Implement a custom ThreadPool using BackgroundWorker, incase you are hating ThreadPool for whatever reason.

The main worker object.

/// 
/// The core entity that handles
/// 
public class CWorkers
{
public int _nIndex { get; private set; }
public BackgroundWorker bgWorker { get; private set; } //the main "culprit"

public CWorkers(int nIndex)
{
_nIndex = nIndex;
bgWorker = new BackgroundWorker();
}
}
The manager class that manages the worker thread.

/// 
/// Manages the worker thread.
/// 
public class CWorkerManager
{
    private List _lstWorkers;//list of worker threads
    private const int MAXWORKERS = 5;//Max workers you want; change/update or pull it from app.config.

    public CWorkerManager()
    {
        Initialize();
    }

    /// 
    /// Initializes the thread pool - sorta customized threadpool
    /// 
    private void Initialize()
    {
        _lstWorkers = new List();//initialize the list

        for (int i = 0; i < MAXWORKERS; i++)
        {
            _lstWorkers.Add(CreateAWorker(i)); //inits a worker objects and adds to list
        }
    }

    /// 
    /// Looks for a free thread
    /// 
    /// Returns the thread if found, else nothing.
    public CWorkers RequestForWorker()
    {
        foreach (var theWorker in _lstWorkers)
        {
            if (!theWorker.bgWorker.IsBusy)
                return theWorker;
        }

        return null;
    }

    /// 
    /// Emulate the BCL's .WaitOne()
    /// 
    public void WaitAndSignalWhenFree()
    {
        while (true)
        {
            //Loop through the list to find an idle thread
            foreach (var theWorker in _lstWorkers)
            {
                if (!theWorker.bgWorker.IsBusy)
                    return;
            }
            Thread.Sleep(1);//This may be a hack; not really recommended as a production code.
        }
    }

    /// 
    /// Inits a CWorker object; adds the 
    /// 
    /// 
/// 
    private static CWorkers CreateAWorker(int nIndex)
    {
        var theWorker = new CWorkers(nIndex);

        theWorker.bgWorker.DoWork += (sender, e) => ((Action)e.Argument).Invoke();
        theWorker.bgWorker.RunWorkerCompleted += (sender, e) => Console.WriteLine("Finished worker number:[" + theWorker._nIndex + "]");

        return theWorker;
    }
}

The test program:

class Program
{
    private static List _lstWorkers;
    private const int MAXWORKERS = 5;
    static CWorkerManager theManager;

    static void Main(string[] args)
    {
        theManager = new CWorkerManager();

        ProcessJobs(20000);
        Console.ReadKey();
    }

    /// 
    /// Simulator that request the Manager for worker threads
    /// 
    /// 
private static void ProcessJobs(int nMaxTime)
    {
        Random rndRandom = new Random();
        DateTime dteStart = DateTime.Now;

        //Run till the max time.
        while (DateTime.Now - dteStart < TimeSpan.FromMilliseconds(nMaxTime))
        {
            var theWorker = theManager.RequestForWorker();//Request for a worker

            if (theWorker != null)
            {
                theWorker.bgWorker.RunWorkerAsync(new Action(() =>
                                    ProcessThis(theWorker._nIndex,
                                        rndRandom.Next(1500, 2500)//Generate somethign random
                                        )));
            }
            else
            {
                Console.WriteLine("All busy, lets wait...");
                theManager.WaitAndSignalWhenFree();
            }
        }
    }

    /// 
    /// Actual method that processes the job.
    /// 
    /// 
/// 
static void ProcessThis(int nIndex, int nTimeout)
    {
        Console.WriteLine("Worker {1} starts to work for {0} ms", nTimeout, nIndex);
        Thread.Sleep(nTimeout);
    }
}

Output:


Happy threading.

Monday, May 24, 2010

Colors of life

1. I believe everything and everyone has a purpose in life. Oblivious or obvious. Allah swt has created some people whose work is to help other people directly or indirectly, going out of the way or just by a therapeutic-talk to someone. They may not even know, because that is so a part of their nature. Probably at some point in time they would sit down and think that they are of no use, but eventually they may realize that they are.

2. Allah swt has created some people whom you want to be around. You may not even know them personally, but just an overhearing about their knowledge, and wisdom, and humbleness, and the insight that they possess about the vast experience of life; they bring a series of joyous moments that you would really want to enjoy every bit of it, and eventually get addicted to such a flavor of life. It is like, raining... and you are able to catch each drop of rain over you skin and on your eyes, and lips and mouth and hands - wide open.

3. I see life as colors, some time back while discussing an odd topic with friends, I came to realize.

Every phase of life is a color; and we should enjoy all colors.

For instance, smiles are green, sadness is dark pink, solitude is gray - happiness with bright blue-white-sky'ish(if thats a color);

Being a toddler is with another color. Being young is another. Life with parent is another color. There could be overlapping colors. For instance, the part of life when you are young and living with parents. Good moments, bad moments - another color.


Married life, another color. Life with kids, your own kids, another color. Waking up in the middle of the night out of deepest of a slumber to feed your baby - another color.

Not necessarily you have to be old in order to experience colors. People who have NDE saw yet another color of life(or death?). Obviously they wouldn't want to experience such a color again, but thats just another color of life that they experienced.

Not necessarily that color that you have seen matches exactly to mine. For instance your experience of running a brand new Corvette Z10 might be different that mine. If you were sitting beside me then your color may be yellowish-brown out of fear, and mine could be shocking-greenish out of fun. (0:

The colors around the people discussed in 1, and 2, can be way different than people who show-case their helps.

Good colors - bad colors. Life without parents, life in poverty, the phase of life when you have crush, infatuation, love, hatred... everything; just more colors than 4.2 billion colors that we are able to define.

A friend complained about the married life; and that its hard get some space to breath; and everyone is so demanding, toddlers waking up all night, cant get enough sleep, etc.

My stand was to "enjoy" the color of life. It is always going to change; you would miss these colors afterward, and this color - at its intensity - is never going to come back again.

The point? is that life is full of colors!

And every color is ought to fade away with the passage of time.

So, enjoy all colors.

Friday, May 21, 2010

.NET Versions: EF4 with Visual Studio 2008

So can you use EF v4.0 with .NET 3.5 in Visual Studio 2008?

Short answer, No!

Longer answer... is still no, but lets go through the reasons it is so;

Similar to, that you can't use C# v2.0 features without at least VS 2005 and you can't use C# v3.0 features without VS 2008; it is that you cannot use EF v4.0 in VS2008.

Still a 'why'? Follow on...

Because EF v4.0 requires .NET v4.0(that is, 4.0.30319.1 to be exact - stable release out in the market, approximately 38 days ago); which means EF v4.0 is actually a part of .NET v4.0 - And, 3.5 uses CLR v2.0 while 4.0 uses CLR v4.0.

Among its many new improvements, Visual Studio 2010 introduces the much-awaited Entity Framework 4.0 and WCF Data Services 4.0 (formerly ADO.NET Data Services), which together simplify how you model, consume and produce data.

So to conclude: This means,
  • .NET v1.0 was used with VS2002 having C# v1.0
  • .NET v1.1 - VS2003
  • .NET v2.0 - VS2005 - C# v2.0
  • .NET v3.0 - Useable in VS2005
  • .NET v3.5 - Visual Studio 2008 having C# v3.0
  • .NET v4.0 - Visual Studio 2010 with C# v4.0

And according to Jon Skeet on SO, C# v5.0 contains major new speculated features such as Meta Programming.

If this makes you interested more in v4.0, checkout what's new in the latest .NET Framework.


References:
1. C# Indepth by Jon Skeet: http://csharpindepth.com/Articles/Chapter1/Versions.aspx
2. .NET Frameworks: http://en.wikipedia.org/wiki/.NET_Framework
3. Microsoft .NET Framework: http://msdn.microsoft.com/en-us/netframework/default.aspx
4. .NET Framework Evolution Map: http://bloggingabout.net/blogs/fernando/archive/2009/01/11/net-framework-release-map.aspx

Wednesday, May 19, 2010

A Practical Review: Dell VOSTRO A860

For a new product implementation, I was recently provided with a brand new, cool looking, shiny Dell VOSTRO A860; with configuration like Intel Core 2 Duo, 2GHz, 4GB DDR, 800MHz bus speed. Felt just a brand new Corvette Stingray 2010.

I am not sure if the reviewers really get a chance to "actually" run and test the product; before reading before enlightening about their views.

This is a brand new 2 months old sweet kid; but I was unpleasantly surprise when for couple of hardware related issues made my eyebrow raised; and then eventually left it raised, for good, for this pc!
  • The sharp hard disk noise that you cannot avoid noticing, and eventually bothered by.
  • CPU fan sometimes works really hard for the system to stay live - and you can feel you're some where near a flour mill is running, even if you've never been there.
  • The hotter it gets the longer you work.

Though I know its not a multimedia series, but further to add the agony...
  • No external mic, talk if you must then go buy a mic - better would be a mic+headset since the speaker is too low you can barely hear anything if specially if you are planning to watch a movie.
  • No web cam (0:
  • Battery life? Forget it if you are planning for a meeting that may continue for more than an hour - consider yourself blessed if you are able to shut it down successfully before the last minute Battery Warning pops up.
  • If you plan to get rid of Vista, then keep in mind there is a large range of hardware in the laptop that requires driver installation, for instance network, wifi, sound, audio, etc.
  • Hard to find drivers XP on DELL website, and even if you do - all they have are the drivers for Vista OS; since this machine comes with Vista.
  • You've got to be very, I mean "very" lucky to find the XP drivers to install.
I have been dealing with the blue screen of death since I got this pc; quite a couple of times; I know its an OS related error, and I did not report to IT support because I was able to restart the PC without problems. But yesterday, I think, was a lucky day! and I ended up writing my review.

The blue screen took this pc with it and they both died.

Both meaning, the OS as well as the system.

In vain in pain, I ran every possible alternate boot-mode, didn't help!
I ran all possible BIOS diagnostic tools, dinn't help!
I attempted to "Repair" the windows installation, but somehow the windows set up was unable to indentify the file allocation table(FAT), let alone the file system. It couldn't discover the existing windows. Dint help!

Well then... yes you guessed it right, I had to reinstall the conventional way - that is, when anything goes wrong, just reinstall.

Planning to buy it? Dont! Don't buy it.

If you have it, throw it. Throw it somewhere no one finds it; save someone from similar agony and pain.

Even if you are getting it for free, well then... take it! I think you can put it on your showcase, because it has a cool shiny outer skin - but dont use it.

Consider yourself warned!

On a serious note, you may well be looking for a short term cost effective buy - but thats just time specific. And this short term may eventually turn out to be long term pain in the arse, and you keep on cursing the moment you took the decision to buy. These may be trivial things to some, but it sure eventually will turn into a continuous nuisance. What bugs me the most is one, the sharp noise; and two, the hotness, I can feel the hot air rising up from the palm-pads(place on the laptop where you rest your palms) and under my palms.

I won't say/nosay its a worthless peice of crap! Why/not?

You decide!

Monday, May 17, 2010

Google Nexus One: The V Turn

While switching tv channels I saw the news slide on CNN, Google taking a step back from their recently launched Google Nexus One.

Though the phone was much appreciated by the industry, but rather than going straight for what was planned, Google, it seems is moving towards a diverted route, the V.
Google has quietly canceled plans to release a Verizon version of its Nexus One phone and is instead steering customers toward the HTC Incredible.
A worth reading article discloses the meaning of latest developments for the search giant's plans in mobile industry.
 
I think the primary reason, besides low sales, it failed is the lack of mature community for Nexus One; those who have handon experience of the device. Usually, people tend to buy products that they know it works, besides the brand name. But some people are just hating the phone.

People are looking for Nexus One related help, but it seems they are in dire agony (0:
The volume of complaints points to a problem that Google faces now that it has decided to try to push a new cell-phone-buying model in the U.S. Since most people buy subsidized phones from a mobile operator, they turn to the operator when they have problems. - PCWorld
 Goodluck Google!

Business Process: Bank Cheque Clearing

Recently, I had to go through the implementation of a cheque clearing system; so, either because of the naive skull sticked on the top of my shoulders or the lack of documentation to find a clear business process, I was unable to understand it; let alone to tell the product users how things work.

And to my amuse, the business guys on the customer end were not sure about the inter-department business processes that happens with Inward/Outward processing of cheque. The guys with technology can only talk about the core banking stuff(for instance, how Phoenix web service would expose the data, or from which Mosaic view/table we can get/update what we want).

Fortunately (the absence of fortunate has been named unfortunate),  my friend google didn't provide me with anything useful that I could use/understand.

So with quite a bit of struggle, I was able to extract the following visual out of the discussions and research after a series of cross questioning the business departments (0:

Much appreciated by the customer, I thought of updating the visual to make it more generic, since the business process is the same for any bank around the globe, so that it would help at least someone who is looking for something similar having skull positioned as mine.



Inward/Outward Clearing
The cheques submitted to bank B, by the customer of bank A. The bank A would process those cheques as Outward clearing, and bank A is going to process those cheques as Inward Clearing. See step 2(Out clearing) and step 5(In clearing).

Returned Cheques
If any of the information provided by the cheque issuer mismatches the actual information of customer account, then the cheque is returned; returning from Inward would go as Inward Returns, and returned to Outward goes as Outward returns. See the alternate flows in the figure.

 Enjoy (0:

References:
1. IBDE - Interbank Data Exchange Format
2. iTRAN - http://www.ncr.com/
3. How bank work - http://www.howbankswork.com/

Sunday, May 9, 2010

Online Payment gateways being banned in Pakistan!

As I read the Gartner ratings decline in list from top 10 offshore software development center, I did not wonder to read the Insult to injury – first no Paypal; now no Payoneer!. It has been some time that payment gateways are getting banned one by one.


"Due to a change in requirements from our regulators, as of June 1, 2010 Payoneer cards will be blocked for transactions in the countries listed by the US government as having strategic Anti Money Laundering (AML) deficiencies. This change will affect card usage in the following countries: Angola, Ecuador, Ethiopia, Pakistan, Turkmenistan and Sao Tome and Principe." -Aqeel Syed
This article discusses the subject in detail with a list of countries where PayPal doesn't operate besides Pakistan includes, Cuba, Iran, North Korea, Afghanistan and Syria.

The interesting part is that no government official has taken any notice on this or spoken about it, let alone a official stand or query.

What would it harm?
1. The current growing IT market in specific.
2. Discourage the growing number of freelance professionals from Pakistan.
3. More brain drain.
4. Lower self esteem, low energy, and an unending morale deflation that results as a part of such a decision.

Thoughts?
I don't understand such a raw decision, that Pakistan was banned. Even so when you close one option you provide alternate solutions as well. Well, one reason could be that US has come across or is expecting such a case that money laundering would happen or could happen through such websites and using such payment gateways. But if one has to do something they would just do it by any means.

I think its not about honour or dignity that the payment gateways should be unbanned, its about the people who have day to day earning associated with freelance websites. There are companies having businesses completely banking upon such sites. There are individuals who get their bread and butter from such websites.

Alternatives?
1. Use Google Checkout

2. If you're a company, you could try to register with some credit card processing company so that you can accept credit cards.

3. Open a bank account and accept money via SWIFT.

4. Use snail mail, I was able to use the snail mail for USD =34/- for my first project.

5. Own a Payment Gateway: Even if we do come up with our own online payment gateway, the question is - would that be globally accepted or as prestigous as Paypal or Payoneer?

I believe its worth a try, to start with, and let the time answer that question. We have international banks(Barclays, for instance) operating within, and I believe its possible to come up with a fully functional integrated payment gateway. Obviously, it would take 5/10 years to earn some repute in the industry - depends how we'd use it.

References:
1. Internet Usage in Asia[http://www.internetworldstats.com/stats3.htm#asia]
2. Rentacoder[http://rentacoder.com]
3. Frauds[http://www.velocityreviews.com/forums/t288446-internet-fraud-by-rentacoder-com.html]

Saturday, May 1, 2010

Microsoft Web Platform Installer v2.0: Fast way for a dev machine!

The Web PI is a free tool that makes getting the latest components of the Microsoft Web Platform, including Internet Information Services (IIS), SQL Server Express, .NET Framework and Visual Web Developer easy.

The Web PI also makes it easy to install and run the most popular free web applications for blogging, content management and more with the built-in Windows Web Application Gallery.

It is the fastest way to take a machine from fresh Windows install to "ready to dev".

It can install everything from .NET 2.0 SP to SQL Server 2008; has several open projects. I was able to install SQL Server 2008 with required service packs, etc. If you would download an open project for instance, that is based upon Perl or Python, it would download it for you along with all of the dependencies. Overall, the performance is proportional to the download speed of you internet connection. "I'm lovin it".

Download it from here.

Related Posts

Popular Posts