How to Migrate from HP-UX to Linux: NULL

On Linux I tried to compile a C program that I had brought over from HP-UX and got the following warning:

foo.c: In function 'bar':

foo.c:42: warning: assignment makes integer from pointer without a cast

The code in question terminates a character string with a nul character.  However, instead of coding the nul character as some variety of zero, it codes it as NULL.  This is bad form, because NULL is intended to be used as a pointer value, not as a number or character.  The compiler may or may not issue a warning, depending on the vendor’s taste, and depending on how the NULL macro is defined.

NULL may be defined in either of two ways:

#define NULL 0

…or:

#define NULL (void *) 0

In the former case, NULL is of type int, and may be assigned to a character variable without a qualm (apart from stylistic objections).  In the latter case, NULL is of type void *, and the compiler may be a little queasy about assigning it to a character.

On Linux, gcc defines NULL as a pointer, and issues the warning.  I’m not sure what the HP-UX compiler does, because the #define is tangled in a thicket of #ifdefs.  It may define NULL as an int, which would probably not result in a warning.  Or maybe we did get a warning and ignored it.

The offending line is embarrassingly gauche, but not actually broken.  Either compiler will almost certainly do the right thing.

I can fix the code before or after migration.  I could even leave it unchanged, if I were willing to ignore the compiler warning.  However I don’t want to get in the habit of ignoring compiler warnings, especially when I can easily eliminate them.

This assessment applies to any case where you misuse NULL as a numeric value.  If you see the same compiler warning in a context where the pointer value is anything other than NULL, the issue is more serious and should be addressed immediately.  However those cases probably would have already been noticed because they would introduce nasty bugs.

Learn more about Legacy Systems Support, contact Unified Development, Inc.

Panel View or Multiple Horizontal Pager View in Android

Android doesn’t provide a default horizontal pager view. It appears as though the Gallery and Horizontal Scroll View can provide this same functionality. The solution described below allows for easy left and right swipes to load different screens controlled by a single activity. We’ll look at an example of how to use these classes to provide swiping behavior.

There are few steps to follow when getting started.  We provide the full source code for the sample application discussed in this tutorial.  Use the link to see examples.

Step One

Define a linear layout and add a weight sum attribute to “1.0”, add 2 more linear layouts inside a main linear layout with an attribute layout weight to “.50” and set the orientation to “horizontal”. Doing this will cause the 2 linear layouts to share the screen equally (horizontal). In the example we will display 6 images (with a text below the image) on each view, to achieve this add 3 more linear layouts in each sub linear layout added above with layout weight set to “.33” and orientation to vertical. Add image views and text views within the linear layouts. Find the attached source code panellinearview.xml file for the complete code.

Step Two

Create a custom view Group. Your activity needs a view group to determine users on touch event, motion event and screen switched to left or right event. Override onTouchEvent and onInterceptTouchEvent method you’ll need to implement several key methods. Find the attached source code PanelPager.java file for the complete code.

Step Three

Define a PanelPager view in your layout resource file and wrap with a linear layout. In the example we will retrieve display list from a web service and load images from the web. So you’ll add the child views to PanelPager view programmatically based on the display list items size.

Step Four

Retrieve the data list. In the display list iteration process inflate the panellinearview.xml for every six items then populate images and text views in the panellinearview.xml. After every six items in the display list add the inflated panellinearview.xml to the PanelPager view. Since you are loading images from the web you can lazy load the images using LazyLoadImage.java file attached source code. Find the attached source code UnidevBlogActivity.java and LazyLoadImage.java files for the complete code.

The PanelPager will provide a neat swiping behavior same as swipe between multiple views on the Android home screen. There are also classes I included for lazy load images in the panel view. In the layout resource file and activity file you will find the code for pagination as well. In your activity you can implement onScreenSwitchListener to handle pagination.

1) System configuration

  • Eclipse Helios
  • Android SDK – Android 3.2

2) Requirement

  • Panel view/multiple views and swipe between multiple views
  • Pagination with active and inactive dots.
  • Image Lazy loading if image need to load from the web
  • Work on all resolutions and sizes

i. Tablet 1280X800

ii. Tablet 1024X600

iii. 7 inch

iv. 10inch

  • Screenshots

3)      Solution

  • panelview.xml
  • panellinearview.xml
  • UnidevBlogActivity.java
  • PanelPager.java
  • LazyLoadImage.java

Outsourcing Mobile Development

As a senior mobile software developer here at Unidev, with over 20 years of client, web-based, and mobile development under my belt, I have learned one simple truth.  Software development companies are not the same.  Outsourcing overseas, although inexpensive, comes at a price.

Many times clients look for the quick, cheap way to get their app done by outsourcing overseas or to local development companies that outsource.  Many companies out there represent themselves as a local US based company but when it’s said and done they simply contract the work out for pennies on the dollar.

This is a great way to get many things done but could come at severe cost in the long run.  I had a client about a year ago that had a horrible experience.  He had an excellent, “why didn’t I ever think of that?” kind of idea for an app.  He wanted it done quickly and didn’t want to invest much to get it done.

He went through a company he thought coded locally and hired them at a price that was about 50% off of the going rate.  This company delivered as promised and he was initially happy.  The app was submitted and started to rank.  The application made it to number 50 in the productivity category and he was bringing in a little cash.

What he didn’t know was, there was another app that had an uncanny resemblance to his original application and was ranking in top ten for a different category.  The app had a different icon and user interface but the idea was identical.   The revenue of the like app was about 20 times that of the original app.

This client managed to save 50% off of going rate but ended up losing much more in revenue in the long run.

When picking a consulting company to create an app, it is important to know where the work is getting done and how far reaching any non-disclosure documents have to go to be enforced.   Intellectual property is about the most valuable asset that many companies own and should be protected as such.

Here at Unidev, we have an excellent team of local full time employees that can get your app from idea to app store while giving the piece of mind that your intellectual property is protected.

Interested in mobile app development? Contact Unidev

Optimizing for the iPhone “Retina Display” and Other High Resolution Devices

Optimizing for the iPhone “Retina Display” and Other High Resolution Devices

The iPhone 4 and new iPhone 4s come featured with Apple’s “Retina Display”. This is a 3.5 inch screen with a resolution of 960×640 at 326 pixel per inch. Compared to its predecessor, the iPhone 3GS, this display is a very significant improvement. Once you get used to the Retina Display older devices will no longer cut it. The pixelation of graphics with lower ppi devices stick out like a sore thumb leaving high resolution users dissatisfied. Here we’ll show you how to target these devices and optimize to bring users the best quality in web graphics.

Below are identical logos being viewed on the iPhone 4 with Retina Display. It’s quite obvious which of the two below has been optimized for the high resolution devices. As mobile application and websites become more and more common using high resolution graphics it is something developers today need to consider when developing applications and websites.

 

Identical logos being viewed on the iPhone 4 with Retina Display.

So how do we go about targeting a high ppi device?

When developing an application much of the work is done for us. Create and save two different versions of each graphic we want to optimize. One of them should be saved at 163ppi (iPhone 3GS) and the other should be twice the size and saved at 326 ppi. Applying the suffix “@2x” in the image title of the high ppi image will trigger iOS to use that particular image when a device with Retina Display is being used. An example of this naming convention would be “myimage.jpg” and “myimage@2x.jpg”.

Mobile Safari does not automatically recognize the “@2x” suffix so we have to target the mobile devices with high dpi and query an alternate stylesheet. The following code will do just that:

<link rel=”stylesheet” type=”text/css” media=”only screen and (-webkit-min-device-pixel-ratio: 2)” href=”retinaDisplay.css” />

If you had a 12×12 icon on your webpage in this stylesheet you would load the 24×24 version of the icon and specify its height and width to be 12×12. It is also possible to do this using just your image tag. For example:

<img src=”myImage24x24” width=”12” height=”12” />

The iPhone uses the name “Retina Display” for its new display because the classification of the images displayed by the device is so high the human eye is unable to differentiate its pixels. Beyond the percentage of resemblance of the human eye and the “Retinal Display”, the reality is that nobody has achieved anything closer to human vision prior to this. Apple has come up with an approach that has changed the way we see images on the iPhone.

 

Interested in Mobile Development? Contact Unidev

Test of Spring MVC annotations

Spring 3 MVC annotation based controller make Unit Testing real easy and straight forward. Since you don’t have to implement any interface or extend super classes for controller as you used to do in Spring 2, you can call methods in controller directly for Unit Testing without Spring or any other container.

With Spring MVC annotation, a controller can be defined as simple as:

@Controller

public class SimpleController {

@RequestMapping(value=”/simple”, method=RequestMethod.GET)

public @ResponseBody String simple() {

return “Hello world!”;

}

}

To test this controller, you can treat it as a POJO. Methods in controller can be called and tested directly:

public class SimpleControllerTests {

@Test

public void test() {

SimpleController controller = new SimpleController();

assertEquals(“Hello world!”, controller.simple());

}

}

If you want to do integration test, Spring TestContext Framework makes it simple. The Spring TestContext Framework provides generic, annotation-driven unit and integration testing support. The easiest way to use Spring TestContext Framework is to use @RunWith & @ContextConfiguration to load Spring container for unit and integration test. It will support for loading application contexts, dependency injection of test instances, transactional test and so on. The Mock object is provided by TestContext Framework as well.

Here is a simple example of using TestContext Framework to do integration testing. We want to test followings in this test:

  • Spring application context is loaded properly.
  • Appropriate handlerAdapter is used.
  • Testing request method & URL mapping
  • Testing @ResponseBody

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(“/servlet-context.xml”)

public class SimpleControllerIntegrationTests {

@Autowired

Private AnnotationMethodHandlerAdapter handlerAdapter;

Private MockHttpServletRequest request;

Private MockHttpServletResponse response;

Private SimpleController controller;

@Before

public void setUp() {

request = new MockHttpServletRequest();

response = new MockHttpServletResponse();

controller = new SimpleController();

}

@Test

public void testSimple() throws Exception {

request.setMethod(“GET”);

request.setRequestURI(“/simple”);

handlerAdapter.handle(request, response, controller);

assertEquals(“Hello world!”, response.getContentAsString());

}

}

In this code, we use @RunWith(SpringJUnit4ClassRunner.class) to setup JUnit 4.5+ environment with Spring. Using @ContextConfiguration(“/servlet-context.xml”) to load application contexts (servlet-context.xml) for test class, all tests in this class will share the configured ApplicationContext . We use Mock objects from Spring for request and response object. As you can see, setup Request URL & method is straight forward.

It should be fairly easy to extend this to more complex examples testing @ModelAttribute, @RequestParam, @PathVariable, @RequestHeader, etc.

Minification and Cache-busting in Asp.Net

Most users of popular libraries like jQuery tend to use a few jQuery plugins also. One project I’ve worked on has 10 jQuery plugins, plus a few scripts that are common across all pages on the site. Each script has to be downloaded, parsed, and executed before your page loads in full. So, a proliferation of Javascript includes on your pages can dramatically slow down load time, but this doesn’t have to be the case.

Another issue that often occurs when working with Javascript and CSS is some browsers are overzealous with their caching, which can result in telling someone to refresh a page to see if it’s working, and while it might work for you, their browser decided to cache the old script, making your changes not appear.

In this post, I will outline a few techniques to help alleviate a few of these problems.

Read the rest of this entry »

How to Migrate from HP-UX to Linux: Encryption

We use some utility encryption routines in C for various purposes. When I first tried to migrate these routines from HP-UX to Red Hat Linux, I ran into a problem right away: the linker couldn’t find the libcl.a library.

There is no library by that name in Linux, and I had no idea what the linker wanted to find there. As an experiment, I edited the make file to remove the reference to –lcl. Now the linker complained that it couldn’t find the functions setkey() and encrypt().

A little research showed that, in Linux, those functions reside in the library libcrypt.a. I edited the make file again, replacing the reference to –lcl with a reference to –lcrypt.

(Under HP-UX, the libcl.a library includes not only the encryption functions but also a bunch of math functions. Under Linux, the math functions presumably reside in the library libmath.a. However I haven’t needed any of them so far, so I’m guessing.)

Now the linker was happy, but I wasn’t. Whenever I tried to encrypt anything, all I got was a string of zeros. Um, that’s not encryption. At best, it’s a really, really, really bad hash function.

At that point I fell down the rabbit hole of debugging – grepping the source, studying the code, inserting displays, Googling for clues, and trying experiments. Here’s what I found out.

The setkey() and encrypt() functions apply DES encryption to blocks of 64 bits at a time. That’s bits, not bytes. However, you don’t pass the bits as 8-character arrays. You pass them as 64-character arrays, one character for each bit. It’s the job of your application to translate back and forth between these bit arrays and whatever the data should really look like.

One reason for this arrangement is probably that not all machines use 8-bit bytes. The C language requires that a byte contain at least eight bits, but it can have more. I’ve heard of CPUs that use 9-bit bytes, and others that use 64-bit bytes. If you really want to be perverse, you could build a machine with 37-bit bytes. It may be easier for an encryption standard to support exotic architectures if it breaks everything down to the bit level.

In the HP-UX version of these functions, the bits in these arrays can be encoded as the ASCII characters ‘1’ and ‘0’. I haven’t found any documentation of that fact, but that’s how our programs were coded, and they seem to work okay.

In the Linux version of these functions, the bits in these bit arrays evidently must be encoded as the binary values 0×00 and 0×01. I haven’t found any documentation of that fact either. The man pages on both systems are ambiguous.

The best evidence is that, after I rewrote our code to pass the bit arrays with binary values instead of ASCII characters, the encryption started working on Linux. I can encrypt something and then decrypt it, and get the same thing I started with. Furthermore I can encrypt something on HP-UX, decrypt it on Linux, and get the right answer.

Out of curiosity, I tried the Linux version on HP-UX – and it worked! Evidently the HP-UX implementation of setkey() and encrypt() can accept either character values or binary values in their bit arrays, but the Linux version only accepts binary values. Once I converted the code to use binary values, I could use it on both platforms without a bunch of ugly #ifdefs cluttering up the code.

Fast Data Loading with SQL Server 2008

A common operation in many systems is bulk loading of data into a database, be it from another system, a flat file, or generated output, which may or may not involve updating existing records. A lesser known class in .Net, SqlBulkCopy, and a new feature in SQL Server 2008, MERGE can greatly increase the speed of these operations.

Read the rest of this entry »

Password Storage Best Practices

With the several high profile security breaches so far this year, security is on the forefront of most developers minds, or it should be. Though, if one has never coded good authentication code before, it can be a rather daunting task. The Internet is rife with poor advice, old advice, or just plain wrong advice. This post will attempt to help demystify some of tools and techniques of building authentication systems.

Most authentication services have different requirements. For example, you would expect there to be more security logging into your bank than into your blogging software. At a point, you have to establish what is good enough for the data your authentication you’re protecting. Users are more likely to not use your system for every additional hoop they have to jump thorough, but if they view the data as worth it, they might be willing to be further inconvenienced (For example, two-factor authentication with a key fob for logging into a bank)

Read the rest of this entry »

How to Migrate from HP-UX to Linux: Undefined Behavior

The C and C++ languages don’t try to define the results of every syntactically correct program. For example, if you dynamically allocate some memory, and then free it, and then try to access the memory you freed, you invoke undefined behavior. The C and C++ standards don’t specify how the program will respond.

Undefined behavior means that anything can happen, because the compiler is under no constraints. The traditional formulation is that undefined behavior can make demons fly out your nose. In practice the consequences are usually less dramatic.

If demons ever fly out your nose, you’ll know you have a bug. You can track it down and fix it. More insidious is undefined behavior that happens to be exactly what you want.

I ran across an example as I was preparing to port some code from HP-UX to Linux. The program was freeing a linked list, using code similar to the following:

 

Node * curr_node = first_node;

while( curr_node )

{

free( curr_node );

curr_node = curr_node->next;

}

 

To a long-time C coder, this code immediately looks fishy, because the loop has only two statements in it. Look a little closer. The second statement in the loop tries to access memory through a pointer that has already been freed. It invokes undefined behavior.

This program has been running for years with no obvious ill effects from this bug. Apparently HP-UX isn’t very persnickety about accessing previously freed memory. That’s legal. “Anything can happen” includes “what you want.”

When I first saw this code, I wasn’t ready to port the entire program to Linux yet, but I could experiment. I dashed off a little test program that built a linked list and then freed it, using the logic shown above. Under HP-UX this program ran to completion without incident. Under Linux, the same program stopped abruptly in the first iteration. It didn’t issue any messages, dump core, or even leave a non-zero condition code; it just stopped cold. That’s legal too. Anything can happen.

I don’t know whether this difference is attributable to the operating systems, the compilers, the libraries, or the machine architectures. I don’t care. What matters is that I can’t run this program under Linux without fixing the loop:

 

Node * curr_node = first_node;

while( curr_node )

{

Node * temp = curr_node->next;

free( curr_node );

curr_node = temp;

}

 

A few days later, another example of undefined behavior popped up, in the form of a buffer overflow. Under HP-UX the overflow had no visible effect, at least not until I started poking around with printf statements. Under Linux the code just didn’t work. Probably the variables are arranged differently in memory. In HP-UX the overflow didn’t damage anything that mattered, and in Linux it did.

These examples are just things that I stumbled across. There will be more, and I won’t catch them all so painlessly. Fancy code analyzers may help catch things in advance, but there is no substitute for vigilance.

It’s tempting to conclude that HP-UX is more forgiving of blunders than Linux is, since some things work in HP-UX but don’t work in Linux. That conclusion is premature. Maybe the two platforms are just forgiving about different things. If the bugs had done obvious damage under HP-UX they would have been fixed already.

There’s a Darwinian process at work here. Bugs survive when they’re well adapted to the environment. When the environment changes, some of those bugs will go extinct. Unfortunately, new species will probably replace them.