public void StartMessenger()
        {
            try
            {
                logger.Info("Starting messenger");
                // Connect to the default gateway
                Gateway gateway = database.Gateways.Find(GlobalConstants.DefaultGatewayID);
                if (gateway != null && !string.IsNullOrEmpty(gateway.GatewayConfig))
                {
                    MobileGatewayConfiguration config = EntityHelper.FromCommonRepresentation <MobileGatewayConfiguration>(gateway.GatewayConfig);

                    // Set log level to debug
                    config.LogLevel      = Core.Log.LogLevel.Verbose;
                    config.LogNameFormat = Core.Log.LogNameFormat.Name;
                    //config.LogLocation = @"c:\temp";

                    MessageGateway <IMobileGateway, MobileGatewayConfiguration> messageGateway = MessageGateway <IMobileGateway, MobileGatewayConfiguration> .NewInstance();

                    messenger = messageGateway.Find(config);
                    if (messenger == null)
                    {
                        string errorMsg = string.Format("Error connecting to gateway at port {0}. Check the log file", config.PortName);
                        logger.ErrorFormat(errorMsg);
                        throw new Exception(errorMsg);
                    }
                    messenger.Id = gateway.GatewayID;
                    ConfigureMessenger();
                    logger.InfoFormat("Successfully started messenger. Model is {0}. Port is {1}", messenger.DeviceInformation.Model, config.PortName);
                }
                else
                {
                    logger.Error("Unable to connect to gateway. Make sure you configure a gateway [" + GlobalConstants.DefaultGatewayID + "] in the Gateway database table");
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString(), ex);
            }
        }
        private void StopMessenger()
        {
            try
            {
                if (serviceControlThread != null && serviceControlThread.IsAlive)
                {
                    serviceControlThread.Abort();
                    serviceControlThread = null;
                }

                // Stop messenger
                if (messenger != null)
                {
                    messenger.Disconnect();
                    messenger.Dispose();
                    messenger = null;
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error stoppping messenger", ex);
            }
        }
        /// <summary>
        /// Does the work.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void DoWork(object sender, ElapsedEventArgs e)
        {
            bool isDataConnectionAvailable = false;

            try
            {
                // Disable and wait until finish execution
                this.timer.Enabled = false;

                messenger = messengerService.Messenger;
                if (messenger == null)
                {
                    return;
                }

                if (logger.IsInfoEnabled)
                {
                    logger.Info("Checking unprocessed message");
                }

                // Get unprocessed messages
                List <IncomingMessage> unProcessedMsgs = database.IncomingMesages.Where(msg => msg.Status == IncomingMessage.ProcessingStatus.NotProcessed).ToList <IncomingMessage>();
                if (unProcessedMsgs.Count > 0)
                {
                    logger.Info("Processing " + unProcessedMsgs.Count + " messages");
                    foreach (IncomingMessage msg in unProcessedMsgs)
                    {
                        MessageInformation msgInfo = EntityHelper.FromCommonRepresentation <MessageInformation>(msg.MsgContent);
                        logger.Info("Processing message from " + msgInfo.PhoneNumber);

                        // Check for matching employee

                        string   employeeID = msgInfo.Content;
                        Employee employee   = database.Employees.Find(employeeID);
                        Gateway  gateway    = database.Gateways.Find(GlobalConstants.DefaultGatewayID);
                        if (employee != null && gateway != null)
                        {
                            if (messenger.InitializeDataConnection())
                            {
                                isDataConnectionAvailable = true;

                                // Send MMS
                                Mms mms = Mms.NewInstance(employee.EmployeeName, gateway.GatewayPhoneNumber);

                                // Multipart mixed
                                mms.MultipartRelatedType = MultimediaMessageConstants.ContentTypeApplicationMultipartMixed;
                                mms.PresentationId       = "<0000>";
                                mms.TransactionId        = EntityHelper.GenerateGuid();
                                mms.AddToAddress(msgInfo.PhoneNumber, MmsAddressType.PhoneNumber);

                                MultimediaMessageContent multimediaMessageContent = new MultimediaMessageContent();
                                multimediaMessageContent.SetContent(employee.EmployeePhoto, 0, employee.EmployeePhoto.Length);
                                multimediaMessageContent.ContentId = EntityHelper.GenerateGuid();
                                multimediaMessageContent.Type      = employee.PhotoImageType;
                                mms.AddContent(multimediaMessageContent);
                                if (messenger.Send(mms))
                                {
                                    msg.Status = IncomingMessage.ProcessingStatus.Processed;
                                }
                                else
                                {
                                    msg.Status   = IncomingMessage.ProcessingStatus.Error;
                                    msg.ErrorMsg = messenger.LastError.Message;
                                }
                                database.SaveChanges();
                            }
                            else
                            {
                                logger.Error("Unable to establish a data connection through the modem. Check if you modem support MMS");
                                if (messenger.LastError != null)
                                {
                                    logger.Error(messenger.LastError.ToString());
                                }
                            }
                        }
                        else
                        {
                            // Employee not found
                            msg.Status   = IncomingMessage.ProcessingStatus.Error;
                            msg.ErrorMsg = "Employee not found";
                            database.SaveChanges();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error polling messages", ex);
            }
            finally
            {
                if (isDataConnectionAvailable)
                {
                    messengerService.StartMessenger();
                }
                this.timer.Enabled = true;
            }
        }