public OperationResult DeleteFaxEntry(int sendToFaxID)
        {
            OperationResult operationResult = new OperationResult();

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

                    operationResult.Success = true;
                    return operationResult;
                }
                catch (Exception er)
                {
                    operationResult.Success = true;
                    operationResult.AddMessage(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.PostOfficeDatabaseConnection))
                {
                    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;
            }
        }
        // POST: api/ImportDocument
        public IHttpActionResult Post([FromBody]ImportDocument importDocument)
        {
            OperationResult operationResult = new OperationResult();

            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Start Import 1");
            operationResult = ProcessBarcodedDocuments(importDocument);
            if (operationResult.Success)
            {
                return Ok();
            }
            else
            {
                return BadRequest(operationResult.MessageList[0]);
            }
        }
        public OperationResult AddPostOfficeFoldersByUser(List<UserFolder> userFolderList)
        {
            DeleteCurrentList(Utility.GetUserName());

            OperationResult operationResult = new OperationResult();

            for (int i = 0; i < userFolderList.Count; i++)
            {
                try
                {
                    string query = "INSERT INTO [PostOfficeFoldersByUser]"
                        + " ("
                        + " [ActiveDirectoryUser]"
                        + " ,[Path]"
                        + " ,[Name]"
                        + " )"
                        + " VALUES"
                        + " ("
                        + " @ActiveDirectoryUser,@Path,@Name"
                        + " )";

                    using (SqlConnection db = new SqlConnection(ConfigurationValues.PostOfficeDatabaseConnection))
                    {
                        db.Execute(query, new
                        {
                            @ActiveDirectoryUser = Utility.GetUserName(),
                            @Path = userFolderList[i].ID,
                            @Name = userFolderList[i].Name
                        }
                            );
                    }

                    operationResult.Success = true;
                    // return operationResult;
                }
                catch (Exception er)
                {
                    operationResult.Success = false;
                    operationResult.AddMessage(er.Message);
                    return operationResult;
                }

            }

            operationResult.Success = true;
            operationResult.ErrorMessage = "None";
            return operationResult;
        }
        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;
            }
        }
        public OperationResult SendTheFax(string faxName, string faxPath, string recipientName,
            string faxNumber,string sendID,string applicationPath)
        {
            OperationResult operationResult = new OperationResult();

            //******************************************************************
            //Testing
            //string test = EncodePdfDocument(faxPath);
            //bytes [] 
            //byte[] base64PdfFile = DecodePdfDocument(test);
            //ByteArrayToFile("D:\\1\\test.pdf", base64PdfFile);
            //*****************************************************


            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;
            }
        }
        private static OperationResult ProcessBarcodedDocuments(ImportDocument newDocumentToImport)
        {

            OperationResult operationResult = new OperationResult();

            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Start Import");
            PostOffice.Api.DataAccess.DocumentRepository documentData = new PostOffice.Api.DataAccess.DocumentRepository();
            CurrentDocuments currentDocument = documentData.GetCurrentDocumentPathPdf(Utility.GetUserName());
            newDocumentToImport.FullPath = currentDocument.PathToCurrentPdfDocument;

            Logging.LogErrors(ConfigurationValues.ErrorLogPath, "Start Creating Base 64");
            try
            {
                System.IO.FileStream inFile;
                byte[] binaryData;

                try
                {
                    inFile = new System.IO.FileStream(newDocumentToImport.FullPath,
                                              System.IO.FileMode.Open,
                                              System.IO.FileAccess.Read);
                    binaryData = new Byte[inFile.Length];
                    inFile.Read(binaryData, 0,
                                         (int)inFile.Length);
                    inFile.Close();
                }
                catch (Exception er)
                {
                    Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                    string[] fileNameArray = newDocumentToImport.FullPath.Split('\\');
                    string fileName = fileNameArray[fileNameArray.Length - 1];
                    File.Copy(newDocumentToImport.FullPath, pathToErrorFolder + fileName, true);
                    operationResult.Success = false;
                    operationResult.AddMessage(er.ToString());
                    return operationResult;
                }

                string base64String;
                try
                {
                    base64String =
                      System.Convert.ToBase64String(binaryData,
                                             0,
                                             binaryData.Length);
                }
                catch (System.ArgumentNullException er)
                {
                    //LogErrors("Binary data array is null.");
                    string[] fileNameArray = newDocumentToImport.FullPath.Split('\\');
                    string fileName = fileNameArray[fileNameArray.Length - 1];
                    File.Copy(newDocumentToImport.FullPath, pathToErrorFolder + fileName, true);
                    operationResult.Success = false;
                    operationResult.AddMessage(er.ToString());
                    return operationResult;
                }

                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "End Base 64");

                ContractBuilder oBuilder = new ContractBuilder();
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "1");
                Greenway.PrimeSuite.DataContracts.Document.DocumentImportChartRequest oRequest = new Greenway.PrimeSuite.DataContracts.Document.DocumentImportChartRequest();
                oRequest.Header = new Greenway.PrimeSuite.DataContracts.API.Header();
                oRequest = oBuilder.BuildDocumentImportChartRequest(base64String);

                oRequest.PrimeSuitePatientId = newDocumentToImport.PatientID;
                oRequest.DocumentTypeID = newDocumentToImport.DocTypeId;
                oRequest.DocumentName = newDocumentToImport.DocumentName;
                oRequest.DocumentDescription = newDocumentToImport.DocumentName + " " + newDocumentToImport.Initials;
                oRequest.DocumentSignerID = int.Parse(ConfigurationValues.ProviderSignerID);
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, "3");
                if (newDocumentToImport.ProviderId.Length > 0)
                {
                    oRequest.DocumentStatus = Greenway.PrimeSuite.DataContracts.Document.DocumentImportDocumentStatusDocumentImportDocumentStatusEnum.InProgress;
                    oRequest.DocumentSignerID = int.Parse(newDocumentToImport.ProviderId);
                }
                oRequest.Credentials.PrimeSuiteCredential.PrimeSuiteUserName = greenwayUserID;
                oRequest.Credentials.PrimeSuiteCredential.PrimeSuiteUserPassword = greenwayUserPassword;

                PostOffice.Api.Document ocall = new PostOffice.Api.Document();

                ocall.SendPdf(oRequest, greenwayServer);
                ArchiveDocument archiveDocument = new ArchiveDocument();

                string[] listOfDocumentsToArchive = currentDocument.CurrentDocumentList.Split('~');
                for (int i = 0; i < listOfDocumentsToArchive.Length - 1; i++)
                {
                    try
                    {
                        string[] documentName = listOfDocumentsToArchive[i].Split('\\');
                        archiveDocument.ArchiveTheDocument(documentName[documentName.Length - 1], listOfDocumentsToArchive[i], Utility.GetUserName());
                        File.Delete(listOfDocumentsToArchive[i]);
                    }
                    catch (Exception er)
                    {
                        Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                        operationResult.Success = true;
                        operationResult.AddMessage("None");
                        return operationResult;
                    }
                }

                operationResult.Success = true;
                operationResult.AddMessage("None");
                return operationResult;
            }
            catch (Exception er)
            {
                Logging.LogErrors(ConfigurationValues.ErrorLogPath, er.ToString());
                string[] fileNameArray = newDocumentToImport.FullPath.Split('\\');
                string fileName = fileNameArray[fileNameArray.Length - 1];
                File.Copy(newDocumentToImport.FullPath, pathToErrorFolder + fileName, true);
                operationResult.Success = false;
                operationResult.AddMessage(er.ToString());
                return operationResult;
            }
        }
        public OperationResult AddPostOfficeFolders(List<FaxFolders> faxFoldersList)
        {
            FaxFolders faxFoldersFullInformation = new FaxFolders();

            DeleteCurrentList(Utility.GetUserName());

            OperationResult operationResult = new OperationResult();

            for (int i = 0; i < faxFoldersList.Count; i++)
            {
                faxFoldersFullInformation = GetFaxingData(faxFoldersList[i].FriendlyName);

                try
                {
                    string query = "INSERT INTO [PostOfficeFoldersByUser]"
                        + " ("
                        + " [ActiveDirectoryUser]"
                        + " ,[PostOfficeFoldersId]"
                        + ")"
                        + " VALUES"
                        + " ("
                        + "@ActiveDirectoryUser,@PostOfficeFoldersId"
                        + " )";
                    {
                        using (SqlConnection db = new SqlConnection(ConfigurationValues.PostOfficeDatabaseConnection))
                        {

                            db.Execute(query, new
                            {
                                @ActiveDirectoryUser = Utility.GetUserName(),
                                @PostOfficeFoldersId = faxFoldersFullInformation.ID
                            }
                                );
                        }
                    }

                }
                catch (Exception er)
                {
                    operationResult.Success = false;
                    operationResult.AddMessage(er.Message);
                    return operationResult;
                }

            }

            operationResult.Success = true;
            operationResult.ErrorMessage = "None";
            return operationResult;
        }
        public OperationResult AddSignatureGroup(SignatureGroup signatureGroup)
        {
            OperationResult operationResult = new OperationResult();
            try
            {
                string query = "INSERT INTO [AnnotationGroups]"
                    + " ("
                    + " [AnnotationGroup]"
                    + ")"
                    + "VALUES"
                    + "("
                    + "@AnnotationGroup"
                    + ")";

                using (SqlConnection db = new SqlConnection(ConfigurationValues.PostOfficeDatabaseConnection))
                {
                    db.Execute(query, new
                    {
                        @AnnotationGroup = signatureGroup.GroupName,
                    }
                        );
                }

                operationResult.Success = true;
                return operationResult;
            }
            catch (Exception er)
            {
                operationResult.Success = false;
                operationResult.AddMessage(er.Message);
                return operationResult;
            }
        }
        public OperationResult AddUserToGroup(UserToGroup userToGroup)
        {
            OperationResult operationResult = new OperationResult();
            try
            {

                string query = "INSERT INTO [AnnotationUserGroups]"
                    + "("
                    + "[GroupId]"
                    + ",[UserName]"
                    + ")"
                    + "VALUES"
                    + " ("
                    + " @GroupId,@UserName"
                    + ")";

                using (SqlConnection db = new SqlConnection(ConfigurationValues.PostOfficeDatabaseConnection))
                {
                    db.Execute(query, new
                    {
                        @UserName = userToGroup.UserName,
                        @GroupId = userToGroup.GroupNameId
                    }
                        );
                }

                operationResult.Success = true;
                return operationResult;
            }
            catch (Exception er)
            {
                operationResult.Success = false;
                operationResult.AddMessage(er.Message);
                return operationResult;
            }
        }