Saturday, May 19, 2012

Hotel Reservation Program In C

Following listing is a C Program for Hotel Reservation System.

/**************************************************************************/
/*                HOTEL RESERVATION MODULE                  */
/**************************************************************************/
/*@(#) Program Name : ProcessHotel.c                      */
/*    date        :16/12/2005                          */
/*      author      : Techno
/* description      : -The program gets the Message from  the Queue       */
/*              "HILTONHOTELQUEUE" under queue manager "HiltonHotel"*/
/*              -Processes the request message(room reservation)    */
/*              -Prepares response message and puts the same in       */
/*               "RESPONSEQUEUE"                      */   
/**************************************************************************/
/* Include necessary header files */

#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
#include <cmqc.h>

/************************************************************************/
/* function name: updateRoomDetails                    */
/* description    : This function finds a string and replaces it with     */
/*          another string both passed as parameters        */
/* parameters   : char fileName[]  - The file containing room details    */
/*          char find[]  - a string to find             */
/*          char replace[] - a string to replace with        */
/* return value : returns 0 if updatation is successful            */
/*          returns 1 if updation is unsuccessful            */
/************************************************************************/

int updateRoomDetails(char fileName[20],char find[20],char replace[20])
{
    int nRequestOk = -1;  /* an integer flag to hold the info about success or failure */
    char cLineRead[20];   /* to hold the line read from the file */
   
    /* open file for reading and writing */
   
    FILE *fp = fopen(fileName, "r+");
   
    /* check if action is successful */
   
    if ( fp == NULL )
    {
        fprintf(stderr,"Unable to open file...");
        /* return 1 on failure */
        return 1;
    }
   
    /* read 11 bytes by bytes through file untill EOF is reached */
   
    while(fgets(cLineRead,11,fp)!=NULL)
    {   
        /* compare the line read with string to be found */
       
        if (strcmp(find,cLineRead) == 0)
        {
            /* This is the code for replacing the string
               move back the file pointer by 10 bytes    
               and place the new string
             */
           
            fseek(fp,ftell(fp)-10,SEEK_SET);
            fputs(replace,fp);
           
            /* put an ENTER */
           
            fputc('\r',fp);
            fprintf(stdout,"\nRooms Details Updated...\n");
           
            /* set action as SUCCESS */
           
            nRequestOk = 1;
           
            /* Break the loop, (only one occurance is sufficient in the present contest) */
           
            break;
        }// end if
    }//end while
   
    /* close the file hanlde */   
   
    fclose(fp);
   
    /* check for the successful action */
   
    if(nRequestOk==1)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

/************************************************************************************/
/*        THE FUNCTION TO CHECK IN THE BOOKED ROOMS TO SEE WHEN THEY ARE FREE       */
/************************************************************************************/
/* function name  : checkAvailability                            */
/* description    : checks from the booked rooms to see when they are going to be   */
/*            emptied, if yes the free date is updated to new date        */
/* author         : Techno                            */
/* date       : 16/12/2005                                */
/* parameters     : char fileName[] - the text to process                */
/*            char find[]     - the string to fine                */
/*            char replace[]  - the string to replace with            */
/* retrun value   : returns 0 on SUCCESS                           */
/*            return 1 on FAILURE                            */
/************************************************************************************/

int checkAvailability(char fileName[20],char find[20],char replace[20],int noOfRooms)
{
    FILE *fp;        /* take file pointer */
    char cLineRead[20];     /* to hold the line read from the file*/
    int nIndex,nIndex1 = 0;
    int nCount = 0;     /* a counter */
    int nRequestOk = 0;     /* action flag */
   
    printf("\nChecking in %s for date %s....\n",fileName,find);
   
    /* open the file for both reading and writing */
   
    fp = fopen(fileName,"r+");   
   
    if (fp == NULL)
    {
        fprintf(stderr,"Unable to open file...");
        return 1;
    }
   
    /* read 11 bytes at a time until EOF */
   
    while (fgets(cLineRead,11,fp) != NULL)
    {
       
        if (strcmp(find,cLineRead) == 0)
        {
            nCount++;
        }
       
        /* see whether requested number of rooms are available*/
       
        if(nCount == noOfRooms)
        {
            fprintf(stdout,"\nRooms availabe...\n");
            break;
        }
    }//end while
   
    if(nCount < noOfRooms) /* requested no of rooms not available*/
    {
        printf("\nRequested no of rooms not available...\n");
        nRequestOk = -1;; /*Rooms Not Available*/
    }
    else
    {  
        /* the rooms rooms.txt  are not available ( meaning that all rooms
           have been booked), so search from the booked rooms
        */
       
        /* reset the file pointer*/
       
        rewind(fp);
        nIndex1=0;
       
        /* read through the file until EOF is reached*/
        /* if both strings are matched, then dates will be updated appropriatly */
       
        while(fgets(cLineRead,11,fp)!=NULL)
        {
            if (strcmp(find,cLineRead) == 0)
            {
                /* this the code for replacing a string by another */
                fseek(fp,ftell(fp)-10,SEEK_SET);
                fputs(replace,fp);
                fputc('\r',fp);   
                nIndex1++;
                if (nIndex1 == noOfRooms)
                {
                    fprintf(stdout,"\nAll Updated...\n");
                    nRequestOk = 1;
                    break;
                }
            }
        }//end while
    }//end else
   
    /* close the file */   
   
    fclose(fp);
   
    if (nRequestOk == 1)
    {
        return 0;
    }
    else
    {
        return 2;
    }
}

/************************************************************************************/
/* function Name : addDate                                */
/* description    : adds n number of days to the existing date                */
/* author         : Techno                            */
/* date       : 16/12/2005                                */
/* parameters     : char cDate[] - the date in format (yyyy-mm-dd)            */
/*            int noOfDays - the number of days to be added            */
/*            char cBuff[] - the result Date                    */
/* retrun value   : nothing                                */   
/************************************************************************************/

void addDate(char cDate1[20],int noOfDays, char cBuff[20])
{

    /*define the delimiter of date format */
   
      const char* delimiter = "-";
   
    /* following varibales are required to hold the parsed date fields */
   
    int nYear;
    int nMonth;
    int nDay;
    int nIndex;   
    char cDate[20];
    strcpy(cDate,cDate1);
   
    /* exctract the indivisual fields from the date */
   
    nYear  = atoi(strtok(cDate,delimiter));
    nMonth = atoi(strtok(NULL,delimiter));
    nDay   = atoi(strtok(NULL,delimiter));
   
    /*loop through the noOfDays and go on adding 1 day at a time to the date */
   
    for(nIndex=0;nIndex<noOfDays;nIndex++)
    {
        nDay++; /* increment the day*/
       
        /* check for the months with 31 days */
       
        if (nMonth == 1 || nMonth == 3 || nMonth ==5 ||nMonth == 7||nMonth == 8 ||nMonth == 10)
        {
            if(nDay > 31)
            {
                nMonth++;
                nDay = 1;
            }
        }
       
        /* check for the months with 30 days */
       
        else if (nMonth == 4 || nMonth == 6 || nMonth ==9 ||nMonth == 11)
        {
            if(nDay > 30)
            {
                nMonth++;
                nDay = 1;
            }
        }
       
        /* check for December month, year incrementation comes into picture if day is 31 */
       
        else if(nMonth == 12)
        {
            if( nDay > 31)
            {
                nMonth = 1;
                nYear++;
                nDay = 1;
            }
        }
        else if( nMonth == 2)
        {
            /* this if statement checks for leap year */
           
            if(nYear%4 == 0 && nYear/100 == 0)
            {
                if(nDay > 29)
                {
                    nDay = 1;
                    nMonth++;
                }
            }
            else
            {
                if(nDay > 28)
                {
                    nDay = 1;
                    nMonth++;
                }
            }
        }
    }
   
    /* Convert the date into standard format (YYYY-MM-DD) */
   
    /* append 0 if day, month < 10) */
    /* and then convert it into string */
       
    if(nDay < 10 && nMonth <  10)
    {           
        sprintf(cBuff,"%d-0%d-0%d",nYear,nMonth,nDay);
    }   
    else if( nDay < 10 && nMonth >= 10)
    {
        sprintf(cBuff,"%d-%d-0%d",nYear,nMonth,nDay);
    }
    else if(nDay >= 10 && nMonth < 10)
    {
        sprintf(cBuff,"%d-0%d-%d",nYear,nMonth,nDay);
    }
    else
    {
        sprintf(cBuff,"%d-%d-%d",nYear,nMonth,nDay);
    }
}

/*********************************************************************/
/*                GETTING MESSAGE FROM THE QUEUE             */
/*********************************************************************/
/*     function name : getMessage                     */
/*     description   : this function gets the message from the queue */
/*               specified                     */
/*     return value  : returns the string (message)              */
/*********************************************************************/
   
char* getMessage(char* cBuff)
 {
   /*   Declare MQI structures needed                                */
   MQOD     od = {MQOD_DEFAULT};    /* Object Descriptor             */
   MQMD     md = {MQMD_DEFAULT};    /* Message Descriptor            */
   MQGMO   gmo = {MQGMO_DEFAULT};   /* get message options           */
     
      /** note, sample uses defaults where it can **/

   MQHCONN  Hcon;                   /* connection handle             */
   MQHOBJ   Hobj;                   /* object handle                 */
   MQLONG   O_options;              /* MQOPEN options                */
   MQLONG   C_options;              /* MQCLOSE options               */
   MQLONG   CompCode;               /* completion code               */
   MQLONG   OpenCode;               /* MQOPEN completion code        */
   MQLONG   Reason;                 /* reason code                   */
   MQLONG   CReason;                /* reason code for MQCONN        */
   MQBYTE   buffer[101];            /* message buffer                */
   MQLONG   buflen;                 /* buffer length                 */
   MQLONG   messlen;                /* message length received       */
   char    QMName[50]="HiltonHotel";/* queue manager name            */
 
   char cmd[150];
 
   /******************************************************************/
   /*                                                                */
   /*   Create object descriptor for subject queue                   */
   /*                                                                */
   /******************************************************************/
   strcpy(od.ObjectName, "HILTONHOTELQUEUE");
  
   /******************************************************************/
   /*                                                                */
   /*   Connect to queue manager                                     */
   /*                                                                */
   /******************************************************************/
  printf("Connecting to Queue manager=> %s\n",QMName);
   MQCONN(QMName,                  /* queue manager                  */
          &Hcon,                   /* connection handle              */
          &CompCode,               /* completion code                */
          &CReason);               /* reason code                    */

   /* report reason and stop if it failed     */
   if (CompCode == MQCC_FAILED)
   {
     printf("MQCONN ended with reason code %d\n", CReason);
     exit( (int)CReason );
   }

   /******************************************************************/
   /*                                                                */
   /*   Open the named message queue for input; exclusive or shared  */
   /*   use of the queue is controlled by the queue definition here  */
   /*                                                                */
   /******************************************************************/

 
     O_options = MQOO_INPUT_AS_Q_DEF    /* open queue for input      */
               | MQOO_FAIL_IF_QUIESCING /* but not if MQM stopping   */
               ;                        /* = 0x2001 = 8193 decimal   */
 
   MQOPEN(Hcon,                      /* connection handle            */
          &od,                       /* object descriptor for queue  */
          O_options,                 /* open options                 */
          &Hobj,                     /* object handle                */
          &OpenCode,                 /* completion code              */
          &Reason);                  /* reason code                  */

   /* report reason, if any; stop if failed      */
   if (Reason != MQRC_NONE)
   {
     printf("MQOPEN ended with reason code %d\n", Reason);
   }

   if (OpenCode == MQCC_FAILED)
   {
     printf("unable to open queue for input\n");
   }

   /******************************************************************/
   /*                                                                */
   /*   Get messages from the message queue                          */
   /*   Loop until there is a failure                                */
   /*                                                                */
   /******************************************************************/
   CompCode = OpenCode;       /* use MQOPEN result for initial test  */

   /******************************************************************/
   /* Use these options when connecting to Queue Managers that also  */
   /* support them, see the Application Programming Reference for    */
   /* details.                                                       */
   /* These options cause the MsgId and CorrelId to be replaced, so  */
   /* that there is no need to reset them before each MQGET          */
   /******************************************************************/
   /*gmo.Version = MQGMO_VERSION_2;*/ /* Avoid need to reset Message */
   /*gmo.MatchOptions = MQMO_NONE; */ /* ID and Correlation ID after */
                                      /* every MQGET                 */
   gmo.Options = MQGMO_WAIT       /* wait for new messages           */
               + MQGMO_CONVERT;   /* convert if necessary            */
   gmo.WaitInterval = 15000;      /* 15 second limit for waiting     */

     buflen = sizeof(buffer) - 1; /* buffer size available for GET   */

     /****************************************************************/
     /* The following two statements are not required if the MQGMO   */
     /* version is set to MQGMO_VERSION_2 and and gmo.MatchOptions   */
     /* is set to MQGMO_NONE                                         */
     /****************************************************************/
     /*                                                              */
     /*   In order to read the messages in sequence, MsgId and       */
     /*   CorrelID must have the default value.  MQGET sets them     */
     /*   to the values in for message it returns, so re-initialise  */
     /*   them before every call                                     */
     /*                                                              */
     /****************************************************************/
     memcpy(md.MsgId, MQMI_NONE, sizeof(md.MsgId));
     memcpy(md.CorrelId, MQCI_NONE, sizeof(md.CorrelId));

     /****************************************************************/
     /*                                                              */
     /*   MQGET sets Encoding and CodedCharSetId to the values in    */
     /*   the message returned, so these fields should be reset to   */
     /*   the default values before every call, as MQGMO_CONVERT is  */
     /*   specified.                                                 */
     /*                                                              */
     /****************************************************************/

     md.Encoding       = MQENC_NATIVE;
     md.CodedCharSetId = MQCCSI_Q_MGR;

     MQGET(Hcon,                /* connection handle                 */
           Hobj,                /* object handle                     */
           &md,                 /* message descriptor                */
           &gmo,                /* get message options               */
           buflen,              /* buffer length                     */
           buffer,              /* message buffer                    */
           &messlen,            /* message length                    */
           &CompCode,           /* completion code                   */
           &Reason);            /* reason code                       */

     /* report reason, if any     */
     if (Reason != MQRC_NONE)
     {  
         printf("MQGET ended with reason code %d\n", Reason);

         /*   treat truncated message as a failure for this sample   */
         if (Reason == MQRC_TRUNCATED_MSG_FAILED)
         {
           CompCode = MQCC_FAILED;
         }
     }
    
   /******************************************************************/
   /*                                                                */
   /*   Close the source queue (if it was opened)                    */
   /*                                                                */
   /******************************************************************/
   if (OpenCode != MQCC_FAILED)
   {
       C_options = MQCO_NONE;        /* no close options             */
    
     MQCLOSE(Hcon,                    /* connection handle           */
             &Hobj,                   /* object handle               */
             C_options,
             &CompCode,               /* completion code             */
             &Reason);                /* reason code                 */

     /* report reason, if any     */
     if (Reason != MQRC_NONE)
     {
       printf("MQCLOSE ended with reason code %d\n", Reason);
     }
   }

   /******************************************************************/
   /*                                                                */
   /*   Disconnect from MQM if not already connected                 */
   /*                                                                */
   /******************************************************************/
   if (CReason != MQRC_ALREADY_CONNECTED )
   {
     MQDISC(&Hcon,                     /* connection handle          */
            &CompCode,                 /* completion code            */
            &Reason);                  /* reason code                */

     /* report reason, if any     */
     if (Reason != MQRC_NONE)
     {
       printf("MQDISC ended with reason code %d\n", Reason);
     }
   }

   buffer[messlen] = '\0';            /* add terminator          */  
   cBuff = buffer;
   return cBuff;
     
 }

 /*********************************************************************/
 /*         PUTTING THE RESPONSE MESSAGE INTO THE QUEUE           */   
 /*********************************************************************/
 /*  function Name : putMessage                              */ 
 /*  description   : the function puts the message into the queue     */
 /*  return value  : an integer                          */
 /*********************************************************************/
    
 int putMessage(char cBuff[101])
 {
   /*  Declare file and character for sample input                   */
   FILE *fp;

   /*   Declare MQI structures needed                                */
   MQOD     od = {MQOD_DEFAULT};    /* Object Descriptor             */
   MQMD     md = {MQMD_DEFAULT};    /* Message Descriptor            */
   MQPMO   pmo = {MQPMO_DEFAULT};   /* put message options           */
      /** note, sample uses defaults where it can **/

   MQHCONN  Hcon;                   /* connection handle             */
   MQHOBJ   Hobj;                   /* object handle                 */
   MQLONG   O_options;              /* MQOPEN options                */
   MQLONG   C_options;              /* MQCLOSE options               */
   MQLONG   CompCode;               /* completion code               */
   MQLONG   OpenCode;               /* MQOPEN completion code        */
   MQLONG   Reason;                 /* reason code                   */
   MQLONG   CReason;                /* reason code for MQCONN        */
   MQLONG   messlen;                /* message length                */
   char     buffer[101];            /* message buffer                */
   char     QMName[50]="HiltonHotel";/* queue manager name            */

   strcpy(buffer,cBuff);
   printf("\nPutting the response message...");
  
   /******************************************************************/
   /*                                                                */
   /*   Connect to queue manager                                     */
   /*                                                                */
   /******************************************************************/
  
   MQCONN(QMName,                  /* queue manager                  */
          &Hcon,                   /* connection handle              */
          &CompCode,               /* completion code                */
          &CReason);               /* reason code                    */

   /* report reason and stop if it failed     */
   if (CompCode == MQCC_FAILED)
   {
     printf("MQCONN ended with reason code %d\n", CReason);
     exit( (int)CReason );
   }

   /******************************************************************/
   /*                                                                */
   /*   Use parameter as the name of the target queue                */
   /*                                                                */
   /******************************************************************/
  
   strncpy(od.ObjectName, "RESPONSEQUEUE", (size_t)MQ_Q_NAME_LENGTH);
   printf("\nTarget Queue=> %s\n", od.ObjectName);

   /******************************************************************/
   /*                                                                */
   /*   Open the target message queue for output                     */
   /*                                                                */
   /******************************************************************/
  
     O_options = MQOO_OUTPUT            /* open queue for output     */
               | MQOO_FAIL_IF_QUIESCING /* but not if MQM stopping   */
               ;                        /* = 0x2010 = 8208 decimal   */

   MQOPEN(Hcon,                      /* connection handle            */
          &od,                       /* object descriptor for queue  */
          O_options,                 /* open options                 */
          &Hobj,                     /* object handle                */
          &OpenCode,                 /* MQOPEN completion code       */
          &Reason);                  /* reason code                  */

   /* report reason, if any; stop if failed      */
   if (Reason != MQRC_NONE)
   {
     printf("MQOPEN ended with reason code %d\n", Reason);
   }

   if (OpenCode == MQCC_FAILED)
   {
     printf("unable to open queue for output\n");
   }
  
       messlen = (MQLONG)strlen(buffer);       /* length without null*/
       if (buffer[messlen-1] == '\n')  /* last char is a new-line    */
       {
         buffer[messlen-1]  = '\0';    /* replace new-line with null */
       }
    

     /****************************************************************/
     /*                                                              */
     /*   Put each buffer to the message queue                       */
     /*                                                              */
     /****************************************************************/
     if (messlen > 0)
     {
      
        memcpy(md.MsgId,           /* reset MsgId to get a new one    */
              MQMI_NONE, sizeof(md.MsgId) );

       memcpy(md.CorrelId,        /* reset CorrelId to get a new one */
              MQCI_NONE, sizeof(md.CorrelId) );

       MQPUT(Hcon,                /* connection handle               */
             Hobj,                /* object handle                   */
             &md,                 /* message descriptor              */
             &pmo,                /* default options (datagram)      */
             messlen,             /* message length                  */
             buffer,              /* message buffer                  */
             &CompCode,           /* completion code                 */
             &Reason);            /* reason code                     */

       /* report reason, if any */
       if (Reason != MQRC_NONE)
       {
         printf("MQPUT ended with reason code %d\n", Reason);
       }
     }
     else   /* satisfy end condition when empty line is read */
       CompCode = MQCC_FAILED;
  
   /******************************************************************/
   /*                                                                */
   /*   Close the target queue (if it was opened)                    */
   /*                                                                */
   /******************************************************************/
   if (OpenCode != MQCC_FAILED)
   {
       C_options = MQCO_NONE;        /* no close options             */
      
       MQCLOSE(Hcon,                   /* connection handle            */
             &Hobj,                  /* object handle                */
             C_options,
             &CompCode,              /* completion code              */
             &Reason);               /* reason code                  */

     /* report reason, if any     */
     if (Reason != MQRC_NONE)
     {
       printf("MQCLOSE ended with reason code %d\n", Reason);
     }
   }

   /******************************************************************/
   /*                                                                */
   /*   Disconnect from MQM if not already connected                 */
   /*                                                                */
   /******************************************************************/
   if (CReason != MQRC_ALREADY_CONNECTED)
   {
     MQDISC(&Hcon,                   /* connection handle            */
            &CompCode,               /* completion code              */
            &Reason);                /* reason code                  */

     /* report reason, if any     */
     if (Reason != MQRC_NONE)
     {
       printf("MQDISC ended with reason code %d\n", Reason);
     }
   }

   /******************************************************************/
   /*                                                                */
   /* END OF AMQSPUT0                                                */
   /*                                                                */
   /******************************************************************/
   printf("\nRESPONSE MESSAGE HAS BEEN SENT\n");
   return(0);
 }

/************************************************************************************/
/* function name  : deleteEntry                                      */
/* description    : Deletes the specified entries from the specified file passed as */
/*            parameters                                */
/* author         : Techno                            */
/* date       : 16/12/2005                                */
/* parameters     : char fileName[] - the textfile to process                */
/*            char find[]     - the string to find                */
/*                  int noOfRooms   - the number of rooms to be cancelled        */   
/* retrun value   : returns 0 on SUCCESS                           */
/*            return 1 on FAILURE                            */
/************************************************************************************/

int deleteEntry(char fileName[20],char find[20],int noOfRooms)
{
    FILE *fp,*fp1;         /* Take two file pointers */
    char cLineRead[20];     /* to hold the date read from the file */
    char cString[11];       /* to hold the string date */
    int nCount = 0;        /* an integer counter */
   
    /* keep original count */
   
    nCount = noOfRooms;   
   
    printf("\nCancelling from [%s], the date [%s]... \n",fileName,find);
   
    /* open the file for reading */
   
    fp = fopen(fileName,"r");
   
    /* open another temperory file for writing */
   
    fp1 = fopen("temp","w");
   
    /* check for failures */
   
    if (fp == NULL || fp1 == NULL)
    {
        fprintf(stderr,"Unable to open file...\n");
        return 1;
    }
   
    /* read from the file until EOF is reached */
    /* copy all the contents from file1 into temp file leaving the matched records */
   
    while (fscanf(fp,"%s",cLineRead) != EOF)
    {
        strcpy(cString,cLineRead);       
        if(strlen(cLineRead)>8)
        {
            if ((strcmp(find,cLineRead) == 0) && (noOfRooms != 0))
            {
                /* one record found, so decrement the no of rooms */
                /* and don't write this record into temp file */
                noOfRooms--;               
            }
            else
            {
                /* no match, so write this record into the temp file */
               
                fprintf(fp1,"%s\n",cLineRead);               
            }
        }
    }
   
    /* close file handles */
   
    fclose(fp);
    fclose(fp1);
   
    /* delete the original file */
    remove(fileName);
   
    /* rename the temp file to the original file */
   
    rename("temp",fileName);
   
    if (noOfRooms == 0) /* means all the rooms requested have been cancelled successfully */
    {
        printf("\n%d Room(s) cancelled...\n",nCount);
    }   
}

/*****************************************************************************************************/
/*                   THE MAIN PROGRAM STARTS HERE                             */
/*****************************************************************************************************/
/*   function Name : main                                         */   
/*   description   : -gets the request message from the queue                         */
/*             -processes the message by calling other functions                     */
/*             -prepares response message and puts into the responsequeue                 */
/*   return value  : return 0                                         */    
/*****************************************************************************************************/
     
int main()
{
    /* Following variables are used to hold parsed message */
   
    char string[50];         /* to hold the request message read */
    char bookingId[5];       /* to hold Booking ID */
    char fromDate[15];       /* to hold start date */
    char toDate[20];         /* to hold end date   */
    char typeOfRoom[10];     /* contains the type of room requested */
    int roomsRequested;      /* to number of rooms requested */
    int nIndex,nIndex1;      /* for indexing in loops */
    char *tokens[5];         /* intermediate char arry to hold parsed tokens */
    char cLineRead[20];      /* to hold the data read from the file*/
    int price;         /* to hold price of particular room read from file */
    int rooms;         /* number of rooms */
    int bytes=0;         /* required for seeking the file */
    int availableRooms;     /* holds the number of rooms available */
    char roomType[5];     /* holds either RT1,RT2 or RT3 (Room Type)*/
    char cBuff[20];         /* a buffer to pass to addDate function, in which result is put */
    char find[20];           /* a string to search in the text file */
    char replace[20];     /* another string to replace with */
    int success = -1;     /* an integer flag to indicate the action is success or not */
    char cDate1[20];     /* to hold the date in the form of string */
    char dateBuff[20];     /* temporary buffer to hold the date */
    int confirmed=-1;     /* a flag to hold whether or not the requested has been confirmed or not */
    int cost;         /* to hold the total cost the hotel reservation */
    char responseMessage[50];/* to put the response message when ready */
    char cRequestType[20];   /* to check if request message is for cancelation */
    FILE *fp1,*fp2;         /* file handles */       
    const char delimiter[] = ":";/*define the delimiter*/
    char* message=NULL;
   
    /* call the getMessage function to retrieve request message from the Queue */
    /* and copy the message into string character arrat */
   
    strcpy(string, getMessage(message));
   
    /* Check how many fields the message contains */
    /* parse the message into indivisual tokens */
   
    printf(" ********** Parse Details *******\n");
       
    strcpy(bookingId,strtok (string, delimiter));    /* get BookingId   */
    strcpy(fromDate,strtok (NULL, delimiter));       /* get start Date  */
    strcpy(toDate,strtok (NULL, delimiter));         /* get end Date    */
    strcpy(typeOfRoom,strtok (NULL, delimiter));     /* get type of room*/
    roomsRequested = atoi(strtok (NULL, delimiter)); /* get no of rooms */
    strcpy(cRequestType,strtok(NULL,delimiter));
   
    printf("\nBooking ID      =>  %s"
            "\nStart Date      =>  %s"
        "\n End Date       =>  %s"
        "\nType Of Room    =>  %s"
        "\nRooms requested =>  %d"
        "\nRequest Type    =>  %s\n",bookingId,fromDate,toDate,typeOfRoom,roomsRequested,cRequestType);
   
    /* processing of the tokens starts here*/
   
    if (strcmp(typeOfRoom,"Suite")==0)
    {
        bytes = 0;
        strcpy(roomType,"RT1");
    }
    else if (strcmp(typeOfRoom,"Single")==0)
    {
        bytes = 11;
        strcpy(roomType,"RT2");
    }
    else if (strcmp(typeOfRoom,"Double")==0)
    {
        bytes = 22;
        strcpy(roomType,"RT3");
    }
   
    fp1 = fopen("rooms.txt","r");
    if (fp1 == NULL)
    {
        fprintf(stderr,"Error:Unable to open file rooms.txt");
        return 1;
    }
       
    /* move the file pointer to by 'bytes' position*/
           
    fseek(fp1,bytes,SEEK_CUR);
   
    /* after moving the file pointer, read the file now */
   
    if(fgets(cLineRead, 11, fp1)==NULL)
    {
        fprintf(stderr,"Error: Unable to read file rooms.txt...");
    }
   
    /* parse the data read */
       
    strcpy(cBuff,strtok (cLineRead, delimiter));
    price= atoi(strtok (NULL, delimiter));
    availableRooms=atoi(strtok (NULL, delimiter));
   
    /* attach the extension to the file */
   
    strcat(typeOfRoom,".txt");
   
    /* check the type of request (whether "Booking" or "Cancel")*/
   
    if(strcmp(cRequestType,"Cancel")==0)
    {
            /* code to cancel the seats */
       
        printf("Canceling the bookings...\n");
       
        /* form the string in the format (RT1:200:04, ie Type of room:Cost:noOfRooms) */
       
        strcpy(find,roomType);
        sprintf(cBuff,":%d",price);
        strcat(find,cBuff);
        strcpy(replace,find);
       
        printf("\nUpdating changes...");
        strcpy(find,roomType);
        sprintf(cBuff,":%d",price);
        strcat(find,cBuff);
        strcpy(replace,find);
        nIndex1 = (availableRooms + roomsRequested);
       
        /* format the string */
       
        if(nIndex1<10)
        {
       
            sprintf(cBuff,":0%d",nIndex1);
        }
        else
        {
            sprintf(cBuff,":%d",nIndex1);
        }
        strcat(replace,cBuff);
       
        if(availableRooms < 10)
        {       
            sprintf(cBuff,":0%d",availableRooms);
        }
        else
        {
            sprintf(cBuff,":%d",availableRooms);
        }
        strcat(find,cBuff);
       
        /* Call the updateRoomsDetails with the strings find and replace as parameters */
               
        if(!updateRoomDetails("rooms.txt",find,replace))
        {
            puts("Changing...\n");
        }       
        /* Delete the entry from the respective files */
       
        addDate(toDate,1,cBuff);
        deleteEntry(typeOfRoom,cBuff,roomsRequested);
        printf("Cancellation SUCCESSFULL...\n");
    }
    /* Check the number of rooms available*/   
    else
    {
        if (availableRooms == 0)
        {
            printf("\nWait Searching...\n");
       
            /* Add one day to the to date (On which date  a particular room(s) is(are) going to be checked out*/
           
            addDate(toDate,1,dateBuff);
       
            /* Check from Booked rooms to see if there are available rooms matching the date */
       
            success = checkAvailability(typeOfRoom,fromDate,dateBuff,2);
       
            if(success == 0)
            {
                printf("\nCreating response Message...");
                confirmed = 1;
            }
        }
        else if(availableRooms < roomsRequested) /* requested no of rooms not available */
        {
            printf("\nError: Requested number of rooms not available...");
        }
        else
        {
            /* UPDATE THE ROOM DETAILS... */
                       
            fp2 = fopen(typeOfRoom,"a");
           
            if (fp2 == NULL)
            {
                printf("Error: Unable Book the rooms...");
            }
            else
            {
                for (nIndex = 0; nIndex < roomsRequested; nIndex++)
                {
                    /* Add 1 nDay to the toDate */
                   
                    addDate(toDate,1,dateBuff);
                   
                    /*insert the free Date...*/
                   
                    fprintf(fp2,"%s",dateBuff);
                   
                    /* insert a new line */
                   
                    fprintf(fp2,"%c",'\r');
                }
            }
            printf("\nUpdating changes...");
            strcpy(find,roomType);
            sprintf(cBuff,":%d",price);
            strcat(find,cBuff);
            strcpy(replace,find);
           
            /* convert the string into standard format */
           
            if ( availableRooms < 10 )
            {
                sprintf(cBuff,":0%d",availableRooms);   
            }
            else
            {
                sprintf(cBuff,":%d",availableRooms);
            }
            strcat(find,cBuff);
            rooms = availableRooms - roomsRequested;
            if (rooms < 10 )
            {
                sprintf(cBuff,":0%d",rooms);
            }
            else
            {
                sprintf(cBuff,":%d",rooms);
            }
            strcat(replace,cBuff);
           
            /* Update the rooms.txt to bring the changes into it */
           
            if(!updateRoomDetails("rooms.txt",find,replace))
            {
                printf("\nPreparing response  message...\n");
                confirmed = 1;
            }
            else
            {
                puts("\nUnable to update...");
            }
            /* close the file */
            fclose(fp2);
        }   
        /* close the file */
        fclose(fp1);
       
        printf("\nResponse Message=> ");
       
        /* check the confirmation flag */
       
        if(confirmed == 1)
        {
            /* prepare the response message */
            /* "Hilton" to indicate the server that the message is from Hilton Hotel */
           
            strcpy(responseMessage,"Hilton:");
            strcat(responseMessage,bookingId);
           
            /* Confirmation is "YES" */
           
            strcat(responseMessage,":YES:");
           
            /* Calculate the price */
           
            cost = price * roomsRequested;
           
            /* convert the cost to its string equivalant */
           
            sprintf(cBuff,"%d",cost);
           
            /* copy entire thing into responseMessage */
           
            strcat(responseMessage,cBuff);
           
            printf("%s",responseMessage);
           
            /* Call the putMessage function to put the message into RESPONSEQUEUE  */
           
            putMessage(responseMessage);
        }
        else
        {
            strcpy(responseMessage,"Hilton:");
            strcat(responseMessage,bookingId);
           
            /* Confirmation is "NO" */
           
            strcat(responseMessage,":NO:");
           
            /* So there is no question of cost of rooms, so put 0 */
           
            strcat(responseMessage,"0");
           
            printf("%s",responseMessage);       
           
            /* call putMessage function to the message int RESPONSEQUEUE*/
           
            putMessage(responseMessage);
        }
        }//end of outer else
   
    puts("\n*** TRANSACTION COMPLETED ***\n");
   
    return 0;
}// end main

Tuesday, May 15, 2012

Performance Aspects of Product Development

Performance aspect of any application plays a critical role for user experience. Slower applications frustrate the customers and customers tend to look for faster application from different vendor.   Its good practice to write non-functional requirements also along with functional requirements. If non-functional requirements are not written as product requirements, it is likely that performance aspects are missed to implement during design and implementation phases of the product/application development.  It usually happens that application performance tuning is carried once the customers using the application start expressing their frustrations. The performance improvement activity is carried out as a separate project itself. Not a good practice anyway. There are several ways to look into products/applications to make it work faster.

Capture performance requirements

This is the first step. Customers inputs can be taken in this regard based on their experience of using similar products in the past. The truth is that the customers will be delighted to give inputs; the only thing is they must be asked for it. I remember many customers had made a list of product improvements but they had never expressed them, when we asked their bad experiences with the product, we were surprised to see performance improvements coming in. Specifically define performance numbers for each of the operations of the product. For ex: File Upload shall be completed within 10 seconds, the report shall be generated within 12 seconds. Deciding on these numbers is tricky here. Few prototypes can be tried to see how fast an operation can be carried out after applying all possible performance improvement guidelines.

Have Network Simulators

Each customer can have different network speed.  Non functional requirements must be written basing a network speed may be considering the worst case scenario.  Now the requirements look better. Ex: File Upload shall be completed within 10 seconds at 256KBPS etc.  It is important that every developer in the team uses the same network simulator for getting accurate performance data.

Design the non functional requirements

The poor performance of the product could be because of its design.  This is simply because there are several methods to implement a given product operation. For example by using different algorithms, program logic etc. A simple understandable example is to avoid multiple reads and writes. Read/Writes are always costlier operations. It could be file read/writes, database read/writes or a hardware device read/writes. So reading once the required information and using the program logic gives better performance over reading the information as and when required. This may not be always true; varies from kind of the product/application being developed. The person who has understood the requirements and more importantly the technology involved can best write the better software design.

Avoid unnecessary program Intelligence

Software has to do exactly what it is supposed to do. No extra things. Developers usually tend to add certain intelligence in the program that end customers never wanted. If you are considering performance requirements as Critical To Quality (CTQs), then not even think of adding a line of code that’s not required to meet the requirements.  For example, if a customer registers himself/herself using a registration web page, you just need to give a confirmation text in the same page. It is not required to send an email and mobile text message unless sending an email and text message to mobile is written as end user requirements.

Measure & Improve

In a performance improving activity, most of the time developers will be spending time measuring the time taken to complete an action. Measurement has to happen following a defined system configuration and defined speed. Some of the important parameters to consider are to note the CPU usage, memory usage etc at the time of taking readings. And all the readings are taken at defined parameters. This will help to get accurate data from multiple systems and more importantly merge the data into a single document.

Conclusion

These are high level guidelines.  Any performance tuning subject falls down to writing faster code. There are several web resources to study how to write a faster code. Involving experienced developers is also another thing towards bringing a good performing product.  
Related Posts Plugin for WordPress, Blogger...