public bool MoveIncomingtoReferrerProccessed(int patientID, int incommingProcesID, string fileData, int instituteID, string status, string userId)
        {
            bool flag = false;

            try
            {
                tbl_DT_PatientReferral_Processed processed = new tbl_DT_PatientReferral_Processed();
                var incommingMsg           = _unitOfWork.DT_Incoming_MessageRepo.Get(o => o.ID == incommingProcesID).FirstOrDefault();
                var incommingMsgAttachment = _unitOfWork.DT_Individial_AttachRepo.Get(o => o.InComingMessageID == incommingProcesID).ToList();

                processed.From    = incommingMsg.From;
                processed.To      = incommingMsg.To;
                processed.Subject = incommingMsg.Subject;
                processed.File_Selected_By_User = fileData;
                processed.MessageBody           = incommingMsg.MessageBody;
                processed.Received_TimeStamp    = incommingMsg.Received;
                processed.Processed_TimeStamp   = DateTime.Now;
                processed.PatientID             = patientID;
                processed.Institute_ID          = instituteID;
                processed.Status     = status;
                processed.UserID     = userId;
                processed.Attachment = incommingMsg.Attachment;

                using (TransactionScope scope =
                           new TransactionScope(TransactionScopeOption.Required,
                                                new System.TimeSpan(0, 15, 0)))
                {
                    _unitOfWork.DT_PatientReferral_ProcessedRepo.Insert(processed);
                    _unitOfWork.DT_Incoming_MessageRepo.Delete(incommingProcesID);
                    //if(status=="Rejected")
                    _unitOfWork.Save();


                    foreach (var attachment in incommingMsgAttachment)
                    {
                        attachment.ReferralProcessedID = processed.ID;

                        _unitOfWork.DT_Individial_AttachRepo.Update(attachment);
                        _unitOfWork.Save();
                    }



                    _unitOfWork.Save();

                    scope.Complete();
                    flag = true;
                }
            }
            catch (Exception)
            {
                throw;
            }
            return(flag);
        }
        /// <summary>
        /// Creates a product
        /// </summary>
        /// <param name="productEntity"></param>
        /// <returns></returns>
        public int CreateDTPatient(int incommingMsgID, string userID, string status, int attachmentID)
        {
            try
            {
                tblPatients patient        = new tblPatients();
                tblReferrer referrerRecord = new tblReferrer();
                tblRefAddr  referrerAddr   = new tblRefAddr();

                //  tbl_DT_Incoming_Message_Individual_Attachments tblAttachment = new tbl_DT_Incoming_Message_Individual_Attachments();
                tbl_DT_PatientReferral_Processed processedPatient = new tbl_DT_PatientReferral_Processed();
                var incomingMessagPprocessEntity = (from p in _unitOfWork.DT_Incoming_MessageRepo.Get()
                                                    join e in _unitOfWork.DT_Individial_AttachRepo.Get()
                                                    on p.ID equals e.InComingMessageID
                                                    where p.ID == incommingMsgID && e.ID == attachmentID
                                                    select new DT_IncomingMessagOperationEntity
                {
                    FileData = e.FileData,
                    EmailID = p.From
                }).ToList().FirstOrDefault();
                var DT_Referrer = (from p in _unitOfWork.DT_Referrer_EmailsRepo.Get()
                                   where p.DT_Email_Address == incomingMessagPprocessEntity.EmailID
                                   select p.Institute_ID).FirstOrDefault();

                string xmlString = incomingMessagPprocessEntity.FileData.ToString();

                //referrer = _unitOfWork.DT_Referrer_EmailsRepo.Get(o => o.Institute_ID == PatientWIP.Institute_ID).FirstOrDefault();

                using (StreamReader reader = new StreamReader(GenerateStreamFromString(xmlString), Encoding.Unicode))
                {
                    string oldstr  = "xmlns=\"urn:hl7-org:v3\"";
                    string oldstr1 = "xmlns:sdtc=\"urn:hl7-org:sdtc\"";

                    xmlString = xmlString.Replace(oldstr, "");
                    xmlString = xmlString.Replace(oldstr1, "");
                    XmlDocument xmlDoc = new XmlDocument();
                    xmlDoc.LoadXml(xmlString);

                    var         nameNode          = xmlDoc.SelectNodes("ClinicalDocument/recordTarget/patientRole/patient/name");
                    var         DOBNode           = xmlDoc.SelectNodes("ClinicalDocument/recordTarget/patientRole/patient");
                    var         CityNode          = xmlDoc.SelectNodes("ClinicalDocument/recordTarget/patientRole/addr");
                    var         referrerNode      = xmlDoc.SelectNodes("ClinicalDocument/legalAuthenticator/assignedEntity/assignedPerson/name");
                    var         referrerAddrNode  = xmlDoc.SelectNodes("ClinicalDocument/legalAuthenticator/assignedEntity/addr");
                    var         referrerPhoneNode = xmlDoc.SelectNodes("ClinicalDocument/legalAuthenticator/assignedEntity/telecom");
                    XmlNodeList xnListtelecom     = xmlDoc.SelectNodes("/ClinicalDocument/recordTarget/patientRole/telecom");
                    ////ClinicalDocument//recordTarget//patientRole//patientRole//name
                    foreach (XmlNode subNode in nameNode)
                    {
                        patient.FirstName = subNode["given"].InnerText;
                        patient.LastName  = subNode["family"].InnerText;
                        patient.NickName  = patient.FirstName;
                    }
                    foreach (XmlNode subNode in referrerNode)
                    {
                        string given2 = string.Empty;
                        if (subNode["given"].NextSibling != null)
                        {
                            given2 = subNode["given"].NextSibling.InnerText.ToStringOrEmpty();
                        }
                        referrerRecord.FirstName   = subNode["given"].InnerText.ToStringOrEmpty() + " " + given2;
                        referrerRecord.LastName    = subNode["family"].InnerText.ToStringOrEmpty();
                        referrerRecord.PrintName   = subNode["family"].InnerText.ToStringOrEmpty() + ", " + subNode["given"].InnerText.ToStringOrEmpty() + " " + given2 + subNode["suffix"].InnerText.ToStringOrEmpty();
                        referrerRecord.Credentials = subNode["suffix"].InnerText.ToStringOrEmpty();
                    }
                    referrerRecord.ReferralType      = "DT";
                    referrerRecord.SendPOCBy         = "DT";
                    referrerRecord.createdby         = "DT-Load";
                    referrerRecord.createdts         = DateTime.Now;
                    referrerRecord.updatedby         = "DT-Load";
                    referrerRecord.updatedts         = DateTime.Now;
                    referrerRecord.NoFax             = false;
                    referrerRecord.ReferralInstitute = DT_Referrer;
                    referrerRecord.Title             = "Dr";
                    referrerRecord.NPINumber         = "";
                    referrerRecord.Email             = incomingMessagPprocessEntity.EmailID;
                    foreach (XmlNode subNode in DOBNode)
                    {
                        patient.BirthDate = subNode["birthTime"].Attributes["value"].Value;

                        DateTime dt;
                        if (DateTime.TryParseExact(patient.BirthDate.ToString(), "yyyyMMdd",
                                                   CultureInfo.InvariantCulture,
                                                   DateTimeStyles.None, out dt))
                        {
                            //Console.WriteLine(dt);
                            //  patient.BirthDate = dt.ToString();
                            patient.BirthDate = dt.ToShortDateString();
                        }


                        string gender = subNode["administrativeGenderCode"].Attributes["code"].Value;
                        if (gender.ToLower() == "f")
                        {
                            patient.Gender = "Female";
                        }
                        patient.Title = "Miss";
                        if (gender.ToLower() == "m")
                        {
                            patient.Gender = "Male";
                        }
                        patient.Title = "MR";
                    }
                    foreach (XmlNode subNode in CityNode)
                    {
                        patient.City     = subNode["city"].InnerText;
                        patient.State    = subNode["state"].InnerText;
                        patient.Address1 = subNode["streetAddressLine"].InnerText;
                        patient.ZipCode  = subNode["postalCode"].InnerText;
                    }
                    foreach (XmlNode subNode in referrerAddrNode)
                    {
                        referrerAddr.City          = subNode["city"].InnerText;
                        referrerAddr.State         = subNode["state"].InnerText;
                        referrerAddr.StreetAddress = subNode["streetAddressLine"].InnerText;
                        referrerAddr.ZipCode       = subNode["postalCode"].InnerText;
                        referrerAddr.startdt       = DateTime.Now;
                        referrerAddr.enddt         = DateTime.Now;
                        referrerAddr.createdby     = "DT-Load";
                        referrerAddr.createdts     = DateTime.Now;
                        referrerAddr.updatedby     = "DT-Load";
                        referrerAddr.updatedts     = DateTime.Now;
                    }
                    foreach (XmlNode xn in referrerPhoneNode)
                    {
                        if (xn.Attributes[0].Value == "WP")
                        {
                            var ph = xn.Attributes[1].Value.Replace("-", "").Replace("(", "").Replace(")", "");
                            referrerAddr.PhoneNo = ph.ToStringOrEmpty().Length > 0 ? ph.Substring(6) : "";
                        }
                    }
                    referrerAddr.FaxNo = "";

                    DateTime NowTime         = DateTime.Now;
                    int      M_Current_Day   = NowTime.Day;                           // Current Date with Day Display
                    int      M_Current_Month = Convert.ToInt32(DateTime.Today.Month); //Current Month as a Single Integer Display
                    int      CurrentYear     = DateTime.Today.Year;                   // Display Year as Integer

                    patient.ReferralDate = DateTime.Now.ToShortDateString();          //**what is referral date?

                    patient.updatedts = DateTime.Now.ToShortDateString().StringToDate();
                    patient.createdts = DateTime.Now.ToShortDateString().StringToDate();

                    //patient.ReferralDate = CurrentYear.ToString()+M_Current_Month.ToString()+M_Current_Day.ToString();  //need to find referral date.
                    // patient.ReferralSource = incomingMessagPprocessEntity.EmailID == null ? "noemail" : incomingMessagPprocessEntity.EmailID.Substring(0, 9);

                    // patient.HomePh = "000000000"; //need to find patient phone.

                    foreach (XmlNode xn in xnListtelecom)
                    {
                        if (xn.Attributes[0].Value == "HP")
                        {
                            patient.HomePh = xn.Attributes[1].Value.ToStringOrEmpty().Length > 0 ? xn.Attributes[1].Value.Substring(4) : "";
                        }
                        if (xn.Attributes[0].Value == "WP")
                        {
                            patient.WorkPh = xn.Attributes[1].Value.ToStringOrEmpty().Length > 0 ? xn.Attributes[1].Value.Substring(4) : "";
                        }
                        if (xn.Attributes[0].Value == "MC")
                        {
                            patient.CellPh = xn.Attributes[1].Value.ToStringOrEmpty().Length > 0 ? xn.Attributes[1].Value.Substring(4) : "";
                        }
                    }
                    //patient.ClinicNo = 7;
                    using (RehabEntities rehab = new RehabEntities())
                    {
                        var clinicnumber = (from inc in rehab.tbl_DT_ClinicUserMapping where inc.EmailId == incomingMessagPprocessEntity.EmailID.ToString() select inc.ClinicNo).FirstOrDefault();
                        if (clinicnumber == null)
                        {
                            patient.ClinicNo = Convert.ToInt16(clinicnumber);
                        }
                        else
                        {
                            patient.ClinicNo = 0;
                        }
                    }
                }


                using (var scopeCreate = new TransactionScope())
                {
                    _unitOfWork.ReferrerRepo.Insert(referrerRecord);
                    _unitOfWork.Save();

                    referrerAddr.Rrowid = referrerRecord.Rrowid;
                    _unitOfWork.RefAddrRepo.Insert(referrerAddr);
                    _unitOfWork.Save();



                    patient.ReferralSource = referrerRecord.Rrowid.ToStringOrEmpty();
                    _unitOfWork.PatientEntityRepo.Insert(patient);
                    _unitOfWork.Save();

                    ImportPatient(patient.Prowid, incommingMsgID, userID, status, attachmentID);

                    scopeCreate.Complete();
                    return(patient.Prowid);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }