Exemplo n.º 1
0
        public byte[] GetXmlBytes(IDataProtection dataProtection)
        {
            XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();

            xmlWriterSettings.Indent   = true;
            xmlWriterSettings.Encoding = Encoding.UTF8;
            MemoryStream memoryStream = new MemoryStream();
            XmlWriter    xmlWriter    = XmlWriter.Create(memoryStream, xmlWriterSettings);

            using (xmlWriter)
            {
                xmlWriter.WriteStartElement("DataSourceDefinition", "http://schemas.microsoft.com/sqlserver/reporting/2006/03/reportdatasource");
                xmlWriter.WriteElementString("Extension", Extension);
                xmlWriter.WriteElementString("ConnectString", GetConnectionString(dataProtection));
                xmlWriter.WriteElementString("CredentialRetrieval", CredentialsRetrieval.ToString());
                if (CredentialsRetrieval == CredentialsRetrievalOption.Prompt || CredentialsRetrieval == CredentialsRetrievalOption.Store)
                {
                    xmlWriter.WriteElementString("WindowsCredentials", WindowsCredentials.ToString());
                }
                if (CredentialsRetrieval == CredentialsRetrievalOption.Prompt)
                {
                    xmlWriter.WriteElementString("Prompt", string.IsNullOrEmpty(Prompt) ? "" : Prompt);
                }
                if (CredentialsRetrieval == CredentialsRetrievalOption.Store)
                {
                    xmlWriter.WriteElementString("ImpersonateUser", ImpersonateUser.ToString());
                }
                xmlWriter.WriteElementString("Enabled", Enabled.ToString());
                xmlWriter.WriteEndElement();
                xmlWriter.Flush();
                return(memoryStream.ToArray());
            }
        }
Exemplo n.º 2
0
 public void GetServices(BO.Host host)
 {
     host.Services = new List <BO.Service>();
     try
     {
         ImpersonateUser iu = new ImpersonateUser();
         if (!(string.IsNullOrEmpty(host.Username) || string.IsNullOrEmpty(host.Password)))
         {
             iu.Impersonate(host.Domain, host.Username, AES.DecryptString(host.Password));
         }
         System.ServiceProcess.ServiceController[] sc = System.ServiceProcess.ServiceController.GetServices(host.Value);
         foreach (var s in sc)
         {
             host.Services.Add(new BO.Service
             {
                 Name   = s.DisplayName,
                 Value  = s.ServiceName,
                 Status = s.Status
             });
         }
         iu.Undo();
     }
     catch (Exception)
     {
         //OnLog(new BO.LogEventArgs(string.Format("Failed to Connect to Server: {0} [{1}]\r\n", host.Name, host.Value )));
     }
 }
Exemplo n.º 3
0
            public void DeleteFiles(List <String> x)
            {
                SafeTokenHandle safeTokenHandle;
                const int       logon32ProviderDefault  = 0;
                const int       logon32LogonInteractive = 2;
                bool            returnValue             = ImpersonateUser.LogonUser(_gfmusername, "MI", _gfmpassword,
                                                                                    logon32LogonInteractive, logon32ProviderDefault,
                                                                                    out safeTokenHandle);

                if (false == returnValue)
                {
                    int ret = Marshal.GetLastWin32Error();
                    throw new System.ComponentModel.Win32Exception(ret);
                }
                using (safeTokenHandle)
                {
                    using (WindowsIdentity newId = new WindowsIdentity(safeTokenHandle.DangerousGetHandle()))
                    {
                        using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
                        {
                            foreach (var item in x)
                            {
                                if (File.Exists(Path.Combine(_path, item)))
                                {
                                    File.Delete(Path.Combine(_path, item));
                                }
                                else
                                {
                                    throw new FileNotFoundException("The file was not found");
                                }
                            }
                        }
                    }
                }
            }
Exemplo n.º 4
0
        private string exportHeader(string exportPath)
        {
            string uploadfilename = "PFIZER_NUC_PCMS_" + DateTime.UtcNow.ToString("yyyyMMddTHHmmss") + ".txt";
            string fullpath       = Path.Combine(exportPath, uploadfilename);

            using (ImpersonateUser u = new ImpersonateUser())
            {
                DirectoryInfo di = new DirectoryInfo(exportPath);
                if (di.Exists == false)
                {
                    di.Create();
                }
                StreamWriter fileStream = new StreamWriter(fullpath, true);
                try
                {
                    fileStream.WriteLine(N360File.exportHeader());
                }
                catch (Exception e)
                {
                    JobLog(myChannel, BatchStatus.Error, e.Message);
                    SMTPHelper.SendAlertInterface(myChannel.name, e.Message);

                    return(null);
                }
                finally
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
            return(fullpath);
        }
Exemplo n.º 5
0
        bool WindowsStop()
        {
            ImpersonateUser iu = new ImpersonateUser();

            try
            {
                if (!(string.IsNullOrEmpty(this.Username) || string.IsNullOrEmpty(this.Password)))
                {
                    iu.Impersonate(this.Domain, this.Username, AES.DecryptString(this.Password));
                }
                using (ServiceController sc = new ServiceController(this.Value, this.Host))
                {
                    OnLog(new LogEventArgs(string.Format("Stopping {0} on {1}", this.Name, this.Server)));
                    if (sc.Status == ServiceControllerStatus.Stopped)
                    {
                        OnLog(new LogEventArgs(string.Format("Service {0} already stopped on {1}", this.Name, this.Server)));
                        OnProgress(new EventArgs());
                        return(true);
                    }
                    sc.Stop();
                    sc.WaitForStatus(ServiceControllerStatus.Stopped, new TimeSpan(0, 0, this.TimeOut));
                    sc.Refresh();
                    OnLog(new LogEventArgs(string.Format("[{2}] - {0} - {1}", this.Name, sc.Status, this.Server)));
                    OnProgress(new EventArgs());
                    Thread.Sleep(this.StopDelay * 1000);
                    return(sc.Status == ServiceControllerStatus.Stopped);
                }
            }
            finally
            {
                iu.Undo();
            }
        }
Exemplo n.º 6
0
        public static void ExportN360()
        {
            PCMSDBContext db             = new PCMSDBContext();
            string        n360importpath = HttpContext.Current.Server.MapPath("~/Content/xfer/xfer.exe");
            string        xferargs       = @"-z https://secure-transfer.cegedim.com -user:okc_pfizer_kr -password:4azr39 -s:" + HttpContext.Current.Server.MapPath("~/Content/xfer/xfer_n360_export.txt");

            try
            {
                using (ImpersonateUser u = new ImpersonateUser())
                {
                    var processInfo = new ProcessStartInfo(n360importpath, xferargs);
                    processInfo.CreateNoWindow   = false;
                    processInfo.UseShellExecute  = true;
                    processInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/Content/xfer/");

                    var process = Process.Start(processInfo);
                    process.WaitForExit();
                    process.Close();
                }
                // System.Diagnostics.Process.Start(n360importpath, xferargs);
            }
            catch (Exception e)
            {
                Batch batch = new Batch {
                    name = @"XferHelper.ExportN360", message = e.Message, status = BatchStatus.Error
                };
                db.Batchs.Add(batch);
                db.SaveChanges();
            }
        }
Exemplo n.º 7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="mustChange"></param>
        /// <param name="domain"></param>
        public static void User_MustChangePasswordNextLogon(string userName, bool mustChange, string domain)
        {
            if (Common.mustChangedNextLogon == false)
            {
                return;
            }

            ADWrapper ad = new ADWrapper(domain, Common.CnnStringNameAD, performCustomWindowsContextImpersonalization);

            //PrincipalContext pr = new PrincipalContext(ContextType.Domain, domain, "dc=corp,dc=local", username, password);



            if (performCustomWindowsContextImpersonalization)
            {
                using (var impersonation = new ImpersonateUser(ad.LDAPUser, ad.LDAPDomain, ad.LDAPPassword, ImpersonateUser.LOGON32_LOGON_NEW_CREDENTIALS))
                {
                    ad.User_MustChangePasswordNextLogon(userName, mustChange);
                }
            }
            else
            {
                ad.User_MustChangePasswordNextLogon(userName, mustChange);
            }
        }
Exemplo n.º 8
0
        internal static void User_Unlock(string userName, string domain)

        {
            ADWrapper ad = new ADWrapper(domain, Common.CnnStringNameAD, performCustomWindowsContextImpersonalization);

            try
            {
                UnlockAccount2(userName, ad);
            }
            catch (Exception y)
            {
                if (performCustomWindowsContextImpersonalization)
                {
                    using (var impersonation = new ImpersonateUser(ad.LDAPUser, ad.LDAPDomain, ad.LDAPPassword, ImpersonateUser.LOGON32_LOGON_NEW_CREDENTIALS))
                    {
                        ad.User_Unlock(userName);
                    }
                }

                else
                {
                    ad.User_Unlock(userName);
                }


                ad.Dispose();
            }
        }
Exemplo n.º 9
0
 private void EndImpersonation()
 {
     if (ImpersonationHandler.IsNull())
     {
         return;
     }
     ImpersonationHandler.Undo();
     ImpersonationHandler.TryDispose();
     ImpersonationHandler = null;
 }
Exemplo n.º 10
0
        public void DeveExecutarComUmaContaDiferente()
        {
            var account  = "DMZ\\sp.admin";
            var password = "******";

            ImpersonateUser.RunWithAccountAndPassword(() =>
            {
                var currentID = WindowsIdentity.GetCurrent();
                Assert.IsTrue(currentID != null);
            }, account, password);
        }
        public virtual void Delete()
        {
            #region
            using (ImpersonateUser iu = new ImpersonateUser())
            {
                ImpersonateUser.ValidUser(iu, _FileServer.Indentity);

                if (File.Exists(_UploadFileEntity.ServerStorePath))
                {
                    File.Delete(_UploadFileEntity.ServerStorePath);
                }
            }
            #endregion
        }
Exemplo n.º 12
0
        public IHttpActionResult SubmittedAction(List <String> x)
        {
            ImpersonateUser callUser = new ImpersonateUser();

            try
            {
                callUser.DeleteFiles(x);
            }
            catch (Exception e)
            {
                Logger.Error(e.Message);
                return(InternalServerError(e));
            }
            return(Ok(x));
        }
Exemplo n.º 13
0
        private string exportData(List <PforceRXFile> datalist, string exportPath, string backuppath)
        {
            string uploadfilename = "KR_CONSENT_IN_" + DateTime.UtcNow.ToString("yyyyMMdd") + ".txt";
            string fullpath       = Path.Combine(exportPath, uploadfilename);

            using (ImpersonateUser u = new ImpersonateUser())
            {
                DirectoryInfo di = new DirectoryInfo(exportPath);
                if (di.Exists == false)
                {
                    di.Create();
                }
                StreamWriter fileStream = new StreamWriter(new FileStream(fullpath, FileMode.OpenOrCreate, FileAccess.ReadWrite), Encoding.UTF8);
                try
                {
                    fileStream.WriteLine(PforceRXFile.exportHeader());
                    foreach (PforceRXFile n in datalist)
                    {
                        fileStream.WriteLine(n.Export());
                    }
                }
                catch (Exception e)
                {
                    JobLog(myChannel, BatchStatus.Error, e.Message);
                    SMTPHelper.SendAlertInterface(myChannel.name, e.Message);

                    return(null);
                }
                finally
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
                // 백업
                try
                {
                    File.Copy(fullpath, Path.Combine(backuppath, uploadfilename), true);
                }
                catch (Exception e)
                {
                    JobLog(myChannel, BatchStatus.Error, e.Message);
                    SMTPHelper.SendAlertInterface(myChannel.name, e.Message);

                    return(null);
                }
            }
            return(fullpath);
        }
Exemplo n.º 14
0
        private string Base64StringEncode(string ruta)
        {
            var rt = "";

            using (var impersonation = new ImpersonateUser(_ldapSettings.usernameServidor, _ldapSettings.Dominio, _ldapSettings.PasswordServidor))
            {
                WindowsIdentity.RunImpersonated(impersonation.Identity.AccessToken, () =>
                {
                    WindowsIdentity useri = WindowsIdentity.GetCurrent();
                    byte[] AsBytes        = File.ReadAllBytes(ruta);
                    rt = Convert.ToBase64String(AsBytes);
                });
            }

            return(rt);
        }
Exemplo n.º 15
0
        public void Execute()
        {
            JobLog(BatchStatus.Begin);
            myChannel = dbContext.Channels.Find(myChannel.ID);
            //CommonUtil.LogWrite("BatchStatus.Begin");
            Channel channel = dbContext.Channels.Where(c => c.name == @"N360" && c.bound == BoundType.Outbound).FirstOrDefault();
            //ChannelStatus(channel, ActionStatus.Running);
            //CommonUtil.LogWrite("ActionStatus.Running");
            // 미처리 채널 데이터를 파일로 export
            string uploadfilename = exportHeader(channel.path);

            //CommonUtil.LogWrite("exportHeader");
            try
            {
                if (countTargetData() > 0)
                {
                    //CommonUtil.LogWrite("initTargetData Before");
                    List <N360File> flist = initTargetData();
                    // 파일생성
                    //CommonUtil.LogWrite("initTargetData After");
                    exportData(flist, channel.path, uploadfilename);
                    //CommonUtil.LogWrite("exportData ");
                }
                // 업로드
                if (!string.IsNullOrEmpty(channel.exportpath))
                {
                    XferHelper.Call(XferHelper.XferActionEnum.Export, channel.path, channel.exportpath);
                }
                else
                {
                    XferHelper.Call(XferHelper.XferActionEnum.Export, @"xfer_n360_export.txt");
                }
            }
            catch (Exception e)
            {
                JobLog(myChannel, BatchStatus.Error, e.Message);
                SMTPHelper.SendAlertInterface(myChannel.name, e.Message);
            }
            // 백업
            CollectionLog(channel, uploadfilename, channel.exportpath, CollectionStatus.UPLOAD);
            //added by venkat for use service accoutn while accessing file son 5th march 2020
            using (ImpersonateUser u = new ImpersonateUser())
            {
                File.Move(uploadfilename, Path.Combine(channel.backuppath, Path.GetFileName(uploadfilename)));
            }
            JobLog(BatchStatus.Completed);
        }
Exemplo n.º 16
0
        internal static void User_Lock(string userName, string domain)
        {
            ADWrapper ad = new ADWrapper(domain, Common.CnnStringNameAD, false);


            if (performCustomWindowsContextImpersonalization)
            {
                using (var impersonation = new ImpersonateUser(ad.LDAPUser, ad.LDAPDomain, ad.LDAPPassword, ImpersonateUser.LOGON32_LOGON_NEW_CREDENTIALS))
                {
                    ad.User_SetLockedStatus(userName, true);
                }
            }
            else
            {
                ad.User_SetLockedStatus(userName, true);
            }
        }
Exemplo n.º 17
0
        private void Impersonate()
        {
            if (UserName.IsNullOrEmpty() || Password.IsNullOrEmpty())
            {
                return;
            }
            ImpersonationHandler = new ImpersonateUser();
            var domainUser = UserName.Split('\\');
            var userPart   = UserName;
            var domainPart = "";

            if (domainUser.Length == 2)
            {
                userPart   = domainUser[1];
                domainPart = domainUser[0];
            }
            ImpersonationHandler.Impersonate(domainPart, userPart, Password);
        }
Exemplo n.º 18
0
        internal static void User_SetActivation(string userName, bool disabled, string domain)
        {
            ADWrapper ad = new ADWrapper(domain, Common.CnnStringNameAD, false);


            if (performCustomWindowsContextImpersonalization)
            {
                using (var impersonation = new ImpersonateUser(ad.LDAPUser, ad.LDAPDomain, ad.LDAPPassword, ImpersonateUser.LOGON32_LOGON_NEW_CREDENTIALS))
                {
                    ad.User_SetActivation(userName, disabled);
                }
            }
            else
            {
                ad.User_SetActivation(userName, disabled);
            }

            ad.Dispose();
        }
Exemplo n.º 19
0
    static void Main(string[] args)
    {
        /////////////////////////////////////////////////////////////////////
        // Gather the credential information of the impersonated user.
        //

        Console.WriteLine("Before impersonation ...");
        Console.WriteLine("Current user is {0}",
                          WindowsIdentity.GetCurrent().Name);

        Console.WriteLine("Input user name");
        string username = Console.ReadLine();

        Console.WriteLine("Input domain name");
        string domain = Console.ReadLine();

        Console.WriteLine("Input password");
        SecureString password = ImpersonateUser.GetPassword();


        /////////////////////////////////////////////////////////////////////
        // Impersonate the specified user. The impersonation is automatically
        // undone after the Impersonate method.
        //

        ImpersonateUser.Impersonate <object, object>(username,
                                                     domain, password, null, delegate
        {
            Console.WriteLine("\nDuring impersonation ...");
            Console.WriteLine("Current user is {0}",
                              WindowsIdentity.GetCurrent().Name);

            // Do the work as the user ...

            return(null);
        });


        Console.WriteLine("\nAfter impersonation is undone ...");
        Console.WriteLine("Current user is {0}",
                          WindowsIdentity.GetCurrent().Name);
    }
Exemplo n.º 20
0
        /// <summary>
        /// Utiliza PrincipalContext y UserPrincipal
        /// </summary>
        /// <param name="usernameToresset"></param>
        /// <param name="domain"></param>
        /// <param name="newPassword"></param>
        /// <param name="UnlockAccount"></param>
        /// <param name="nextlogon">Usuario debe cambiar su clave en proximo logeo</param>
        /// <returns></returns>
        public static Boolean ResetPassword(string usernameToresset, string domain, string newPassword, Boolean UnlockAccount, bool nextLogon = false)
        {
            ADWrapper ad = new ADWrapper(domain, Common.CnnStringNameAD, performCustomWindowsContextImpersonalization);

            //PrincipalContext pr = new PrincipalContext(ContextType.Domain, domain, "dc=corp,dc=local", username, password);



            if (performCustomWindowsContextImpersonalization)
            {
                using (var impersonation = new ImpersonateUser(ad.LDAPUser, ad.LDAPDomain, ad.LDAPPassword, ImpersonateUser.LOGON32_LOGON_NEW_CREDENTIALS))
                {
                    return(ResetPassword2(usernameToresset, newPassword, ad, nextLogon));
                }
            }
            else
            {
                return(ResetPassword2(usernameToresset, newPassword, ad, nextLogon));
            }
        }
        /// <summary>
        /// 文件路径
        /// </summary>
        public virtual string Read(string filePath)
        {
            #region
            var result = "";
            using (ImpersonateUser iu = new ImpersonateUser())
            {
                ImpersonateUser.ValidUser(iu, _FileServer.Indentity);

                if (File.Exists(filePath))
                {
                    using (FileStream reader = File.Open(filePath, FileMode.OpenOrCreate))
                    {
                        var content = new byte[reader.Length];
                        reader.Read(content, 0, content.Length);
                        reader.Close();
                        result = System.Text.Encoding.Default.GetString(content);
                    }
                }
            }
            return result;
            #endregion
        }
Exemplo n.º 22
0
        private void exportData(List <N360File> datalist, string exportPath, string appendfile)
        {
            string uploadfilename = "PFIZER_NUC_PCMS_" + DateTime.UtcNow.ToString("yyyyMMddTHHmmss") + ".txt";
            string fullpath       = Path.Combine(exportPath, uploadfilename);

            if (!string.IsNullOrEmpty(appendfile))
            {
                fullpath = appendfile;
            }

            using (ImpersonateUser u = new ImpersonateUser())
            {
                DirectoryInfo di = new DirectoryInfo(exportPath);
                if (di.Exists == false)
                {
                    di.Create();
                }
                StreamWriter fileStream = new StreamWriter(fullpath, true);
                try
                {
                    foreach (N360File n in datalist)
                    {
                        fileStream.WriteLine(n.Export());
                    }
                }
                catch (Exception e)
                {
                    JobLog(myChannel, BatchStatus.Error, e.Message);
                    SMTPHelper.SendAlertInterface(myChannel.name, e.Message);
                }
                finally
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
        }
        public virtual void Save()
        {
            #region
            if (_UploadFileEntity.Content.Length <= 0)
                return;
            using (ImpersonateUser iu = new ImpersonateUser())
            {
                ImpersonateUser.ValidUser(iu, _FileServer.Indentity);

                string dirPath = Path.GetDirectoryName(_UploadFileEntity.ServerStorePath);
                if (!System.IO.Directory.Exists(dirPath))
                {
                    Directory.CreateDirectory(dirPath);
                }

                using (FileStream writer = File.Open(_UploadFileEntity.ServerStorePath, FileMode.OpenOrCreate))
                {
                    writer.Write(_UploadFileEntity.Content, 0, _UploadFileEntity.Content.Length);
                    writer.Flush();
                    writer.Close();
                }
            }
            #endregion
        }
Exemplo n.º 24
0
        private bool IsUserAccountInfomationValid()
        {
            ImpersonateUser impersonateUser = null;

            try
            {
                SetStatusLabel("Checking account credentials.");

                if (chkUseImpersonation.Checked == true)
                {
                    try
                    {
                        impersonateUser = new ImpersonateUser(txtUserName.Text, txtPassword.Text);

                        Configuration.Default.DefaultUsername = txtUserName.Text;
                        Configuration.Default.DefaultPassword = Encryption.Encrypt(txtPassword.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return(false);
                    }
                }
            }
            finally
            {
                if (impersonateUser != null && impersonateUser.IsImpersonating == true)
                {
                    impersonateUser.Undo();
                }

                SetStatusLabel("Ready.");
            }

            return(true);
        }
Exemplo n.º 25
0
        /// <summary>
        /// Intenta con el método ResetPassword2 y si falla utiliza ResetPassword
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="newPassword"></param>
        /// <param name="domain"></param>
        internal static void User_Reset_Password(string userName, string newPassword, string domain)
        {
            try
            {
                ResetPassword(userName, domain, newPassword, true, Common.mustChangedNextLogon);
            }
            catch (Exception y)
            {
                //userDirectoryEntry.Properties["pwdLastSet"].Value =
                //pwdLastSet = 0  must be changed at the next logon.
                // -1  = This value does the reverse of 0.It makes the password not expired
                //
                int flagmustChangedNextLogon = -1;
                if (Common.mustChangedNextLogon)
                {
                    flagmustChangedNextLogon = 0;
                }

                ADWrapper ad = new ADWrapper(domain, Common.CnnStringNameAD, performCustomWindowsContextImpersonalization);
                //ADWrapper ad3 = new ADWrapper(domain,"reseteos","*R3s3t30s+");

                if (performCustomWindowsContextImpersonalization)
                {
                    using (var impersonation = new ImpersonateUser(ad.LDAPUser, ad.LDAPDomain, ad.LDAPPassword, ImpersonateUser.LOGON32_LOGON_NEW_CREDENTIALS))
                    {
                        ad.User_ResetPwd(userName, newPassword, true, flagmustChangedNextLogon);
                    }
                }
                else
                {
                    ad.User_ResetPwd(userName, newPassword, true, flagmustChangedNextLogon);
                }

                ad.Dispose();
            }
        }
Exemplo n.º 26
0
        public void Execute()
        {
            bool bTrjStarted = false;

            JobLog(BatchStatus.Begin);
            myChannel = dbContext.Channels.Find(myChannel.ID);
            log.Info(MethodBase.GetCurrentMethod().DeclaringType.Name);
            try
            {
                using (ImpersonateUser u = new ImpersonateUser())
                {
                    // 가져오기
                    var filter = new Regex(@"^KR_CONSENT_OUT_\d{8}.txt$");
                    if (Directory.Exists(myChannel.path))
                    {
                        DirectoryInfo di    = new DirectoryInfo(myChannel.path);
                        var           files = di.GetFiles().Where(f => filter.IsMatch(f.Name)).ToList();
                        foreach (var item in files)
                        {
                            //if (!CheckFile(myChannel, item.Name)) comment by Venkat for apaccr-287
                            if (!CheckFile(myChannel, item.FullName))
                            {
                                // 찾았음 표시
                                CollectionLog(myChannel, item.Name, item.FullName, CollectionStatus.DOWNLOAD);
                            }
                        }
                    }

                    ODSMEntities ODSM = new ODSMEntities();

                    // Parsing
                    List <Collection> paringlist = dbContext.Collections.Where(c => c.status == CollectionStatus.DOWNLOAD && c.channelId == myChannel.ID).ToList();
                    foreach (Collection pfile in paringlist)
                    {
                        // 파일이 없는 경우
                        if (!File.Exists(Path.Combine(myChannel.path, pfile.name)))
                        {
                            Collection one = dbContext.Collections.Find(pfile.ID);
                            one.status = CollectionStatus.ERROR;
                            dbContext.SaveChanges();
                            continue;
                        }
                        // 실제 파일 입력
                        using (DbContextTransaction dbTran = upsertContext.Database.BeginTransaction())
                        {
                            bTrjStarted = true;
                            try
                            {
                                // 임포트
                                string       line;
                                PforceRXFile f    = null;
                                StreamReader file = new StreamReader(Path.Combine(myChannel.path, pfile.name));
                                Collection   one  = upsertContext.Collections.Find(pfile.ID);
                                one.status = CollectionStatus.COMPLETED;
                                line       = file.ReadLine();
                                //added by venkat

                                /*Changes done as part of APACCR-287
                                 * Assuming will get Opt Out records first and later Opt In records
                                 * Inserting "Opt Out" record in database if not avaiable and skipiing remaining "Opt In" record in that file with respective to nucleus id and (email/phone)
                                 * done bug fix while loging in collection log changed to pass "full name" of file alonng with ftp details.
                                 * */
                                List <Privacy> inserteddata = new List <Privacy>();
                                // end of comment
                                while ((line = file.ReadLine()) != null)
                                {
                                    string[] arr = line.Split('|');
                                    f = new PforceRXFile(one, arr);


                                    List <Privacy> templist = upsertContext.Privacies.Where(pt => pt.NucleusKey == f.IND_ID && ((pt.EMAIL != null && pt.EMAIL == f.CONSENT_EMAIL) || (pt.MOBILE != null && pt.MOBILE.Replace("-", "") == f.CONSENT_MOBILE.Replace("-", "")))).ToList();

                                    if (inserteddata.Where(insert => insert.NucleusKey == f.IND_ID && ((insert.EMAIL != null && insert.EMAIL == f.CONSENT_EMAIL) || (insert.MOBILE != null && insert.MOBILE.Replace("-", "") == f.CONSENT_MOBILE.Replace("-", "")))).ToList().Count() == 0)
                                    {
                                        // 원키나 PCMSID가 아니라 N키여서 여러 항목이 동시에 삭제될 가능성이 있음.
                                        if (templist.Count() > 0 && !string.IsNullOrEmpty(f.IND_ID) && f.CONSENT_STATUS == false)
                                        {
                                            //comment below line as part of apaccr-287 by venkat on 3/9/2020
                                            /*List<Privacy> templist = upsertContext.Privacies.Where(pt => pt.NucleusKey == f.IND_ID).ToList(); */

                                            foreach (Privacy p in templist)
                                            {
                                                /* comment as part of apaccr-287 by venkat on 3/9/2020
                                                 * p.IND_FIRSTNAME = "*****";
                                                 * p.IND_LASTNAME = "*****";
                                                 * p.IND_FULL_NAME = "*****";
                                                 * p.MOBILE = "*****";
                                                 * p.EMAIL = "*****";
                                                 * p.CONSENT.CONSENT_ABROAD = false;
                                                 * p.CONSENT.CONSENT_SIGN = false;
                                                 * p.CONSENT.CONSENT_TRUST = false;
                                                 * p.CONSENT.CONSENT_USE = false; */
                                                p.Unsubscribe = true;

                                                /* comment as part of apaccr-287 by venkat
                                                 * p.status = PrivacyStatus.ERASED;
                                                 * p.SENDCHANEL &= ~SendChannel.N360; */

                                                upsertContext.Entry(p).State = System.Data.Entity.EntityState.Modified;
                                                upsertContext.PrivacyLogs.Add(new PrivacyLog {
                                                    Privacy = p, creater = @"PFORCERX", changes = @"OptOut NucleusKey :  => " + p.NucleusKey
                                                });
                                                upsertContext.SaveChanges();
                                            }
                                        }
                                        else
                                        {
                                            try
                                            {
                                                Privacy p = new Privacy();
                                                p.pcmsid     = IdGenerater.Generater();
                                                p.IND_ID     = f.IND_ID;
                                                p.NucleusKey = f.IND_ID;

                                                if (f.CONSENT_EMAIL != null && f.CONSENT_EMAIL.Length > 0)
                                                {
                                                    p.EMAIL = f.CONSENT_EMAIL;
                                                }
                                                if (f.CONSENT_MOBILE != null && f.CONSENT_MOBILE.Length > 0)
                                                {
                                                    p.MOBILE = f.CONSENT_MOBILE;
                                                }
                                                p.CONSENT_SOURCE = f.CONSENT_SOURCE;
                                                p.COUNTRY_CD     = f.COUNTRY_CD;
                                                p.Unsubscribe    = !f.CONSENT_STATUS;
                                                p.Consents.Add(new Consent
                                                {
                                                    CONSENT_USE    = f.CONSENT_STATUS,
                                                    CONSENT_TRUST  = f.CONSENT_STATUS,
                                                    CONSENT_ABROAD = f.CONSENT_STATUS,
                                                    CONSENT_SIGN   = f.CONSENT_STATUS,
                                                    CONSENT_DATE   = f.CONSENT_DATE,
                                                    CONSENT_SOURCE = f.CONSENT_SOURCE
                                                });

                                                p.channelId = myChannel.ID;
                                                p.status    = PrivacyStatus.IMPORTED;

                                                VW_CONSENT_ALIGNMENT vca = ODSM.VW_CONSENT_ALIGNMENT.Where(x => x.D_NUC_ID.Equals(f.IND_ID)).FirstOrDefault();
                                                if (vca != null)
                                                {
                                                    p.IND_FULL_NAME = vca.D_NAME;
                                                    p.ZIP           = vca.H_POSTCODE;
                                                    p.WKP_NAME      = vca.H_NAME;
                                                    p.WKP_TEL       = vca.H_PHONE;
                                                    p.FULL_ADDR     = vca.H_ADDR;
                                                    p.IND_SP        = vca.D_SPEC;
                                                    p.OneKey        = vca.D_ONEKEY_ID;
                                                }

                                                upsertContext.Privacies.Add(p);
                                                upsertContext.SaveChanges();

                                                //added by Venkat for apaccr-287
                                                inserteddata.Add(p);
                                                // end of comment

                                                List <string> tracelist = new List <string>();
                                                tracelist.Add("NucleusKey :  => " + p.NucleusKey);
                                                tracelist.Add("OneKey :  => " + p.OneKey);
                                                tracelist.Add("EMAIL :  => " + p.EMAIL);
                                                tracelist.Add("MOBILE :  => " + p.MOBILE);
                                                tracelist.Add("CONSENT_SOURCE :  => " + p.CONSENT_SOURCE);
                                                tracelist.Add("COUNTRY_CD :  => " + p.COUNTRY_CD);
                                                tracelist.Add("IND_FULL_NAME :  => " + p.IND_FULL_NAME);
                                                tracelist.Add("ZIP :  => " + p.ZIP);
                                                tracelist.Add("WKP_NAME :  => " + p.WKP_NAME);
                                                tracelist.Add("WKP_TEL :  => " + p.WKP_TEL);
                                                tracelist.Add("FULL_ADDR :  => " + p.FULL_ADDR);
                                                tracelist.Add("IND_SP :  => " + p.IND_SP);
                                                string changes = tracelist.Aggregate((a, b) => a + ", " + b);
                                                upsertContext.PrivacyLogs.Add(new PrivacyLog {
                                                    Privacy = p, creater = @"PFORCERX", changes = changes
                                                });
                                                upsertContext.SaveChanges();
                                            }
                                            catch (Exception e)
                                            {
                                                JobLog(myChannel, BatchStatus.Error, e.Message);
                                                SMTPHelper.SendAlertInterface(myChannel.name, e.Message);
                                            }
                                        }
                                    }
                                }
                                dbTran.Commit();
                                bTrjStarted = false;
                                file.Close();
                                // Backup으로 이동
                                File.Move(Path.Combine(myChannel.path, pfile.name), Path.Combine(myChannel.backuppath, pfile.name));
                            }
                            catch (Exception e)
                            {
                                log.Error(e);
                                if (bTrjStarted)
                                {
                                    dbTran.Rollback();
                                }
                                JobLog(myChannel, BatchStatus.Error, e.Message);
                                SMTPHelper.SendAlertInterface(myChannel.name, e.Message);
                            }
                            finally
                            {
                                dbTran.Dispose();
                            }
                        }
                    }
                }
                ChannelStatus(myChannel, ActionStatus.Waiting);
                JobLog(BatchStatus.Completed);
            }
            catch (Exception e)
            {
                //added by venkat for exception habding on 5th march 2020
                JobLog(myChannel, BatchStatus.Error, e.Message);
                JobLog(BatchStatus.Completed);
                SMTPHelper.SendAlertInterface(myChannel.name, e.Message);
            }
        }
Exemplo n.º 27
0
 private void EndImpersonation()
 {
     if (ImpersonationHandler.IsNull()) return;
     ImpersonationHandler.Undo();
     ImpersonationHandler.TryDispose();
     ImpersonationHandler = null;
 }
        /// <summary>
        /// 将指定的文件直接写入 HTTP 响应输出流,而不在内存中缓冲该文件。
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="response"></param>
        public virtual bool TransmitFile(string fileName, string filePath, HttpResponse Response)
        {
            #region
            var flag = false;
            using (ImpersonateUser iu = new ImpersonateUser())
            {
                ImpersonateUser.ValidUser(iu, _FileServer.Indentity);

                //if (File.Exists(filePath))
                //{
                //    response.TransmitFile(filePath);
                //    flag = true;
                //}
                System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
                if (fileInfo.Exists == true)
                {
                    Response.ContentType = "application/octet-stream";
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
                    const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
                    byte[] buffer = new byte[ChunkSize];
                    Response.Clear();
                    System.IO.FileStream fileStream = System.IO.File.OpenRead(filePath);
                    long dataTotalLength = fileStream.Length;
                    int readDataLength = 0;
                    while (dataTotalLength > 0 && Response.IsClientConnected)
                    {
                        readDataLength = fileStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));
                        Response.OutputStream.Write(buffer, 0, readDataLength);
                        Response.Flush();
                        dataTotalLength = dataTotalLength - readDataLength;
                    }
                    Response.Close();

                    flag = true;
                }
            }
            return flag;
            #endregion
        }
Exemplo n.º 29
0
        private bool IsUserAccountInfomationValid()
        {
            ImpersonateUser impersonateUser = null;

            try
            {
                SetStatusLabel("Checking account credentials.");

                if (chkUseImpersonation.Checked == true)
                {
                    try
                    {
                        impersonateUser = new ImpersonateUser(txtUserName.Text, txtPassword.Text);

                        Configuration.Default.DefaultUsername = txtUserName.Text;
                        Configuration.Default.DefaultPassword = Encryption.Encrypt(txtPassword.Text);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return false;
                    }
                }
            }
            finally
            {
                if (impersonateUser != null && impersonateUser.IsImpersonating == true)
                    impersonateUser.Undo();

                SetStatusLabel("Ready.");
            }

            return true;
        }
Exemplo n.º 30
0
        private void drpbx_IngestionSource_SelectedValueChanged(object sender, EventArgs e)
        {
            bool result = true;


            SQLFunction sqlfunc = new SQLFunction();

            lstbx_MediaType.Items.Clear();
            lstbx_Publisher.Items.Clear();

            if (Grd_MetaDataPub.ColumnCount > 0)
            {
                Grd_MetaDataPub.DataSource = null;
                Grd_MetaDataPub.Columns.Clear();

                btn_Injestion.BackColor = Color.DimGray;
                btn_Injestion.Enabled   = false;
                btn_Injestion.Refresh();
                System.Windows.Forms.Application.DoEvents();

                btn_Ingestion2.BackColor = Color.DimGray;
                btn_Ingestion2.Enabled   = false;
                btn_Ingestion2.Refresh();
                System.Windows.Forms.Application.DoEvents();


                btn_ErrorLog.BackColor = Color.DimGray;
                btn_ErrorLog.Enabled   = false;
                btn_ErrorLog.Refresh();
                System.Windows.Forms.Application.DoEvents();
            }



            if (drpbx_IngestionSource.SelectedValue.ToString() == "Recorded Books")
            {
                lbl_CompanySelected.Text = "RB";
                lbl_CompanySelected.Refresh();
                System.Windows.Forms.Application.DoEvents();

                ErrorLogCount("RB");
                Check_TitleCount("RB");

                btn_RoyaltyRateDiscount.Visible = true;
                btn_RoyaltyRateDiscount.Enabled = true;

                lbl_Message.Text = "";
                #region 'Populate the MediaType'
                result = sqlfunc.PopulateMediaType("RB", lstbx_MediaType);
                #endregion
            }
            else if (drpbx_IngestionSource.SelectedValue.ToString() == "W F Howes")
            {
                lbl_CompanySelected.Text = "WFH";
                lbl_CompanySelected.Refresh();
                System.Windows.Forms.Application.DoEvents();


                if (System.Configuration.ConfigurationManager.AppSettings["Platform"].ToString().ToLower() != "dev")
                {
                    ImpersonateUser iU = new ImpersonateUser();
                    // TODO: Replace credentials
                    iU.Impersonate();
                }
                ErrorLogCount("WFH");
                Check_TitleCount("WFH");

                btn_RoyaltyRateDiscount.Visible = false;
                btn_RoyaltyRateDiscount.Enabled = false;

                lbl_Message.Text = "";
                #region 'Populate the MediaType'
                result = sqlfunc.PopulateMediaType("WFH", lstbx_MediaType);
                #endregion
            }
            else
            {
                lbl_CompanySelected.Text = "";
                lbl_CompanySelected.Refresh();
                System.Windows.Forms.Application.DoEvents();

                lbl_Message.Text = "";

                lstbx_MediaType.Items.Clear();
                lstbx_Publisher.Items.Clear();
            }

            if (!result)
            {
                lbl_Message.Text = "There has been some problem with your request. Please Check the Error Logs";
            }
        }
Exemplo n.º 31
0
 private void Impersonate()
 {
     if (UserName.IsNullOrEmpty() || Password.IsNullOrEmpty()) return;
     ImpersonationHandler = new ImpersonateUser();
     var domainUser = UserName.Split('\\');
     var userPart = UserName;
     var domainPart = "";
     if (domainUser.Length == 2)
     {
         userPart = domainUser[1];
         domainPart = domainUser[0];
     }
     ImpersonationHandler.Impersonate(domainPart, userPart, Password);
 }
Exemplo n.º 32
0
        public void Execute()
        {
            JobLog(BatchStatus.Begin);
            myChannel = dbContext.Channels.Find(myChannel.ID);
            try
            {
                // 가져오기
                //added by venkat for use service account while accessing file son 5th march 2020
                using (ImpersonateUser u = new ImpersonateUser())
                {
                    using (SftpClient sftp = new SftpClient(myChannel.host, myChannel.account, myChannel.pwd))
                    {
                        try
                        {
                            sftp.Connect();
                            sftp.ChangeDirectory(myChannel.path);
                        }
#pragma warning disable CS0168 // The variable 'e' is declared but never used
                        catch (Exception e)
#pragma warning restore CS0168 // The variable 'e' is declared but never used
                        {
                            JobLog(myChannel, BatchStatus.Error, @"Cannot connect SFTP:" + myChannel.host + "[" + myChannel.account + "/" + myChannel.pwd + "]");
                            JobLog(BatchStatus.Completed);
                            SMTPHelper.SendAlertInterface(myChannel.name, @"Cannot connect SFTP:" + myChannel.host + "[" + myChannel.account + "/" + myChannel.pwd + "]");
                            return;
                        }


                        var filter = new Regex(@"^mms_\d{8}_pcms.csv$");
                        var files  = sftp.ListDirectory(myChannel.path).Where(f => filter.IsMatch(f.Name)).ToList();
                        foreach (var file in files)
                        {
                            if (CheckFile(myChannel, file.FullName))
                            {
                                // 이미 존재 패스
                            }
                            else
                            {
                                // 찾았음 표시
                                CollectionLog(myChannel, file.Name, file.FullName, CollectionStatus.FIND);
                            }
                        }
                        // 다운로드
                        var downloadlist = dbContext.Collections.Where(c => c.status == CollectionStatus.FIND && c.channelId == myChannel.ID);
                        try
                        {
                            foreach (var clt in downloadlist)
                            {
                                Stream fileStream = File.OpenWrite(Path.Combine(myChannel.exportpath, clt.name));
                                sftp.DownloadFile(clt.ftpname, fileStream);
                                CollectionLog(clt, CollectionStatus.DOWNLOAD);
                                fileStream.Flush();
                                fileStream.Close();
                            }
                        }
                        catch (Exception e)
                        {
                            //added by venkat for exception habding on 5th march 2020
                            JobLog(myChannel, BatchStatus.Error, e.Message);
                            JobLog(BatchStatus.Completed);
                            SMTPHelper.SendAlertInterface(myChannel.name, e.Message);
                            return;
                        }

                        sftp.Disconnect();
                    }

                    // Parsing
                    List <Collection> collectionlist = dbContext.Collections.Where(c => c.channelId == myChannel.ID && c.status == CollectionStatus.DOWNLOAD).ToList();
                    foreach (Collection collection in collectionlist)
                    {
                        string       line;
                        StreamReader file;
                        try
                        {
                            file = new StreamReader(Path.Combine(myChannel.exportpath, collection.name));
                        }
                        catch (Exception e)
                        {
                            continue;
                        }
                        line = file.ReadLine();
                        try
                        {
                            List <MMSFile> mms = new List <MMSFile>();

                            while ((line = file.ReadLine()) != null)
                            {
                                string[] arr = line.Split('|');
                                mms.Add(new MMSFile(collection, arr));
                            }
                            file.Close();

                            // privacy 추가
                            foreach (MMSFile m in mms)
                            {
                                Privacy p = new Privacy(
                                    m.COMPANY                       // WKP_NAME
                                    , m.TEL                         // WKP_TEL
                                    , m.ZIP                         // ZIP
                                    , string.Empty                  // PROVINCE
                                    , string.Empty                  // CITY
                                    , m.ADDRESS1                    // DONG
                                    , m.ADDRESS2                    // STREET
                                    , m.ADDRESS1 + " " + m.ADDRESS2 // FUKKADDR
                                    , m.CATEGORY                    // IND_SP
                                    , string.Empty                  // TITLE
                                    , m.NAME                        // FULL_NAME
                                    , m.EMAIL                       // EMAIL
                                    , m.HP                          // MOBILE
                                    , "MMS"                         // CONSENT_SOURCE
                                    , m.SUB_CHANNEL                 // CONSENT_SUB_SOURCE
                                    , string.Empty, string.Empty    // LINK Re / LINK PHONE
                                    , CommonUtil.toUtcDT(m.AGR_DATE)
                                    , m.AGR_VER                     // CONSENT_VERSION
                                    , chkOptIn2(m.AGREE1)
                                    , chkOptIn2(m.AGREE2)
                                    , chkOptIn2(m.AGREE3)
                                    , true
                                    , !chkOptIn2(m.RCV_MAIL)
                                    , true
                                    );
                                p.Channel        = myChannel;
                                p.CONSENT_SOURCE = @"MMS";

                                bool           bExist = false;
                                List <Privacy> tmp    = dbContext.Privacies.Where(pp => pp.EMAIL == m.EMAIL && pp.CONSENT_SOURCE.Equals(@"MMS")).ToList();
                                foreach (Privacy pitem in tmp)
                                {
                                    bExist = true;
                                    Privacy       priv      = pitem;
                                    List <string> tracelist = new List <string>();

                                    if (!IsEqual(m.COMPANY, priv.WKP_NAME))
                                    {
                                        tracelist.Add("근무처(병원명) : " + priv.WKP_NAME + " => " + m.COMPANY);
                                        priv.WKP_NAME = m.COMPANY;
                                    }
                                    if (!IsEqual(m.TEL, priv.WKP_TEL))
                                    {
                                        tracelist.Add("근무지연락처 : " + priv.WKP_TEL + " => " + m.TEL);
                                        priv.WKP_TEL = m.TEL;
                                    }
                                    if (!IsEqual(m.ZIP, priv.ZIP))
                                    {
                                        tracelist.Add("우편번호 : " + priv.ZIP + " => " + m.ZIP);
                                        priv.ZIP = m.ZIP;
                                    }
                                    if (!IsEqual(m.ADDRESS1, priv.DONG))
                                    {
                                        tracelist.Add("주소(군/구/동) : " + priv.DONG + " => " + m.ADDRESS1);
                                        priv.DONG = m.ADDRESS1;
                                    }
                                    if (!IsEqual(m.ADDRESS2, priv.STREET))
                                    {
                                        tracelist.Add("상세주소 : " + priv.STREET + " => " + m.ADDRESS2);
                                        priv.STREET = m.ADDRESS2;
                                    }
                                    string tmpaddr = m.ADDRESS1 + " " + m.ADDRESS2;
                                    if (!IsEqual(tmpaddr, priv.FULL_ADDR))
                                    {
                                        tracelist.Add("주소 : " + priv.FULL_ADDR + " => " + tmpaddr);
                                        priv.FULL_ADDR = tmpaddr;
                                    }
                                    if (!IsEqual(m.CATEGORY, priv.IND_SP))
                                    {
                                        tracelist.Add("진료과 : " + priv.IND_SP + " => " + m.CATEGORY);
                                        priv.IND_SP = m.CATEGORY;
                                    }
                                    if (!IsEqual(m.NAME, priv.IND_FULL_NAME))
                                    {
                                        tracelist.Add("고객명 : " + priv.IND_FULL_NAME + " => " + m.NAME);
                                        priv.IND_FULL_NAME = m.NAME;
                                    }
                                    if (!IsEqual(m.HP, priv.MOBILE))
                                    {
                                        tracelist.Add("핸드폰 : " + priv.MOBILE + " => " + m.HP);
                                        priv.MOBILE = m.HP;
                                    }
                                    if (!IsEqual(m.SUB_CHANNEL, priv.CONSENT_SUB_SOURCE))
                                    {
                                        tracelist.Add("채널(부) : " + priv.CONSENT_SUB_SOURCE + " => " + m.SUB_CHANNEL);
                                        priv.CONSENT_SUB_SOURCE = m.SUB_CHANNEL;
                                    }
                                    if (!chkOptIn2(m.RCV_MAIL) != priv.Unsubscribe)
                                    {
                                        tracelist.Add("수신거부 : " + priv.Unsubscribe + " => " + !chkOptIn2(m.RCV_MAIL));
                                        priv.Unsubscribe = !chkOptIn2(m.RCV_MAIL);
                                    }
                                    // 동의서 변경시
                                    if (priv.CONSENT == null)
                                    {
                                        priv.Consents.Add(new Consent
                                        {
                                            CONSENT_DATE    = CommonUtil.toUtcDT(m.AGR_DATE),
                                            CONSENT_VERSION = m.AGR_VER,
                                            CONSENT_USE     = chkOptIn2(m.AGREE1),
                                            CONSENT_TRUST   = chkOptIn2(m.AGREE2),
                                            CONSENT_ABROAD  = chkOptIn2(m.AGREE3),
                                            CONSENT_SIGN    = true,
                                            CONSENT_SOURCE  = "MMS"
                                        });
                                    }
                                    else if (priv.CONSENT != null && CommonUtil.toUtcDT(m.AGR_DATE) != priv.CONSENTDATE)
                                    {
                                        priv.Consents.Add(new Consent
                                        {
                                            CONSENT_DATE    = CommonUtil.toUtcDT(m.AGR_DATE),
                                            CONSENT_VERSION = m.AGR_VER,
                                            CONSENT_USE     = chkOptIn2(m.AGREE1),
                                            CONSENT_TRUST   = chkOptIn2(m.AGREE2),
                                            CONSENT_ABROAD  = chkOptIn2(m.AGREE3),
                                            CONSENT_SIGN    = true,
                                            CONSENT_SOURCE  = "MMS"
                                        });
                                    }
                                    // 변경사항 저장
                                    if (tracelist.Count() > 0)
                                    {
                                        string changes = tracelist.Aggregate((a, b) => a + ", " + b);
                                        dbContext.PrivacyLogs.Add(new PrivacyLog {
                                            Privacy = priv, creater = @"MMS", changes = changes
                                        });
                                    }

                                    dbContext.Entry(priv).State = System.Data.Entity.EntityState.Modified;
                                    dbContext.SaveChanges();
                                } // for 존재하면 업데이트
                                if (bExist == false)
                                {
                                    // mms 에서 온 데이터가 없는 경우 새로 추가
                                    dbContext.Privacies.Add(p);
                                    dbContext.SaveChanges();

                                    List <string> tracelist = new List <string>();
                                    tracelist.Add("근무처(병원명) :  => " + p.WKP_NAME);
                                    tracelist.Add("근무지연락처 :  => " + p.WKP_TEL);
                                    tracelist.Add("우편번호 :  => " + p.ZIP);
                                    tracelist.Add("주소 :  => " + p.FULL_ADDR);
                                    tracelist.Add("진료과 :  => " + p.IND_SP);
                                    tracelist.Add("고객명 :  => " + p.IND_FULL_NAME);
                                    tracelist.Add("핸드폰 :  => " + p.MOBILE);
                                    tracelist.Add("채널(부) :  => " + p.CONSENT_SUB_SOURCE);
                                    tracelist.Add("채널 :  => " + p.CONSENT_SOURCE);
                                    tracelist.Add("수신거부 :  => " + p.Unsubscribe);
                                    string changes = tracelist.Aggregate((a, b) => a + ", " + b);

                                    dbContext.PrivacyLogs.Add(new PrivacyLog {
                                        Privacy = p, creater = @"MMS", changes = changes
                                    });
                                    dbContext.SaveChanges();
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            JobLog(myChannel, BatchStatus.Error, e.Message);
                            SMTPHelper.SendAlertInterface(myChannel.name, e.Message);
                        }
                        finally
                        {
                            if (file != null)
                            {
                                file.Dispose();
                            }
                        }
                        // 완료처리
                        collection.status = CollectionStatus.COMPLETED;
                        dbContext.Entry(collection).State = System.Data.Entity.EntityState.Modified;
                        dbContext.SaveChanges();
                        // 백업처리
                        try
                        {
                            File.Move(Path.Combine(myChannel.exportpath, collection.name), Path.Combine(myChannel.backuppath, collection.name));
                        }
#pragma warning disable CS0168 // The variable 'e' is declared but never used
                        catch (Exception e)
                        {
#pragma warning restore CS0168 // The variable 'e' is declared but never used
                            File.Move(Path.Combine(myChannel.exportpath, collection.name), Path.Combine(myChannel.backuppath, Guid.NewGuid().ToString()));
                        }
                    }
                }
            }
            catch (Exception e)
            {
                //added by venkat for exception habding on 5th march 2020
                JobLog(myChannel, BatchStatus.Error, e.Message);
                JobLog(BatchStatus.Completed);
                SMTPHelper.SendAlertInterface(myChannel.name, e.Message);
            }
            JobLog(BatchStatus.Completed);
        }