public HttpResponseMessage SendEnvelope(TemplateSend template)
        {
            HttpResponseMessage responseToClient = new HttpResponseMessage();
            try
            {                
                int displayCode = 0;
                bool flagRole = true;
                System.Collections.Generic.IEnumerable<string> iHeader;
                Request.Headers.TryGetValues("AuthToken", out iHeader);
                string authToken = iHeader.ElementAt(0);
                Envelope envelope = new Envelope();
                Dictionary<string, string> roleDic = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);

                EnvelopeHelperMain objEnvelope = new EnvelopeHelperMain();
                EntityCollection<Recipients> recipients = new EntityCollection<Recipients>();
                Recipients recipint = new Recipients();

                using (var dbContext = new eSignEntities())
                {
                    List<Roles> roleList = new List<Roles>();
                    UserTokenRepository tokenRepository = new UserTokenRepository(dbContext);
                    EnvelopeRepository envelopeRepository = new EnvelopeRepository(dbContext);                    
                    string userEmail = tokenRepository.GetUserEmailByToken(authToken);

                    Guid UserId = tokenRepository.GetUserProfileUserIDByID(tokenRepository.GetUserProfileIDByEmail(userEmail));
                    envelope = envelopeRepository.GetTemplateDetails(template.TemplateCode, UserId);
                    
                    if (envelope == null)
                    {
                        ResponseMessage responseMessage = new ResponseMessage();
                        responseMessage.StatusCode = HttpStatusCode.NoContent;
                        responseMessage.StatusMessage = "NoContent";
                        responseMessage.Message = Convert.ToString(ConfigurationManager.AppSettings["NoContent"].ToString());
                        responseToClient = Request.CreateResponse(HttpStatusCode.NoContent, responseMessage);
                        return responseToClient;                     
                    }

                    envelope.Message = template.MailBody;
                    envelope.Subject = template.MailSubject;
                    roleList = envelopeRepository.GetRoles(envelope.ID);
                    envelope.IsEnvelopeComplete = true;
                    envelope.IsEnvelopePrepare = true;
                    
                    if (template.Recipients.Count != roleList.Count)
                    {
                        ResponseMessage responseMessage = new ResponseMessage();
                        responseMessage.StatusCode = HttpStatusCode.Forbidden;
                        responseMessage.StatusMessage = "Forbidden";
                        responseMessage.Message = Convert.ToString(ConfigurationManager.AppSettings["RolesCount"].ToString());
                        responseToClient = Request.CreateResponse(HttpStatusCode.Forbidden, responseMessage);
                        return responseToClient;   
                    }



                    foreach (var recip in template.Recipients)
                    {
                        flagRole = EnvelopeHelper.IsEmailValid(recip.EmailAddress);
                        if (!flagRole)
                        {
                            ResponseMessage responseMessage = new ResponseMessage();
                            responseMessage.StatusCode = HttpStatusCode.Forbidden;
                            responseMessage.StatusMessage = "Forbidden";
                            responseMessage.Message = Convert.ToString(ConfigurationManager.AppSettings["Email"].ToString());
                            responseToClient = Request.CreateResponse(HttpStatusCode.Forbidden, responseMessage);
                            return responseToClient;   
                        }

                        foreach (var role in roleList)
                        {
                            if (role.Name.ToLower() == recip.Role.ToLower())
                            {
                                recipint.EmailAddress = recip.EmailAddress;
                                recipint.Name = recip.Role;
                                recipint.Order = role.Order;
                                recipint.RecipientTypeID = role.RecipientTypeID;
                                roleDic.Add(recipint.Name, recipint.EmailAddress);
                            }
                        }
                    }
                   


                    foreach (var role in roleList)
                    {
                        if (!roleDic.ContainsKey(role.Name))
                            flagRole = false;

                    }

                    if (!flagRole)
                    {
                        ResponseMessage responseMessage = new ResponseMessage();
                        responseMessage.StatusCode = HttpStatusCode.Forbidden;
                        responseMessage.StatusMessage = "Forbidden";
                        responseMessage.Message = Convert.ToString(ConfigurationManager.AppSettings["RolesCount"].ToString());
                        responseToClient = Request.CreateResponse(HttpStatusCode.Forbidden, responseMessage);
                        return responseToClient;   
                    }

                    string Password = string.Empty;

                    if (envelope.PasswordReqdtoSign)
                    {
                        Password = ModelHelper.Decrypt(envelope.PasswordtoSign, envelope.PasswordKey, (int)envelope.PasswordKeySize);
                        envelope.PasswordtoSign = Password;
                    }
                    else
                        envelope.PasswordtoSign = null;


                    if (envelope.PasswordReqdtoOpen)
                    {
                        Password = ModelHelper.Decrypt(envelope.PasswordtoOpen, envelope.PasswordKey, (int)envelope.PasswordKeySize);
                        envelope.PasswordtoOpen = Password;
                    }
                    else
                        envelope.PasswordtoOpen = null;

                   roleDic.Add("Sender", userEmail);

                   objEnvelope.SetApiCallFlag();
                   bool status = objEnvelope.UpdatedEnvelope(envelope, template.TemplateCode, roleDic, userEmail, out displayCode);
                  if (status == false)
                  {                     
                      ResponseMessage responseMessageFail = new ResponseMessage();
                      responseMessageFail.StatusCode = HttpStatusCode.Ambiguous;
                      responseMessageFail.StatusMessage = "Ambiguous";
                      responseMessageFail.Message = Convert.ToString(ConfigurationManager.AppSettings["EnvelopeFail"].ToString());
                      responseToClient = Request.CreateResponse(HttpStatusCode.OK, responseMessageFail);
                      return responseToClient;
                  }
                }
                ResponseMessageWithEnvID responseMessageSuccess = new ResponseMessageWithEnvID();
                responseMessageSuccess.StatusCode = HttpStatusCode.OK;
                responseMessageSuccess.StatusMessage = "OK";
                responseMessageSuccess.EnvId = displayCode;
                responseMessageSuccess.Message = Convert.ToString(ConfigurationManager.AppSettings["EnvelopeSucess"].ToString());
                responseToClient = Request.CreateResponse(HttpStatusCode.OK, responseMessageSuccess);
                return responseToClient;
            }
            catch (Exception ex)
            {                
                responseToClient = Request.CreateResponse((HttpStatusCode)422);
                responseToClient.Content = new StringContent(Convert.ToString(ConfigurationManager.AppSettings["EnvelopeFail"].ToString()), Encoding.Unicode);
                throw new HttpResponseException(responseToClient);
            }
        }
        public HttpResponseMessage DeleteDocument(string envelopeCode, string id)
        {
            string documentCode = id;
            HttpResponseMessage     responseToClient = new HttpResponseMessage();
            ResponseMessageDocument responseMessage  = new ResponseMessageDocument();
            string documentName = string.Empty;

            try
            {
                System.Collections.Generic.IEnumerable <string> iHeader;
                Request.Headers.TryGetValues("AuthToken", out iHeader);
                string authToken = iHeader.ElementAt(0);

                string tempDirectory      = ConfigurationManager.AppSettings["TempDirectory"].ToString();
                string documentUploadPath = Path.Combine(tempDirectory, envelopeCode, ConfigurationManager.AppSettings["UploadedDocuments"].ToString());
                using (var dbContext = new eSignEntities())
                {
                    EnvelopeHelperMain envelopeHelperMain = new EnvelopeHelperMain();
                    var envelopeRepository = new EnvelopeRepository(dbContext);
                    if (!Directory.Exists(Path.Combine(tempDirectory, envelopeCode)))
                    {
                        responseMessage.StatusCode    = HttpStatusCode.BadRequest;
                        responseMessage.StatusMessage = "BadRequest";
                        responseMessage.Message       = ConfigurationManager.AppSettings["EnvelopeIdMissing"].ToString();
                        responseMessage.EnvelopeId    = envelopeCode;
                        responseToClient = Request.CreateResponse(HttpStatusCode.BadRequest, responseMessage);
                        return(responseToClient);
                    }
                    bool isEnvelopePrepare = envelopeRepository.IsEnvelopePrepare(new Guid(envelopeCode));
                    if (isEnvelopePrepare == true)
                    {
                        responseMessage.StatusCode    = HttpStatusCode.BadRequest;
                        responseMessage.StatusMessage = "BadRequest";
                        responseMessage.Message       = ConfigurationManager.AppSettings["EnvelopePrepared"].ToString();
                        responseMessage.EnvelopeId    = envelopeCode;
                        responseToClient = Request.CreateResponse(HttpStatusCode.BadRequest, responseMessage);
                        return(responseToClient);
                    }
                    DocumentRepository         documentRepository         = new DocumentRepository(dbContext);
                    UnitOfWork                 unitOfWork                 = new UnitOfWork(dbContext);
                    DocumentContentsRepository documentContentsRepository = new DocumentContentsRepository(dbContext);
                    Documents doc          = documentRepository.GetEntity(new Guid(documentCode));
                    string    documentPath = string.Empty;
                    if (doc != null)
                    {
                        documentName = doc.DocumentName;
                        documentPath = Path.Combine(documentUploadPath, documentName);
                    }
                    if (doc == null)
                    {
                        responseMessage.StatusCode    = HttpStatusCode.BadRequest;
                        responseMessage.StatusMessage = "BadRequest";
                        responseMessage.Message       = ConfigurationManager.AppSettings["DocumentIdMissing"].ToString();
                        responseMessage.EnvelopeId    = envelopeCode;
                        responseToClient = Request.CreateResponse(HttpStatusCode.BadRequest, responseMessage);
                        return(responseToClient);
                    }
                    else
                    {
                        UserTokenRepository userTokenRepository = new UserTokenRepository(dbContext);
                        string userEmail        = userTokenRepository.GetUserEmailByToken(authToken);
                        Guid   UserId           = userTokenRepository.GetUserProfileUserIDByID(userTokenRepository.GetUserProfileIDByEmail(userEmail));
                        bool   isEnvelopeExists = envelopeRepository.IsUserEnvelopeExists(UserId, new Guid(envelopeCode));
                        if (!isEnvelopeExists)
                        {
                            responseMessage.StatusCode    = HttpStatusCode.NoContent;
                            responseMessage.StatusMessage = "NoContent";
                            responseMessage.Message       = Convert.ToString(ConfigurationManager.AppSettings["NoContent"].ToString());
                            responseMessage.EnvelopeId    = envelopeCode;
                            responseToClient = Request.CreateResponse(HttpStatusCode.NoContent, responseMessage, Configuration.Formatters.XmlFormatter);
                            return(responseToClient);
                        }
                        Envelope envelope = envelopeRepository.GetEntity(new Guid(envelopeCode));
                        envelopeHelperMain.SetApiCallFlag();
                        envelopeHelperMain.DeleteFile(envelope.Documents.Where(d => d.ID == new Guid(documentCode)).FirstOrDefault().DocumentName, Convert.ToString(envelope.ID), envelope.Documents.Count, envelope);
                        bool documentContentDelete = documentContentsRepository.Delete(doc);
                        bool documentDelete        = documentRepository.Delete(new Guid(documentCode));
                        unitOfWork.SaveChanges();
                        if (documentDelete == true)
                        {
                            responseMessage.StatusCode    = HttpStatusCode.OK;
                            responseMessage.StatusMessage = "OK";
                            responseMessage.Message       = ConfigurationManager.AppSettings["DocumentDeleted"].ToString();
                            responseMessage.EnvelopeId    = envelopeCode;
                            responseToClient = Request.CreateResponse(HttpStatusCode.OK, responseMessage);
                            return(responseToClient);
                        }
                        else
                        {
                            responseMessage.StatusCode    = HttpStatusCode.OK;
                            responseMessage.StatusMessage = "OK";
                            responseMessage.Message       = ConfigurationManager.AppSettings["DocumentDeleted"].ToString();
                            responseMessage.EnvelopeId    = envelopeCode;
                            responseToClient = Request.CreateResponse(HttpStatusCode.OK, responseMessage);
                            return(responseToClient);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                responseToClient         = Request.CreateResponse((HttpStatusCode)422);
                responseToClient.Content = new StringContent(ex.Message, Encoding.Unicode);
                throw new HttpResponseException(responseToClient);
            }
        }