Uncategorized

Article hero image

Software Practices and Tradition

A note on software tradition - practices, conventions and standards. How it started and how is it going.

Bloggi - Request for Updates

The quest for the simple blogging platform of my dreams continues. Tried this. Tried that. Stumbled upon Bloggi. It is simple, beautiful, content-centric and everything I could ask for. So, am I ready to move this blog to Bloggi?

Rebooting on Ghost Land

Many languages support union types, and it is high time Scala did. Union types are coming in upcoming version of Scala - Dotty. Union types (|) are already being compared with Either and Option (disjoint unions).

Article hero image

C++/CLI Primer – An Apress Book

Earlier this year, I wrote1 about publishing2 C++/CLI Primer on [LeanPub.com]3. I wondered if there is anybody else besides myself and Microsoft using C++/CLI but readers surprised and humbled me with their support. Seems C++/CLI is here to stay. Know why?

A couple of months back Apress4 Publications took notice of the book and offered to publish/print. So here it is: C++/CLI Primer for .NET Development, my first book; who would’ve thought 😎

More ...

Importance of Semantics

semantics | /sɪˈmæntɪks/ | noun (functioning as sing)

‐ the branch of linguistics that deals with the study of meaning, changes in meaning, and the principles that govern the relationship between sentences or words and their meanings the study of the relationships between signs and symbols and what they represent (logic)

‐ the study of interpretations of a formal theory

‐ the study of the relationship between the structure of a theory and its subject matter (of a formal theory) the principles that determine the truth or falsehood of sentences within the theory, and the references of its terms

Article hero image

Application Models

A typical business application is composed of several flows or use-cases. Also, these flows consist of logical ones like a transaction that spans several flows. Take for instance an e-commerce application which consists of user registration/login, product lookup, and one of the most important interactions in an e-commerce application – the shopping cart, and much more. Although these application flows might appear to be discrete and independent of one another, it is after producing a working solution that we realize that these flows are inherently interrelated for one reason or another. The idea of designing stateless application flows is many times confused with the relation between the flows. More ...

Iterators vs. Generators

Yes, there is a difference. Although both produce the same end effect, an iterator is not the same as a generator. The difference is in the way it is implemented and also consumed. Iterator is a (design/implementation) pattern while Generator is a language construct supported by the compiler. More ...

Mundane vs JINQ Way

New things are not always instantly accepted. Beyond skepticism, new things challenge the comfort people are accustomed to. JINQ wasn’t particularly welcomed. It was either discarded as unknown angel or worse … ridiculed. However, JINQ still promises expressive succinct code. More ...

Text Editors

I am not a *nix commands expert … but a professional? So why not relish educating my brother a couple of nifty commands, especially – find and grep, which he was looking into at the time. You can find a few more here if you are interested.

So much for the command line, watch out for the overdose1. I find it funny when people, especially developers, copy files on the command line on a Mac (or Ubuntu for that matter); I mean files on the local machine. Specifically, they either copy the file (Cmd-C) via the Finder and paste it, or worse drag and drop, on the Terminal 2(/posts/text-editors-rundown/#fn-1559-2). Our next laugh is about editing local files in vim 😆3.

More ...

Selective Combinations

You have a list of strings with which you have generate ordered selective combinations of strings starting with the first string in the list. Let us say the list of strings is abc, def and ghi. I have to generate ordered combinations of the above list restricted to the ones starting with abc.

More ...

Article hero image

JINQ

JINQ (Java INtegrated Query) is an ultra minimalistic library inspired from and mimicking the .NET LINQ. While LINQ is a language level construct, JINQ is composed of types - classes and methods, but to the same effect.

Partial Classes – Java ???

I am really sorry if I tricked you into believing that Java is offering partial class feature. Unfortunately, Java doesn’t. Maybe never will. But I am going to talk about a workaround also presenting the thought process. Hence the length of the post. More ...

Sporting a new look

I am very particular about composing the content of the posts (and pages) on this blog. By content, I mean whatever goes in the body of a post/page – text, image, HTML, etc. I like to keep the content extremely clean and avoid polluting with HTML like I had to on Blogspot. With such content, it is a terrible pain to migrate blogs or render posts flawless and consistent across browsers. Blogger is notorious for that aspect1. More ...

Publishing C++/CLI on LeanPub

I came across LeanPub 1 a few months back. I believe it was through hanselman2 – blog, video or something. I liked LeanPub instantly because of a couple of reasons.

I hadn’t written/published any lengthy material in a long time except the C+/CLI Primer on CodeProject4. Why not publish same, I thought, and actually published5. I wasn’t even expecting any response from anyone since the material was on C++/CLI, a language that gave me the impression that I was the only one using it at the time I published on CodeProject. 😀 I am really impressed that the material topped more than 50 downloads in about three months since it was published. Heck, a couple of them even paid despite the fact that the material is free. Not only am I humbled by this encouraging gesture but I am also convinced that C++/CLI is still being pursued and will continue to live – production, academic or as a pet language. Go grab your copy of the booklet – C++/CLI Primer. It’s free!

More ...

Article hero image

Written in Stone

This article was published also on LinkedIn.

Academia

The Mamallapuram Shore Temple, constructed on the deep southern shores of the Bay of Bengal, is one of the oldest stone structures on the planet. It was built around the beginning of the Anno Domini (AD). The site consists of three temple structures, subsidiary structures, and statues primarily built with granite. Prominent statues are that of a lion and elephant with great significance in the way it was rock-cut. Chariots are the primary subsidiary structures other than the temple. It is inevitable not to be marveled at the temple design, intricate and precise carvings and inscriptions. Carvings are made on a monolithic rock on which the works of an elephant and its ear with its loose skin are nearly impossible even today. Inscriptions, according to linguists, is poetic and metaphorical, a sophisticated language nevertheless. Another marvel is Krishna’s Butter Ball, a massive boulder of rock sitting tight above a rocky slope.

More ...

Lights Preserved

lights preserved

I have a separate blog – Lights Preserved where I get to claim myself a photographer, and where I publish some of my artistic snapshots. 😀

Nothing entertains me on a Sunday beating the nap and pecking around my old store. Published a few good snaps that brought back good memories. Take a look!

.NET for the next generation

It was about a decade ago when Visual Studio .NET 2002 was launched. Having worked with Visual Studio 6 until then, the new interface was refreshing and powerful along with .NET and the suite of languages, tools and technologies. If you were there, you would have felt times were changing. Beyond the cool and modern interface, Visual Studio .NET 2002 had a lot more to offer  compared to Visual Studio 6 — .NET. It was an exciting time for me back then. More ...

final, const and beyond

What are your thoughts on the following piece of code?

public String someGibberishMethod() {
	int length = someMethodReturningLength();
	int sum = 0;

	for (int index = 0; index < length; ++index) {
	   // some code that updates the sum variable
	}

	SomeClass someClass = new SomeClass(sum);
	int sumValueInsideSomeClass = someClass.getSumValue();
	// use someText, maybe log or something

	String someText = someClass.doSomeOperation(/*some parameters*/);
	// use someText, maybe log or something
	return someText;
}
More ...

The unconquerable

Hercules was a strong man; a tall muscular perfect masculine figure. He moved boulders with his bare hands. He stopped elephants and swung them by their tusks. No doubt, he prevented battles by his mere presence. His body drew its strength from within. He was no less than unconquerable.

Even such a mighty Hercules was brought down to his knees. He was taken over by an invisible force that turned him weak and set him on a curse, a terrible painful experience. He started worrying deeply, and wept like a scared kid. There was a time when he fought elephants head on. But this was a battle within that he was losing. He could still win this battle only if he could meet eye-to-eye with the enemy.

More ...

JAR Tips: Loading dependencies

If you are writing a typical console based application in Windows, you would end up with an executable (exe). You might also have one or more dependent libraries (DLL). The question is where do we place these DLLs so that they are picked up at runtime by the application; loaded and consumed. Actually it is no brainer, just put them along side the console application executable. Or you could place the DLLs in the System32 directory. Or you could add the directory to the PATH. Well, my point was actually to say that the DLLs can be simply placed alongside the executable and it would be picked up. More ...

An Unfair World of Tuples, Anons., var and auto

It all began when I wanted to return more than one value from one of the methods. Although my attempts ended futile, it was fun exploring and musing how things could have been.

There are at least a couple of options to return multiple values from a method:-

  1. return an instance of a class that holds the values
  2. return a tuple
More ...

A funny moment of IoC

IoC - Inversion of control, is a design that enables fluid flow of control by decoupling tight dependencies between the portion of a code that exhibits behavior and another portion of code that provides required functionality. One form of IoC, as we know, is Dependency Injection (DI). For instance, a TextEditor could refer an ISpellChecker instead of direct coupling to a specific implementation of spell checker thereby enabling the text editor to switch spell checker or even use more than one. More ...

Mutating Strings

Today, we question our beliefs! Is string really immutable?

  
string message = "Hello World!";

Console.WriteLine(message); // Prints "Hello World!"

unsafe {
  int length = message.Length;
  
  fixed (char *p = message) {
    for (int index = 0; index < length; ++index) {
      *(p + index) = '?';
    }
  }
}

Console.WriteLine(message); // Prints what? See for yourself!
More ...

A time when time did not exist …

Those of us, non-physicists, we do seem to realize that time is eternal. Yet there was a time when time did not exist; tough to comprehend? For us, time is something running on a clock or tracked on a calendar. Let me share what I think about when time did not exist. More ...

Quiz: Choosing an array of integers !!!

In the recent interviews, I asked the candidates the following question:

Is there a difference that I need to consider in the following declarations? Both allocate fixed size array to store integers:

int[] na1 = new int[10];
Integer[] na2 = new Integer[10];
More ...

A-Team Library

A short while ago, I had to write a compelling document for a client about a library that I had developed during my tenure, call it A-Team Library or ATL. Having to learn the “eyes-wide-shut” culture to maintain the couples-of-decades old code and simultaneously develop on the top of it was very disheartening. It was time a lot of things were given fresh thoughts. Not the least of all duplication of code and functionality. But not just that. Like in a programming language, when there is more than one way of doing something, when those ways are opposing, it causes nothing but confusion. So was the case. The business seemed to be far from realizing it. More ...

The Secret behind Bjarne and Herb’s Papers on Unified Syntax

A long time back, in one of my posts here1, I had discussed about Extension Methods2 … in C++; sorta! It seems that the grand daddy, Bjarne Stroustoup3, had read my post, and was impressed. So he has published a paper – Call syntax4: x.f(y) vs. f(x,y). Good thing except I don’t like the idea of assuming x.f(y) for f(x, y) while the reverse is the actual idea of extension methods. You will know when you read his paper. It seems the commander, Herb Sutter5, also was impressed with my post. Not only that he too doesn’t seem to like the x.f(y) for f(x, y) idea. Great men think alike. LOL! So he published his paper – Unified Syntax6. How is that? More ...

A Simple Tree List View

Digging up stash is one of the best pass times. You know you never know what you will find. I had an article written quite some time back but had not posted it anywhere. Not sure why. I posted it at CodeProject – A Simple Tree List View.

PHP Savers – PropertyBag

The ubiquitous and the universal data structure in PHP is the [array][1]. It is an amalgamation of commonly used data structures – list, map etc. In the recent times, PHP has also adopted object orientation and introduced classes. The syntactic difference in the way a property of an array and object poses an inconvenience in the user code1 specifically when there is a need to interact with code that is not open for change; legacy or not. More ...

Cool Regex Testers

Anytime I have to play with regular expressions, I use one of the online regex testing web sites to come up with the regex I need. Last couple of times I had to come up with a regex for most common everyday stuff like dates and such. Oh yeah, last time it was date actually. I had a server response that had a date in the format yyyy-mm-dd, ISO format. I was working with JavaScript, and initially I was naive to use the Date class to parse the date in the response. Turned that there is difference in the way the date is interpreted by Firefox and other browsers. More ...

Overloading vs Variable Arguments !!!

In a statically typed (object oriented?) language, function overloading offers the facility of organizing your code into two or more functions with different types and/or number of arguments. This is highly useful when the functionality offered by the function can be invoked in different scenarios. For instance, let us consider the function(s) below: More ...

Getting reminded of the reminder !!!

I have been using Android for quite some time now, and only recently I noticed that Android pops up a notification reminding you of a reminder. It says “Upcoming alarm – Buy Milk”, where Buy Milk is the reminder I had set.

Is it smart enough to help a lazy volatile minded guy like me or is it trying to be my wife who would not rest until I buy milk? Don’t know.

More ...

jqGrid: Handling array data !!!

This post is primarily a personal reference. I also consider this a tribute to Oleg, who played a big role in improving my understanding of the jqGrid internals – the way it handles source data types, which, if I may say, led him in discovering a bug in jqGrid. More ...

Clean Code

I received quite a lot of criticism for Dealing with Bad Code. The criticism was mostly along these lines – There is no good or bad programmer. The good programmer thing is more of an illusion. When you place a programmer in a domain in which he has little or no experience (like a PHP web programmer writing C++ code), he will soon be seen as a bad programmer. What is branded good or bad is subjective. More ...

The Windows Phone Epic !!!

Dear Reader,

Do not be overwhelmed by the length of the article. I have tried my best to keep the length of the article NOT directly proportional to the time required to read it.

If you want to tell people the truth, make them laugh, otherwise they’ll kill you - Oscar Wilde

There are times when truth tends to be subjective, such as this article. However, I have definitely added the fun component to keep up earlier promise. Consider the time you spent reading this article as a break from your work or routine. I am sure you will enjoy it; doesn’t matter if you are using a Windows Phone 1. Perhaps you will read it again.

I am programmer1 gadget savvy, an avid fan of Microsoft products (especially Visual Studio and associated suite of development tools), and an honest critic of any product I use. I have an Android Phone, an iPhone, and for a few months now, a Windows Phone. And this is my experience with the Windows Phone – good, bad and grey.

To begin with, the Windows Phone landscape (app and feature set) is dry and unpromising. There are a few good things here and there to console ourselves for the money we spent on the phone, and for the love of Microsoft!

More ...

Dealing with Bad Code

Read this fine article by Joel Spolsky: Things You Should Never Do

It is a great article, one that invokes mixed feelings. The article talks against rewriting (large scale) software…..from scratch. Joel was kind enough to consider all those who write software as true programmers; people who give enough thought and not just code up something that works. However, it is far different in the real world. That said, I am neither completely in disagreement with Joel nor am I advocating to rewrite large scale software once the code is identified as a mess.

More ...

Linked List Quiz – Part II !!!

In the previous post, we saw the academic (not general purpose) version of a linked list used to solve the puzzles, and solved the following puzzles on linked list.

In this part, I will be solving the remaining two puzzles that I listed in the last part.

Finding the cyclic node in a cyclic linked list

  1. According to my solution, the node which is actually supposed to be the end of the linked list is the cyclic node. Let us call Cn. Taking node Cn as the cyclic one has an advantage wherein you can break the cycle; assign Cn->next = nullptr;
  2. But some people take the node after Cn as the cyclic node. The node after Cn is the node somewhere back in the list. This way it is not possible to break the cycle as we would traversed past Cn.
LinkedList::Node* LinkedList::FindCyclicNode() const
{
   int iterCount = 0;

   auto jmpBy1Ptr = root;
   auto jmpBy2Ptr = root;

   while (jmpBy1Ptr != nullptr && jmpBy2Ptr != nullptr && jmpBy2Ptr->Next() != nullptr)
   {
      jmpBy1Ptr = jmpBy1Ptr->Next();
      jmpBy2Ptr = jmpBy2Ptr->Next()->Next();

      if (jmpBy1Ptr == jmpBy2Ptr)
      {
         const int noOfNodesInLoop = CountNoOfNodesInLoop(jmpBy1Ptr);

         cout << "No of nodes in loop: " << noOfNodesInLoop << std::endl;

         auto p1= root;
         auto p2 = GetNthNode(noOfNodesInLoop - 1); // zero based index

         cout << "Node at index " << noOfNodesInLoop << ": " << p2->Item() << std::endl;

         // Pointers meet at eye of the loop (this node is as per point #2 above)

         while (p1 != p2)
         {
            p1 = p1->Next();
            p2 = p2->Next();
         }

         // This piece of code takes you to the loop starting node (this node is as per #1 above)
         p2 = p2->Next();

         while(p2->Next() != p1)
         {
            p2 = p2->Next();
         }

         return p2;
      }

      ++iterCount;
   }

   return nullptr;
}

int LinkedList::CountNoOfNodesInLoop(Node* stopNode) const
{
   int count = 1;
   auto p1 = stopNode;
   auto p2 = stopNode;

   while (p1->Next() != p2)
   {
      p1 = p1->Next();
      ++count;
   }

   return count;
}

The code above is the result of several iterations of discussions with Azhagu. It wasn’t written that way the first time. The first version was much complex and naive. I think it looks better now. What do you say?

More ...

Offering __FILE__ and __LINE__ for C# !!!

Not the same way but we could say better.

Visual Studio 2012, another power packed release of Visual Studio, among a lot of other powerful fancy language features, offers the ability to deduce the method caller details at compile time.

C++ offered the compiler defined macros FILE and LINE (and DATE and TIME), which are primarily intended for diagnostic purposes in a program, whereby the caller information is captured and logged. For instance, using LINE would be replaced with the exact line number in the file where this macro has been used. That sometimes beats the purpose and doesn’t gives us what we actually expect. Let’s see.

More ...

Linked List Quiz – Part I !!!

A short while back, Sammy quizzed me on linked list based problems; singly linked list.

I am recording those problems, solutions and my experience as a two part series. In the first part, I am introducing the linked list class, which I wrote for packaging the implementation of the solutions. This class pertains to the context of the problem(s) and cannot be used as a general purpose linked list. A std::list might more pertinent in the context of the general purpose implementation of a list.

More ...

Sms FireWall Update

I gave SMS FireWall a refresh with a couple of features requested by users:-

Hope they are useful to others too. And let me know if you need any other features to be in the application.

More ...

OrderedThreadPool – Bug Fix !!!

Hugh pointed out a bug in the OrderedThreadPool.

I think there is a small window for error in the OrderedThreadPool class. Basically, if an item of work is queued, then a worker thread runs, takes the item off the queue and is about to call wcb(state) – but at that instant is (say) context switched. Then another item gets queued and another worker thread runs and dequeues the item and then again is about to call wcb(state). There is scope here for the two operations to run concurrently or even out of order…

More ...

Unique Id Generation !!!

A short while I was engaged in a little project where I had to interact with a third party service provider who required a (30 length) unique id as part of the transaction. I am little dumb and am used to GUIDs for a long time when it comes to unique ids. But GUIDs are more than 30 in length. I was trying out some stupid ways like stripping out the trail part of the GUID to make 30 length unique but my intuition wasn’t convinced about the tricks I was working out. More ...

Sms FireWall

Tired of prank SMSes. Need a simple way to block them, and keep your inbox clean? Don’t worry. You got it!

SMS Firewall is a simple and cute (hope you like it!) Android application to block and quarantine unwanted SMS from reaching your inbox. Unwanted are those who are neither in your contacts list nor in the allowed list, which is provided by the application. Phone numbers or sender names such as your bank or mobile service provider can be added to the allowed list. You got an option to either notify you of the blocked SMS or ignore it, in which case you will have check the quarantine vault by yourself. Besides, you have a ‘Just Monitor’ mode, which is primarily used for debugging purposes or when you don’t want to block SMS from unknown sender(s) (for a while). When this mode is switched on, SMS from unknown senders will reach the inbox and also a copy of it is saved in the quarantine vault.

More ...

To Ritchie

Dennis Ritchie1, whom we all know as the creator of the C programming language passed away on Oct 12, 2011. We have lost one of the brilliant minds of mankind. I owe him this post for he has been one of the greatest inspirations in my life and the very reason that I am into programming.

Dennis Ritchie (1941-2011)
Dennis Ritchie (1941-2011)

The first time I saw Ritchie’s picture, for a moment, he looked like Jesus to me. I would say that the divinity in his face pulled into the world of programming.

More ...

Seinfeld Calendar Update !!!

We have released an update for Seinfeld Calendar with a bunch of some exciting features and defect fixes. I hope they are exciting for you too.

So with the above features, doing the task and tracking it has become super easy. Despite all the handy features, it is all in your hands to do your task. It is just not about marking it done.

More ...

Android meets .NET

It is always fun to program in C# (besides C++). If so, how would I feel if I was able to program in C# on Android? You may be wondering what in the world I am talking about. Android development environment is all Java and open source stuff. How could this Microsoft thing fit onto it? Well, it seems that some clever guys1 had huddled up and ported Mono for Android, developed .NET libraries for the Android SDK, and also supplemented it with a Mono for Android project template in Visual Studio. Thus we relish writing C# code for Android. More ...

Quiz - Beauty of Numbers - Solution

One hint that should be helpful in building our solution is that we got to get retained after every wave of removal (until nobody else remains). That means it got to be really some special number or special kind of number. We could do what functional programmers would do. Write down the steps of removal for every queue size N, and it is not worth trying for very large N; in our case, even 20 or 30 could be large. But the point is we could iterate the steps manually and find a position K for every queue size N, where K is the position that remains after all the waves of removal. Once we are done with that, we should stare intensely 😂 on every K to derive a pattern, which would tell us something about those Ks, and with that we should be able to solve the problem. More ...

Quiz - Beauty of Numbers

Sriram quizzed:

Imagine there is a queue of people for getting a ticket for a movie or somehing. Where should be standing in the queue to last until the manager or some guy keeps removing people at odd indices. For instance, if the queue has 5 people given a token A to E, first we remove the first set of odd numbered positions in the queue, so A, C and E are gone. Now B and D remain. Again we remove the odd numbered positions. This time B alone is gone, and D is the winner. So in a queue like that, what is the lucky position you should hold so that you survive the wave of removals?

More ...

To Hold or Not to Hold – A story on Thread references !!!

void SomeMethod(int x, double y) {
  // some code
  ...
  new Thread(ThreadFunc).Start();
}

What do you think about the code above?

Some may say nothing seems to be wrong. Some may say there is not enough information to comment. A few may say that it is awful to spin off a thread like that (the last line of the method), and that there is a probability for the thread to be garbage collected at an unexpected point of execution. That is something interesting to discuss about.

More ...

Crazy Brackets – [](){}();

What does this cryptic bracket sequence mean? What programming language is it? Is it valid syntax? If there is even a weak chance of this syntax being valid? If so, what does it mean?

Alright, alright, alright! It is C++. That would calm most people; with all their love (pun) for C++. Specifically, it is C++0x. Amongst many other features that we have been waiting for, C++0x gives us the power of lambdas.

More ...

Wetting my feet in Android – Seinfeld Calendar

A couple of my colleagues and I huddled up to learn a bit of Android. I think I told you about that a short while back. We developed a very simple application – The Seinfeld Calendar.

Seinfeld calendar or otherwise called the habit calendar is Seinfeld’s productivity secret. The secret of achieving your goal is practising something, whatever your goal is, everyday and make it a habit. And mark it in your calendar each day you practice, and make sure you do not break the chain. Our application helps you keep track of your everyday tasks.

More ...

Anonymous Classes vs Delegates !!!

I am not a java programmer. By that, I do not mean I am against Java. As a programmer by profession and passion, I try to learn things along the way. That includes a little of bit of Java. I should say that my proper encounter, so to say, with Java is a simple application that I am trying out with Android. There might be some hard core differences and/or limitations in the Android version of Java. But I am almost certain that I am using only primary level features of Java. More ...

Quiz – Where am I ?

The question is, in C++, how do detect if an object is allocated on the stack or heap.

On Windows, the stack address is in the range of 0x80000000. If the address of the variable is in this range, then you could say that the object is allocated on the stack; else it is allocated on the heap. This technique of detecting is not preferable since it may not work on other operating systems (such as linux), and deals with the platform specific information making it a non-portable solution.

More ...

Meeting Martin

You may not know the guy in black. You should definitely be knowing the guy in green. Don’t you?

Martin Fowler

I am not a patron of his philosophies against planned design. But he sure is a great guy with lots of good ideas. It was nice having an hour long chat with him.

Invoking methods with out and ref – Finale !!!

Alright, it is a long wait. And I am going to keep it short.

Recap of the problem: Why did the ref variable in SomeMethod not get the expected result (DayOfWeek.Friday) when called from a different thread?

Boxing. Yes, that is the culprit. Sometimes, it is subtle to note. DayOfWeek is an enum – a value type. When the method is called from a different thread, we put the argument (arg3) in an object array, and that’s where the value gets boxed. So we happen to assign the resultant value to the boxed value.

More ...

Invoking methods with Out and Ref (Part 2) !!!

Straight to code…..

int SomeMethod(string arg1,
    string arg2,
    ref DayOfWeek arg3)
{
    // Wildest implementation!
}

The above method had to be executed on its dispatcher thread. So let unravel a bit of the wildest implementation above.

int SomeMethod(string arg1,
    string arg2,
    ref DayOfWeek arg3)
{
    if (Disptacher.CheckAccess())
    {
        var funcDelegate = (Func<string, string, DayOfWeek, int>)SomeMthod;
    return Dispatcher.Invoke(funcDelegate,
        arg1,
        arg2,
        ref arg3);
}

// Wilder implementation!!

}

Before you say anything, yes, the compiler spat the following errors:-

More ...

Thinking Currying

Currying is a mathematical concept based on lambda calculus. It is a technique of operating on a function (taking multiple arguments) by splitting and capable of chaining into a series of single argument functions. It is very similar to what a human would attempt to do on paper. For example, if you have to add numbers 1 through 10, what would you do? Class II mathematics -0 in hand, 1 in the mind, add 0 and 1, so 1 in the mind, then 2 in the hand, … up to 10. So we compute the addition with one argument at a time. More ...

Quiz – (Journey through templates, SFINAE and specialization) !!!

template<typename A, typename B>
class TClass
{
public: TClass()
        {
        }

        // Overload #1
public: std::string SomeMethod(A a, B b)
        {
           std::ostringstream ostr;
           ostr << a << "-" << b;
           return ostr.str();
        }

        // Overload #2
public: std::string SomeMethod(B b, A a)
        {
           std::ostringstream ostr;
           ostr << b << "-" << a;
           return ostr.str();
        }
};

So that is a template class with SomeMethod overloads. Why would somebody write such a class? Imagine it is an adder class, and the method overloads could used to add with parameters specified in either order. Following is the way one could use the above (based on the adder example):-

More ...

Missing MI !!!

We all know C# does not offer multiple inheritance but offers arguments that programmers can live without it. It is true in almost all cases, especially all cat and animal or employee and manager projects. I have seen a few cases where if C# offered multiple inheritance, the solution would have been natural, elegant and succinct.

Imagine that I have a component (UI, non-UI, doesn’t matter). You can make calls into the component, which does some interesting work for you. Imagine that the component takes an interface IComponentCallback to notify its parent. So I would do is have my parent class derive from IComponentCallback interface and pass this to the component. The code would look something like this:-

More ...

sizeof vs Marshal.SizeOf !!!

There are two facilities in C# to determine the size of a type – sizeof operator andMarshal.SizeOf method. Let us discuss what they offer and how they differ.

Before we settle the difference between sizeof and Marshal.SizeOf, let us discuss why would we want to compute the size of a variable or type. Other than academic, one typical reason to know the size of a type (in a production code) would be allocate memory for an array of items; typically done while using malloc. Unlike in C++ (or unmanaged world), computing the size of a type definitely has no such use in C# (managed world). Within the managed application, size does not matter; since there are types provided by the CLR for creating \ managing fixed size and variable size (typed) arrays. And as per MSDN, the size cannot be computed accurately. Does that mean we don’t need to compute the size of a type at all when working in the CLR world? Obviously no, else I would not be writing this post.

More ...

Curious Case Of Anonymous Delegates !!!

Senthil has left us thrilled in his new post, and also inspired me to write about the topic. Although, anonymous delegates have become a mundane stuff amongst programmers, there is still these subtle stuff left unexplored. Alright, let us try to answer Senthil’s question before he unravels the mystery in his next post.

A delegate is identified by its target. The target is the method to be executed on a delegate invocation and its associated instance or type. If the target is an instance method, the delegate preserves the target method pointer and the object instance. If the target is a static method, the delegate preserves the target method pointer and the type to which it belongs. So when a code like the one below to register a method to an event (or multicast delegate) is executed, a delegate object (EventHandler here) with the target information embedded is created and added to the invocation list of the event (or multicast delegate, KeyPressed here).

More ...

finally and Return Values !!!

Let us read some code:-

int SomeMethod()
{
    int num = 1;

    try
    {
        num = 5;
        return num;
    }
    finally
    {
        num += 5;
    }
}

What is the return value of SomeMethod? Some anonymous guy asked that question in the code project forum, and it has been answered. I am writing about it here because it is interesting and subtle. One should not be surprised when people misinterpret finally. So let us take a guess, 10 (i = 5, then incremented by 5 in the finally block).It is not the right answer; rather SomeMethod returns 5. Agreed that finally is called in all cases of returning from SomeMethod but the return value is calculated when it is time to return from SomeMethod, normally or abnormally. The subtlety lies not in the way finally is executed but in the return value is calculated. So the return value (5) is decided when a return is encountered in the try block. The finally is just called for cleanup; and the num modified there is local to SomeMethod. So make the return value 10, it is no use being hasty making SomeMethod return from the finally block. Because returning from finally is not allowed. (We will talk about it later why returning from catch block is a bad practice and why can’t we return from finally block). Had such modifications been done on a reference type, they would have been visible outside of SomeMethod, although the return value may be different.

More ...

Type Safe Logger

Article co-authored with Sanjeev, and published on CodeProject


PROBLEM

Every application logs a whole bunch of diagnostic messages, primarily for (production) debugging, to the console or the standard error device or to files. There are so many other destinations where the logs can be written to. Irrespective of the destination that each application must be able to configure, the diagnostic log message and the way to generate the message is of our interest now. So we are in need of a logger class that can behave transparent to the logging destination. That should not be a problem, it would be fun to design that.

More ...

Simple Array Class For C++

This is a simple array like class for C++, which can be used as a safe wrapper for accessing a block of memory pointed by a bare pointer.

CComPtr Misconception !!!

This is about a killer bug identified by our chief software engineer in our application. What was devised for ease of use and write smart code ended up in this killer defect due to improper perception. Ok, let us go!

CComPtr is a template class in ATL designed to wrap the discrete functionality of COM object management – AddRef and Release. Technically it is a smart pointer for a COM object.

More ...

OrderedThreadPool – Task Execution In Queued Order !!!

I would not want to write chunks of code to spawns threads and perform many of my background tasks such as firing events, UI update etc. Instead I would use the System.Threading.ThreadPool class which serves this purpose. And a programmer who knows to use this class for such cases would also be aware that the tasks queued to the thread pool are NOT dispatched in the order they are queued. They get dispatched for execution in a haphazard fashion. More ...

Settling Casting Restrictions

Remember the Casting Restrictions we discussed a while back, let us settle that now. So we have some code like this:

object obj = i;
long l = (long)obj;

And an invalid cast exception while casting ‘obj’ to long. It is obvious that we are not changing the value held by obj, but just reading it. Then why restrict such casting. Let us disassemble and see what we got.

.locals init (
  [0] int32 i,
  [1] object obj,
  [2] int64 l
)
L_0000: nop
L_0001: ldc.i4.s 100
L_0003: stloc.0
L_0004: ldloc.0
L_0005: box int32
L_000a: stloc.1
L_000b: ldloc.1
L_000c: unbox.any int64
L_0011: stloc.2
L_0012: ret

Oh, there we see something interesting - unbox. So the C# compiler uses the unbox instruction to retrieve the value from obj while casting; it does not use Convert.ToInt64 or similar mechanism. That is why the exception was thrown.

More ...

The WD Anti-Propaganda Campaign !!!

Thanks to the internet. If nobody else bothers or understands what loss of data means, you can shout it aloud here. I lost 500GB of data - every moment of my personal and professional life captured in bits and bytes.

It is a Western Digital Premium Edition external hard disk (USB/Firewire). I bought it despite my friend warning of bad sectors and hardware issues that WD is known to have. As with any story, one fine morning, I was copying some songs, pictures from my pen drive to the hard disk. All of a sudden, the hard disk and my laptop hung up. I restarted the system thinking I would make fresh start. But to my dismay, all my drives on the hard disk had vanished like dust. I tried connecting and reconnecting a few times, the drives showed up once or twice like a sick man’s last few breadths.

More ...

Casting Restrictions ???

We all know that the runtime can detect the actual type of a System.Object instance. The primitive data types provided by the runtime are compatible with one another for casting (assuming that we do not truncate the values). So if I have an int, it can be cast to long or ulong. All that is fine. Watch this:-

interface IAppDataTypeBase
{
   // Other methods
   GetValue();
}

Since IAppDataTypeBase represents the mother of all types of data in my application, I have made GetValue to return the value as object (I could have used generics, that is for another day!).

More ...

Understanding (ref)erences

Let us take a look at the following piece of code:-

public void Operate(IList iList2)
{
 iList2 = new List();
 iList2.Add(1);
 iList2.Add(2);
 iList2.Add(3);
}

public static void Main()
{
 IList iList= new List();
 iList.Add(10);
 Operate(iList);
 Console.WriteLine(iList[0].ToString());
}

Be thinking about what would the above program print to the console ? And that is what we are going to talk about in this post – simple but subtle.

More ...

Extension Methods – A Polished C++ Feature

Extension Methods is an excellent feature in C# 3.0. It is a mechanism by which new methods can be exposed from an existing type (interface or class) without directly adding the method to the type. Why do we need extension methods anyway ? Ok, that is the big story of lamba and LINQ. But from a conceptual standpoint, the extension methods establish a mechanism to extend the public interface of a type. The compiler is smart enough to make the method a part of the public interface of the type. Yeah, that is what it does, and the intellisense is very cool in making us believe that. It is cleaner and easier (for the library developers and for us programmers even) to add extra functionality (methods) not provided in the type. That is the intent. And we know that was exercised extravagantly in LINQ. The IEnumerable was extended with a whole lot set of methods to aid the LINQ design. Remember the Where, Select etc methods on IEnumerable. More ...

The Surprising Finalize Call

Guess the output of the following program:-

class SomeClass : IDisposable
{
  public SomeClass()
  {
		Trace.WriteLine("SomeClass - Attempting instance creation");
		throw new Exception("Ohh !!! Not Now");
	}

	public void Dispose()
	{
		Trace.WriteLine("SomeClass::Dispose");
	}

	~SomeClass()
	{
		Trace.WriteLine("SomeClass::Finalizer");
	}
}

int Main(string args[]){
	try{
		SomeClass sc = new SomeClass();
  }
	catch(Exception ex){
		Trace.WriteLine("Main - {0}", ex.Message);
  }
}

This will be the output of the program:-

More ...

Learning Type Access Modifiers Basics

When I started developing my module, I had an interface IParamCountBasedAlgo declared as a nested type in a class AlgorithmOneExecutor, declared as follows:-

namespace DataStructuresAndAlgo
{
   partial class AlgorithmOneExecutor
   {
      private interface IParamCountBasedAlgo
      {
         void Validate();
         void Execute();
      }
   }
}
More ...

First Google Gadget(s)

I did some cool stuff here with google. I wrote my first “Hello World” sort of google gadget. It claims no rewards but just was fun. Since I am a novice in html and javascript sort of things, this gadget is pretty simple.

Use the following URL to enjoy the gadgets.:

Follow the trail…….Join the Concurrency Revolution !!!

I could not stop writing this post after I read this article by Herb Sutter. The article is just a casual technical discussion but very encouraging that a person requires at the right time – the time when he is a student. Even after several years after my college, I have been trying to keep myself a student and I got a right encouragement to join the Concurrency revolution. Thanks to Herb Sutter. More ...

The New Looking Post

I am very much fond of tools, updates and stuff. So I keep updating my softwares and hear/learn about new tools etc. I am excited about the new spaces - Live Spaces. Looks much better than before. I thought I would write something about the new spaces. Please spaces guys, make the arranging the boxes on the home page a bit easier and intelligent. That is a feature request. Otherwise the default skin/theme is cool and professional. Old themes are still old and not much appealing. Anyway, i write the post just to say i love it. More ...

where enum does not work

I was writing a generic method with enum as the Constraint, and the compiler spat a few errors that did not directly convey me that enums cannot used as generic constraints. I learnt the following from my investigation:

Following is an excerpt from the C# language specification for generic constraints


A class-type constraint must satisfy the following rules:

Overloading - A Matter Of Taste

This was a pretty interesting discussion about method overloading in the managed world. As the discussion says that the overloading is a matter of taste. It seems that the method overloading in the managed world, indeed, is a matter of taste. Sad BUT True !!! But on the contrary, it must have been a [strict] rule. Overloading might be exhibited differently by each language in the unmanaged world. But as far as .NET goes, it must have been made a standard specification. Pardon me, if there is one. More ...

Fooled by the Activator !!!

It was interesting to know that a custom exception, say an exception class derived from System.ApplicationException, thrown while creating an instance of a type using Activator.CreateInstance does not get caught in its appropriate exception handler, instead gets caught in the global exception handler catch(Exception ex), if provided. Any exception raised while creating an instance of the loaded type is wrapped inside a new exception object as InnerException by Activator.CreateInstance.

I was fooled that there was some problem with the image generation for quite some time, and then very lately inspected the members of the exception caught and found my exception object wrapped as InnerException.

More ...

Properties C# 2.0 – Not Elegant Enough

Prior to .NET 2.0, there wasn’t the facility in C# to opt the visibility level for the get and set property or indexers. And i take my comment in my previous post that C# does not provide the facility of having different visibility levels for the get and set accessors. While that is partly correct, it is no more in C# 2.0.

And obviously it isn’t in the easy and elegant way. Take a look at this code snippet:-

More ...

Singularity – Safety & Speed !!!

I read about this interesting thing somewhere in MSDN.

There are two types of programming or programming languages. The good old C/C++ kind called the unsafe programming languages, and the other is the safe programming type which we realised very much after advent of Java/C#. And there has always been debate about safety and speed. And neither of the two has won.

So Microsoft is doing a research on a new operating system called Singularity which is written in a safe programming language [C#]. Although there are parts in the OS, especially the kernel, that uses unsafe code, it stills uses the safe C#. So in the Singularity environment, every program that runs is safe. And the environment as such is reinventing from the hardware layers up and above.

More ...

out, ref and InvokeMember !!!

When I was working on the .NET reflection extravaganza thing that I explained in my previous column, i learnt one another interesting thing, that is about the Type.InvokeMember. How will pass out or ref parameters for the method invoked using Type.InvokeMember ? If you are going to invoke a method with the prototype

int DoSomething(string someString, int someInt);

then you would use InvokeMember like this:-

object obj = someType.InvokeMember(“DoSomething”,
        BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
        null,
        this,
        new object[] {“Largest Integer”, 1});

or use some variables in the new object[] {…}. But what do you with the args if DoSomething takes out or ref parameters ?

More ...

Where is my C++ ?

I have been using C# for quite some time now, and that too VS 2005. I see that Programming Pain at a macro level has boiled down to thinking than coding. Though it might be an advantage on one side, I feel I have become lazy. Since I am a programmer from the C++ world, it was very easy to become lazy. The small and handy applications that I write for myself in C++, I am writing them in C#. Even now I am a great disciple of C++. And even though C++/CLI is out there, and I work a small amount of it in my project, I am getting inclined to C#. More ...

Infinite .NET Languages !!!

Though I knew that there are quite a few languages for the .NET platform, I came to know when surfing today that there are many well beyond my knowledge, most surprisingly like the COBOL.

Check it out @ http://www.dotnetpowered.com/languages.aspx

Implementing COM OutOfProc Servers in C# .NET !!!

Had to implement our COM OOP Server project in .NET, and I found this solution from the internet after a great deal of search, but unfortunately the whole idea was ruled out, and we wrapped it as a .NET assembly. This is worth knowing.

Step 1

Implement IClassFactory in a class in .NET. Use the following definition for IClassFactory.

namespace COM
{
   static class Guids
   {
      public const string IClassFactory = "00000001-0000-0000-C000-000000000046";
      public const string IUnknown = "00000000-0000-0000-C000-000000000046";
   }

   ///
   /// IClassFactory declaration
   ///
   [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid(COM.Guids.IClassFactory)]
   internal interface IClassFactory
   {
      [PreserveSig]
      int CreateInstance(IntPtr pUnkOuter, ref Guid riid, out IntPtr ppvObject);
      [PreserveSig]
      int LockServer(bool fLock);
   }
}

Step 2

More ...

Non-conventional Window Shapes [I love C#] !!!

I am not a UI guy. More specifically, I love to work with UIs. I think (only) a UI can give a better picture of the system in a multitasking environment unlike Unix. I do not say I hate Unix. And I do not like to work on UIs ie program on UIs cuz I do not know much. But have always wanted to create a non-conventional window, say an elliptical one. .NET made things like that very easy for guys like me. Look at the code below for creating a ellipitcal window. More ...

Serialization and Exceptions !!!

I am just like Alice in Wonderland, and not yet got out of the wonders of the .NET framework, C# and the VS 2003(5) IDE. I thought that the serialization is all not my thing until I do something big in C#. I had written this custom exception class in my project that has 3 processes connected by .NET Remoting Infrastructure. I throw my custom exception for a scenario but all I got was some other exception: More ...

Know where you initialize and Do not forget to uninitialize !!!

If you have long been programming in C++/COM and then you move to C#.NET, the first difference you can feel is that you got a ctor for the object you create unlike the CoCreateInstance. In the C++/COM world, you generally would have a Initialize method to do the construction sort of, paired with Terminate/Uninitialize method. Similar is the case with singleton classes. For singleton classes in C++, you will have public static Instance or GetInstance method to get the only and one instance of the class and then use the initialize method to do the construction. This is certainly advantageous than the ctor facility in .NET, since you will not know when the instance will be initialized without the initialize method. Any call like SingletonClass.GetInstance().SomeMethod may initialize the singleton anywhere and you will not exactly do the initialization during the application startup, which in many cases will lead to application errors after startup. More ...

An encounter with Hashtables !!!

I encountered a situation like this where I had a hashtable in which the key is a string and the value is some object, and I had to change the values of all the keys [from zero to count] to null or some other value. I used the some of the facilities – enumerator, the Keys property etc provided by the hash table itself but it did not work out, and I spent too much time on this. More ...

A Note On Finalize !!!

This is not about what Finalize is, but well Finalize is the last call on a managed object, where you can perform some clean up operations, before getting garbage collected by the .NET runtime. A few important things that are to be noted about finalizers are:-

The most interesting part of the finalizer is not when it is called but when all is it NOT called. This is where we need to watch and rely on the Dipose method IDispoable - Dispose pattern1.

More ...

Explicit Interface Implementation !!!

I have encountered this [wait i’ll explain] sort of situation many times and I mostly do this way in C++.

Assume you have a class CMyClass that exposes its functionality through its public methods, and also let it listen to events from some sources, events being OnSomeEvent or OnXXXX(), by implementing some event interface IXModuleEvents. Now these event listener methods are reserved only for internal use and are not meant to be called by the users. So when I implement the IXModuleEvents interface in CMyClass, I make them private. Think about it and the problem is solved. It is the polymorphism game, that never cares for the accessibility of the method.

More ...

The Interface Based Programming Argument !!!

I am always a great fan of interface programming. I mean not exactly the interface keyowrd but some way to expose the functionality of the class or your module relieving the user about the worries of the implementation. But definitely make him curious of the stuff inside.

The Win32 APIs are not that good in what I am talking about. Well, there are several reasons for that. And I strongly object that they are raw APIs and not for the ordinary application programmer. That kind of an abstraction is there at every level. Even a programmer using the Win32 APIs does not know what goes inside though some of the APIs expose unknowningly the sort of internals. This is an argument, but what I mean to say is that anything that you wish your users to use must have a elegant interface just exposing the functionality, and in the most intuitive way that makes sense. It may be an interface in C# or an abstract class in C++. And once you do that, you will slowly be under the tree where you can clearly realise the roots of an object oriented system.

More ...

Properties in C++/CLI - The C# look alike

Inherently after writing some code in C#, I wanted everything to be as easy to do like in C#. And could not resist myself writing property like syntax in C++ [ofcourse C++/CLI, threw away the ugly Managed C++ before it was too late for my code to grow into a tree]. Then I learnt that properties are supported in C++.NET too but as always in the ugly way. But in C++/CLI, I was happy enough that the syntax is more elegantly redefined. For instance, there was this boolean member logToStdError in my class, and in my legacy code, the property definition for logToStdError looked like:- More ...

Managed Debugging Assistant !!!

The Loader Lock is a synchronization object that helps to provide mutual exclusion during DLL loading and unloading. It helps to prevent DLLs being re-entered before they are completely initialized [in the DLLMain].

When some dll load code is executed, the loader lock is set and after the complete initialization it is unset. But there is a possibility of deadlock when threads do not properly synchronize on the loader lock. This mostly happens when threads try to call other Win32 APIs (LoadLibrary, GetProcAddress, FreeLibrary etc.) that also require the loader lock. Often this is evident in the mixed managed/unmanaged code, whereby it is not intentional but the CLR may have to call those APIs like during a call using platform invoke on one of the above listed Win32 API.

More ...

Do not delete [] a scalar pointer !!!

Recently I got tangled into this problem in my code - Calling a vector destructor for a scalar pointer. We all know that it is perfectly illegal to do that. For example, if we allocate something like this:-

OurClass *p = new OurClass();

and try to delete like this:-

delete []p;

then we are going to end up in trouble. Of course, we know that we will end up in trouble. But I have really not given a thought WHY!

More ...

Where do you QueryInterface ???

For an ATL class, the QueryInterface is implemented in CComObject. The figure below is the inheritance hierarchy for a class generated by the wizard representing an ATL-COM object.

CComObjectRootBase has an InternalQueryInterface method, which uses the interface map built by the BEGIN_COM_MAP macro to resolve IID -> interface pointer. The BEGIN_COM_MAP macro also defines a method _InternalQueryInterface, which passes the map on to InternalQueryInterface. CComObject implements QueryInterface, and calls _InternalQueryInterface.

More ...

Use Of Class Factories !!!

To understand quickly and to explain in the simplest way, Class Factories are the factory classes that create a COM object. A class factory may be responsible for creating one or more COM objects. In the case of COM OutOfProc servers, the server registers the class factories for objects that it can create in a system-global table using CoRegisterClassObject. Whenever a client does CoGetClassObject for a CLSID, the COM run-time can look it up in the system global table, and return the factory instance. The case with InProc servers is also similar but through the DLLGetClassObject. More ...

Unsafe Operations with STL !!!

It is UNSAFE to do any operation on an STL container that will modify its size while holding a reference to one of its existing element. What could happen is, when you do an operation, say push_back on a vector, it determines if there is enough space available to add a new element. If there is not sufficient space available, it allocates new space for whole of the data structure and deletes the old buffer. At this point, any reference to one of its elements created prior to push_back would have gotten corrupted. More ...

Consoles for Mr.GUI !!!

Learnt something new, a small one but very useful.

Many times I have seen GUI applications accompanied by console windows that show logs or trace information of the application. How do we do that for our application ?

Any GUI application can create its own console window just by calling AllocConsole Win32 API. Actually any process can use that API to allocate a new console. And the application must also learn to be disciplined enough to FreeConsole. Ok, fine. I used that in my small MFC application and was happy to see the console. But I did not see anything displayed on the console. As we know, each process has its own stdin, stdout and stderr. So redirect the console output of your parent application to the console. How do you do that ?

More ...

Setting Environment Variables !!!

Need to change or set the value of an environment variable programmatically and without the need to restart/log off the machine. I need the change to reflect for all processes, ie, I need to change the global environment value and not the one in the PEB [Process Environment Block] of a process. Frustated with setting the value of an environment variable !!!

For getting the set of environment variables or to get the value of an environment vaible from your C# program, there is the GetEnvironmentVariables/GetEnvironmentVariable API in the System.Environment class. But there is no API for setting the value of an environment variable.

More ...

Consts in .NET !!!

I was doing some programming with C# and I had to use some consts as everybody does generally in programming. I had a class that simply had const string variables for my DB table names and stuff like that. My program was not working well and I started debugging and in the debugger, I was shocked to see that the const variables did not show the string values I had assigned. I did rebuilt and other non-sensical stuff like that until I learnt this about the consts in .NET:- const variables in .NET do not exist as variables out of the assembly they exist in. Instead, during compilation, they get embedded - hard-coded, where ever you use them, and so when you debug, you do not see the proper value that you had assigned. For debugging purposes you have to output diagnostic trace messages and verify. More ...

Joining the Game

Everything has a beginning.