public OperationResult UpdateCopier(Copier copier)
        {
            OperationResult operationResult = new OperationResult();

            using (IDbConnection db = new SqlConnection(ConfigurationValues.DeskTopConnection))
            {
                try
                {
                    const string query = "UPDATE [Scanners]"
                        + " SET DeviceName = @DeviceName"
                        + ", SerialNumber = @SerialNumber"
                        + " WHERE ID = @ID";

                    int rowsAffectd = db.Execute(query, new
                    {
                        @DeviceName = copier.DeviceName,
                        @SerialNumber = copier.SerialNumber,
                        @ID = copier.ID
                    });

                    operationResult.Success = true;
                    operationResult.ErrorMessage = "None";
                    return operationResult;
                }
                catch (Exception er)
                {
                    operationResult.Success = true;
                    operationResult.ErrorMessage = er.ToString();
                    return operationResult;
                }
            }
        }
        public OperationResult AddFaxAddressbookEntry(FaxToInformation faxToInformation)
        {
            OperationResult operationResult = new OperationResult();
            try
            {
                string query = "INSERT INTO [FaxSendingInformation]("
                    + "[AccountID],[FirstName],[LastName],[Name],[FaxNumber],[Prefix],[Suffix]"
                    + ")VALUES("
                    + "@AccountID,@FirstName,@LastName,@Name,@FaxNumber,@Prefix,@Suffix)";

                using (SqlConnection db = new SqlConnection(ConfigurationValues.WaldenFaxConnection))
                {
                    int rowsAffectd = db.Execute(query, new
                    {
                        @AccountID = "1001",
                        @FirstName = faxToInformation.FirstName,
                        @LastName = faxToInformation.LastName,
                        @Name = faxToInformation.Name,
                        @FaxNumber = faxToInformation.FaxNumber,
                        @Prefix = faxToInformation.Prefix,
                        @Suffix = faxToInformation.Suffix
                    }
                        );
                }

                operationResult.Success = true;
                return operationResult;
            }
            catch (Exception er)
            {
                operationResult.Success = false;
                operationResult.AddMessage(er.Message);
                return operationResult;
            }
        }
        public OperationResult AddCopier(Copier copier)
        {
            OperationResult operationResult = new OperationResult();

            using (IDbConnection db = new SqlConnection(ConfigurationValues.DeskTopConnection))
            {
                try
                {
                    const string query = "INSERT INTO [Scanners]"
                        + " ("
                        + " [DeviceName],[SerialNumber]"
                        + ")"
                        + "VALUES"
                        + "("
                        + " @DeviceName,@SerialNumber"
                        + ")";

                    int rowsAffectd = db.Execute(query, new
                    {
                        @DeviceName = copier.DeviceName,
                        @SerialNumber = copier.SerialNumber,
                    });

                    operationResult.Success = true;
                    operationResult.ErrorMessage = "None";
                    return operationResult;
                }
                catch (Exception er)
                {
                    operationResult.Success = true;
                    operationResult.ErrorMessage = er.ToString();
                    return operationResult;
                }
            }
        }
        public OperationResult DeleteFaxEntry(int sendToFaxID)
        {
            OperationResult operationResult = new OperationResult();

            using (IDbConnection db = new SqlConnection(ConfigurationValues.WaldenFaxConnection))
            {
                try
                {
                    const string query = "delete from FaxSendingInformation "
                        + " where SendFaxID = @SendFaxID";
                    int rowsAffectd = db.Execute(query, new
                    {
                        @SendFaxID = sendToFaxID.ToString()
                    });

                    operationResult.Success = true;
                    return operationResult;
                }
                catch (Exception er)
                {
                    operationResult.Success = true;
                    operationResult.AddMessage(er.ToString());
                    return operationResult;
                }
            }
        }
        // DELETE: api/Message/5
        public IHttpActionResult Delete(int id)
        {
            OperationResult operationResult = new OperationResult();
            MessageData messageData = new MessageData();
            operationResult = messageData.RemoveMessage(id.ToString());

            if (operationResult.Success)
            {
                return Ok();
            }
            else
            {
                return BadRequest(operationResult.ErrorMessage);
            }
        }
        public OperationResult CreateFaxSendTo(string firstName, string lastName, string faxNumber)
        {
            OperationResult operationResult = new OperationResult();
            try
            {
                faxNumber = faxNumber.Replace("(", "")
                    .Replace(")", "")
                    .Replace(" ", "")
                    .Replace("-", "");

                string query = "INSERT INTO [FaxSendingInformation]("
                    + "[AccountID],[FirstName],[LastName],[Name],[FaxNumber]"
                    + ")VALUES("
                    + "@AccountID,@FirstName,@LastName,@Name,@FaxNumber)";

                using (SqlConnection db = new SqlConnection(ConfigurationValues.WaldenFaxConnection))
                {
                    int rowsAffectd = db.Execute(query, new
                    {
                        @AccountID = "1001",
                        @FirstName = firstName,
                        @LastName = lastName,
                        @Name = firstName + " " + lastName,
                        @FaxNumber = faxNumber
                    }
                        );
                }

                operationResult.Success = true;
                return operationResult;
            }
            catch (Exception er)
            {
                operationResult.Success = false;
                operationResult.AddMessage(er.Message);
                return operationResult;
            }
        }
        private OperationResult ValidatePageCounts(string pathTofile)
        {
            OperationResult operationResult = new OperationResult();
            bool foundBarCode = false;
            string currentUser = Utility.GetUserName();
            int testCounter = 1;
            string currentPatientID = string.Empty;
            string currentTabID = string.Empty;

            Aspose.Pdf.Document pdfDocument = new Aspose.Pdf.Document(pathTofile);
            barCodeText = new List<ScannedDocument>();

            int pageCount = pdfDocument.Pages.Count;

            for (var i = 1; i <= pageCount; i++)
            {
                var converter = new PdfConverter();
                converter.BindPdf(pathTofile);
                converter.StartPage = i;
                converter.EndPage = i;
                converter.RenderingOptions.BarcodeOptimization = true;
                converter.Resolution = new Aspose.Pdf.Devices.Resolution(300);
                converter.DoConvert();
                MemoryStream stream = new MemoryStream();
                converter.GetNextImage(stream, ImageFormat.Png);
                using (BarCodeReader reader = new BarCodeReader(stream, BarCodeReadType.Code39Standard))
                {
                    while (reader.Read())
                    {
                        string[] barCodeDocument = reader.GetCodeText().Split('-');
                        ScannedDocument scannedDocument = new ScannedDocument();
                        scannedDocument.PatientID = barCodeDocument[0];
                        scannedDocument.TabID = barCodeDocument[1];
                        scannedDocument.CurrentPageNumber = int.Parse(barCodeDocument[2]);
                        scannedDocument.PageCount = int.Parse(barCodeDocument[3]);
                        scannedDocument.Text = reader.GetCodeText();
                        scannedDocument.FullPath = pathTofile;
                        scannedDocument.User = currentUser;
                        barCodeText.Add(scannedDocument);
                        foundBarCode = true;
                    }
                }
                converter.Close();
                converter.Dispose();

                if (foundBarCode != true)
                {
                    operationResult.Success = false;
                    operationResult.ErrorMessage = "Job Failed: Could not Read Bar Code";
                    return operationResult;
                }
                foundBarCode = false;
            }

            //Step 1 Check to be sure the number of pages in the document
            //matches the number of pages in the bar code
            int pdfPageCount = 0;
            int pdfPageCountCheck = 0;
            Aspose.Pdf.Document pdfDocumentPageCount = new Aspose.Pdf.Document(barCodeText[0].FullPath);
            pdfPageCount = pdfDocumentPageCount.Pages.Count;

            currentPatientID = barCodeText[0].PatientID;
            currentTabID = barCodeText[0].TabID;

            for (int i = 0; i < barCodeText.Count; i++)
            {
                try
                {
                    if (int.Parse(barCodeText[i].PatientID) < 1)
                    {
                        operationResult.Success = false;
                        operationResult.ErrorMessage = "Patient ID Invalid";
                        return operationResult;
                    }
                }
                catch 
                {
                    operationResult.Success = false;
                    operationResult.ErrorMessage = "Patient ID Invalid";
                    return operationResult;
                }
                try
                {
                    if (int.Parse(barCodeText[i].TabID) < 1)
                    {
                        operationResult.Success = false;
                        operationResult.ErrorMessage = "Tab ID Invalid";
                        return operationResult;
                    }
                }
                catch
                {
                    operationResult.Success = false;
                    operationResult.ErrorMessage = "Tab ID Invalid";
                    return operationResult;
                }

                if (testCounter == barCodeText[i].CurrentPageNumber && barCodeText[i].PageCount == barCodeText[i].CurrentPageNumber && barCodeText[i].PatientID == currentPatientID && barCodeText[i].TabID == currentTabID)
                {
                    //string[] barCodePageCount = barCodeText[i].Text.Split('-');
                    pdfPageCountCheck = pdfPageCountCheck + barCodeText[i].PageCount;
                    testCounter = 1;

                    if (barCodeText[i].PageCount == barCodeText[i].CurrentPageNumber)
                    {

                        try
                        {
                            currentPatientID = barCodeText[i + 1].PatientID;
                            currentTabID = barCodeText[i + 1].TabID;
                        }
                        catch { }
                    }
                }
                else
                {
                    if (testCounter == barCodeText[i].CurrentPageNumber && barCodeText[i].PatientID == currentPatientID && barCodeText[i].TabID == currentTabID)
                    {
                        testCounter++;
                    }
                    else
                    {
                        operationResult.Success = false;
                        operationResult.ErrorMessage = "Job Failed: Documents out of Order";
                        return operationResult;
                    }
                }
            }

            if (pageCount != pdfPageCountCheck)
            {
                operationResult.Success = false;
                operationResult.ErrorMessage = "Job Failed: Documents out of Order";
                return operationResult;
            }

            operationResult.Success = true;
            operationResult.ErrorMessage = "Job Confirmed";
            return operationResult;
        }
        // PUT: api/TagDocument/5
        public IHttpActionResult Put(string id)
        {
            OperationResult operationResult = new OperationResult();
            OperationResult getDocumentArchiveID = new OperationResult();

            DocumentsData documentsData = new DocumentsData();
            CopierData copierData = new CopierData();

            File.Copy(ConfigurationValues.ReviewDocumentPath + id
                , ConfigurationValues.PathToArchiveFolder + id, true);

            File.Copy(ConfigurationValues.ReviewDocumentPath + id
                , ConfigurationValues.ProcessDocumentPath + id, true);

            File.Delete(ConfigurationValues.ReviewDocumentPath + id);

            //CopierData Location
            //PageCount
            //CreationDate
            ReviewScannedDocuments reviewScannedDocuments = new ReviewScannedDocuments();
            //reviewScannedDocuments.CopierLocation = 
            string[] copierLocation = id.Split('_');

            reviewScannedDocuments = new Models.ReviewScannedDocuments();

            FileInfo fileInfo = new FileInfo(ConfigurationValues.ProcessDocumentPath + id);

            //FileAttributes fileAttributes = File.GetAttributes(ConfigurationValues.ProcessDocumentPath + id);

            reviewScannedDocuments.CreationDate = fileInfo.CreationTime.ToShortDateString()
                + " " + fileInfo.CreationTime.ToShortTimeString();
            reviewScannedDocuments.DocumentName = fileInfo.Name;
            reviewScannedDocuments.PageCount = Walden.Medical.Library.Pdf.GetPDFPageCount(ConfigurationValues.ProcessDocumentPath + id);
            reviewScannedDocuments.DocumentPath = ConfigurationValues.PdfFolder + fileInfo.Name;
            reviewScannedDocuments.CopierLocation = copierData.GetCopierLocationName(copierLocation[0]);

            OperationResult operationResult2 = ValidatePageCounts(ConfigurationValues.ProcessDocumentPath + id);

            if (operationResult2.Success != true)
            {

                getDocumentArchiveID = documentsData.ArchiveScannedDocument(reviewScannedDocuments, "F", operationResult2.ErrorMessage);

                File.Copy(ConfigurationValues.ProcessDocumentPath + id,
                    ConfigurationValues.PathToViewErrorFolder + id, true);

                File.Delete(ConfigurationValues.ProcessDocumentPath + id);

                return BadRequest("Please review your documents and try again");
            }

            getDocumentArchiveID = documentsData.ArchiveScannedDocument(reviewScannedDocuments, "T", operationResult2.ErrorMessage);

            documentArchiveID = int.Parse(getDocumentArchiveID.MessageList[0]);

            System.Timers.Timer timer = new System.Timers.Timer();
            timer.Interval = (3000);
            timer.Elapsed += (sender, e) => { HandleTimerElapsed(barCodeText, documentArchiveID); };
            timer.Enabled = true;
            timer.AutoReset = false;

            return Ok();
        }
        public OperationResult DeleteCopier(Copier copier)
        {
            OperationResult operationResult = new OperationResult();

            using (IDbConnection db = new SqlConnection(ConfigurationValues.DeskTopConnection))
            {
                try
                {
                    const string query = "delete from [Scanners]"
                        + " where id = @id";

                    int rowsAffectd = db.Execute(query, new
                    {
                        @id = copier.ID
                    });

                    operationResult.Success = true;
                    operationResult.ErrorMessage = "None";
                    return operationResult;
                }
                catch (Exception er)
                {
                    operationResult.Success = true;
                    operationResult.ErrorMessage = er.ToString();
                    return operationResult;
                }
            }
        }
        public OperationResult ArchiveScannedDocument(ReviewScannedDocuments reviewScannedDocuments, string archived, string errorMessage)
        {
            OperationResult operationResult = new OperationResult();
            string dateTime = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
            using (IDbConnection db = new SqlConnection(ConfigurationValues.DeskTopConnection))
            {
                try
                {
                    const string query = "INSERT INTO [ScannedDocumentsArchive]"
                        + " ([UserName],[CopierDataLocation],[PageCount],[Archive],[SubmittedDate],[CreationDate],[ViewDocumentLocation],[ErrorMessage],[SubmittedToGreenway])"
                        + " VALUES("
                        + "@UserName,@CopierDataLocation,@PageCount,@Archive,@SubmittedDate,@CreationDate,@ViewDocumentLocation,@ErrorMessage,@SubmittedToGreenway);"
                        + " SELECT CAST(SCOPE_IDENTITY() as int)";
                    var newIDCreated = db.Query<int>(query, new
                    {
                        @UserName =  Utility.GetUserName(),
                        @CopierDataLocation = reviewScannedDocuments.CopierLocation,
                        @PageCount = reviewScannedDocuments.PageCount,
                        @Archive = archived,
                        @SubmittedDate = dateTime,
                        @CreationDate = reviewScannedDocuments.CreationDate,
                        @ViewDocumentLocation = ConfigurationValues.ViewErrorDocumentPath + reviewScannedDocuments.DocumentName,
                        @ErrorMessage = errorMessage,
                        @SubmittedToGreenway = "F"
                    });
                    operationResult.AddMessage(newIDCreated.ElementAt(0).ToString());
                    return operationResult;
                }
                catch (Exception er)
                {
                    EmployeeDesktop.API.Exceptions.ExceptionHandling.InsertErrorMessage(er.ToString());
                    EmployeeDesktop.API.Exceptions.ExceptionHandling.SendErrorEmail(er.ToString(), ConfigurationValues.EmailFromFriendly, ConfigurationValues.EmailSendToFriendly, ConfigurationValues.EmailSubject);
                    operationResult.AddMessage("0");
                    operationResult.Success = false;
                    operationResult.ErrorMessage = er.ToString();
                    return operationResult;
                }
            }

            //try
            //{
            //    using (IDbConnection db = new SqlConnection(ConfigurationValues.DeskTopConnection))
            //    {
            //        const string query = "SELECT max(ID) from ScannedDocumentsArchive";
            //        operationResult.AddMessage(db.Query<int>(query).Single().ToString());
            //    }
            //}
            //catch (Exception er)
            //{
            //    EmployeeDesktop.API.Exceptions.ExceptionHandling.InsertErrorMessage(er.ToString());
            //    EmployeeDesktop.API.Exceptions.ExceptionHandling.SendErrorEmail(er.ToString(), ConfigurationValues.EmailFromFriendly, ConfigurationValues.EmailSendToFriendly, ConfigurationValues.EmailSubject);
            //    operationResult.AddMessage("0");
            //}
            //return operationResult;
        }
        public OperationResult AddScannedDocument(List<ScannedDocument> barCodeText, int documentArchiveID)
        {
            OperationResult operationResult = new OperationResult();

            for (int i = 0; i < barCodeText.Count; i++)
            {
                if (barCodeText[i].CurrentPageNumber == barCodeText[i].PageCount)
                {
                    System.Threading.Thread.Sleep(5000);

                    string newlyCreatedfileName = string.Empty;
                    newlyCreatedfileName = CreateDocumentBasedOnPageCount(barCodeText[i]);

                    using (IDbConnection db = new SqlConnection(ConfigurationValues.DeskTopConnection))
                    {
                        try
                        {
                            const string query = "INSERT INTO [ScannedDocuments]("
                                + " [UserName],[DocumentName],[PageCount],[PatientID],[TabID],[DateCreated],[ArchiveID])"
                                + " VALUES(@UserName,@DocumentName,@PageCount,@PatientID,@TabID,@DateCreated,@ArchiveID)";

                            int rowsAffectd = db.Execute(query, new
                            {
                                @UserName = barCodeText[i].User,
                                @DocumentName = newlyCreatedfileName,
                                @DateCreated = DateTime.Now,
                                @PageCount = barCodeText[i].PageCount,
                                @PatientID = barCodeText[i].PatientID,
                                @TabID = barCodeText[i].TabID,
                                @ArchiveID = documentArchiveID
                            });
                        }
                        catch (Exception er)
                        {
                            operationResult.Success = true;
                            operationResult.ErrorMessage = er.ToString();
                            return operationResult;
                        }
                    }
                }
            }

            File.Delete(barCodeText[0].FullPath);
            operationResult.Success = true;
            operationResult.ErrorMessage = "None";
            return operationResult;
        }
        public OperationResult RemoveMessage(string id)
        {
            OperationResult operationResult = new OperationResult();

            try
            {
                using (SqlConnection cn = new SqlConnection(ConfigurationValues.DeskTopConnection))
                {
                    cn.Open();
                    using (SqlCommand cm = cn.CreateCommand())
                    {
                        cm.CommandText = "update [Messages]"
                            + " set showMessage = 'F'"
                            + " where ID = @ID";

                        cm.CommandType = System.Data.CommandType.Text;
                        cm.Parameters.AddWithValue("@ID", id);

                        cm.ExecuteNonQuery();
                        operationResult.Success = true;
                        operationResult.ErrorMessage = "None";
                        return operationResult;
                    }
                }
            }
            catch (Exception er)
            {
                operationResult.Success = true;
                operationResult.ErrorMessage = er.ToString();
                return operationResult;
            }
        }
        public OperationResult SendTheFax(string faxName, string faxPath, string recipientName,
            string faxNumber,string sendID,string applicationPath)
        {
            OperationResult operationResult = new OperationResult();

            FileStream fileStream;
            StreamReader reader = null; ;
            Stream data = null;
            WebResponse response = null;
            StreamWriter streamWriter = null;

            faxName = faxName.Replace("&", "");
            recipientName = recipientName.Replace("&", "");

            try
            {
                fileName = applicationPath + "\\schedule.xml";

                fileStream = File.Create(fileName);

                fileStream.Close();

                streamWriter = File.AppendText(fileName);

                streamWriter.WriteLine("<?xml version=”1.0” encoding=”UTF-8”?>");  
                streamWriter.WriteLine("<schedule_fax>");
                streamWriter.WriteLine("<cover_page>");
                streamWriter.WriteLine("<enabled>false</enabled>");
                streamWriter.WriteLine("</cover_page>");
                streamWriter.WriteLine("<sender>");
                streamWriter.WriteLine("<name>" + faxName + "</name>");
                streamWriter.WriteLine("<email_address>" + sendID + "</email_address>");
                streamWriter.WriteLine("</sender>");
                streamWriter.WriteLine("<recipient>");
                streamWriter.WriteLine("<name>" + recipientName + "</name>");
                streamWriter.WriteLine("<fax_number>" + faxNumber + "</fax_number>");
                streamWriter.WriteLine("</recipient>");
                streamWriter.WriteLine("<attachment>");
                streamWriter.WriteLine("<location>inline</location>");
                streamWriter.WriteLine("<name>test.pdf</name>");
                streamWriter.WriteLine("<receipt_attachment>never</receipt_attachment>");
                streamWriter.WriteLine("<content_type>application/pdf</content_type>");
                streamWriter.WriteLine("<content_transfer_encoding>base64</content_transfer_encoding>");
                streamWriter.WriteLine("<content>");
                streamWriter.WriteLine(EncodePDFDocument(faxPath));
                streamWriter.WriteLine("</content>");
                streamWriter.WriteLine("</attachment>");
                streamWriter.WriteLine("<max_tries>3</max_tries>");
                streamWriter.WriteLine("<priority>1</priority>");
                streamWriter.WriteLine("<try_interval>600</try_interval>");
                streamWriter.WriteLine("<receipt>never</receipt>");
                streamWriter.WriteLine("<receipt_attachment>none</receipt_attachment>");
                streamWriter.WriteLine("</schedule_fax>");

                streamWriter.Close();

                ServicePointManager.Expect100Continue = false;

                //Create a request using a URL that can receive a post. 
                //WebRequest request = WebRequest.Create("http://216.133.69.247/ffws/v1/ofax");

                WebRequest request = WebRequest.Create("http://192.168.105.92/ffws/v1/ofax");


                string authInfo = "admin:admin";
                //string authInfo = userName + ":" + userPassword;
                authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
                request.Headers["Authorization"] = "Basic " + authInfo;

                //Add authentication to request  
                //request.Credentials = new NetworkCredential("admin", "admin");

                //Set the Method property of the request to POST.
                request.Method = "POST";

                //Set the ContentType property of the WebRequest.
                request.ContentType = "application/xml";

                //Get File size
                //FileInfo fileSize = new FileInfo("C:/Users/test/Documents/Visual Studio 2008/Projects/sendFax/sendFax/schedule.xml");
                FileInfo fileSize = new FileInfo(fileName);
                int len = (int)fileSize.Length;


                //Set the ContentLength property of the WebRequest.
                request.ContentLength = len;

                //Get the request stream.
                Stream dataStream = request.GetRequestStream();

                StreamReader textIn = new StreamReader(new FileStream(fileName,
                                                            FileMode.Open, FileAccess.Read));

                string TextLines = textIn.ReadToEnd();
                byte[] byteArray = Encoding.UTF8.GetBytes(TextLines);
                //Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);

                textIn.Close();
                //Close the Stream object.
                dataStream.Close();

                //Get the response.
                response = request.GetResponse();

                //Display the status.
                Console.WriteLine(((HttpWebResponse)response).StatusDescription);

                //Get the stream containing content returned by the server.
                data = response.GetResponseStream();

                //Open the stream using a StreamReader for easy access.
                reader = new StreamReader(data);

                //Read the content.
                string responseFromServer = reader.ReadToEnd();

                //Display the content.
                Console.WriteLine(responseFromServer);

                //Clean up the streams.
                reader.Close();
                data.Close();
                response.Close();
                operationResult.Success = true;
                return operationResult;
            }
            catch(Exception er)
            {
                try
                {
                    //Clean up the streams.
                    reader.Close();
                }
                catch { }
                try
                {
                    data.Close();
                }
                catch { }
                try
                {
                    response.Close();
                }
                catch { }
                try
                {
                    streamWriter.Close();
                }
                catch { }
                operationResult.Success = false;
                operationResult.AddMessage(er.ToString());
                return operationResult;
            }
        }