2012-07-08

One thousand visits

Pont de Diable, Hérault river.
When I started blogging  it was just to get firsthand experience of blogging and I decided to write about my professional life only. I have avoided meta blogging, i.e. write about the fact I’m blogging. But now I got 1000 visits on my blog and I think that deserves a post of its own. When I started I really didn’t expect anything I just wrote some posts and that were more or less it. But very early on I became obsessed with the statistics Google served me. Who reads what posts, when and from where. To me one thousand visits  from all over the globe is big. I’m not writing about popular topics and I have not done much to make my blog stand out. And I also realized how hard it is to write good coherent posts, especially in an language which I do not fully master. It is two very different things read and write. I read English more or less fluently, but I do not write nearly as good. My vocabulary is IT and a bit academic and I miss the nuances of words. But I do think my posts are written well enough to be understood. And I find it fun to write these posts. Blogging is a very good experience. I also got one comment for which  I’m very happy, proud and thankful. I also got some comments from people who want to promote commercial software. I have decided not to publish such comments, since I cannot take any responsibility for those products. Free software would be something else though.
I also realized you can use a blog as a documentation system for your software, overviews of software makes good posts. I have referred to some of my posts in my daily work. I can well imagine a good blog is a very effective way for consultants to market themselves. When I hire a consultant first thing I do is to search the internet. What do my own blog tell about me? I have not given that any thoughts, my goal was not to market myself, if that had been the case I would have structured the blog differently and be much more careful with what and how I write. This is also a learning experience, you need to practice blogging to be good at it. The topic I ‘ve chosen for my blog ‘software development’ is not the simplest thing to write about. You need to publish good examples, correct measurements etc. and great attention to details. If I wrote post to market myself I would have put much more efforts to the examples, readability and layout. And there are some posts that not should have been published.
Will I proceed to post here? I think so, but probably less frequent and I do not intend this blog to stay for eternality. I may start other  blogs writing, on other topics, I have other interests beside IT, science, history are things I can imagine myself to write about. People have told me I’m funny in a positive way, in Swedish I can write things people laugh at (in a positive way). It would be a great challenge to try to write humorous posts in English. I have an eye for petty everyday things that go wrong. And I can write about renovating kitchen when everything goes wrong.
I write this post from a small southern French town Gignac just west of Montpellier. I’m not much for traveling these days, my sons persuaded me to come along and we went by car, a bit too long it’s about 2300 km from Stockholm. It is very nice here, not so much tourists. We swim in the river Hérault where the local youngsters jump from the 18 meters high medieval bridge Pont de Diable (the devil's bridge), I saw some guys jumping off a modern 25 meter bridge.  This is dangerous some die, I been told you can get caught in a powerful  undertow, but I suspect the jump in itself can be mortal it looks scary, I would never do it. But I got a friend who would and he would add one or two somersaults just for fun. Today we will do some sightseeing, there is an authentic crusaders village up in the mountains we all like to see. We are a bit sunburnt and should stay away from the sun, so sightseeing is perfect today.
I have noticed it is popular among blogging IT guys to write about local beers  when they travel. This is something I cannot do. I do not drink beer anymore I suspect I get migraine from it. I do not drink red wine or colored liquor either.  It’s the same thing migraine. I only drink Gin, Vodka, white wine including Champagne. It is a tough life I live.

2012-07-02

PHP, CURL and Murphy

I have written a nice automatic PHP Curl procedure to scrape currency rates from an internal  web page. It works beautifully, and has done so since a year. Now I’m on a road trip to southern France , and this morning I got an emergency alert from the routine ‘URL inaccessible’. WTF has happened? It took me some minutes to realize the web server is not responding. I missed this in the design, what to do if this web server is down. It is a serious error in financial reporting not to have valid currency rates, so the entire reporting system/Business Intelligence is stopped! But I didn’t worried too much, I alerted the operations and hoped they could restart this server in minutes. I called the operations early morning from Wiesbaden in Germany they restarted the web server and I got a new error msg from my routine ‘the URL cannot be found’. I misinterpreted the error msg. I still thought there was a problem with the server. I find it hard to do debugging in 200 km/h, just being able to connect over a 3G modem on Autobahn is amazing. I think I have a record in speed-debugging. Later in an hotel room I found out the URL in the webpage was changed and the structure of the webpage was also changed. I realized I would not be able to fix this on my vacation. I discussed the situation with the only remaining colleague at the office (this is vacation period in Sweden). We decided the best thing to do was copy the previous month currency rates, and correct the figure after my vacation.
If I had done a proper risk analysis up front this situation would probably not have happened. But if you always do everything according to the book, not much is done. It is a fine balance how much effort should be spent on design up front, if the resources are scarce you have to compromise. And to be honest I seldom overdo the design work, I often start the build phase a bit premature, most of the time it works well but this time it came back and bit me, at the most inconvenient time. Murphy’s law applies as usual.  I will redesign the system so it always works with the most appropriate currency rates entered (the latest), and some self-correcting mechanism when the correct rates are entered. It shouldn’t be that hard to do.
I end this with the Curl PHP code. This is my first and only piece of Curl code, so I have used examples found on the web, some of the code I do not understand well myself,
but it works beautifully when the web server is up, and when it’s down! I got an alert telling me the servers down, what more can you expect.
#!/home/tooljn/PHP5.3/usr/local/bin/php
<?php
/**
* @package dummy
* @ignore
*/
/**
* This code scrapes
a webpage and downloads an excel file linked from the webpage
* //$link = $webhost.'/'.'Rates)';
* @return bool TRUE
if all is hunky dory
*/
$scriptName = $job['pgm'];
$scriptParm = $job['parm'];
$curlAgent = $context['_xlate']['C_application'];
$eop =$job['eop'][0]['value'];
if (!$eop) $eop=15;
//default
$period =date('Y-m',mktime(0, 0, 0, date("m"), date("d")-$eop,
date("Y")));
$webhost =$job['webhost'][0]['value'];
$weburl =$job['weburl'][0]['value'];
$log->enter('Info',"Enter
script=$scriptName, job=$jobName, Curl agent=$curlAgent, period=$period");
$link =$webhost.'/'.$weburl;
$result =get_web_page($link,$curlAgent);
file_put_contents('WEBPAGE.txt',$result);
$excelname ='EXC'.$period.' Published';
$link =get_excel_link($excelname,$result,$period);
if ($link == NULL) {
   $log->enter('Error',"No
currency rate Excel link for period=$period, end of period=$eop");
                $_RESULT = FALSE;
                return FALSE;
}
$link =$webhost.'/'.$link;
$sufix =substr($link,strrpos($link,'.'));
$excelfilename ='excel'.$sufix;
get_web_file($link,$excelfilename,$curlAgent);
file_put_contents('EXCELFILE',serialize(array(
                array('EXCEL' => $excelname, 'WORKBOOK' => $excelfilename,'PERIOD'=> $period, 'LINK'=>$link ))));
$_RESULT = TRUE;
// indicate successful execution
return(TRUE);
/**
* This function
extracts the latest link to monthly Exchange rates Excel workbook
*/
function
get_excel_link($excelname,$htmltxt,$period){
                $linktab = get_link_tab($htmltxt);
                return $linktab["$excelname"];
}
/**
* This function
extracts html href and creates an associative array Excelname => Url
*/
function
get_link_tab($htmltxt){
                $exceltab = array();
                $regexp2 = "alt=\"[^\"]*";
                $regexp = "<a\s[^>]*href=(\"??)([^\" >]*?)\\1[^>]*>(.*)<\/a>";
   if(preg_match_all("/$regexp/siU",
$htmltxt, $matches, PREG_SET_ORDER)) {
            foreach($matches
as $match) {
                            preg_match("/$regexp2/",
$match[3], $matches2);
                            //
$match[2] = link address
                            //
$match[3] = link text
                            $excelna
= explode('.',(substr($matches2[0],5)));
                            $exceltab[$excelna[0]]
= $match[2];
            }
                }
//
var_dump($exceltab);
                return $exceltab;
}
/**
* Get a web file
(HTML, XHTML, XML, image, etc.) from a URL.  Return an
* array containing
the HTTP server response header fields and content.
*/
function
get_web_file($url,$fileName,$curlAgent){
//print "get_web_file $url,$fileName,$curlAgent \n";
                $fp = fopen ("$fileName", 'w+');
                $ch = curl_init($url);
                curl_setopt($ch, CURLOPT_TIMEOUT, 50);
                curl_setopt($ch, CURLOPT_FILE, $fp);
                curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
// curl_setopt($ch,CURLOPT_USERAGENT, "$curlAgent");
                curl_exec($ch);
                curl_close($ch);
                fclose($fp);
}
/**
* Get a web page from
a URL.  Return an array with the contents of the array
*/
function
get_web_page($url,$curlAgent){
                $options = array(
                CURLOPT_RETURNTRANSFER
=> true,     // return web page
                CURLOPT_HEADER
                   => false,              // don't return headers
                CURLOPT_FOLLOWLOCATION
=> true,                //
follow redirects
                CURLOPT_ENCODING
               =>
"",                   // handle all encodings
                CURLOPT_USERAGENT
            =>
"$curlAgent", // who am i
                CURLOPT_AUTOREFERER          =>
true,                //
set referer on redirect
                CURLOPT_CONNECTTIMEOUT
=> 120,                //
timeout on connect
                CURLOPT_TIMEOUT
   =>
120,                //
timeout on response
                CURLOPT_MAXREDIRS
             =>
10,                  //
stop after 10 redirects
            CURLOPT_POSTFIELDS
            =>
"",
            CURLOPT_VERBOSE
                        => false,
            );
                $ch           = curl_init($url);
                curl_setopt_array($ch, $options);
                $content = curl_exec($ch);
                $err          = curl_errno($ch);
                $errmsg  = curl_error($ch);
                $header  = curl_getinfo($ch);
                curl_close( $ch );
                $header['errno']   = $err;
                $header['errmsg']  = $errmsg;
                $header['content'] = $content;
//var_dump($header);
                return $content;
}

2012-06-26

Email SAP SQVI reports.

Many years from now I was involved in creating a client-server application, in those days this was a new concept, clients was Windows PC computers, and server was a backend computer of some kind. Often these apps didn’t work due to bad communications and buggy comms protocol those days you actually had to be a rocket scientist to successfully connect PCs to servers and make multi update apps work. It was 1990 and the app was an ordering system, retailers sent purchase orders to a wholesaler and received an acknowledgement in return. The twist with this system was the backend it was a DB2 system in an IBM mainframe. How the f-k should the Windows client connect to the mainframe DB2 system?. I came up with a solution, use mail. The dominant mainframe mail system MEMO (developed by the car manufacturer Volvo!) had a Windows client that had a reliable connection to the mainframe MEMO system.  I thought why not use a mail system for sending messages, it is designed for that. So I created an interface between MEMO and DB2. When a mail arrived I picked up the mail, translated it into appropriate SQLs and sent back an email with an order acknowledgment as an attachment that the Windows client software picked up from the mailbox in the PC. This system worked well, which is more than I could say about other Windows client-server apps I had seen at that time.
I have written a post on extracting data from SAP using SAP RFC and PHP . SAP RFC is a very reliable and fast and definitely the first choice for extracting (large) data from SAP. The problem with RFC communication you need an RFC enabled ABAP program or a BAPI on the SAP end. What if you do not have an RFC enabled program in SAP that give you the information you need? It is not a simple task to create an RFC enabled ABAP program.

In this post I  will schedule and send an SQVI   report by the mail to a target system.

SQVI is a user friendly report-generator in SAP. It is a simple, well relatively simple, thing to knock up an SQVI report. If you are not an ABAP programmer this is a more passable way to route data out of SAP, just bear in mind this is not the most efficient way to extract data from SAP.  
Automatic workflow exporting SQVI reports from SAP into MySQL
This is a picture of the workflow I have in mind. Create an automated workflow from the SQVI report into The Business Intelligence application the Data Warehouse. We start with an SQVI report. (I will not explain how you create SQVI reports, I barely know this myself).
The first thing we need to create is a ‘mail printer’, we use this printer to print the report.

SPAD

Use SAP transaction SPAD  to create a new printer.
Here are screenshots from creating the printer  LassesMailPrinter .
1. Fire up SPAD and display output Devices.
2 press Create or Create using template (of you have a suitable printer definition to copy)
When the mail printer is created we put it into use.

SQVI

I select report RUNE and then press Execute (you have to create a report of your own first)
Then I select Execute in Background  and fill in all parameters
Then I choose my mail printer LassesMailPrinter
That’s it. SAP will now create the report and print/send it to your specified email address.
This is the first part of my workflow, the way out of SAP. The second part is to bounce the mail to my FTP server. For that i need some help, we use Lotus Notes for mail and I do not talk Lotus Notes and there is also some security concerns about bouncing emails, to cut it short ‘I can not write this routing so I got help from a colleague.
But now I’m off for vacation and if I recall this when I’m coming back I will create the last part of my workflow from the FTP server into the Data Warehouse.  (It’s the green part of the picture in the beginning).

2012-06-21

Telephone Sale

“You are looking for an IS/IT manager?” I have asked this ominous question a zillion times and the unsuspecting answer is always ‘yes?’. Then I finish the conversation with ” I’m sorry but he  is in our  IT-service company IT Help,  I do not know his name but please call our switchboard and ask for the manager of IT help . ThankyouandGoodbye.”

These days I am no longer responsible for IT and I can just hand salesmen over to others.

When I was IT manager I got lots of calls from telephone salesmen. On a bad day it could be more than 15 calls on a good day about five calls. To survive you got to find a strategy to limit both the number of calls and the time of each call. These salesmen are doing an honest (and very hard) work and deserves to be treated with respect.  Nevertheless you have to cut him/her short to be able to do your work.  These calls are especially annoying when you are in the middle of a ‘debugging session’ or some kind of thought process that demands thinking in many layers or structures, since it takes you time to go to the bottom. Being disturbed in the middle may force you to start all over again. Why didn’t I just turned off the telephone? I wanted to be a modern open ‘always online manager’ so I very seldom switched off my telephone.

When these calls started to become a nuisance, I developed a web-app for these salesmen where they could leave a message and I could called them up if I was interested. Then I talked with our switchboard staff asking them to instruct the sales guys to go to the web-app. But the switchboard guys could not do this, that would be all too time consuming. Then I asked for a special IT-manager sales telephone-number with an automatic reply instructing callers how to use my sales web-app. But that was against company policy! I then decided I should end these calls in less than two minutes. This is in fact harder than it sounds, a telephone salesman is a specialist of keeping a conversation going. It is very much a question of taking the initiative before the opponent have a chance to start his sales pitch. You must tell the opponent what to do.  Interrupt the guy when he has introduced himself, and tell him what he has to offer is not relevant for you and tell him to call the next one on his list. (You know what he/she want to offer after the first introduction.)  Remember to be polite, (it can be hard when the 15th guy call on a busy day).  It can also be someone searching for a job, they can be hard to spot after the first introduction they are also in a selling position. These guys not only deserves respect they also deserves some of your precious time.

Why does these salesmen deserves your respect in the first place? At least in my country, Sweden, we have traditionally a mild contempt for sales in general.  And I suffered from the same mild contempt for sales guys until I worked with pre- and post-sales support,  I then realized how hard and frustrating sales jobs actually are. Without a good sales-force a company is not worth a cent. Without the sales guys,  you and I would not have a job. Actually everyone deserves respect. Well almost, there are some real ...        

I wrote this post after yet another of these calls and I feel like a grumpy old man.

2012-06-16

Load SAP forecasts into MySQL with RFC_READ_TABLE and PHP

Why do we not have the history of forecasts in the Data Warehouse? Because you have not asked for it.

Update: If this post is of interest you should also read this post.

Summary

This post describes how you can extract sales forecasts from SAP. How you can create dynamic SQL predicates for RFC_READ_TABLE. And how you can parallel process these predicates for performant extraction of data from SAP.

Forecast

Forecasts in SAP is stored in the PROW table (forecast results). Or to be correct the Sales forecasts for our products and spare parts are stored in the PROW table. The key to this table is a sequence number PNUM2, a pointer to forecast results. PNUM2 does not tell you much. PNUM2 has to be translated into PNUM1 which is the key to the PROP table (forecast parameters). Unfortunately the PNUM1 key does not tell you much, it must be translated into MATNR and WERKS those fields are the key to products (and components). Translate PNUM1 into WERKS and MATNR can be done in table MAPR.
To find all  forecasts for a product you:
  1. Look for the product (WERKS & MATNR) in MAPR.  
  2. Take all PNUM1 in MAPR and find all corresponding rows in table PROP.
  3. Take all PNUM2 in PROP and find all  corresponding rows in PROW.
Material forecasts are stored in PROW table. But it is not indexed by material number. It is indexed by pointer. The link to PROW is through PROP through MAPR. MAPR-> Get Pointer for forecast Parameters (PNUM1)-> Read PROP ->Get Pointer for forecast results (PNUM2)->Read PROW using PNUM2.  RAVI KALYANA SUNDARAM
As you can see I started with the MPOP_V table, but after consulting Google  I changed that to MAPR.

Ok let’s fetch the data from SAP and import it into our  Data Warehouse.

There is no problem to pick up all rows for a product or spare part, the problem arises when you download all forecasts for a plant. Using my PHP job scheduler  I quickly set up jobs to extract data from MAPR using RFC_READ_TABLE. To test extracting via a pointer (PNUM1 and PNUM2), I downloaded about 137,000 rows with RFC_READ_TABLE from PROP selecting on date.
But how to extract the corresponding rows from the PROW table? Here I only could select on PNUM2. Our PROW table contains a hell of lot of rows. I decided to to play a little with RFC_READ_TABLE and parallel process selection on PNUM2 from the 137,000 rows PROP table.
First I created a job genArray  that creates a selection predicate for each PNUM2 in the PROP table.
select distinct concat("PNUM2 EQ '",PNUM2,"'") as TEXT from @C_DB.FCC_PROP order by PNUM2;
Then I split the result into chunks that SAP program RFC_READ_TABLE can munch. I decided 10,000 ‘ PNUM2 or predicates ’ was a reasonable chunk to send over to SAP. The program mergesplit_array.php  in job splitArray  takes the result array from genArray and chops it up into 10,000 (2 * 5000) chunk arrays that we feed into the <forevery> job iterator in job getPROW . Here you can see the schedule with the jobs defined.
The SAP forecast schedule. The splitArray job generates arrays with SQL predicates use in the getProw job.  
The split of the SQL result array is not a standard function so I had to write the mergesplit_array.php program used in job splitArray , here it is.  
I removed top documentation and compacted the code a bit, as you see the processing code is quite small.
Now I only had to run the schedule. With a cold cache it takes about one minute  to extract 1,629,660 rows  from PROW and insert them into a Data Warehouse table by 14 parallel tasks each of them with an SQL where clause with 10,000 ‘PNUM2=n OR ’ predicates.  
I consider this test extremely successful. Now we only have to denormalise the MAPR,PROP and PROW tables and create one usable history file and load that forecast history into a graphical user interface and create some snazzy graphics. It will take me an hour or two to create a proper production schedule out of this once the users decide they want this. Then we create a Qlikview  app for presentation. If and when this is done I post some graphics showing forecast history diagrams.  
More examples can be found here .

2012-06-11

Outsourcing people

I didn’t participate myself in my first encounter with outsourcing. I left the company 2 years before it actually happened. But I had lots of friends still in the company and I assisted in the handover process. It was ‘my’ old company Atlas Copco Data AB that was outsourced to the company Ericson. AC Data at that time 1987 managed the computer operations of Atlas Copco. The reason for outsourcing the operations were mainly size not efficiency,  Atlas Copco’s operations were streamlined and slimmed down to a minimum, the operation were automated, the personal staff  highly professional.

This was one of the first large outsourcing deal in Sweden  and there were a shortage of skilled IBM mainframe technicians. AC Data could negotiate from a strong position, the CEO actually let the employees participate in negotiations and one of the conditions were all interested should have a new job at the outsourcing company (Ericson) equal or better than he/she had at AC Data. During this time I happened to meet the CEO and he said ‘I never seen people so motivated to lay themselves off’. Very few were happy about the transition to Ericson, but that was more a fact that they all knew each other since many years and now they were split up in a new huge organization. This was probably as happy an outsourcing can be for the employees.

The next encounter with outsourcing hit me more direct I was working for a big computer service bureau; Esselte Datacenter. The owner negotiated the conditions without any of us employees  were involved at all. My (still) good friend the CEO resigned and in came a consultant CEO. He was probably a good guy, but his mission was clear. ‘Do the transition to as fast as possible, only those the outsourcing company wants will be offered a job’. Of about 120 employees we were a handful that got offers in the end and we all thankfully accepted , 1992 Sweden had hit a severe recession and jobs were not to be found. Yes I was very thankful for the offer. At the time I was CTO and become very involved in the handover. I knew that I was important for the continuous operation. In the middle of the transfer I handed in my resignation. This was a calculated risk I had no other job, but as I expected I was offered  a nice bonus if I promised to stay a year, later I understood I could easily have doubled that bonus, but anyway it was a nice bonus. (I demanded the same bonus for a colleague, which to my surprise was granted.)  

The strategy for this outsourcing was very different from AC Data. The new CEO promised openness, we were all going to get all information about all aspects of the outsourcing deal, but in reality we only got information on  ‘as needed base’ and as late as possible. I had the impression we were deliberately stressed so we should not have the time to think but just do our work. Vague talk about job offers but no promises from the consultant CEO. I had one guy that was desperate, he had just bought a house with a hefty  mortgage,  three small kids and an unemployed wife. This guy I actually could help. I ‘promoted’ him to part time assembler programmer and made him responsible for a credit information system and persuaded the outsourcing company he was vital for the system, they bought it and he was given a job. To my grief I could not help more than one, there were many good guys there and there were a lot of tragedies. One guy told me he was considering take up smuggling (stolen?) cars between Spain and Morocco but that is another story. This outsourcing was not happy for anyone of us employees, not even those of us who had a new job to go to, I stayed just over a year at the outsourcing company.  From this outsourcing I learned leave do not stay one minute more than needed  when you are at the risk being outsourced. Even if you can gain some dough by staying it is not worth it.

Some years ago as an IT-manager of the company I’m working for, I had to outsource/lay off some of my staff, due to an anticipated financial crisis. They were not many but that is no consolation for those afflicted. And it is not a pleasant  task for the manager to lay off anyone, and these were good guys. I used my experience from the previous  encounters with outsourcing.

The first thing I did, on a Monday morning ( always tell bad news beginning of the week, NEVER EVER on a Friday ), was to tell the afflicted guys as straight as I could what was going to happen. I told them they were going to get laid off, this was inevitable, the chance they had was to impress the outsourcing company, since we not in a position to demand the outsourcing company to employ them. The reaction was not what I had anticipated. They just did not believe me! They thought they were more or less irreplaceable.  This was of course a mistake from their side, no employee is irreplaceable. Do not ever for a second believe you as an employee is irreplaceable, you are replaceable and expendable .

Next thing I did was to select an outsourcing company.  I made a list of the candidate outsourcing companies the best at the top of the list. I draw a line between those I thought I could work with and those (below the line) I didn’t thought I could work with and told my boss to pick a company above the line. He chose the second from the top, and we are still doing business with them.

My staff found jobs outside the company. They did what I should have done myself, but I tried to arrange for them to go to the outsourcer, but they were not interested.

Outsourcing and laying people off are sometimes necessary, it is your task as manager to do this as smooth and painless as possible for all. This is probably the most stressful task you will encounter as a manager, and you should not do this alone, you should not only engage the HR department but the whole management team if possible.

Never lie, never give false hope and never promise anything you cannot hold. Be frank, open and tell your staff as early as possible what is going to happen.  These are the best advice I can give you, I pray you never have to use them.