Wednesday, November 7, 2007

Rounding a calculated value in .net

I have had to round a calculated value before it is presented in the display. This is what I did to accomplish this task.

Use the function System.Math.Round(value, precision) where Value is the number that needs to be rounded to precision number of digits.

The other option is to set the control's DataFormatString to {0:n2} where n denotes a float or double value and the number 2 denotes the precision that is required. Don't forget to set HtmlEncode to false!

Though both methods work great, I decided to go with the later option as I would be able to delay the rounding until it is actually ready to be displayed.

How to determine if a data value is null

When we try to get data using a series of SQL joins, at some point, we are bound to hit a data element with a Null value. It took me a little bit of time the first time i came across such an error. This is how i dealt with it:


If TypeOf (MyDs.Tables(0).Rows(j).Item(3)) Is System.DBNull Then
' do something here

End If

Monday, August 6, 2007

Water heater goes kaput!

As if the problem of having to deal with the loss of a phone number was not enough, last week, our water heater literally decided to leave us high and dry (well, uh, not exactly dry as we live in this high humidity zone, but I suppose you get the point).

Though the need for hot water is not as crucial during the hot, hazy days of summer, we pampered souls still like the convenience of having hot water at the push of a lever. And then, there are the usual reasons when we cannot do without hot water (like bathing the children, washing clothes/dishes etc.).

Under those situations, our initial reaction would be to reach out for the phone and get in touch with a plumber/electrician that can solve our problem the fastest! Well, I too reacted along similar lines, but instead of hitting the phone book, I took to the web searching for plumbers. An online service allowed me to search for and send requests to plumbers in the area, but all it could find was one plumber who was at least a good half an hour away. To his credit, this plumber called and left a voicemail saying that he could help me get a new heater real fast. While waiting on his reply, I had been trolling the various forums trying to see if I could find suggestions to my predicament. Some went as far as recommending I replace both thermostats as well as both heating elements where as some others suggested I drain the heater tank and clean the elements. But none of them went so far as to suggest replacing the water heater itself.

Our water heater has an auto shut off feature that shuts off power to the heater if the tank temperature becomes too hot. My initial assessment told me that this was what was happening as the water from the faucets became very hot a few hours before it turned dead cold. So, I opened up the heater access panel and hit the reset button. This seemed to rectify the problem, but the next morning, I noticed that the water was hotter than normal. As anticipated, the auto shut off system jumped back in action and turned off the heater. The result? No hot water for the second time in as many days. Further searching on the net brought me to what seemed to be a knowledgeable suggestion from an experienced (plumbing?) mind. The suggestion was to replace the lower thermostat. The explanation? The lower thermostat might have gotten fried and so the lower element doesn’t know when to stop working. When the water becomes overheated, the heater’s auto shut off system kicks in and switches off power to the heater. The only way this can be overridden is by hitting the reset button behind the access panel on the heater.

A quick run to Lowes and back and about fifteen minutes to replace the fried thermostat was all it took for me to have the heater back online and in action.

Determining if two numbers are evenly divisible or not

Recently, I have had to validate a couple of entry fields to ensure that the value entered in one field is evenly divisible by the value entered in the other field. The built in function %Rem() worked perfectly for me.

If %Rem(Numerator:Denominator) > 0
// reminder exists, fields not divisible
.......raise error condition - let user know that value is not a multiple
EndIf;

This function returns the reminder from the division operation of its factors -(Numerator/Denominator).

Tuesday, July 31, 2007

Hate spending a fortune on passport photos?

It is not often that one needs passport photos, but when the need arises, it is usually arrives in the form of a deluge! Anyone who has had to file for the I485 or the N400 or Passports/Visa/PIO/OCI for the entire family knows what I am talking about. And those passport photos are not cheap either!

If you have had yours taken recently, you know how it works at the photo shops. They snap your photo using a digital camera and then hand it over to their photo software to do the rest. If you are a little bit enterprising, here is a cheap but efficient way of getting your passport photos.

Use your digital camera to take the photograph.
If you choose, you can use photo-editing software like Picasa (a free service) to refine the photo.
Then, use epassportphoto (also a free service) and follow the steps to upload your photograph, format to desired size and then save it back to your computer. Each image will be automatically sized to fit on a 4x6 paper and will have six to eight copies of your photograph depending on your chosen size. Copy this saved image onto your portable media and take it to a photo-printing lab to have it printed. If you are not able to use portable media, you can even choose a service like Snapfish (listed on the website) to have your photos printed at a neighborhood photo shop.

Alternatively, you can even print it at home provided you already have the required hardware. Once you have the printout, cut out the photographs and you are ready to put them to use! All this for the price (maybe lesser) of having a single 4x6 sheet printed.

Thursday, July 26, 2007

magicJack - the advent of truly portable, affordable VOIP?

When the nation’s second largest VOIP service provider bit the rocket (err… bullet) mid-July, it was time for me to start searching for another provider to satisfy my long distance calling requirements. My home phone is local only and I cannot use my cell phone for long distance.

VOIP providers lost no time in making attempts to woo ex-Sunrocket customers. Via talk was offering a ‘contract buyout’ of up to a year for those who got scorched by the rocket’s fumes, but that offer was cut overnight to a maximum of six months (I understand it was later cut down to three months)! This prompted me to start looking elsewhere for a solution that would work for me.

The search led me first to GrandCentral (see previous post), the telephone management company that was recently acquired by the ubiquitous Google. The concept was interesting but it still didn’t solve my problem, as it worked fine for incoming calls, but I wouldn’t be able to call long distance using the GC number.

Next, I took a look at Skype that I had first used a few years back when it was still a free service. I recalled that call quality was not that bad, but I didn’t get around to using it much at that time. This service doesn’t give you a dedicated phone line either. With Skype’s new avatar, it looked like I will have to pay about 60 bucks a year to have the ability to make unlimited incoming and outgoing calls within the US. And then I had also heard of complaints about their overall call quality.

A little more searching got me to what I might say is an interesting alternative in the form of magicJack. This is basically a VOIP solution, but it doesn’t involve an adapter or wires. Instead, it comes in the form of a USB device that has a phone jack on the other end. The first time you plug in the device into your computer, you will be allowed to choose a US phone number and you are ready to start making/receiving calls. You can receive calls either on the computer itself or on the phone that is plugged into this device. The only downside is that your computer will have to be constantly on (with an active broadband connection) if you need to make calls. Yes, traditional VOIP is portable, but magicJack goes one up here as there are no adapters or additional wires to carry around! The magicJack device includes voicemail and has a feature whereby incoming calls can be forwarded to another number. All this for a cost of $20 per year! Yes, that was not a typo; it is really supposed to cost you $20 a year for unlimited long distance within the US. As this company is still in beta, they have very few area codes available at this time.

An interesting possibility is the use of magicJack in combination with GrandCentral. Setup GrandCentral to transfer all incoming calls to the numbers of your choice (home/cell /magicJack etc.) and use the magicJack number to make your long distance calls. What makes it even more appealing is the possibility of using this device to call your US number from anywhere in the world provided you have a computer with a broadband connection. And setup is a breeze!

MagicJack even did it’s own bit in trying to attract Sunrocket’s ex-base by placing this humorous ad on it’s website.

Tuesday, July 24, 2007

GrandCentral - Manage your phones with one number!

Grand central has since been acquired by Google and is now called Google Voice.

Recently, I came across a telephone provider that had come up with an innovative approach of treating your phone number. GrandCentral operates on the simple concept that your phone number(s) should be tied to you, not the other way around!

What a neat concept! These days, most of us have at least three phone lines. Heck, some of us even have more phone lines than TV remote controls! How would it be if we can give out just one number to all of our contacts and that one number then manages the rest of our numbers? That way, regardless of the number of times our numbers may change, as long as the main number doesn't change, we don't have to communicate a number change ever again! That one main number is the number that you can now have from GrandCentral.

Once a GrandCentral (GCNumber) phone number is assigned to you, you can keep it for ever and you can link up all of your US numbers to your (US) GCNumber. Anybody calling your GCNumber will be forwarded to the (USA) numbers that you have asked your GCNumber to forward the call to. There are a host of other cool settings that can be setup right down to the individual contact level. You can record your conversation with a press of a button, have your voicemails forwarded in the form of emails, setup buttons on websites (like the one I have in the sidebar on this blog), transfer your call to another of your phones in the middle of your conversation and much much more.

Check out the demo that is posted on Tom's blog. For more information, goto the GrandCentral website or google 'grandcentral phone'.

Itching to check it out? Ever since Google purchased Grand Central early this month, signing up is by invitation only. I had been able to sign up thanks to Tom, and I now have a very few invites left. Just leave your full name and email Id. in a comment if you would like to be invited.

Will the insult go unpunished this time?

The recently concluded Presidential elections in India has been widely perceived as a big joke that was thrust upon the hapless people of India against their wishes. This was a case of the politicians (well, almost all of them) brushing aside the popular will of the people to ensure that the 'prestige' that came with the highest office of the country was retained within the 'political class'.

The people of India wanted the highly popular current incumbent Dr Abdul Kalam to continue for another term, but the politicians (as usual) were not willing to listen. There was no major election coming up, so they had little to fear. Given the short memory of the voters, by the time the next election came about, this incident would have long been forgotten.

The reasoning that only a politician should be President was put forth, but it was not the least bit convincing. The general perception was that the politicians looked upon the post of the President as their exclusive birth-right. In the long run, such an attitude may not sit well with the citizens of the land.

The final insult came about when many politicians started throwing verbal jabs at the Dr Kalam when he agreed to contest the election at the behest of the 'Third Front'. The ruling coalition took their banter to a new level when even veteran leaders came out criticizing Dr. Kalam for his decision. Never once did they think that by making digs at a Bharat Ratna, they were undermining their stature in the eyes of the people even further. It looks like the politicians are quite a distance away from learning to understand that if India is to make strides into the future, it is essential that the prominent posts of India should be represented by accomplished, younger beings in the class of Dr. Kalam (politician or not). Gone are the days when such posts were reserved only for old hags or politicians on the verge of retirement.

This incident has brought back calls from various groups to make the election of the President of India a direct election where the people elect him/her instead of the present format where the politicians get to elect the President (and the VP).
I can only hope that, come election time, the people of India don't forget this insult that was thrust down on them by their elected politicians.

The politicians may justify their decision by saying that India was ready for a female Head of State, but that argument is pretty feeble. I think India is past the stage where we will have to have a Head of State from each sect and category. India, at this stage of her economic journey, is ready for Heads of State who, among other things, will be able to rub shoulders with the leaders of the world on an equal footing and who will be the face of a knowledgeable India to the world. In this era when information and knowledge is king, a politician is the last person that anybody would turn to in search of such a face.

In hindsight, it may go down in history that the lady at the helm of the Congress party didn't want Dr. Kalam to continue in office. The reason? My opinion: Vendetta. Revenge. Three summers ago, the lady almost became the Prime Minister of India. It was widely believed in several circles that she was advised by the President's office not to take up the post. What did Dr Kalam tell Sonia on that fateful day when she decided to 'give up' the seat of power? We may never know, but it may well turn out that the whole drama that unfurled in front of us over the last few weeks may be a direct result of that piece of advice that Dr. Kalam gave Sonia on an eventful summer day.

Friday, July 13, 2007

Using Monitor to trap errors

In good old RPG, what would we do if we wanted to check if the value in an alpha variable is integer or not?

Well, we would have defined a constant that has all integers or characters as the value (like '0123456789' for integers, I will not even try to demo the alpha equivalent) and then use the CheckR Opcode or the %CheckR BIF (built in function) to determine if the variable has any matches or not.

With the advent of Free RPG and the Monitor OpCode, there is a better way to do this. Here is how we can handle the error (using free form RPG) if the value in an alpha field is not integer:

Monitor;
CustInt = %Int(%Trim(Cust));
OsCust = %EditC(CustInt:'X'); // Customer number
On-Error; // If value is non-integer
OsCust = Cust;
EndMon;

The vlaue in the variable Cust should always be numeric, but sometimes, it turns out that it can be alpha too. When that happens, as the statement [CustInt = %Int(%Trim(Cust)); ] throwing an error condition is within the [Monitor - EndMon] block, the system flags an error condition and control skips to the statement following the "On-Error" statement. In my case, I just move the value in Cust as is to the OsCust field (which is also alpha)! The "On-Error" statement is executed only when an error condition exists within the Monitor block.

If the value is numeric, I make sure that it is padded with leading zeros (that is where the %EditC comes in handy) before moving it into the target alpha field.

Friday, June 15, 2007

Removing leading zeroes from a non zero character variable

I have a character variable which accepts numeric data. If this data is non-zero, we will have to take out any leading zeroes and then pass the resulting data to an SQL statement for further processing. This is how I acheived it using free form RPG.

InUpc is the character variable.

If %Trim(InUpc) <> *Zeros; // if data is non-zero
DoW %SubSt(%Trim(InUpc):1:1) = '0'; // take out first digit if it is zero
InUpc = %SubSt(%Trim(InUpc):2);
EndDo;
EndIf;

Wednesday, June 13, 2007

Recursion example - RPG, i5

Here is an example of recursion using a procedure in RPG:


P CrtDataQ B Export

D CrtDataQ Pi

D DtaQNam 10A Const
D KeyLen 10i 0 Const
D DtaQLen 10i 0 Const Options(*NoPass)
D LibName 10A Const Options(*NoPass)
D CmdStr S 300A Inz Varying
D Library S 10A Inz('QTEMP')
D DtaQLn S 10i 0 Inz(256)

/Free
// set default values for DtaQLen and LibName...
Select;
When %Parms() = 3;
DtaQLn = DtaQLen;
When %Parms() = 4;
DtaQLn = DtaQLen;
Library = LibName;
EndSl;
CmdStr = 'CRTDTAQ DTAQ(' + %Trim(Library) + '/' + %Trim(DtaQNam) + ') MAXLEN(' + %Trim(%Char(DtaQLn)) + ') SEQ (*KEYED) KEYLEN(' + %Trim(%Char(KeyLen)) + ')';

// Monitor for the possiblity of Data queue already present
// If data queue is already present, delete it and then create.
Monitor;
ExcClCmd(CmdStr:%Len(CmdStr));
On-Error;
DltDataQ(DtaQNam);
CrtDataQ(DtaQNam:KeyLen:DtaQLn:Library); // recursion example
EndMon;

/End-Free

P CrtDataQ E

Convert date into numeric format - RPG free

StrDt is a date field into which a date is being updated. PlHBeg is a julian date in the form yyyyddd.

The code block - %SubSt(%Char(PlHBeg - 1900000):2) gets us the Julian date that is recognized by i5.

StrDt = %Date(%SubSt(%Char(PlHBeg - 1900000):2):*Jul0);

PxHBeg is an 8 digit numeric field into which we are trying to feed a date in Iso (yyyymmdd) format. We use the built in function SubDt to extract each portion of the date and with some basic calculations, we have the date converted to numeric form.

PxHBeg = %SubDt(StrDt:*Y) * 10000 + %SubDt(StrDt:*M) * 100
+ %SubDt(StrDt:*D);

Where change seems to be the only constant

A first hand account

For the first time ever, I had to visit India under rather tragic and gloomy conditions, so I had neither the inclination nor the time to indulge in the usual fun activities. But observe I did, and what a dramatic change it has been since my last visit two years back! during my last visit, I saw an attitude shift in general with people not backing off from spending and patiently lining up in front of ATM machines waiting for their chance to withdraw (spend?) some of their hard earned money. Gone were the days of trying to save for a rainy day! Just when I thought that I have seen it all, this time around, it looked like change was the only real constant. Though change was all-pervasive, it was all the more visible in the suburbia and the smaller two tier centers.

The first surprise was Bombay (Mumbai) airport. They really turned it around. What was a murky, dirty, cramped up place on my last encounter has now turned into a spacious, spick and span, well lighted airport on par with the best that India has to offer. The new immigration counters are more spacious with minimal waiting times. It took us more time waiting at the expanded and more roomy baggage claim area than in immigration. Though customs also was more streamlined, this is one area where the officers will have to be more courteous. I couldn’t help but observe that there was also a baggage re-check area for domestic connections. It is amazing what a little bit of private enterprise can do.

The once ubiquitous Ambassador seems to have all but been relegated to the history books nowadays. It looks like that tag now belongs to the Marutis and the Tatas. And it looks like the Tatas might well get hold of that tag ultimately with their Indicas and their Indigos. The once popular Sumo had already yielded to the Qualis but after Toyota decided to replace the Qualis with the Innova, it looks like the Innova is well on the way to take over that segment. You still do see the odd Camry, Accord or Civic, but they are few and far between. People perceive them to be overpriced, as they know that they are about half the cost here in the US.

And then, there is fast food. While the McDonalds, Pizza huts, Dominos and Subways are making inroads everywhere, Indian fast food has not lost its appeal. In south India, the idlis, vadas, dosas, indo-chinese and thali still hold sway, though people don’t mind venturing into a subway or a pizza hut now and then. I couldn’t help but notice that while people fret over the price of onions touching 16 rupees a kilo, they don’t care for the price when they order a foot long sub for 200 bucks or a plate of (five) fried jumbo shrimp (served on the seashore) for 300 bucks. I suppose it is the experience of dining on the sand with the waves crashing nearby that people are willing to pay for!

Retail is exploding like never before with national chains like Reliance, Subhiksha and Spencers competing with the more regional chains like Trinethra or TruMart for the same customers. Finally, more power to the customers, though at the cost of displacing a few smaller hitherto cramped stores. With Walmart and Bharti teaming up, the retail landscape can only get spicier.

It looks like real estate is also going hand in hand with the retail boom. In some places, land that used to go for 20,000 a square yard two years ago is now going for 50,000 a square yard. The immediate suburbs of Vizag, for example, are going for about 2 crores an acre (provided you can find a chunk of land that size). With the stretch of the golden quadrilateral that passes through Vizag completed, distances are no longer an issue and people are willing to go as far as 40 to 50 Kms in search of land. The result? 30 kms from Vizag, land costs near the highway range from 15 to 60 lakhs per acre depending on how far the land is from the highway. Farmers in the suburbs are benefiting from this uptick in prices as more and more of them are not being able to refuse the offers being doled out for their lands.

Almost everybody in the average family now has a cell phone. Cell phones have become the preferred choice and landlines are very rarely used. So much so that, people are even having their news delivered to their mobiles and are even starting to pay bills using SMS. Some are not backing off from buying the more expensive models. I could not believe my eyes when I saw huge lines in front of an ATM in Guntakal at 7pm. What was more surprising was that the line didn’t seem to dissipate even at 9pm!

Be it a low profile center like Guntakal or the high profile centers like Pune or Hyderabad, change is certainly in the air. No matter where I have been to in India, there is this positive outlook that permeates all sections giving way to a perception that India’s time has finally arrived. Granted that IT is still the driving force, but other sectors like pharma, tourism, biotech and entertainment are making inroads into this once exclusive club of growth drivers. It sure looks like India is all set to embark upon one more golden period.

And finally, the one bright spot on the way back to the US on Air India was that we were on time and each and every landing (Delhi, Heathrow and JFK) was perfect, without any bumps, jerks or jolts. Should say that those were among the best landings I have ever experienced.

Calculating Time difference using Free form RPG

This is how I calculate the difference between two times in minutes...

TimeDiff = %Int(%Diff(%Time(CurTime:*Hms):%Time(OrdTime:*Hms):*mn));

where Curtime and OrdTime are numeric and *mn denotes that we need the difference in minutes to be put in the TimeDiff field.